How to get Android Firestore auto generated document Id

As part of my android cloud Firestore example code, we are going to learn how to get the auto generated document id in android cloud Firestore.

When we use the add() method in Firestore to create a new document, Firestore database will automatically generates an id for your newly created document.

This document id is unique and it helps to differentiate one document from others.

Since the document id is not part of the document properties, if you use DocumentSnapshot class method toObject(), your mapped object will not contain the document id.

But you can directly access your document id using the DocumentSnapshot method getId();

Another way to simply get your document auto generated id is to initially create an empty document and return the id.

You can use the document id to set data to the empty document.

A simple code example is shown below.

String id = db.collection("collection_name").document().getId();
db.collection("collection_name").document(id).set(object);

Simple Code Example

We will create a simple application to illustrate what we have been learning.

Add an EditText and Button widgets in activity layout file.

The user input from the text field will be used to create a new document and the id of the new document is printed out.

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

xml layout file

<?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">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title"
        android:textSize="20sp"
        android:layout_marginTop="90dp"/>

    <View
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="2sp"
        android:layout_below="@id/title"
        android:background="@color/colorAccent"/>

    <TextView
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="body"
        android:textSize="30sp"
        android:layout_below="@id/view1"/>

</RelativeLayout>

activity class

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

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class FirestoreActivity13 extends AppCompatActivity {
    private static final String TAG = FirestoreActivity13.class.getSimpleName()
    private TextView title;
    private TextView body;
    private FirebaseFirestore mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firestore13);
        title = (TextView)findViewById(R.id.title);
        body = (TextView)findViewById(R.id.body);
        mDatabase = FirebaseFirestore.getInstance();
        DocumentReference documentReference = mDatabase.collection("AndroidView").document("Post");
        documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if(task.isSuccessful()){
                    DocumentSnapshot documentSnapshot = task.getResult();
                    Log.d(TAG, "Document id = " + documentSnapshop.getId());
                }
            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(FirestoreActivity13.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