How to use BaseAdapter and OnItemClickListener in Android

Hi Android lovers :-) Till now we have developed some list item applications. But have you ever tried to click on one item of the ListView. Every time we passed a String Array or ArrayList witch type safe with String, to the Adapter. Is that the only way we can create an Adapter? Can’t we create our own fancy list to show our data? :O Don’t worry. We are going to cover all of that in this small blog post.

As usual I will show you the final out put of what we are going to do during this post.

How to use BaseAdapter and OnItemClickListener in Android
Figure 1

You can see form the Figure 1, this is not a usual list that we can get by default in android. Here you have CheckBox, TextView and ImageView in a single raw of the list.

When you are designing the XML layout, make sure to give Focusable attribute value as “false” for the CheckBox. Unless you wont be able to see the Toast message in Figure 2 after you click on an item in the ListView.

I have used an inner class to write the adapter class which extends the BaseAdapter class. You have to implement four abstract methods in the BaseAdapter class after you extends it. I wrote some System.out.println methods to show you how the code runs. Other than that you no need to put those codes in your final product. You can see the out put of System.out.println methods in your LogCat window.

How to use BaseAdapter and OnItemClickListener in Android
Figure 2

In my previous posts I have used ArrayAdapter class to join the UI (User Interface) component with the data set. Instead of that, here I have used my own class CustomAdapter that extends BaseAdapter class to perform that job.

When you go through the code, you will be able to see that there are four arguments in the onItemClick method. onItemClick is an abstract method in OnItemClickListener interface. By using a Toast message I show you the difference between the last two arguments of the onItemClick method. In the code comments, I have clearly explained those things.

package com.anuja.android;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BookListActivity extends Activity implements OnItemClickListener {

	private ListView bookListView;
	private TextView rawTextView;
	private ArrayList<Book> bookArray;

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

        // To show the books in a list
        bookListView = (ListView) findViewById(R.id.booksListView);

        // We pass this bookArray to our CustomAdapter
        bookArray = new ArrayList();

        // Setting values to books
        for( int i=20; i<50; i++){
        	Book aBookDetail = new Book();
        	aBookDetail.setBookIsbn(i);
        	aBookDetail.setBookName("Book name : " + i);
        	aBookDetail.setBookAutorName("Book author : " + i);

        	bookArray.add(aBookDetail);
        }

        // Initialize our Adapter and plug it to the ListView
        CustomAdapter customAdapter = new CustomAdapter(bookArray);
        bookListView.setAdapter(customAdapter);     

        // Activate the Click even of the List items
        bookListView.setOnItemClickListener(this);
    }

    // Regular inner class which act as the Adapter
	public class CustomAdapter extends BaseAdapter{
		private ArrayList<Book> innerClassBookArray;

		public CustomAdapter(ArrayList<Book> paraBookArray) {
			System.out.println("*** 1 CustomAdapter constructor");
			innerClassBookArray = paraBookArray;
		}

		// How many items are in the data set represented by this Adapter.
		@Override
		public int getCount() {
			System.out.println("*** 2 getCount method");
			System.out.println(innerClassBookArray.size());
			return innerClassBookArray.size();
		}

		// Get the data item associated with the specified position in the data set.
		@Override
		public Object getItem(int position) {
			System.out.println("*** ? getItem method");
			System.out.println(innerClassBookArray.get(position));
			return innerClassBookArray.get(position);
		}

		// Get the row id associated with the specified position in the list.
		@Override
		public long getItemId(int position) {
			System.out.println("*** 3 getItemId method");
			System.out.println(innerClassBookArray.get(position).getBookIsbn());
			return innerClassBookArray.get(position).getBookIsbn();
		}

		// Get a View that displays the data at the specified position in the data set.
		// You can either create a View manually or inflate it from an XML layout file.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			System.out.println("*** 4 getView method");
			System.out.println(position);

			if(convertView == null){
				// LayoutInflater class is used to instantiate layout XML file into its corresponding View objects.
				LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				convertView = layoutInflater.inflate(R.layout.one_raw_of_list, null);
			}

			rawTextView = (TextView) convertView.findViewById(R.id.rawTextView);
			rawTextView.setText(innerClassBookArray.get(position).getBookName());

			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// arg2 = the id of the item in our view (List/Grid) that we clicked
		// arg3 = the id of the item that we have clicked
		// if we didn't assign any id for the Object (Book) the arg3 value is 0
		// That means if we comment, aBookDetail.setBookIsbn(i); arg3 value become 0
		Toast.makeText(getApplicationContext(), "You clicked on position : " + arg2 + " and id : " + arg3, Toast.LENGTH_LONG).show();
	}
}

Oops… I have figured out a formatting conflict with WordPress. When I use the angle brackets, the code get messed up if I do not specifically mention it in the code snippet. :-( I tried to correct all the points as best I can. So don’t worry. Anyway I am always give you my GitHub profile link where you can download the whole project. :D

I am always encourage you to copy the code and paste it in an IDE where you can clearly see the difference between comments and the real code. Because the I have done code explanation as comments, therefore no need to duplicate it here.

That is it for today’s post and here is the link to download the full source from my GitHub repository. Have a nice day. :-)

About these ads

About anujarosha

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in Android Examples. Bookmark the permalink.

9 Responses to How to use BaseAdapter and OnItemClickListener in Android

  1. Chris says:

    I am getting
    Cannot instantiate the type Book line 38
    the method getBookIsbn() is undefined for the type Book line 83
    the method getBookIsbn() is undefined for the type Book line 84
    the method getBookName() is undefined for the type Book line 102
    the method setBookAutoName(string) is undefined for the type Book line 41
    the method setBookIsdn(int) is undefinded for the type Book line 39
    the method setBookName(string) is undfined for the type Book line 40

    • anujarosha says:

      Hi Chris,

      Have you created the Book class (POJO). It contains “private” variables for bookIsbn, bookName and bookAuthorName. So you should have “public” getters and setters to access those variables. Check that out. If your Book class is not in the same package, make sure to import it too.

      Good luck

  2. Tanmay Gill says:

    I want to compare the View (arg1) with a View( i.e.Button), declared in my Adapter class.
    How can I do it?

  3. ujjwala says:

    hi,,,,i want a program on listview using arraylist,,,,if we click on one contact then that details shuld be display in next page,,,,,,hw to do this program,can u please tell me

  4. meo pro says:

    thanks a lot, but I didn’t call @Override onItemClick method, I did listView.setOnItemClickListener and it’s done, thanks a lot again!

  5. Raj says:

    Thanks a lot!
    I am new to android. your blogs very useful for me Friend..,

  6. Amit Kumar says:

    Hi
    I wonder this issue didn’t strike to anyone. actually when I click on one chkbox the corresponding checkbox afterscrolling also gets checked. any solutions for this.

  7. Tyson says:

    Thank you VERY much for writing this. This is the best example I’ve been able to find on the ‘net after a full day of searching- the only one that shows how to do it with an Activity vs. a ListActivity. Thanks again and happy.. whatever you celebrate in winter in Sri Lanka, from a grateful Canadian!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s