lundi 30 mai 2016

How to save checkbox state in listview using sharedpreference

I have checkboxes in listview, i want checkbox states to be saved when i click on it,now when i resume my app ,all the checkboxes will be unchecked.I am trying to develop TODO List app where list row textview will be striken and checkbox will be checked, how can i save checkbox state and striken textview into sharedpreference and load.

 protected void onCreate(Bundle saved) {
        super.onCreate(saved);
        setContentView(R.layout.cbox_list);
        Listvw = (ListView) findViewById(R.id.clistvw);
        Listvw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cText = (TextView) view.findViewById(R.id.ctext);
                cBox = (CheckBox) view.findViewById(R.id.cbox);
                cBox.setChecked(true);
                //Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
                cText.setPaintFlags(cText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                //boolean value=cBox.isChecked();
                int b = Listvw.getAdapter().getCount();
                for (int i1 = 0; i1 < b; i1++) {
                    if (cBox.isChecked()) {
                        SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
                        SharedPreferences.Editor edit = spf.edit();
                        edit.putBoolean("name"+i1, cBox.isChecked());
                        edit.commit();
                    }
                }
            }
        });

        model = new CheckModel[12];
        model[0] = new CheckModel("Item1", 0);
        model[1] = new CheckModel("Item", 0);
        model[2] = new CheckModel("Item", 0);
        model[3] = new CheckModel("Item", 0);
        model[4] = new CheckModel("Item", 0);
        model[5] = new CheckModel("Item", 0);
        model[6] = new CheckModel("Item", 0);
        model[7] = new CheckModel("Home Head", 0);
        model[8] = new CheckModel("Item", 0);
        model[9] = new CheckModel("Item", 0);
        model[10] = new CheckModel("Item", 0);
        model[11] = new CheckModel("Item", 0);
        CustomAdapter adpter = new CustomAdapter(this, model);
       int c=Listvw.getAdapter().getCount();
        for(int i=0;i<c;i++)
        {
            SharedPreferences pf=PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
            boolean chkbx=pf.getBoolean("name"+i,false);
            if(chkbx){
                cBox.setChecked(true);
            }else{
                cBox.setChecked(false);
            }
        }
        Listvw.setAdapter(adpter);




Aucun commentaire:

Enregistrer un commentaire