ListView using BaseAdapter – Android

The previous post, Create List Using ListView was about displaying an array of a list. It dealt with only one element in a list item. In order to display a List with multiple views in a list item, BaseAdapter could be used. A ListView using BaseAdapter could display a List with multiple views in it.

In this tutorial, we are going to create ListView using BaseAdapter. So, this tutorial covers following points.
– Create custom BaseAdapter, and
– Inflating a custom view as the list item.

Before proceeding with this tutorial, we would like to share one piece of advice. If it is a problem only a ListView can solve, then only use ListView. Android has provided a new component RecyclerView. It is similar to ListView implementation. But, have many modifications for memory management. In addition to that, RecyclerView also provides animations for transitions like addition, removal and update of the list item. For its implementation, we have provided a tutorial RecyclerView – Android.

Create Android Application Project

If you are new to Android Studio, then you could learn about creating new projects from our tutorial Create Android Application Project in Android Studio Continued.

Create Android application project with following attributes.

Project Name CustomListViewDemo
Package Name pcsalt.example.customlistviewdemo
Minimum SDK Version 16
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_name




Prepare layout screens

activity_main.xml: Layout for MainActivity.java. For this demo application, it would contain only a ListView.

layout_list_item.xml: Layout for list items to be displayed in ListView. In this list, each list item will display an ImageView and two TextView.

Create model class

ListData.java: This model class contains two String type values for Title and Description. imgResId is for displaying image in list items.

Inherit BaseAdapter and modify according to functionality

MyBaseAdapter.java: Create a custom BaseAdapter to inflate the ListView items with layout_list_item.xml layout.

Let us discuss this block of code

In this code, we are checking if convertView is already initialized or not. If not, then inflate the list item layout, create ViewHolder object and save it in a tag of convertView. If convertView is already initialized, then retrieve the instance of ViewHolder from the convertView tag.

This is required to reuse the memory, which was already instantiated for previous list item. If this is not done, then for each new item getting displayed in the list will instantiate its own memory. And, it may cause OutOfMemoryException.

Populate BaseAdapter with data

To populate data into BaseAdapter, we will pass a List of model class from MainActivity.java

Download Source:

Download source code from GitHub

Video tutorial:

About Krrishnaaaa

Socially known as Navkrishna.. An Android application developer. He likes to create tutorials and post them here or on YouTube or GitHub.. All these activities are shared on Facebook, Twitter, and G+ page.

