2

I'm new to this multi-select listview. I want to save the checked state of the checkbox in the listview so that if user closes the app and then opens again, the selected checkbox still remain selected. Is there any way to do this. I searched for it and found that it can be done using SharedPreference but I didn't get more information on how to use it. Thanks

public class MainActivity extends AppCompatActivity {

    ListView myList;
    Button getChoice;

    String[] listContent = {

            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myList = (ListView)findViewById(R.id.list);
        getChoice = (Button)findViewById(R.id.getchoice);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listContent);
        myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        myList.setAdapter(adapter);

        getChoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String selected = "";
                int cntChoice = myList.getCount();

                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
                for(int i = 0; i < cntChoice; i++){
                    if(sparseBooleanArray.get(i)) {
                        selected += myList.getItemAtPosition(i).toString() + "\n";

                    }

                }

                Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();

            }
        });



    }
}
Cookie Ninja
  • 1,156
  • 15
  • 29
CodeAssasins
  • 237
  • 5
  • 17

4 Answers4

1

You can save state, for example, in SharedPreferences.

So your onCreate and onDestroy methods will be look like:

SharedPreferences sharedPreferences = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);

@Override
protected void onCreate(final Bundle savedInstanceState) {
    ...
    Set<String> checkedItemsSource = sharedPreferences.getStringSet("checked_items", new HashSet<String>());
    SparseBooleanArray checkedItems = convertToCheckedItems(checkedItemsSource);
    for (int i = 0; i < checkedItems.size(); i++) {
        int checkedPosition = checkedItems.keyAt(i);
        listView.setItemChecked(checkedPosition, true);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
    Set<String> stringSet = convertToStringSet(checkedItems);
    sharedPreferences.edit()
            .putStringSet("checked_items", stringSet)
            .apply();
}

private SparseBooleanArray convertToCheckedItems(Set<String> checkedItems) {
    SparseBooleanArray array = new SparseBooleanArray();
    for(String itemPositionStr : checkedItems) {
        int position = Integer.parseInt(itemPositionStr);
        array.put(position, true);
    }

    return array;
}

private Set<String> convertToStringSet(SparseBooleanArray checkedItems) {
    Set<String> result = new HashSet<>();
    for (int i = 0; i < checkedItems.size(); i++) {
        result.add(String.valueOf(checkedItems.keyAt(i)));
    }

    return result;
}
Michael Spitsin
  • 2,539
  • 2
  • 19
  • 29
0

on list item set your checkbox checked like this

listView.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                AppListOfAllApps hideSelectedApps = (AppListOfAllApps) parent.getItemAtPosition(position);
                if (view != null)
                {
                    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
                    hideSelectedApps = (AppListOfAllApps) checkBox.getTag();
                    hideSelectedApps.setSelected(!checkBox.isChecked());
                    checkBox.setChecked(!checkBox.isChecked());
                }
            }
        });

Store the selected items in a sharedprefrence and then on button hit make a comparision between all present items in list and item stored in shared prefrence like this

boolean chkbox = false;
        String selecteditem = SharedPreferences.getSharedPref(getApplicationContext()).selecteditem();

then just do this

if (allitems.contains(selecteditem ))
                {
                    chkbox = true;
                }
                else
                {
                    chkbox = false;
                }

Now pass this to adapter constructor this saves the check box state and also retrives it

tanmeet
  • 220
  • 2
  • 11
  • What's `AppListOfAllApps` here? And how to save selected items in SharedPreference? – CodeAssasins Jul 28 '16 at 07:57
  • sorry i added my code i have achieved what u wanted to do.....appslistofallapps is allitems in ur adapter.......save the selected item with key value pair bro – tanmeet Jul 28 '16 at 09:40
0

For that you need to maintain the status in your model. And on every onBindView call just reset the status as per model. For details you can take help from -

https://stackoverflow.com/a/38182528/1741586

Hope it will help you :)

Community
  • 1
  • 1
Neo
  • 3,546
  • 1
  • 24
  • 31
  • I'm using listview. So how to use model class with listview in here? @Neo – CodeAssasins Jul 28 '16 at 08:02
  • Its simple just make a model with all your data, u need for a row. And in getView just update your checkbox as per model. And on state change of checkbox chnge in model tooo. – Neo Jul 28 '16 at 08:04
  • Try it! if still unable to solve the problem please let me know, I will happy to help :) – Neo Jul 28 '16 at 08:45
0

First of all you need to maintain boolean array for selected values and then you can store it in sharedpreference and you also need custom adapter for that,also check Multiple Checkbox values in listview storing & retrieving using sharedpreferences

Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    String[] listArray = new String[] { //Add String values };
    SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);

    Boolean[] checkedStatus = new Boolean[listArray.length];
    for ( int index = 0; index < checkedStatus.length; index++)
        checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);

    ListView listView = (ListView) findViewById(R.id.listview);
    CustomAdapter adapter = new CustomAdapter(this, R.layout.row_layout, listArray, checkedStatus);
    listView.setAdapter(adapter);
}

try this way

public class CustomAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{

String[] values;
Boolean[] checkedStatus;

public CustomAdapter(Context context, int resource, String[] values, Boolean[] checkedStatus) {
    super(context, resource, values);

    this.values = values;
    this.checkedStatus = checkedStatus;
}

@Override
public int getCount() {
    return values.length;
}

@Override
public String getItem(int position) {
    return values[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if(view == null){
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.row_layout, null);
    }

    TextView textView = (TextView) view.findViewById(R.id.title);
    textView.setText(values[position]);

    CheckBox box = (CheckBox) view.findViewById(R.id.chk);
    box.setTag(position);
    box.setOnCheckedChangeListener(this);
    box.setChecked(checkedStatus[position]);

    return view;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Integer index = (Integer) buttonView.getTag();
    checkedStatus[index] = isChecked;
    String key = index.toString();

    SharedPreferences sharedPreferences=getContext().getSharedPreferences("status", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putBoolean(key,isChecked);
    editor.apply();
}
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96