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.
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 :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.