0

In my application, I use a checkBox that when it is checked, a piece of music is played. But when the user moves to another activity and then returns to the activity that the checkBox is there, it is unchecked. In order to stop the music, you have to check the checkBox again and after that uncheck it. How can I save the state of checkBox unchanged as I move between activities?

    This is my XML code:
    <CheckBox
    android:id="@+id/chk_box_music"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center"
    android:layout_marginTop="4dp"
    android:layout_marginLeft="12dp"
    android:layout_gravity="center"
    android:layout_marginStart="12dp"/>

This is my JAVA code:
CheckBox checkBox = (CheckBox) findViewById(R.id.chk_box_music);
checkBox.setOnCheckedChangeListener(new 
CompoundButton.OnCheckedChangeListener({
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b == true){
startService(new Intent(SettingsActivity.this, MyService.class));
}else{ stopService(new Intent(SettingsActivity.this, MyService.class));
}
}
});

2 Answers2

0

You can either save the CheckBox state in:

  1. Shared preferences
  2. Bundle onSaveInstanceState(Bundle) and then getting that value/flag in onCreate(Bundle).
  3. Local database (using Room, SQLite or any other tool)
Daniel Beleza
  • 389
  • 1
  • 15
  • I don't agree with this, by moving between activities work in object oriented para time Don't need to save in shared preferences or in database. – Asad Ali Choudhry Apr 13 '19 at 10:11
  • The thing is, since this is configuration, it should be centralized somewhere, since this is the good practice. For scalability, if you had more configurations it makes all sense to save them into a table inside database. For small projects, this isn't the best approach, therefore you should be using `onSaveInstanceState(Bundle)` – Daniel Beleza Apr 13 '19 at 10:27
  • I understand what you mean when you say it is just a work between activities, but this is specific case where you should send or pass your configuration settings around. This approach follows the best architecture practices like MVVM, MVP or Clean Architecture. – Daniel Beleza Apr 13 '19 at 10:28
  • For sending and receiving info between activities the simplest and easiest approach is to startActivityForResult & OnAcitivityResult Methods, I already mentioned the link in my answer. https://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android/10407371#10407371 – Asad Ali Choudhry Apr 13 '19 at 10:38
0

You can override onResume Method of your activity. This method will be called when Activity will be resumed again. so in this method you can set checkbox state whatever you want to set, like

  @Override
   protected void onResume() {
    super.onResume();
    checkBox.setChecked(true); // or false, according to your logic
    }

And if you want to send/receive some information from the other Activity then you need to start activity for result and handle its results. its help is here

Edited:

Another simplest way could be to save info in Shared Preferences Like

 @Override
 protected void onResume() {
    super.onResume();

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean isChecked  = pref.getBoolean("isChecked", false);
   checkBox.setChecked(isChecked); // or false, according to your logic

    // And on checked change update shared Preferences

    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
            pref.edit().putBoolean("isChecked",isChecked).commit();
        }
    });

}

Now as you told that you want to clear checkbox when App closed, so that next time when user comes checkbox should be cleared. for that update SharedPreferences in same Activity on Destroy method, where checkbox is present.

@Override
 public onDestroy() {

     SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
     pref.edit().putBoolean("isChecked",false).commit();
     super.onDestroy();
 }
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
  • Many thanks. But the onResume() method keeps it checked or not checked when I totally exit the app and run it again. – Mohammad Sadegh May 26 '19 at 20:43
  • I need a method when the user checks the checkbox, keep the checkbox checked as the user moves across the activities. and when he/she closes the app and runs it again, the checkbox must be empty and unchecked. – Mohammad Sadegh May 26 '19 at 20:46
  • if you have checkbox in activity A and you move to Activity B, C & D. If you simply finish() activity D, C & B. Checkbox will still be checked in Activity A. It will be only change if you start activity A again. don't start it again, just keep it in stack, it will remain checked. Other possible way could be the shared Preferences. Let me update my code for shared preferences. – Asad Ali Choudhry May 27 '19 at 05:36
  • please check my updated answer it should work now. Now Only thing is to try to avoid finishing activity A where checkbox is present, because I am clearing SharedPreferences in its OnDestroy() method. – Asad Ali Choudhry May 27 '19 at 05:49
  • If you still face some issue let me know. Or If it works, please accept my answer, Thanks. – Asad Ali Choudhry May 27 '19 at 05:50
  • It does not work. How can I send you the full code? I mean the codes in MyService class and those in the activity in which the checkbox is placed? – Mohammad Sadegh May 27 '19 at 07:09
  • The problem might be somewhere else. because I have tried many many ways. – Mohammad Sadegh May 27 '19 at 07:11
  • you can post code in the question, service is not the issue, you just need to tell the flow of activities and how are you are starting and finishing in between activities. – Asad Ali Choudhry May 27 '19 at 07:28