-4

I have two buttons on a fragment, "start" and "finish". when "start" is pressed, it gets hidden and "end" is shown. when "end" is pressed "start" is shown. i want to retain the state when app is closed and run again

Saad
  • 13
  • 5

1 Answers1

0

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`
Surya Teja Karra
  • 541
  • 1
  • 6
  • 19