Title: Add Firebase Client-Android to Android Application for Database ...

6 downloads 307 Views 19KB Size Report
Title: Add Firebase Client-Android to Android Application for Database. Owner: Purvik. YouTube Tutorial Link: https://yo
Title: Add Firebase Client-Android to Android Application for Database Owner: Purvik YouTube Tutorial Link: https://youtu.be/Rkr4B5x77fo Steps: 1. First Set up Firebase SDK for your Android Project A.

Add in root level build.gradle file in dependencies, classpath 'com.google.gms:google-services:3.0.0'

B. Add in app level build.gradle file in dependencies, compile 'com.firebase:firebase-client-android:2.5.2' //only for 2.5.2 (for 3.0.0 all things will change) & at bottom of the file apply plugin: 'com.google.gms.google-services & add this in android section of your file packagingOptions{ exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } 2. Register your project to the FireBase Console and get the google-services.json file from there & put it in the app directory 3. Go to the Database tab and copy the link for the database A. Create a Config class and define a String with copied value 4. In Database section of firebase console, go to the rules section and change them to { "rules": { ".read": true, ".write": true } } That’ll add permission to read and write from any one o this database //NOTE: This rule is set like this for only practice purpose, it’s need to set different for real app. 5. Create a class Person with two field “name” and “address” & an empty constructor. Add getters and setters for this fields. 6. Modify activity_layout as require. I have took name and address from user for this tutorial.

7. In MainActivity, //set the context of this application Firebase.setAndroidContext(this); //get the Firebase instance Firebase ref = new Firebase(Config.FIREBASE_URL); //get the user inputted values String name = editTextName.getText().toString().trim(); String address = editTextAddress.getText().toString().trim(); //create Person object & set this values //Storing values to firebase database ref.child("Person").setValue(person); //Value event listener for realtime data update ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (DataSnapshot postSnapshot : snapshot.getChildren()) { //Getting the data from snapshot Person person = postSnapshot.getValue(Person.class); //Adding it to a string String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n"; //Displaying it on textview textViewPersons.setText(string); } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); } }); 8. Add Internet permission to the Android Manifest File. 9. That it. DONE. 