ListView Example 3 – Simple Multiple Selection Checkboxes

This is the third blog post in series of posts that will demonstrate how Android ListView can be used in your application. We started the series off with the most basic loading of hard coded arraylist in a ListView. In the second post we loaded the data from the Xml file. In this post we will build up on the example from second post. After loading the listview from an Xml resource file we will display it as simple multiple selection checkboxes which user can select and unselect and save their selections in the and load the data in the ListView from that Xml file at runtime.

Skill Assumptions:

  1. You have configured your Android development environment on Eclipse or other tools
  2. You know how to create a new Android project

What you will learn:

  1. How to load a listview based on Xml resource file
  2. How to display checkboxes for each item in the list and allow user to select multiple items
  3. How to save user selections to SharedPreferences so that the selected items can be loaded back as checked items when the activity starts again
  4. How to handle onPause event so that selections are saved when activity goes in the background and/or it is paused

What are we doing in this project:

  1. Create an Activity [Start.java] with layout containing one button
  2. When the button is clicked we will launch another activity [SimpleListView.java] that will load the listview from Xml resource file and display items as checkboxes
  3. When user clicks Save, we will save the items that are checked in SharedPreferences
  4. When user clicks Clear, we will clear the selection on listview and saved items
  5. When user clicks back button or restarts the application, we will load any previously checked items from the SharedPreferences and set them as checked

Lets jump into the second example.

Step 1 – Create a new Eclipse project

Step 2 - Add a default Activity named Start which will add main.xml under layout folder and Start.java under your namespace folder under src.

Step 3 – In your eclipse project under the res folder create a new subfolder named xml [all lowercase]. Create a new Xml file named todolist.xml in your res/xml folder using your favorite editor with following content pasted in it. Save the file and refresh your res folder in Eclipse. This step is same as second post.

Here is how your folder structure will look like:

// layout/todolist.xml




	
	
	
	

Step 4 – Copy paste following Xml on your main.xml file.

// layout/main.xml






			






		





Step 5 – Copy paste following code in your AndroidManifest.xml file. The most important attribute is to android:theme=”@android:style/Theme.NoTitleBar” which will disable the default Android title bar because we are replacing that with our own Action bar.

Also, notice the additional activity node we have added that registers the activity with Android – activity android:name=”.SimpleListView”. We will add the SimpleListView class and related layout in next steps.

// AndroidManifest.xml



    
        
            
                
                
            
        
		
    
    


Step 6 – Copy and paste following code in your Start.java class file.

// src/Start.java

package com.appfulcrum.blog.examples.listviewxml;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Start extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnSimple = (Button) findViewById(R.id.btnSimple);
        btnSimple.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast.makeText(getApplicationContext(),
						" You clicked Simple ListView button", Toast.LENGTH_SHORT).show();

				Intent intent = new Intent(v.getContext(), SimpleListView.class);
       		  	startActivityForResult(intent, 0);
			}
		});

    }
}

Step 7 – Add a new Android layout file in your res/layout folder named simple.xml. Then copy and paste following xml in simple.xml file.

// res/layout/simple.xml






			


			
			
		




		


Step 8 – Add a new class file named SimpleListView.java to your project in your src folder. Then copy and paste following code in the SimpleListView.java file. Notice the resource id – android.R.layout.simple_list_item_multiple_choice. That is the magic default Android layout that allows us to fill up the ListView and show checkbox next to each item without specifying the layout Xml for individual list items.

// src/SimpleListView.java

package com.appfulcrum.blog.examples.listviewxml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.content.*;
import android.content.res.XmlResourceParser;

public class SimpleListView extends ListActivity {

	private String[] lv_arr = {};
	private ListView mainListView = null;
	final String SETTING_TODOLIST = "todolist";

	private ArrayList selectedItems = new ArrayList();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simple);

		Button btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast.makeText(getApplicationContext(),
						" You clicked Save button", Toast.LENGTH_SHORT).show();

				SaveSelections();
			}
		});

		Button btnClear = (Button) findViewById(R.id.btnClear);
		btnClear.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Toast.makeText(getApplicationContext(),
						" You clicked Clear button", Toast.LENGTH_SHORT).show();

				ClearSelections();
			}
		});

		// Prepare an ArrayList of todo items
		ArrayList listTODO = PrepareListFromXml();

		this.mainListView = getListView();

		mainListView.setCacheColorHint(0);

		// Bind the data with the list
		lv_arr = (String[]) listTODO.toArray(new String[0]);
		mainListView.setAdapter(new ArrayAdapter(SimpleListView.this,
				android.R.layout.simple_list_item_multiple_choice, lv_arr));

		mainListView.setItemsCanFocus(false);
		mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		LoadSelections();
	}

	@Override
	protected void onPause() {
		// always handle the onPause to make sure selections are saved if user clicks back button
		SaveSelections();

		super.onPause();
	}

	private void ClearSelections() {

		// user has clicked clear button so uncheck all the items

		int count = this.mainListView.getAdapter().getCount();

		for (int i = 0; i < count; i++) {
			this.mainListView.setItemChecked(i, false);
		}

		// also clear the saved selections
		SaveSelections();

	}

	private void LoadSelections() {
		// if the selections were previously saved load them

		SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);

		if (settingsActivity.contains(SETTING_TODOLIST)) {
			String savedItems = settingsActivity
					.getString(SETTING_TODOLIST, "");

			this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
			int count = this.mainListView.getAdapter().getCount();

			for (int i = 0; i < count; i++) {
				String currentItem = (String) this.mainListView.getAdapter()
						.getItem(i);
				if (this.selectedItems.contains(currentItem)) {
					this.mainListView.setItemChecked(i, true);
				}

			}

		}
	}

	private void SaveSelections() {

		// save the selections in the shared preference in private mode for the user

		SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
		SharedPreferences.Editor prefEditor = settingsActivity.edit();

		String savedItems = getSavedItems();

		prefEditor.putString(SETTING_TODOLIST, savedItems);

		prefEditor.commit();
	}

	private String getSavedItems() {
		String savedItems = "";

		int count = this.mainListView.getAdapter().getCount();

		for (int i = 0; i < count; i++) {

			if (this.mainListView.isItemChecked(i)) {
				if (savedItems.length() > 0) {
					savedItems += "," + this.mainListView.getItemAtPosition(i);
				} else {
					savedItems += this.mainListView.getItemAtPosition(i);
				}
			}

		}
		return savedItems;
	}

	private ArrayList PrepareListFromXml() {
		ArrayList todoItems = new ArrayList();
		XmlResourceParser todolistXml = getResources().getXml(R.xml.todolist);

		int eventType = -1;
		while (eventType != XmlResourceParser.END_DOCUMENT) {
			if (eventType == XmlResourceParser.START_TAG) {

				String strNode = todolistXml.getName();
				if (strNode.equals("item")) {
					todoItems.add(todolistXml.getAttributeValue(null, "title"));
				}
			}

			try {
				eventType = todolistXml.next();
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return todoItems;
	}
}

Step 9 – Run the application as Android Application and you should see below for output.


Tags: , , , , , , , , ,

http://downloadpart.com