Issue
I am a Junior and I encounter a problem.
I am using Realm on Android (Java) and I would like to delete the data in my local BDD when it is closing. I always finish my activity before starting a new one and I never know what will be the last activity before user decided to close app.
Is there a way to execute code when app is closing?
EDIT
Here's my code, thanks to @Mohanad
public class ApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration mRealmConfig = new RealmConfiguration.Builder()
.schemaVersion(1)
.migration(new RealmMigrations())
.inMemory()
.build();
Realm.setDefaultConfiguration(mRealmConfig);
registerActivityLifecycleCallBack();
Log.i("XXX", "I've been created");
}
public void registerActivityLifecycleCallBack() {
ActivityLifecycleCallbacks mActivity = new ActivityLifecycleCallbacks() {
int mCounter = 0;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mCounter++;
Log.i("XXX", "I'm called again and again");
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
mCounter--;
if (mCounter == 0) {
Realm mRealm = Realm.getDefaultInstance();
mRealm.close();
}
}
};
}
}
Solution
Steps:
1.) use inMemory()
configuration
RealmConfiguration config = new RealmConfiguration.Builder()
.inMemory()
.build();
2.) Call realm.init()
in Application.onCreate()
, set the default configuration as usual, and afterwards, initialize/close Realm like this:
public class MyActivity extends AppCompatActivity {
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
}
Now when Realm is closed on all threads and you are quitting the app (or the app is killed), the Realm will be deleted.
Answered By - EpicPandaForce
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.