-1

Please help me! Checkbox does not save state after restarting the app I have a ListView with CheckBoxes and I want that when user selects any check box and closes the application, and again opens the application, the same CheckBoxes should be selected. i.e I have to save the state of the CheckBoxes

  // custom BaseAdapter class
  ...
  boolean [] itemChecked;     
 //getView  ...
 //getSharedPreferences
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
   //Click ckeckbox    
    viewHolder.check_task.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME , false));
  viewHolder.check_task.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
   //SharedPreferences    
            SharedPreferences.Editor editor = context.getSharedPreferences(PACKAGE_NAME , Context.MODE_PRIVATE).edit();    
            if (viewHolder.check_task.isChecked()) {
                //if value is false
                itemChecked[i] = true;
                viewHolder.check_task.setChecked(true);
                 //put True
                editor.putBoolean(PACKAGE_NAME, true);
                editor.apply();
     } else {
                //if value is false
                itemChecked[i] = false;
                viewHolder.check_task.setChecked(false);
                //put False
                editor.putBoolean(PACKAGE_NAME, false);
                editor.apply();
            }}});  return myView; }
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
ula
  • 5
  • 2

1 Answers1

0

You are always setting the last checked box state in shared preferences since you are using the same key each time. If you want to set multiples you would have to define a new key for each boolean using something like editor.putBoolean(PACKAGE_NAME + index, true); then retrieve it using the same logic. This will result in each index having an entry in shared preferences. Another approach would be to use GSON to save the entire array in onPause and restore it when the app is relaunched.

SRoseDev88
  • 184
  • 6