Firebase Realtime Database
Database is an important part in our Project.Firebase realtime database allows data update,delete and store realtime data.It is an cloud hosted data which allows to store data in database as the form of NoSQL as JSON format and synchronized in realtime to every connected client.We don’t need to put any efforts in configuring the server, the Firebase will handle everything automatically and saves a big span of time and increase the productivity.
How it works in Realtime
In realtime it store data on cloud and notifies all devices in milliseconds
How it works in Offline
In offline it persist data in disk and when user comeback online all data will automatically synchronized.
Creating UserInfo class
1 2 3 4 5 6 7 8 9 10 11 12 |
@IgnoreExtraProperties public class User { public String name; public String mobile; public User(){ // Default constructor required for calls to DataSnapshot.getValue(User.class) } public User(String name, String mobile) { this.name = name; this.email = mobile; } } |
Get Database Reference
To read and write into database we need to get Reference of database.
1 2 3 |
private DatabaseReference mDatabase; mDatabase = FirebaseDatabase.getInstance().getReference("users"); |
Read and Write data :
Write Data
For writing data in database basically we use setValue() method on database reference path.This will create or update value on provided path.
1 2 3 4 |
private void createUser(String name,String mobile){ User user=new User(name,mobile); mDatabase.child("users").setValue(user) } |
The realtime database accepts multiple data types.String, Long, Double, Boolean, Map<String, Object>, List<Object> to store the data
Read Data
For read data ,we use the ValueEventListener() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
mDatabase.child("users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); Log.d(TAG, "User name: " + user.getName() + ", email " + user.getMobile()); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } }); |
Delete Data
For Deleting Data you can we can use simpley removeValue() method
1 |
mDatabase.child(“users”).removeValue(); |