0

I need to save values from the checkbox to shared preferences so that even after exiting, the checked boxes are still checked. Could anyone please show me how to solve this issue?

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

    ListView listView;
    ArrayAdapter<Model> adapter;
    List<Model> list = new ArrayList<Model>();

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.my_list);
        adapter = new MyAdapter(this,getModel());
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
        TextView label = (TextView) v.getTag(R.id.label);
        CheckBox checkbox = (CheckBox) v.getTag(R.id.check);
        Toast.makeText(v.getContext(), label.getText().toString() + " " + isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
    }

    private String isCheckedOrNot(CheckBox checkbox) {
        if(checkbox.isChecked())
            return "is checked";
        else
            return "is not checked";
    }

    private List<Model> getModel() {
        list.add(new Model("1"));
        list.add(new Model("2"));
        list.add(new Model("3"));


        return list;
    }
}
GabEA
  • 19
  • 3
  • 1
    Possible duplicate of [How to use SharedPreferences in Android to store, fetch and edit values](http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) – Andrew Brooke Nov 24 '15 at 14:45

1 Answers1

0

I made this class, use it:

public class SavePreferences {
private final static String MYAPP_PREFERENCES = "MyAppPreferences";


public void savePreferencesData(View view, String KEY, String TEXT) {
        SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        if (TEXT != null && KEY != null) {
            editor.putString(KEY, TEXT);
            editor.commit();
        }
    }

private String loadPreferencesData(View view, String KEY){
        SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
        String data = prefs.getString(KEY, "No Data!");
        return data;
    }
}

And then:

savePreferencesData(View, "CheckBox1", "true");
Michele Lacorte
  • 5,323
  • 7
  • 32
  • 54