How to save document in Android Cloud Firestore Database

If you are working with Android Cloud Firestore for the first time or you want to refresh mind on how to add document in Android Cloud Firestore, this simple walk through tutorial will help you to get a grip.

This is focus on code samples you can adopt to your project or customize it as you want.

We are not going to talk about how to add android Cloud Firestore database to Android project because I have already covered it. Use the link above to access it.

There are different ways to store a document in Android Firestore. We will cover the following three below

  1. Save document to Cloud Firestore database with user generated Id
  2. Save document to Cloud Firestore database with Firestore internally generated Id
  3. Save document to Cloud Firestore database from using Java class object

1. Add Internet Permission in AndroidManifest.xml

Open AndroidManifest.xml file and add the permission below.

<uses-permission android:name="android.permission.INTERNET" />

2. Create a Custom Application Class

We will create a Java class which I will name CustomApplication.java. It will extends the Android Application class.

Inside this class, create an instance of the FirebaseFirestore class which will be accessible to other classes in our project.

import android.app.Application;

import com.google.firebase.firestore.FirebaseFirestore;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class CustomApplication extends Application {

    private static CustomApplication instance;

    private FirebaseFirestore db;

    private Gson gson;

    private GsonBuilder builder;


    public static CustomApplication getAppInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        db = FirebaseFirestore.getInstance();
        builder = new GsonBuilder();
        gson = builder.create();
    }

    public Gson getGson() {
        return gson;
    }

    public FirebaseFirestore getDbInstance(){
        return db;
    }
}

Creating custom application class is optional but since we are going to cover lots of tutorial on Android Cloud Firestore, I decided to use it this ways so that we can easily make use of these classes when we add more classes.

3. Create a Custom Application Class

Create a new package in your project and name it addDoc. Inside addDoc folder, create a new java class and name it AddDocToFirestore.java

Inside this class, we are going to add all the different methods we will use to save a new document to Android Cloud Firestore Database

4. Add different ways to create documentin in Android Cloud Firestore

i. Save document to Cloud Firestore database with user generated Id.

public void addDocumentWithKnownId(String docId, String cityName, String countryOfCity){
       Map<String, Object> city = new HashMap<>();
       city.put(CITY_NAME, cityName);
       city.put(COUNTRY_Of_CITY, countryOfCity);

       firestore.collection(CITY_COLLECTION).document(docId).set(city).addOnSuccessListener(new OnSuccessListener<Void>() {
           @Override
           public void onSuccess(Void aVoid) {
               Toast.makeText(context, "Document successfully created", Toast.LENGTH_SHORT).show();
           }
       }).addOnFailureListener(new OnFailureListener() {
           @Override
           public void onFailure(@NonNull Exception e) {
               Log.d(TAG, "Error!! " + e.getMessage());
               Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
           }
       });
   }

ii. Save document to Cloud Firestore database with Firestore internally generated Id

public void addDocumentWitGeneratedId(String cityName, String countryOfCity){
        Map<String, Object> city = new HashMap<>();
        city.put(CITY_NAME, cityName);
        city.put(COUNTRY_Of_CITY, countryOfCity);

        firestore.collection(CITY_COLLECTION).add(city).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                //get the generated city ID
                String newCityID = documentReference.getId();
                Toast.makeText(context, "City ID - " + newCityID, Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Error!! " + e.getMessage());
                Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }

iii. Save document to Cloud Firestore database from using Java class object

public void addDocumentUsingObject(CityModel cityModel){
        firestore.collection(CITY_COLLECTION).add(cityModel).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                //get the generated city ID
                String newCityID = documentReference.getId();
                Toast.makeText(context, "City ID - " + newCityID, Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Error!! " + e.getMessage());
                Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }

The complete code in AddDocToFirestore class is as shown below.

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.inducesmile.firestoreproject.CustomApplication;

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

public class AddDocToFirestore {

    private static final String TAG = AddDocToFirestore.class.getSimpleName();

    private Context context;

    private static final String CITY_COLLECTION = "cities";
    private static final String CITY_NAME = "name";
    private static final String COUNTRY_Of_CITY = "country";

    private FirebaseFirestore firestore;


    public AddDocToFirestore(Context context) {
        this.context = context;
        firestore = CustomApplication.getAppInstance().getDbInstance();
    }
    

    public void addDocumentWithKnownId(String docId, String cityName, String countryOfCity){
        Map<String, Object> city = new HashMap<>();
        city.put(CITY_NAME, cityName);
        city.put(COUNTRY_Of_CITY, countryOfCity);

        firestore.collection(CITY_COLLECTION).document(docId).set(city).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(context, "Document successfully created", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Error!! " + e.getMessage());
                Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void addDocumentWitGeneratedId(String cityName, String countryOfCity){
        Map<String, Object> city = new HashMap<>();
        city.put(CITY_NAME, cityName);
        city.put(COUNTRY_Of_CITY, countryOfCity);

        firestore.collection(CITY_COLLECTION).add(city).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                //get the generated city ID
                String newCityID = documentReference.getId();
                Toast.makeText(context, "City ID - " + newCityID, Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Error!! " + e.getMessage());
                Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void addDocumentUsingObject(CityModel cityModel){
        firestore.collection(CITY_COLLECTION).add(cityModel).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                //get the generated city ID
                String newCityID = documentReference.getId();
                Toast.makeText(context, "City ID - " + newCityID, Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Error!! " + e.getMessage());
                Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

5. Call AddDocToFirestore class methods in MainActivity class

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.inducesmile.firestoreproject.addDoc.AddDocToFirestore;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private AddDocToFirestore addDocToFirestore;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addDocToFirestore = new AddDocToFirestore(this);

        //create doc in cloud firestore with id
        addDocToFirestore.addDocumentWithKnownId("city", "Lagos", "Nigeria");
    }
}

 

Other Android Cloud Firestore Tutorials

  1. How to add Android Cloud Firestore Database to Android Project
  2. How to save document in Android Cloud Firestore Database

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