Saturday, 29 September 2012

Android Multiple Select ListView

Android Multiple Choice ListView Using Custom Adapter.This listview you can use when you send sms to more than one friend or any notification to your friends.

So using Custom Adapeter we have to create row.xml layout which has checkbox.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/white" >

        android:textStyle="bold" >

        android:focusableInTouchMode="false" >

 Now Using Adapter we can bind data to ListView.But we need to learn easy way to bind data with custom ListView and also hadle CheckBox Listener For Each Row.

So here i have RSS Feed to get data from web and then i add it in List<NameBean>.NameBean is bean class which contains value of Rss Feed Element and we have to maintain one boolean for checkbox state either checked or not.And generate Getters And Setters.

public class NameBean {

private String name;
private boolean selected;

public String getName() {
return name;

public void setName(String name) { = name;

public boolean isSelected() {
return selected;

public void setSelected(boolean selected) {
this.selected = selected;


Now when you get data through XML Parsing you have to create Object of NameBean and you can set data and add Object to List.

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

                  if (nNode.getNodeType() == Node.ELEMENT_NODE) {

   Element eElement = (Element) nNode;

    NameBean objItem = new NameBean();

   objItem.setName(getTagValue("name", eElement));


Now list  is fill up with NameBean Objects.And you can retrive data in Adapter so when you set ListView you just retrieve data in getView(...) method of Adapter.

In getView(...) method put checkBox listener to listen checkbox is check or not, if its checked then set boolean true for that object of NameBean And if its not checked then setSelected false to Namebean object.

So when you start this example in listview and its get data from webservice and bind data to listview using NameAdapter Class.

import java.util.List;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class NamesAdapter extends ArrayAdapter<NameBean> {

private List<NameBean> list;
private LayoutInflater inflator;

public NamesAdapter(Activity context, List<NameBean> list) {
super(context, R.layout.row, list);
this.list = list;
inflator = context.getLayoutInflater();

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(;
holder.chk = (CheckBox) convertView.findViewById(;
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();

convertView.setTag(, holder.title);
convertView.setTag(, holder.chk);
} else {
holder = (ViewHolder) convertView.getTag();


return convertView;

static class ViewHolder {
protected TextView title;
protected CheckBox chk;

When your listView is bind with data you can see checkbox in row with name and now you can get Selected name using NameBean Object and you can retrieve it from list.

                // Retrive Data from list Using for-each loop
                StringBuffer sb = new StringBuffer();
for (NameBean bean : items) {

if (bean.isSelected()) {

Now you get All Selected name from ListView.So its so easy to write Multiple Choice ListView in Android.

You Can Download Full Source Code

Wednesday, 26 September 2012

Android Populate Spinner From Sqlite Database

Android Spinner is DropDown Choice List in Android.You can pick up one item and make your choice from list.

When you get Data from database and display in Spinner, So first you have to create database to get data from database and save it in Dynamic Array.

So first Create that create database and add data in database.

package com.samir.spinner;

import java.util.HashSet;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "mydb";
private static final String TABLE_NAME = "mytable";
private static final String _id = "_id";
private static final String name = "name";

public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);

public void onCreate(SQLiteDatabase db) {
String createTableQuery = "create table " + TABLE_NAME + "(" + _id+ "     INTEGER PRIMARY KEY," + name + " TEXT)";

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)  

db.execSQL("drop table if exists " + TABLE_NAME);

public void insertData(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(name, label);
db.insert(TABLE_NAME, null, values);

public Set<String> getAllData() {
Set<String> set = new HashSet<String>();
String selectQuery = "select * from " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
} while (cursor.moveToNext());
return set;

Now you can see Oncreate Method is Create Database and using query you can create database.Database have two column one in _id which is primary key and second is name which we  want to save in database.

Then Using  ContentValue you can insert Data in database see method insertData(String lable) in above class.

Now, To get All data from database you just fire query and its return Cursor.Then put data in dynamic array from cursor.See method  getAllData().

Here i used Set<String> as dynamic array Because Set doesnot allow duplicates.And Spinner only show unique name.

Once you get Set then you can easily convert it in List<String>.Then you can easily append data to spinner using ArrayAdapter.

       Set<String> set = db.getAllData();
       //Convert set into list
  List<String> list = new ArrayList<String>(set);
  //Sort Data Alphabetical order
  Collections.sort(list, new Comparator<String>() {
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
  adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, list);

Now spinner have listener to listen selected item .

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int position,long id) {
     String name = parent.getItemAtPosition(position).toString();
showToast("You Selected Item :: " + name);
public void onNothingSelected(AdapterView<?> arg0) {

Download Full Source Code::

You Can Download Full Source Code

Tuesday, 15 May 2012

Android Sectioned Listview with Search Bar


Here i put  Sectioned Listview in android.And I add some feature like AsyncTask,Xml Parsing,Bind data in listview with section,Sorting Data to A to Z,Searching in Listview using search bar And onclick in listview get row name.

Features ::

1. How to Work with AsyncTask in android?  

       - See this Example

2.Android XML parser using DOM parser.

      - See this Example

3.Bind data in Listview using Custom Adapter.

   -Using ArrayAdapter<ClassName> we can bind data in listview.
      Android custom adapter have a row layout you can add your view in this layout and then you can add this view(row) in listview row.Using Inflater we can add row in getView() method is bind one by one data in Listview.Use ViewHolder to inflate row is better.See this Video For Fast UI and Efficient .

4.Sort data in Alphabetical order using Comparable.


 -In java to sort any Collection here List<Item>,we have to way one is Comparator<Item> and other is  Comparable<Item>.Between angle brackets there is your bean class name.

When we implements this interfacee that implements one method compareTo(Items another).this method's 
parameter have another object and you can compare any field with another object.

if you have List<Items>  objListItems = new ArrayList<Items>(); 

then you can sort it , Collections.sort(objListItems);

5.Sectioned Listview.

- In section view there are first letter of list items and we can see separated list items using section .See above Screen Shots.

when we get data from web then catch first letter from list items and add it in dynamic array .Then bind it in listview using in different view .

In my code put some logic for sectioned Listview and how to bind sectioned data in Listview.

6.How to Work with Search Bar in ListView?

-In search bar we have one Edittext and You can type any Letter then Listview filter data and so only filtered data.Suppose i have name listview.And i type `s`,then listview display only items which startwith `s`

you can do it using TextWatcher  interface in android EditText.


Now implements  TextWatcher to your Activity and implemented three methods.Now, In afterTextChanged method we can filter ListView and then refresh ListView.Using adapter.notifyDataSetChanged(); you can refresh ListView.