Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Firebase Persistence Set

I'm currently developing a android project and I have a little problem. I'm using firebase for database and I'm saving datas offline to local storage but when I set database.setPersistenceEnabled(true); second time, my app crashes. How can I prevent that? I'm setting that just once in LoginActivity and I don't use that but my app is in the background and re-open the app my app crashes because of the persistence. And a little question too, after saving any data to firebase my activity re-opens. I don't understand that either. Can anyone help me?

like image 622
Gürsel Avatar asked Mar 11 '23 00:03

Gürsel


2 Answers

you need to override Application class, add it to manifest and then call database.setPersistenceEnabled(true); there. example:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }

}

then in your AndroidManifest.xml :

<application
        android:name=".MyApplication"  <!--Relative path of MyApplication.java-->
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        tools:replace="android:supportsRtl"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
...
</application>
like image 118
Saurabh Avatar answered Apr 03 '23 03:04

Saurabh


best place for to keep it with viewmodel class with! and it will never destory you query after recreating of fragment or activity

class DashboardViewModel : ViewModel() {
    private lateinit var database: DatabaseReference
    private var postdata = MutableLiveData<List<Post>>()

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

}
like image 44
Nitish Kumar Avatar answered Apr 03 '23 02:04

Nitish Kumar