markdown android-java.md
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown android-java.md相关的知识,希望对你有一定的参考价值。
# Before Android, Have a Java MasterClass
## Java Compilation process
Usually we have a source code written in Java. It then goes compiler which checks if the code is correctly written which then spits our byte code to be utilized by JVM and if a device has JVM then it can use the byte code.
## Variables
They are buckets that are needed to store data in our computer. They are like capacity that has limit/threshold on what they can store.
byte, short(2*byte), int, long, float(decimal,fractional number with suffix of f),String,double(bigger than float, used for money and has no suffix of f), char( each letter in word, text, single item/value with one quote ''), boolean(two states
## Relational Operators
==, !=, <, > , >=, <=
## Logical Operators
And (&&), Or(||), Not(!).
### Relationship btn Logical and Relational Operators
Relational operators compare two values and produce a Boolean result. A relational operator tests data values against one another.
Logical operators don't Compare values they combine Boolean values and produce a Boolean result.
## Basic Operators
+/*- % . They work with same type. If not in same type then they should be casted.
## Loop Controls.
Repeating the execution of code block. We can do that with for, while, do while loops.
Loop control variable, initialization, conditions, increment, break, continue. **NB**: Know how to end loop.
## Methods and Return types.
Enclosed group of statements that do something with usually a return value.
```java
public class HelloWorld{
public static void main(String []args){
astatic();
nonstatic(); //error: non-static method nonstatic() cannot be referenced from a static context nonstatic();
}
public static void astatic(){
System.out.println("Hello World");
}
public void nonstatic(){
System.out.println("Hello World");
}
public void nonstatic1(){
this.nonstatic(); // no error
}
}
```
### What to learn about Java methods
* Non static methods can't be called in static method like main and so do nonstaic cant call static
* this can be ignored
## Class Vs Object
Class are like blueprint of objects. It is just a guide, model or what should become something. They are building blocks for objects we create in real world. Like a map to build a house.
## Access modifiers
private, protected, public
## Getters and Setters
private instance made accessible with setters and getters.
## Overloading Constructor
Same constructor name but different number of parameters. Thus different signatures.
## Inheritance.
Getting certain traits from parent class. It is about building relationships. Child class gets everything from parent class. Even though child class gets information from parents but they have their own features. And in other to differentiate what child class get from parents from what they have, it creates its own methods and properties.
## Override
Child class is bound to parents but how ever, it can have its own behaviours as parents but are different hence we override that method
## Java Class Library:
Java comes with pre-baked library that we can use in our projects.
Available at javase api.
## Bigger Buckets. (Data Structures)
Hard Coding vs Limitless data to be stored vs Giving a limit of data to be stored.
```java
int myArray[] = {1,3,5};
for (int i = 0; i < 10; i++) {
System.out.println("MyArray" + myArray[i]);
}
ArrayList animals = new ArrayList();
animals.add("Pig");
animals.add("Cow");
animals.add("Parrot");
//How to get items to print ou
System.out.println(animals.get(0)); // output == Pig
System.out.println(animals.get(1)); // output == Cow
//We can also remove and do all sort of things wiht ArrayLists
animals.remove(0); //removes the first item in our arraylist
//we can add items on the fly
animals.add(0, "Dog"); //add Dog on index 0
//We can remove by calling the object name
animals.remove("Cow"); //will remove "Cow"
//Find the size of the arraylist
animals.size();
//How to iterate through our arrayList
//use "contains()" method to do some checking logic
if (animals.contains("Cow")) {
//Do something here!
}
for (int i=0; i<animals.size(); i++ ) {
System.out.println("Animals:" +animals.get(i)); // get all animals in our arraylist
}
//Enhanced for-loop
for(Object animal : animals) {
System.out.println("Animals:" +animal; // get all animals in our arraylist
}
int[] newArray = new int[5];
String[] newStringArray = new String[5];
newArray[0] = 3;
newArray[1] = 4;
newArray[2] = 6;
newArray[3] = 1;
newArray[4] = 12;
newStringArray[0] = "Marcos";
newStringArray[1] = "James";
newStringArray[2] = "Jason";
newStringArray[3] = "Laura";
newStringArray[4] = "Bonni";
for (int i = 0; i < newStringArray.length ; i++) {
System.out.println("Item " + newStringArray[i]);
}
```
# File System
We can write, read from file. We use of built in classes in Java to accomplish this. One of the them is the
input and output stream where data comes in as bits or stream of bits. With that there is a process to
transform those bits into strings or strings into bits.
* open file
* Write
* close
# Android
## App Creation Process
**NB** The fastest way to fail in app development is not knowing what exactly you are building.
* Define App Goals
1. What are the goals of the app?
2. What does the app do? the idea
3. What kind of information?
4. What is it for?
* User Goals.
1. What will be shown on the screen?
2. How is the information going to be shown?
* Product Goals, thus the app.
1. Reach 50,000 downloadd in three months
2. Earn $10000 gross in three months( Free or Premium- inapp purchase)
3. Release a beta version to board members in six weeks
4. Release 1.0 to Google Play
**NB**: Dont let this product goals affect the development process.
* Storyboard and Flowcharts
Develop a paper work flow on what is going to be built.
## Android Architecture
It is stack of different softwares.
![alt text](https://developer.android.com/guide/platform/images/android-stack_2x.png "Logo Title Text 1")
* Systems -level: That is why our application we built stands. Some come by default. Like dailer, email.etc.
* Java API Framework: Tap in by programmers to build apps like views, activities,
* Native Libraries(C/C++): They are core systems of that provide to
*
## No more casting in new Android studio for Views
```java
private Button quote_button;
quote_button = findViewById((R.id.quote_button));
```
## Setting Listerner on a View. Know what Args is needed.
```java
quote_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
```
### UI components are inherited from View Parent Class
So anything including events can be done on all views. Eg.
```java
myTextView = findViewById(R.id.textViewId);
myTextView.setText("Hey I am here at Andela");
myTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Clicked Text View");
}
});
```
**NB:** All Properties in Design/XML Mode can be done in Java Code. eg. Visibility be set with Java code as viewObject.setVisibility(View.VISIBLE).
## DPI (Dot-Per-Inch)
Determines the quality of elements on screen. The higher the dpi the better the quality.
## Layouts
* **Relative Layout:** You can relatively position items of the same siblings
* **Frame Layout:** Contains only one element.
## importing Dependencies
**NB** All dependencies are added to build.gradle(Module app).
In android folder, open Gradle scripts and choose build.gradle(Module app)
```java
//recyclerview
compile 'com.android.support:recyclerview-v7:27.0.2'
//design library for Coordinator Layout, Tabs, Navigation Bars, Floating Action Buttons..etc..
compile 'com.android.support:design:27.0.2'
//circle images
compile 'de.hdodenhof:circleimageview:2.1.0'
//LikeButton
compile 'com.github.jd-alexander:LikeButton:0.2.3'
//glide
implementation 'com.github.bumptech.glide:glide:4.4.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'
//BottomNavigationView customization
compile 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
```
## Reference to repository outside maven
```java
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }
}
}
```
## onclick different implementation
```java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.d(TAG, "onCreate: started");
mLogin = findViewById(R.id.btn_login);
mLogin.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.btn_login){
Log.d(TAG, "onClick: Lgging");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
//preventing coming to login screen
finish();
}
}
}
```
## Extending created activity to Main class Activity than AppCompatActivity
Activity is a window that has properties that a user can interact with.
Activity is the true activity class and AppCompatActivity is a version of that.
AppCompatActivity is a class from e v7 appcompat library. This is a compatibility library that back ports some features of recent versions of Android to older devices. It enables the use of the ActionBar and Material Design specific implementations like the Toolbar for older devices using versions of Android as old as Android 2.1 (API level 7). So if your app's minSdkVersion is a version that does not support the new features in newer APIs you can use the support library to enable those features. If you use support library ,you have to have all your activities extend AppCompatActivity instead of the Activity base class.
## Activity Stages
onCreate , onStart, OnPostResume, OnPause, OnStop and onDestroy.
onCreate , onStart are must have.
## Navigating between Activities
This can be done with Intent. Intent is an action. What is it that the application wants to do.
We want to go from Activity A to Activity B.
```java
Intent intent = new Intent(CurrentActivity.this, nextActivity.class)
startAtivity(intent)
```
## Attach data to Activity and sent to Activity B.
A will do:
```java
//onclick
Intent intent = new Intent(CurrentActivity.this, nextActivity.class);
intent.putExtra(key, value);
startAtivity(intent)
```
B will do:
//onCreate
`Bundle extras = getIntent().getExtras();
extras.getString(key);`
## Send data Back to First Activity From Second Activity.
Override onActivityResult. This will catch all data from activity B. What can we do to get the data.
* RequestCode: A code that allows us to know what kind of result we are expecting or the result we are expecting is actually happening.
Create a request code in first activity as `private final int REQUEST_CODE = 2` .
B will do :
```java
//onclick
Intent returnIntent = getIntent();
returnIntent.putExtra(key, value);
setResult(RESULT_OK,returnIntent );
finish()
```
A will do:
```java
//onClick eventlistner
Intent intent = new Intent(CurrentActivity.this, nextActivity.class);
intent.putExtra(key, value);
startAtivityForResult(intent, REQUEST_CODE);
//onActivityResult
if(requestCode == REQUEST_CODE ) {
if(resultCode == RESULT_OK){
result = data.getStringExtra(key from second activity)
}
```
## Remove activity stack
finish();
## Log Class
Log outputs. It takes TAG and a TAG tells which activity we are in now.
## Inflation of XML.
Takes XML and make it view that a user can interact with. This happens in onCreateView by using
LayoutInflater or other forms.
## RecycleView
For it to work, it should have an adapter which is the interface between the data and the view.
* It allows us to connect to our list row to display in the data.
## overide default activity animation
## SharedPreferences
## AlertDialog
## Fragments
Fragment is incomplete part of something. They are usually isolated.
Fragment A can be fitted in Activity a and b.
### Fragment Basics
* Choosing API level should be at least 19(Android 4.4)
* Creating Fragment from Activity via class and its xml
* Connect fragment to activity via a class. A fragment needs its class to control that fragment. It extends to Adroid support app fragment.
* Create a constructor to prevent App Crashing on different orientation.
* onCreateView method to render the xml
```java
View view = inflatet.inflate(fragemnt, container, attach_to_parent(boolean))
return view
//example
View view = inflater.inflate(R.layout.fragment_first, container, false);
return view;
```
* Invoke class to show the content show.
* via xml or code
* Via xml, attach the fragment xml to activity
* We can only use one at a time
```java
<fragment
name
/>
```
* Preffered way to do it is programmatically via Java Code
* Fetch fragment and use it in our activity(screen) with FragmentManager
```java
FragmentManager fragmentManager = getSupportFragmentManager();
//get fragment by checking if there is a fragement
Fragment fragment = fragmentManager.findFragmentById(R.id.wheretoputfragmentInActivity)
//if no fragment, get our fragment and add it
if(fragment == null){
frament = new Fragment Class;
fragmentManager.beginTransaction()
.add(R.id.wheretoputfragmentInActivity, fragment)
.commit() //attach both and say yes to changes.
//Example
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.container);
if(fragment == null){
fragment = new FirstFragment();
fragmentManager.beginTransaction().add(R.id.container, fragment).commit();
}
}
}
```
## Moving from Fragment A to B
Fragments live in activity and so meaning the Activity listens to which fragment is calling which fragment so that It can tell that hey
Fragment A needs u now.
To do a fragment that want to communicate to another fragment establishes a contract with their activity through setting up an interface in the fragment and allow that to be implemented by the activity
## Use dp for textSize
## Showing Some Resourcecs only on Tablet with SW600dp
## SharedPreferences
Get stored as xml files.
## getting rid of error after draging recycler view
set the constraints on the properties if you are using constraint layouts
# Firebase
Allows developers to use some services in the cloud to achieve amazing works. They are allow us to develop
applications in reatime, authentication, cloud messaging, storage, hosting, etc. On top of that we can
do admob for making money from our app.
* So we will Go ahead and do that by going to the sdk manager > sdk tools
* We will need to have android support repository, Google Repository and Google play services installed.
* Create firebase andrioid app
** Add Package name
** Adding sha1
*** Gradle Panel
*** click on the move back and forward icon
*** go the app/android to find the signReport
*** click on it
*** u will see some gibrish stuff
*** Look for SHA1.
*** Copy and paste and register app.
** skip the next steps, we ill do that in android studio.
** Set it up in android studio.
*** Change the configuration from signingReport to App
*** Tools > Firebase
*** Connect to firebase
*** Reatime realtime database
** lets check in our gradle if all the dependencies and plugins are added
** We have all the information in our IDE to work with firebase.
### Writing to database
* Get instance
* Reference to where it should be stored.
* Testing
** Change Rules to
".read" : true.
But we should never happen but for testing purpose.
# Authentication
* FireabaseAuth
* Firebase.AuthStateListener
* Overide onStart and onStop with auth instance body.
mAuth.addAuthStateListener(mAuthListener);
mAuth.removeAuthStateListener(mAuthListener);
# Creating menu
* inside of res, right click directory(menu)
* inside of menu, right click resource file
# Get icons from material io
downlaod it as png
以上是关于markdown android-java.md的主要内容,如果未能解决你的问题,请参考以下文章