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?
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>
                        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);
   }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With