简体   繁体   中英

Android app crashes if destroyed by back button because of Parse exception

In my onCreate() method I initialize the Parse library as suggested in their documentation:

// Init Parse and enable Local Datastore.
ParseObject.registerSubclass(AlertObject.class);
Parse.enableLocalDatastore(this);
Parse.initialize(this, getString(R.string.parse_app_id),
            getString(R.string.parse_client_key));

However, if I press the back button (so the app is stopped and destroyed) and then I resume the app by clicking on it from the last used apps menu, it crashes throwing the following exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{my.app.pro/my.app.MainActivity}: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
[...]

Essentially, it suggests to invoke enableLocalDatastore() before initialize() , as actually I do.

Of course, if I override the onBackPressed() method as following:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

the problem is solved because the app is not destroyed. BUT, why do I get that exception in the default behavior?

Try to move Parse initialization to the onCreate method of your Application class. If you don't have it you can create a class which extends from Application , example:

public class AppAplication extends Application {
   @Override
   public void onCreate() {
      super.onCreate();

      ParseObject.registerSubclass(AlertObject.class);
      Parse.enableLocalDatastore(this);
      Parse.initialize(this, getString(R.string.parse_app_id), getString(R.string.parse_client_key));
  }
}

And write in the AndroidManifest.xml file that you are using your own Application object adding the android:name attribute to the <application> tag. Example:

<application
    android:name=".AppApplication"
    >

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM