35

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();
Vincent Macharia
  • 475
  • 2
  • 7
  • 20
  • 2
    In addition to Frank's answer, you should add a check, for example `savedInstanceState == null`, to ensure that the statement is not executed again on activity restart. Otherwise, you'll get the exception when you rotate the device. – Bob Snyder Jun 10 '16 at 18:21

9 Answers9

106

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.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
Siddhesh Dighe
  • 2,894
  • 3
  • 16
  • 16
  • I tried this and I get the following exception repeatedly FATAL EXCEPTION: main Process: co.transportsystems.offrie:background_crash, PID: 27025 java.lang.RuntimeException: Unable to create application com.android.tools.fd.runtime.BootstrapApplication: java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist. Any ideas of why this happens? – Nicolás Arias Sep 24 '16 at 03:11
  • 1
    This worked for me... Thanx siddhesh.. +1 from my side. – Arpit Patel Oct 07 '16 at 10:30
  • 3
    In addition to this, if you're already using `android:name` for another Application class on the application tag and you can't change it (like using MultiDexApplication for configure the app with over 64K methods like I was doing) you can make MyFirebaseApp extend that class. – Albert Feb 14 '17 at 17:10
  • 1
    This worked for me and seems to be the way to go. Thanks! – Nathan O'Kane Nov 27 '17 at 23:32
23

Something like this (iirc):

 if (mDatabase == null) {
     FirebaseDatabase database = FirebaseDatabase.getInstance();
     database.setPersistenceEnabled(true);
     mDatabase = database.getReference();
     // ...
 }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 5
    does the firebase team have a best practice for this issue Frank? I've seen you provide 2 or 3 different answers to this question. Can you point us to a best practice please? – drod May 11 '17 at 13:22
15

Create an application class that will be used across your entire application and initialize firebase Persistence in it: The Class should extend Application.( ClassName extends Application):

Heres An Example:

FirebaseHandler class

You can call/name the class whatever you want to name it

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

Add the application class to your Manifest:

 <application
    android:name=".FirebaseHandler"
    android:allowBackup="true"
    android:icon="@mipmap/app_icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

This way data persistance will be applied to your entire project. Inorder to apply disk persistence to specific data.

DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("people"); 
myRef.keepSynced(true);

This will keep your offline data synced and up to date

myRef.keepSynced(true);

Learn more about Disk Persistence Here

RileyManda
  • 2,536
  • 25
  • 30
6

This solution works for me without extends android.app.Application

private static FirebaseDatabase firebaseDatabase;

    if (firebaseDatabase == null) {
        firebaseDatabase=FirebaseDatabase.getInstance();
        firebaseDatabase.setPersistenceEnabled(true);
    }
    /* Do your other stuff  */

OR

if (savedInstanceState == null) {
   FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
Vishal G. Gohel
  • 1,008
  • 1
  • 16
  • 31
5

Just add this at the top of your activity class:

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

Worked for me, not sure if it's the best practice though.

zarsky
  • 680
  • 2
  • 14
  • 24
3

If you extend a ContentProvider in your app you can call FirebaseDatabase.getInstance().setPersistenceEnabled(true); in your ContentProvider's onCreate() method because this method is called even before the onCreate() method of your launcher activity. This will also be useful when you use TaskStackBuilder in your app to create a synthetic stack of activities to skip some activities and move forward like when you use in app notifications. So when you come back to the launcher activity moving backwards you might have already used FirebaseDatabase instance somewhere in your application and the error you are getting might pop up in this case as well.

Kartik Watwani
  • 129
  • 1
  • 1
  • 7
1

If you are using Kotlin, the following code worked for me. I declared as private member variable at the top of the class.

private val firebaseInstance = FirebaseDatabase.getInstance().apply { setPersistenceEnabled(true) }
MetaPlanet
  • 129
  • 4
1

This works for me. Add this to your launching activity!

try {           
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
} catch (Exception e) {}
Lakpriya Senevirathna
  • 2,488
  • 2
  • 17
  • 35
0

You could try checking if there are any initialized firebase apps before calling setPersistenceEnabled.

if (FirebaseApp.getApps(this).size() == 0)
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Isaac Sekamatte
  • 5,500
  • 1
  • 34
  • 40