Firebase realtime database read write update and delete operations in android

Firebase database is a NoSql database in which user can do operation realtime. Since it is not an sql database, data will be stored in the form of json tree. In this tutoral we will learn how to implement read,write,update and delete operations in a firebase realtime database.

Steps

  1. Create new project in android studio.
  2. Configure new project on firebase console.
  3. Add realtime database to project.
  4. Write record.
  5. Read record.
  6. Update record.
  7. Delete record.

Create project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Configure new project on firebase console

Refer How to configure a firebase console in android  will help you to create new project in firebase.Please note that you need to use same package name as android project.

Add realtime database to project

Next step is to add realtime database to our project. For doing that you need to click on Tools and then click on firebase. A assisstant window will open which is similar to the following screen.

In the above screen click on Save and retreive data link under Realtime database which will lead you to the following screen.

Next you need to sclick on connect to firebase button followed by Add the realtime database to your app button. After that there will be some gradle build operations which will lead to the following screen. If you get the following screen then your connection is successfull.

Write Record

As i said earlier data is stored here as json tree instead of sql. For doing that it is important to have a model class which will be easier to store seperate records in array list. In this tutoral i am creating a user info storage and retreival. So am calling it UserModel.

public class UserModel {
    String id,name;

    public UserModel() {
    }

    public UserModel(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Next we need a layout which will help us to collect the data from user. The layout will have a button to submit the data to realtime database. For implementing the layout file add the following code to your activity’s layout file. The layout file contain widgets for display ,update aslo. This will be used in next steps.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <RelativeLayout
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <EditText
            android:id="@+id/ed_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter name" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/ed_name"
            android:text="Add" />

        <LinearLayout
            android:id="@+id/ll_update"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_submit"
            android:visibility="gone"
            android:orientation="vertical">

            <EditText
                android:id="@+id/ed_update"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Update" />

            <Button
                android:id="@+id/btn_update"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Update" />

            <Button
                android:id="@+id/btn_delete"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Delete" />

        </LinearLayout>

        <ListView
            android:id="@+id/lv_users"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ll_update"></ListView>

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Now use the following code in your activity’s java file. Here i am skipping the part of gettting reference of edittext and buttons. So you need to place the following code inside the onclick of the submit button.

DatabaseReference databaseuser = FirebaseDatabase.getInstance().getReference("users");
String name = ed_name.getText().toString().trim();
if (!TextUtils.isEmpty(name)) {
String id = databaseMeetz.push().getKey();
UserModel userModel = new UserModel(id, name);
databaseuser.child(id).setValue(userModel);
ed_name.setText("");
Toast.makeText(this, "User added successfully", Toast.LENGTH_LONG).show();

} else {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
}

Read Record

In this step you need to get the list of data you stored in firebase database. After retrieving data of course you need to display it. So you need to create a listivew first. Please refer Android Listview if you are beginner. So use the following code to retreive the data from firebase. The code will retrieve the data and put it in usermodel arraylist. You need to initialize your adapter with that list and set to your listview.

databaseuser.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        userModelList.clear();
        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            UserModel userModel = postSnapshot.getValue(UserModel.class);
            //adding user to the list
            userModelList.add(userModel);
        }
//use your adapter for listview
        UserAdapter userAdapter = new UserAdapter(MainActivity.this, userModelList);
        lv_users.setAdapter(userAdapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Update Record

For updating an item first you need to get access to that item. So when user clicks on an item in that list we will show that item in a form to update.Use the following code to get the item and display it in update form (considering i have only id and name of person). The string update_id and update_name is declared globally. When a user clicks on an item this value will be overwritten.

update_id = userModelList.get(position).getId();
update_name = userModelList.get(position).getName();
ed_update.setText(update_name);

Now user can edit the form and once click on update button use the following code to update in firebase database.

DatabaseReference dR = FirebaseDatabase.getInstance().getReference("users").child(update_id);
UserModel userModel = new UserModel(update_id, ed_update.getText().toString());
dR.setValue(userModel);
Toast.makeText(getApplicationContext(), "User Updated", Toast.LENGTH_LONG).show();

Delete Record

In this case i am showing delete button also with update button. So when user clicks on an item update_id and update_name strings will contain the clicks item records. Here for doing delete operation we just need id. Use the following code to do the delete operation.

DatabaseReference dR = FirebaseDatabase.getInstance().getReference("users").child(update_id);
dR.removeValue();
Toast.makeText(getApplicationContext(), "User Deleted", Toast.LENGTH_LONG).show();

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *