Multiple Checkbox values in listview storing & retrieving using sharedpreferences
In this blog post, I would like explain how to store multiple checkbox values from the listview using shared preferences.
1. Create a new project File -> Android Project. While creating a new project give activity name as CheckBoxSharedPreferences(CheckBoxSharedPreferences.java) and copy this code:
import java.util.ArrayList; import java.util.Arrays; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.SparseBooleanArray; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class CheckboxSharedPreferences extends Activity{ ListView myList; Button getChoice, clearAll; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyUserChoice" ; ArrayList<String> selectedItems = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); myList = (ListView)findViewById(R.id.list); getChoice = (Button)findViewById(R.id.getchoice); clearAll = (Button)findViewById(R.id.clearall); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.Mobile_OS)); myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); myList.setAdapter(adapter); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); if(sharedpreferences.contains(MyPREFERENCES)){ LoadSelections(); } getChoice.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { 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"; System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString()); SaveSelections(); } } Toast.makeText(CheckboxSharedPreferences.this, selected, Toast.LENGTH_LONG).show(); }}); clearAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ClearSelections(); } }); } private void SaveSelections() { // save the selections in the shared preference in private mode for the user SharedPreferences.Editor prefEditor = sharedpreferences.edit(); String savedItems = getSavedItems(); prefEditor.putString(MyPREFERENCES.toString(), savedItems); prefEditor.commit(); } private String getSavedItems() { String savedItems = ""; int count = this.myList.getAdapter().getCount(); for (int i = 0; i < count; i++) { if (this.myList.isItemChecked(i)) { if (savedItems.length() > 0) { savedItems += "," + this.myList.getItemAtPosition(i); } else { savedItems += this.myList.getItemAtPosition(i); } } } return savedItems; } private void LoadSelections() { // if the selections were previously saved load them if (sharedpreferences.contains(MyPREFERENCES.toString())) { String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), ""); selectedItems.addAll(Arrays.asList(savedItems.split(","))); int count = this.myList.getAdapter().getCount(); for (int i = 0; i < count; i++) { String currentItem = (String) myList.getAdapter() .getItem(i); if (selectedItems.contains(currentItem)) { myList.setItemChecked(i, true); Toast.makeText(getApplicationContext(), "Curren Item: " + currentItem, Toast.LENGTH_LONG).show(); } else { myList.setItemChecked(i, false); } } } } private void ClearSelections() { // user has clicked clear button so uncheck all the items int count = this.myList.getAdapter().getCount(); for (int i = 0; i < count; i++) { this.myList.setItemChecked(i, false); } // also clear the saved selections SaveSelections(); } }
2. Now open your main.xml layout and copy this code:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/getchoice" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Get Choice"/> <Button android:id="@+id/clearall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clear All" /> <ListView android:id="@+id/list" android:layout_height="wrap_content" android:layout_width="fill_parent" /> </LinearLayout>
Tips to Remember always:
1) I have retrieved array values from array.xml file directly into the listview.(On line no: 30)
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.Mobile_OS));
My array.xml file in res/values folder:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="Mobile_OS"> <item>Android</item> <item>IOS</item> <item>Windows</item> <item>Bada</item> <item>Ubuntu Touch</item> <item>Firefox</item> <item>Salfish</item> <item>Tizen</item> </string-array> </resources>
The code snippet to retrieve array values directly in ArrayAdapter is getResources().getStringArray(R.array.Mobile_OS).
You can also add multiple array values in the single array file by defining different name for retrieving.
2) If you noticed, while i’m adding values in arraylist to store in the sharedpreferences, i’m adding it by appending one value to the another with comma “,” and while retrieving i’m spliting it up with the same “,” comma , instead of storing single values. (On line no: 88 and 103)
If you want, you can store each value with different key value pair. Read this post for more details.
3) To clear all checkboxes at once use this method:
private void ClearSelections() { // user has clicked clear button so uncheck all the items int count = this.myList.getAdapter().getCount(); for (int i = 0; i < count; i++) { this.myList.setItemChecked(i, false); } // also clear the saved selections then uncomment the below line. // SaveSelections(); }
Similarly, to select all checkboxes at once then change false to true in setItemchecked().
private void SelectAllSelections() { // user has clicked clear button so uncheck all the items int count = this.myList.getAdapter().getCount(); for (int i = 0; i < count; i++) { this.myList.setItemChecked(i, true); } // also clear the saved selections then uncomment the below line. // SaveSelections(); }
4) If you noticed, i used indirect method of clearing the values from sharedpreferences. You can use default method of sharedpreferences also. i.e
editor.clear(); // to clear all values at once editor.remove("android"); // will delete key android, if you use add by key value pair editor.commit(); // commit changes
Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.
Related Posts
durga chiranjeevi
Latest posts by durga chiranjeevi (see all)
- Sharing Application Data Between Two Android Apps – Part III - April 8, 2015
- Sharing Application Data Between Two Android Apps – Part II - April 8, 2015
- Sharing Application Data Between Two Android Apps – Part I - April 8, 2015
Hi Durga!!
Congrats for the post!!
I have a problem, I have a very long list of verbs and I new to check the verbs that I dont know. I think that its th same that your exeple in the post.
But I can’t fix it!
Can you mail me the project to see what happens.
Thanks,
Ivan.
Hello Ivan, Thanks for using Geeks.gallery and sorry to say that i have lost the source code of that blog and more over the blog contains all the information and as well as code except AndroidManifest.xml where you don’t need any change it. Just create a new project and copy paste those coding might help you up. Happy Coding.
Hi Durga!!
Thanks for the post!!
I have one question, where is the xml for the layout “simple_list_item_multiple_choice”. I guess that is where the checkboxes are defined… can you please post it?
Thanks,
Hello rajesh, Thanks for using Geeks.gallery. android.R.layout contains all of the publicly available layouts that the Android OS uses to display various items. One can simply use this to functionality. If you want to customize the layout, then you have to create a new xml similar to this and along with this you have to use baseadapter to work on.
hello sir,
i have implemented the code and when i am passing data on the click of getchoice button to another activity , it shows me the data. but when i reopen that activity that data was lost. please sir help me on this.
i passed the data after writing above below the sparse boolean array under click of button:
Intent learnintent = new Intent(DepartmentList1.this,Depart.class);
learnintent.putExtra(EXT_STRING,selected);
Toast.makeText(DepartmentList1.this, selected, Toast.LENGTH_LONG).show();
startActivity(learnintent);
Please provide “simple_list_item_multiple_choice” in your post. how u set checkbox in your layout.