0

I want my app to save data locally offline. whenever i reopen the app while their is no Internet. It should work

in onCreate of Application I call

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

offline capablilites are working as long as the app is started while having internet. And if I close the app and restart it the data is not synched.

also tried

keepSynched(true);

But as long as you kill the app. It loses connection and no offline data is available. How to do persistance data in android

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
ZA BroadPeak
  • 29
  • 1
  • 9
  • Possible duplicate of [Firebase offline capabilities as cache](https://stackoverflow.com/questions/38778680/firebase-offline-capabilities-as-cache) –  May 03 '18 at 08:39

2 Answers2

4

you have to call FirebaseDatabase.getInstance().setPersistenceEnabled(true); in every where that you want your retrieved data to be stored locally. Therefore, you should create a helper class like this:

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class FirebaseUtils {
    private static DatabaseReference mDatabaseRef;
    private static FirebaseDatabase database;
    public static DatabaseReference getDatabaseRef() {
        if (mDatabaseRef == null) {
            getDatabase();
            mDatabaseRef = database.getReference();
            // ...
        }
        return mDatabaseRef;
    }

    public static FirebaseDatabase getDatabase() {
        if (database == null) {
            database = FirebaseDatabase.getInstance();
            database.setPersistenceEnabled(true);
            // ...
        }
        return database;
    }
}

Then, in your activity and fragment and other places where you want to do your database stuff, you initialize the DatabaseReference object like this:

private DatabaseReference mDatabase;
private DatabaseReference mPlaceRef;

....

mDatabase = FirebaseUtils.getDatabaseRef();
mPlaceRef = mDatabase .child("places");

...
Fazan Cheng
  • 866
  • 1
  • 8
  • 13
  • you have choosen sb with bad reputation to reply to,this hasnt marked as answer even once –  May 03 '18 at 08:38
  • @D.'s thanks buddy. Thats okay. at least i have you who care about my effort. appreciate it – Fazan Cheng May 03 '18 at 23:50
  • This doesn't work anymore. Firebase throws this exception: com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance – Ahmed Shahid Apr 07 '22 at 05:45
0

FirebaseDatabase.getInstance().setPersistenceEnabled(true) should only be called once during start or initialization of your app.

I tested this in iOS and it works well, but in android it is not working.

William Baker Morrison
  • 1,642
  • 4
  • 21
  • 33
  • The OP asked how to do persistance in an Android env. Would you happen to know _why_ it's not working there? – cueedee Jan 23 '21 at 14:10