This document provides an overview of using Android and Firebase. It outlines key aspects of working with Firebase databases including their tree-like JSON structure, offline data support, and CRUD operations. Example code is given for creating a user model class, inserting, reading, updating, and deleting data from the Firebase database. Implementation in an Android app is discussed, including layout design and creating the database structure with nodes for app title and user profiles.
3. Firebase Database
• Structure of firebase database is like json only. It means it’s having tree like structure like json.
{
“teacher": [
{
"name": “Nilesh Sawardekar“,
"email": “nilnil.nilesh@gmail.com",
"address": "XXX, XXXX, 1234"
}
],
"students": [
{
"id": 100,
“stud_name": “Parth",
“stud_address": “AAA AAA AAA",
"timestamp": "13892733894“,
“division”: “B”
}
]
}
4. • Firebase support offline data. Whether your having internet or not firebase
saves the data. It means when you are offline its hold the data in local
memory and once your connected to internet data get saved. Yup, its happen
after restart also.
▫ Use below command to achieve this,
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
• CRUD Operation is possible with firebase.
▫ First add reference like below,
• We can store different type of data to be stored like String, Long, Double,
Boolean, Map<String, Object>, List<Object> to store the data.
• We can store model (class) object to firebase.
private DatabaseReference mDatabase;
mDatabase =
FirebaseDatabase.getInstance().getReference();
5. Create model
public class User {
public String name;
public String email;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
Every table required unique id, simply calling push method below creates new id.
String userId = mDatabase.push().getKey();
6. Inserting data
Below is whole code,
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
User user = new User(“Nilesh Sawardekar", “nilnil.nilesh@gmail.com");
// pushing user to 'users' node using the userId
mDatabase.child(userId).setValue(user);
Result of above code would be,
{
"users": [
"-KTYWvZG4Qn9ZYTc47O6" : {
"email" : " nilnil.nilesh@gmail.com ",
"name" : " Nilesh Sawardekar "
},
{
...
}
]
}
7. Reading data
• To read the data, you need to attach the ValueEventListener() to the database reference.
mDatabase.child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Log.d(TAG, "User name: " + user.getName() + ", email " + user.getEmail());
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
8. Updating and deleting
String newEmail = ‘nilnil.nilesh@gmail.com';
mDatabase.child(userId).child("email").setValue(newEmail);
You can also use updateChildren() by passing the path to update data
without disturbing other child nodes data.
• To delete data, you can simply call removeValue() method on to
database reference. You can also pass null to setValue() method which
do the same delete operation.
9. Setting Rules
• Rules allows user to perform read & write operation only after authentication.
▫ The below rules allow authenticated users only to read or write data.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Below rules allows everyone to read & write data without authentication.
{
"rules": {
".read": true,
".write": true
}
}
10. Validating Data for CRUD
• You can also use these rules to validate data before inserting into database. For example below rules validates the name to be less
than 50 chars and email to be valid using email regular expression.
{
"rules": {
".read": true,
".write": true,
"users": {
"$user": {
"name": {
".validate": "newData.isString() && newData.val().length < 50"
},
"email": {
".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i)"
}
}
}
}
}
13. Our goal is to create the json structure as below in which ‘app_title’ stores the app
title. ‘users’ stores user profiles as an array of nodes.
{
"app_title" : "Realtime Database",
"users" : {
"-KTYWvZG4Qn9ZYTc47O6" : {
"email" : “nilnil.nilesh@gmail.com",
"name" : “Nilesh Sawardekar"
}
}
}
• > getReference(“app_title”) create a node named app_title which stores the toolbar title.
• > getReference(“users”) gets reference to users node.
• > createUser() method stores a new user in real time database.
• > updateUser() method updates user information like name and email.
Editor's Notes
Lesson descriptions should be brief.
How presentation will benefit audience: Adult learners are more interested in a subject if they know how or why it is important to them.
Presenter’s level of expertise in the subject: Briefly state your credentials in this area, or explain why participants should listen to you.