One Pingback/Trackback

  • tvedaz

    That is brilliant! Thank you really much!
    But just one problem…
    How can I use that list view for my fragment swipe tabs ?
    Is that possible to get any help on this?

    • Jinni

      Same problem here…. How to implement in fragment with swipe tabs? Worked in activity but not in fragment swipe tabs.

  • Jolson

    thank you my friend. it really helped me.

  • heinousdog

    Thanks for the lesson!
    BTW, if you change getView() like this ,it would be much faster.

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    MyViewHolder mViewHolder;

    if(convertView == null) {
    convertView = inflater.inflate(R.layout.layout_list_item, null);
    mViewHolder = new MyViewHolder();
    convertView.setTag(mViewHolder);
    mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
    mViewHolder.tvDesc = detail(convertView, R.id.tvDesc, myList.get(position).getDescription());
    mViewHolder.ivIcon = detail(convertView, R.id.ivIcon, myList.get(position).getImgResId());
    } else {
    mViewHolder = (MyViewHolder) convertView.getTag();
    }

    return convertView;
    }

    • Hi heinousdog,

      Your suggestion may cause problem in larger list The list item may not get refreshed on scroll.

      ViewHolder is meant to store the reference(s) to the views inside list item. But, the content needs to be refreshed on scroll.

      Thanks,
      Krrishnaaaa

  • Joe

    Hi,

    Great tutorial and very helpful.

    Thank you

  • Siddhesh

    what you are doing here is creating object on every scroll in your detail method which is unnecessary and inefficient.

    basically your viewholder is of no use as you every time create a new object and assign it to viewholder elements.

    you can see it. you have created mViewHolder but never used after initialization.

    your code must look like
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    MyViewHolder mViewHolder = null;

    if(convertView == null) {
    convertView = inflater.inflate(R.layout.layout_list_item, parent,false);
    mViewHolder = new MyViewHolder();
    mViewHolder.tvTitle = (TextView)convertView.findViewById(resId);
    mViewHolder.tvDesc = (TextView)convertView.findViewById(resId);
    mViewHolder.ivIcon = (ImageView)convertView.findViewById(resId);
    convertView.setTag(mViewHolder);
    } else {
    mViewHolder = (MyViewHolder) convertView.getTag();
    }
    ListData ld = getItem(position);
    mViewHolder.tvTitle.setText(ld.getTitle());
    mViewHolder.tvDesc.setText(ld.getDescription());
    mViewHolder.ivIcon.setImageResource(ld.getImgResId());
    return convertView;
    }

    • Hi Siddhesh,

      Thank you for pointing that out. I have updated the code.

  • Farooq

    this syntax will not work
    ArrayList myList = new ArrayList();

    this should be
    ArrayList myList = new ArrayList();

    and this one
    for(int i=0;i<8;i++)

    should be
    for(int i=0;i < title.length;i++)

    • Hi Farooq,
      Thank you for suggesting the edit.

  • Unaiza

    Thank you so much for the example.

    Its a clean and easy approach.

    Helped me a lot.

    Thank you again 🙂

    • Happy to help. If you have any other query, drop a comment, we will try to get a tutorial for it.

      Thanks.

  • alendra

    How to put a custom section for that code ?
    would you mind to put another good tutorial about this listview with header listview ?
    Thanks

    • We would be creating a blog post for header list items. Meanwhile, we would like to know, if you would like tutorial for ListView or RecyclerView or both?

      Thank you

      • alendra

        Sorry for late reply, yes, i am wondering how to expand your method by adding custom header (consist of picture and text that are sourced by array), perhaps i can learn from your explanation
        thank a lot

    • Hi Alendra,

      I have uploaded a sample project on GitHub ListViewHeader. A blog for the same is in queue.

      Hope this would help you.

      • alendra

        thanks a lot, it is a good start for newbie like me, ok i will try to do some experiment on it to enhance my knowledge, have you any plan to add some sticky listview simple method in the future ?

        • Sorry, I took this long to reply.

          For Sticky Header ListView a lot of states needs to be maintained. There are many solutions available already for this problem. I would suggest you to try some of the open source solutions. Let me know in case you need help with those solutions.

    • Hi Alendra,

      I have published a blog post for Header ListView using BaseAdapter.

      • alendra

        Hi Krishnaaa,
        The link you provide was not redirected to your new blogpost, it link to this current page,
        is it already posted ?
        wow, i will learn from it.
        thanks

        • My bad.. Updated the link. Thank you for notifying.

  • ardya

    Hi,
    I have tried your listView header code,
    it was awesome, i able to expand it by inflating 3 views item into item.xml however while i add a searchview into it, i unable performing filter, would you mind to add the searchview into your listview header,
    Thank you

    • It is great that it worked for you. However, with SearchView filter will work. You just need to specify the data and section which needs to be in filtered list.

      I would try to provide a solution for SearchView in HeaderListView.

      • ardya

        wow,
        can’t wait for that actually.
        thank a lot

      • alendra

        Hi,
        how is it going ?,
        could not find your listview with searchview on post.
        Can’t wait for that.

  • Pingback: Header ListView using BaseAdapter - Android - PCSalt()

  • lakshman

    how can we implement Check box for this ListView..?

    • In order to implement CheckBox in ListView, you need to maintain the checked state of each CheckBox in their model class. And, in getView() set checked state based on position of list item and value in corresponding model class.

      I hope this will help. If not, then reply. I will try to put a blog post for this problem.

      Happy New Year 2016.

  • lakshman

    thank you sooooooooo much for this..
    this helps me a looooooot…..

  • subhash

    what is meaning for “baseadapter” in android.please provide extact defintion