How to update data in Android Cloud FireStore Database

Imagine when we covered how to add data to android cloud Firestore database we realized that we have added a wrong data.

Beside that, may be our application is design in such a way that some user actions can trigger changes to data in our cloud Firestore database.

It is time to learn how to update data already present in android cloud Firestore database.

Update Firestore Database Field

To update a particular field in a document, first we need to get the document reference like below.

DocumentReference documentReference = mDatabase.collection("AndroidView").document("Post2");

We can now call the update() method to the document reference if we want to change only the listed field values in the update() method.

documentReference.update("title", "Hello");

Update Nested Object in Firestore

Updating Firestore nested object is also similar to updating a field.

You can access a nested object by using the object name with a dot and the field property.

documentReference.update("title", "Hello", "user.comment", "I am reading this article");

Update Elements in an Array in Firestore

Updating elements of an array in Firestore makes use of two important methods arrayUnion() and arrayRemove()

To learn more about updating data in cloud Firestore database check the official doc here.

Simple Code Example

To illustrate what we have been learning with a practical code example, we are going to use two EditText and Button widgets.

A user will add data to the fields and use button click to update our cloud Firestore database using the added data.

CREATE A NEW ANDROID PROJECT

  • Open Android Studio
  • Go to file menu
  • Select  new
  • Enter project name
  • Enter activity name
  • Select Default Activity
  • Click on finish button to create a new android project

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/titleinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/title"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/bodyinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/titleinput">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/body"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>


    <Button
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@id/bodyinput"
        android:textColor="#ffffff"
        android:text="Edit"/>

</RelativeLayout>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.HashMap;
import java.util.Map;

public class FirestoreActivity4 extends AppCompatActivity {
    private TextInputEditText title;
    private TextInputEditText body;
    private FirebaseFirestore mDatabase;
    private Button edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firestore4);
        title = (TextInputEditText)findViewById(R.id.title);
        body = (TextInputEditText)findViewById(R.id.body);
        edit = (Button)findViewById(R.id.edit);
        mDatabase = FirebaseFirestore.getInstance();

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String enteredtitle = title.getText().toString();
                String enteredbody = body.getText().toString();
                updateDocument(enteredtitle, enteredbody);
            }
        });
    }

    private void updateDocument(String strTitle, String strBody){
        DocumentReference documentReference = mDatabase.collection("AndroidView").document("Post2");
        documentReference.update("title", strTitle);
        documentReference.update("body", strBody)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(FirestoreActivity4.this,"Document Updated",Toast.LENGTH_LONG).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(FirestoreActivity4.this,e.getMessage(),Toast.LENGTH_LONG).show();
                        Log.d("Androidview", e.getMessage());
                    }
                });
    }
}

Add Dependencies

app/build.gradle

implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-firestore:19.0.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment