2

I have a Map:

  Map<String, String> noidung = new HashMap<>();

The Map receives data from Firebase and I show them in a Gridview. Everything worked well. But when the phone goes offline, I want the data I have loaded to remain on the Gridview. My idea is to store the Map noidung to a file (I think SharedPreference) to use offline. I have tried very much solutions but failed.

Niels
  • 725
  • 5
  • 14
Ben Pham
  • 57
  • 7
  • 1
    Persist your changes (e.g. with sqlite) and recover them `onResume` of your `Activity`. – Mena Jun 23 '16 at 13:35

1 Answers1

9

Take a look at this:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

From the documentation:

Firebase apps automatically handle temporary network interruptions for you. Cached data will still be available while offline and your writes will be resent when network connectivity is recovered. Enabling disk persistence allows our app to also keep all of its state even after an app restart. We can enable disk persistence with just one line of code.

https://firebase.google.com/docs/database/android/offline-capabilities

In addition, you can keep specific locations in sync:

DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.keepSynced(true);

Setting persistence enabled has to be the very first call to the Firebase API. So before you do any queries/etc. A good location is in your Application subclass:

public class MainApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }

Don't forget to update your manifest accordingly:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="my.package" >

    ...
    <application android:name=".MainApplication">
        ...
    </application>
</manifest>

It's really that easy. And that is what Firebase makes so awesome :-)

Niels
  • 725
  • 5
  • 14
  • Thank you for answering. Can you tell me where to add FirebaseDatabase.getInstance().setPersistenceEnabled(true); ? I use firebase in a fragment, and it has error: – Ben Pham Jun 23 '16 at 13:58
  • com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance. at com.google.firebase.database.FirebaseDatabase.zzhM(Unknown Source) at com.google.firebase.database.FirebaseDatabase.setPersistenceEnabled(Unknown Source) – Ben Pham Jun 23 '16 at 14:00
  • It has to be the very first call to the Firebase API. So before you do any queries/etc. A common place for this code is your `Application` subclass. See my updated answer. – Niels Jun 23 '16 at 14:03
  • Thank you and i finally get the answer at here: http://stackoverflow.com/questions/37753991/com-google-firebase-database-databaseexception-calls-to-setpersistenceenabled – Ben Pham Jun 23 '16 at 14:28