How to add Offline Cache in Android Cloud Firestore Database

We have been looking at different features of android cloud Firestore database and what we can use them for in our android project.

In this example code, we will dive into how to add offline cache in cloud Firestore database.

Offline cache has many advantages specially where mobile data is a concern to application users.

Beside that, it increase the response speed of an app and users can as well use the app even when they are offline.

Firestore Offline Cache

Cloud Firestore offline cache is handle by FirebaseFirestoreSettings class.

It has a method setPersistanceEnable(). The default value is false. To activate it we will need to set it to true

Below is how to enable offline cache in cloud Firestore database

FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setPersistenceEnabled(true)
                .build();
        mDatabase.setFirestoreSettings(settings);

Simple Code Example

The code example below illustrate how to use offline cache in cloud Firestore database to retrieve data from database.

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

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

MainActivity.java

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;
import com.google.firebase.firestore.FirebaseFirestoreSettings;

public class FirestoreActivity5 extends AppCompatActivity {
    private TextView title;
    private TextView body;
    private FirebaseFirestore mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firestore5);
        title = (TextView)findViewById(R.id.title);
        body = (TextView)findViewById(R.id.body);
        mDatabase = FirebaseFirestore.getInstance();
        offlinecache();
    }

    private void offlinecache(){
        FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setPersistenceEnabled(true)
                .build();
        mDatabase.setFirestoreSettings(settings);
        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();
                    title.setText(documentSnapshot.get("title").toString());
                    body.setText(documentSnapshot.get("body").toString());

                }
            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(FirestoreActivity5.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