com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance

Vincent Macharia picture Vincent Macharia · Jun 10, 2016 · Viewed 15.1k times · Source

I am having a problem when I try to setPersistence in fIREBASE,can someone please explain on how to go about it,

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meal_details);

        if (mDatabase == null) {
            mDatabase = FirebaseDatabase.getInstance().getReference();
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
            // ...
        }


       // FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        mDatabase = FirebaseDatabase.getInstance().getReference();

Answer

Siddhesh Dighe picture Siddhesh Dighe · Jun 11, 2016

According to Firebase Documentations setPersistenceEnabled is to be called only once (before any other instances of FirebaseDatabase are made)

So the solution to this issue for me was the following

  1. You need to create a class which extends android.app.Application and setPersistenceEnabled(true) over there.

For Example

class MyFirebaseApp extends android.app.Application 

@Override
public void onCreate() {
    super.onCreate();
    /* Enable disk persistence  */
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
  1. In the Manifest, link the MyFirebaseApp class to the application tag

For Example

in your application tag add the following

android:name="com.example.MyFirebaseApp"

this should work fine.

Also don't use setPersistenceEnabled in any other Activity.