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

Screenshot:
Screenshot_2014-05-09-16-23-28

Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. Ivan
    • durga chiranjeevi
  2. Rajesh
    • durga chiranjeevi
  3. jashan
  4. pavan

Leave a Reply

Your email address will not be published. Required fields are marked *