Greetings People!
Today I am going write about Firebase, which will be targeting mostly the people who don’t know what Firebase is.
What is Firebase?
Before Google owned Firebase. It was real-time database. Now it has many other features like Cloud Messaging, Storage and etc. Read more
Lets start with making a simple application. Open https://console.firebase.google.com/. Login with your google account. Click Create New Project add name and location to it then click Create Project.
You’ll be redirected to your project’s dashboard. Then click on Add Firebase to your Android app
Add your package name. I have already created a project so I added its name. Then click Add App.
After clicking that you’ll get a google-services.json file.
Open your project in Android Studio and in the Explorer paste your google-services.json file under app folder.
In your Project build.gradle.
And in your Module build.gradle.
Click on your Database then click Rules. Make Read and Write both to true.
After that open your activty_main.xml and add a Edit text and a Button, and reference in a the MainActivity.
Create Firebase database object by using the following code:
1 2 |
FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference myRef = database.getReference("Sample Firebase"); |
Now its time to set values to Firebase. In your button listener.
1 2 3 4 5 6 7 8 9 |
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Get the text from Edit text String text = editText.getText().toString(); //set it on Firebase myRef.setValue(text); } }); |
In order to listen to changes to Firebase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Invokes whenever data is updated or changed String value = dataSnapshot.getValue(String.class); Toast.makeText(getApplication(),"Value Changed To:"+value,Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(DatabaseError databaseError) { } }); |
With this being done. You’re all set up and now ready to set data to Firebase.
Run your project and test by sending data.
Testing on Simulator.
You can find this project on Github.
If you have any questions leave a comment. I’ll get back to you as soon as I can. 🙂
See ya!
23 Comments