[Solved] How to save the state of fragment (Android) when application is closed and restore it when application is run again?


I would recommend using SharedPreferences to achieve this. They are meant to be to retain app state when run at a later time.

In your case, you need to use putBoolean() method from SharedPreferences.Editor something like this:

“Start” button onClickListener:

SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.editor();
editor.putBoolean("isJobRunning","true");
editor.commit();

In the same way, you set the isJobRunning to false once “End” button is called.

I would also move this code to a dedicated method something like this:

private void updateJobStatus(boolean isJobRunning) {
    SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.editor();
    editor.putBoolean("isJobRunning", isJobRunning); // difference is visible here! 
    editor.commit();
}

On the onCreateView() method on the Activity, you can check if the job is running this way:

SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
sharedPref.getBoolean("isJobRunning", false); // Here, `false` is the default value if the key is not located in `SharedPref`

solved How to save the state of fragment (Android) when application is closed and restore it when application is run again?