Custom Data Adapters with Checked List Views – Part II

This entry is part 41 of 50 in the series Android Development Primer

In the last post, I showed you how to make the front end for the List View with check box using Custom Data Adapters. This post will deal with the coding of the custom Data Adapters. This one coupled with the last post, will complete the procedure.

The custom Data Adapter class is named Adapter.java and extends the ArrayAdapter<String> class. Quite obviously, this is because if you recall the lost post, you can see that I’ve used an ArrayList to populate the List View. Had I used a database, we could have used a CursorAdapter.

This code is complicated and hence I provide the explanations below.

Understanding the Code

  • A HashMap is a Java class that allows for key-value pair mapping. We are going to map each item with a boolean value that identifies if it is checked or unchecked.
  • We initialize all the items to unchecked in the constructor.
  • The toggle() function serves the purpose of checking or unchecking the item once it is clicked, depending on it’s previous state.
  • getCheckedItemPosition() serves the purpose of returning the indices of items that are checked.
  • getCheckedItems() serves the purpose of returning the items that are checked.
  • Remember that all these methods make use of the basic functions of the HashMap class of Java. If you face any difficulty understanding them, I suggest you read the Java HashMap documentation here.

CDA

COMPLETE SOURCE CODE

row_item.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/checkedtextview"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingBottom="10dip"
    android:paddingLeft="20dip"
    android:paddingRight="20dip"
    android:paddingTop="10dip"
    android:textColor="#000000" 
    
    android:onClick="toggle"
    >

</CheckedTextView>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#D0D0D0" >

    <Button
        android:id="@+id/addcourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Go" />
    
    <EditText
        android:id="@+id/coursenameet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="2dp"
        android:hint="Course Name" 
        android:inputType="textCapWords" >

    </EditText>
    
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:layout_below="@+id/coursenameet"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray" >
    </View>
    
    <TextView
        android:id="@+id/weekdaytv"
        android:layout_width="wrap_content"
		android:layout_height="wrap_content"
        android:layout_below="@+id/divider"
        android:layout_marginBottom="3dp"
        android:layout_marginTop="3dp"
        android:layout_centerHorizontal="true"
        android:text="Select weekdays for this Course" >
    </TextView>
    
    <RelativeLayout 
    	android:id="@+id/rlinner"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:layout_centerVertical="true"
    	android:layout_centerHorizontal="true"  
    	android:layout_above="@+id/addcourse"
	    android:layout_below="@+id/weekdaytv">
	    
        <RelativeLayout 
	    	android:id="@+id/rlinnermost"
	    	android:layout_width="match_parent"
	    	android:layout_height="wrap_content"
	    	android:layout_centerVertical="true"
	    	android:layout_centerHorizontal="true" >
    	
		    <ListView
		        android:id="@+id/listView1"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content"
		        android:divider="#FFFFFF"
		    	android:dividerHeight="2dp" />
	    </RelativeLayout>
    	
	</RelativeLayout>

</RelativeLayout>

Adapter.java

package com.nero.myfirstapp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.R.color;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.Toast;

public class Adapter extends ArrayAdapter {

	HashMap<Integer, Boolean> checked = new HashMap<Integer, Boolean>();
	ArrayListweekdays;
	Context context;
	private int[] colors = new int[] { Color.parseColor("#D0D0D0"), Color.parseColor("#D8D8D8") };
	public Adapter(Context context, int resource, int textViewResourceId, ArrayList weekdays) {
		super(context, resource, textViewResourceId, weekdays);
		this.context=context;
		this.weekdays=weekdays;
		for(int i=0;i<weekdays.size();i++)checked.put(i, false);
	}

	public Adapter(Context context, int resource, int textViewResourceId, ArrayList weekdays, ArrayListoldweekdays) {
		super(context, resource, textViewResourceId, weekdays);
		this.context=context;
		this.weekdays=weekdays;
		for(int i=0;i<weekdays.size();i++)checked.put(i, false);
		for(int i=0;i<oldweekdays.size();i++)checked.put(oldweekdays.get(i),true);
	}

	public void toggle(int position){
		if(checked.get(position))checked.put(position, false);
		else checked.put(position, true);
		notifyDataSetChanged();
	}

	public ArrayList getCheckedItemPosition(){
		ArrayListcheck = new ArrayList();
		for(int i=0;i<checked.size();i++){
			if(checked.get(i))check.add(i);
		}
		return check;
	}

	public ArrayList getCheckedItems(){
		ArrayList check = new ArrayList();
		for(int i=0;i<checked.size();i++){
			if(checked.get(i))check.add(weekdays.get(i));
		}
		return check;
	}

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

		   if(row == null){
		    LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = vi.inflate(R.layout.row_item, null);
		   }

		   CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.checkedtextview);
		   checkedTextView.setText(weekdays.get(position));
		   row.setBackgroundColor(colors[position % colors.length]);
		   return row;
	}
}

MainActivity.java

package com.nero.myfirstapp;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Main extends Activity {
    ArrayList weekdays = new ArrayList();
    ArrayList ret = new ArrayList();
    ListView lv;
    EditText coursename;
    Button addcourse;
    Adapter adapter;
    String c;
    long courseid;

    public void initialize(){
        weekdays.add("Monday");weekdays.add("Tuesday");weekdays.add("Wednesday");
        weekdays.add("Thursday");weekdays.add("Friday");weekdays.add("Saturday");
    }

    public void getoldweekdays(long id){
        ret.clear();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ret.clear();
        initialize();
        lv = (ListView) findViewById(R.id.listView1);
        coursename = (EditText) findViewById(R.id.coursenameet);
        addcourse = (Button) findViewById(R.id.addcourse);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        courseid = getIntent().getLongExtra("courseid", -1);
        adapter = new Adapter(this, R.layout.row_item, R.id.checkedtextview, weekdays);
        lv.setAdapter(adapter);
        for(int i=0;i<ret.size();i++)lv.setItemChecked(ret.get(i), true);

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,   long id) {
                adapter.toggle(position);
            }
        });

        addcourse.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ArrayList checkeditem = adapter.getCheckedItems();
                finish();
            }
        });
    }
}
Series Navigation<< Custom Data Adapters with Checked List Views – Part IAlarm Manager in Android >>

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

43,751 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>