Expandable list view is used to group list data by categories. It has the capability of expanding and collapsing the groups when user touches header.

If you are not aware of list view before please refer to this tutorial Android ListView Tutorial

Download Code
This image is for thumbnail purpose only
android expandable list view

Let’s start by creating a new project..

1. Create a new project in the Eclipse IDE from File โ‡’ Android Application Project and fill all required details. I left my main activity name as MainActivity.java

2. In order to create an expandable list view, we need three xml layout files. First one is for main listview, 2nd one for list view group item and 3rd one is for list view child item. Open your activity_main.xml and add ExpandableListView element.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#f4f4f4" >

            <ExpandableListView
                android:id="@+id/lvExp"
                android:layout_height="match_parent"
                android:layout_width="match_parent"/>   

</LinearLayout>

3. Create another xml layout for list view group header. I created an xml file named list_group.xml and pasted following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp" 
    android:background="#000000">


    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textSize="17dp"
        android:textColor="#f9f93d" />

</LinearLayout>

4.Create one more xml file named list_item.xml for child list item. This will contain simple TextView element.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="17dip"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

</LinearLayout>

5. I am using a custom adapter class to create list view. Create a new class file called ExpandableListAdapter.java and extend this from BaseExpandableListAdapter. This class provides required methods to render listview.

getGroupView() – Returns view for the list group header
getChildView() – Returns view for list child item

package info.androidhive.expandablelistview;

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

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class ExpandableListAdapter extends BaseExpandableListAdapter {

	private Context _context;
	private List<String> _listDataHeader; // header titles
	// child data in format of header title, child title
	private HashMap<String, List<String>> _listDataChild;

	public ExpandableListAdapter(Context context, List<String> listDataHeader,
			HashMap<String, List<String>> listChildData) {
		this._context = context;
		this._listDataHeader = listDataHeader;
		this._listDataChild = listChildData;
	}

	@Override
	public Object getChild(int groupPosition, int childPosititon) {
		return this._listDataChild.get(this._listDataHeader.get(groupPosition))
				.get(childPosititon);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public View getChildView(int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {

		final String childText = (String) getChild(groupPosition, childPosition);

		if (convertView == null) {
			LayoutInflater infalInflater = (LayoutInflater) this._context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infalInflater.inflate(R.layout.list_item, null);
		}

		TextView txtListChild = (TextView) convertView
				.findViewById(R.id.lblListItem);

		txtListChild.setText(childText);
		return convertView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return this._listDataChild.get(this._listDataHeader.get(groupPosition))
				.size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return this._listDataHeader.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return this._listDataHeader.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		String headerTitle = (String) getGroup(groupPosition);
		if (convertView == null) {
			LayoutInflater infalInflater = (LayoutInflater) this._context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infalInflater.inflate(R.layout.list_group, null);
		}

		TextView lblListHeader = (TextView) convertView
				.findViewById(R.id.lblListHeader);
		lblListHeader.setTypeface(null, Typeface.BOLD);
		lblListHeader.setText(headerTitle);

		return convertView;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}
}

6. Once you are done with customer adapter, open your MainActivity.java and do the following changes. In the following I created required data needed for list view and passed it to custom adapter.

package info.androidhive.expandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

public class MainActivity extends Activity {

	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
	List<String> listDataHeader;
	HashMap<String, List<String>> listDataChild;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// get the listview
		expListView = (ExpandableListView) findViewById(R.id.lvExp);

		// preparing list data
		prepareListData();

		listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

		// setting list adapter
		expListView.setAdapter(listAdapter);
	}

	/*
	 * Preparing the list data
	 */
	private void prepareListData() {
		listDataHeader = new ArrayList<String>();
		listDataChild = new HashMap<String, List<String>>();

		// Adding child data
		listDataHeader.add("Top 250");
		listDataHeader.add("Now Showing");
		listDataHeader.add("Coming Soon..");

		// Adding child data
		List<String> top250 = new ArrayList<String>();
		top250.add("The Shawshank Redemption");
		top250.add("The Godfather");
		top250.add("The Godfather: Part II");
		top250.add("Pulp Fiction");
		top250.add("The Good, the Bad and the Ugly");
		top250.add("The Dark Knight");
		top250.add("12 Angry Men");

		List<String> nowShowing = new ArrayList<String>();
		nowShowing.add("The Conjuring");
		nowShowing.add("Despicable Me 2");
		nowShowing.add("Turbo");
		nowShowing.add("Grown Ups 2");
		nowShowing.add("Red 2");
		nowShowing.add("The Wolverine");

		List<String> comingSoon = new ArrayList<String>();
		comingSoon.add("2 Guns");
		comingSoon.add("The Smurfs 2");
		comingSoon.add("The Spectacular Now");
		comingSoon.add("The Canyons");
		comingSoon.add("Europa Report");

		listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
		listDataChild.put(listDataHeader.get(1), nowShowing);
		listDataChild.put(listDataHeader.get(2), comingSoon);
	}
}

Run your project, you should see following output. (Note: The list view group indicators might change depending upon your android version)

android expandable list view

ListView child item click listener

Detecting the child item click can be done by implementing setOnChildClickListener listener on listview.

// Listview on child click listener
		expListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				Toast.makeText(
						getApplicationContext(),
						listDataHeader.get(groupPosition)
								+ " : "
								+ listDataChild.get(
										listDataHeader.get(groupPosition)).get(
										childPosition), Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		});

Listening when group is expanded

You may want to execute some lines of code when the listview group is expanded. For this you can use setOnGroupExpandListener which triggers an event when listview group expanded.

		// Listview Group expanded listener
		expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Expanded",
						Toast.LENGTH_SHORT).show();
			}
		});

Listening when group is collapsed

Implementing setOnGroupCollapseListener will trigger an event when listview group is collapsed.

		// Listview Group collasped listener
		expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

			@Override
			public void onGroupCollapse(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Collapsed",
						Toast.LENGTH_SHORT).show();

			}
		});

Complete Code

Here is the final code for MainActivity.java

package info.androidhive.expandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

public class MainActivity extends Activity {

	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
	List<String> listDataHeader;
	HashMap<String, List<String>> listDataChild;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// get the listview
		expListView = (ExpandableListView) findViewById(R.id.lvExp);

		// preparing list data
		prepareListData();

		listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

		// setting list adapter
		expListView.setAdapter(listAdapter);

		// Listview Group click listener
		expListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// Toast.makeText(getApplicationContext(),
				// "Group Clicked " + listDataHeader.get(groupPosition),
				// Toast.LENGTH_SHORT).show();
				return false;
			}
		});

		// Listview Group expanded listener
		expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Expanded",
						Toast.LENGTH_SHORT).show();
			}
		});

		// Listview Group collasped listener
		expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

			@Override
			public void onGroupCollapse(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Collapsed",
						Toast.LENGTH_SHORT).show();

			}
		});

		// Listview on child click listener
		expListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(
						getApplicationContext(),
						listDataHeader.get(groupPosition)
								+ " : "
								+ listDataChild.get(
										listDataHeader.get(groupPosition)).get(
										childPosition), Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		});
	}

	/*
	 * Preparing the list data
	 */
	private void prepareListData() {
		listDataHeader = new ArrayList<String>();
		listDataChild = new HashMap<String, List<String>>();

		// Adding child data
		listDataHeader.add("Top 250");
		listDataHeader.add("Now Showing");
		listDataHeader.add("Coming Soon..");

		// Adding child data
		List<String> top250 = new ArrayList<String>();
		top250.add("The Shawshank Redemption");
		top250.add("The Godfather");
		top250.add("The Godfather: Part II");
		top250.add("Pulp Fiction");
		top250.add("The Good, the Bad and the Ugly");
		top250.add("The Dark Knight");
		top250.add("12 Angry Men");

		List<String> nowShowing = new ArrayList<String>();
		nowShowing.add("The Conjuring");
		nowShowing.add("Despicable Me 2");
		nowShowing.add("Turbo");
		nowShowing.add("Grown Ups 2");
		nowShowing.add("Red 2");
		nowShowing.add("The Wolverine");

		List<String> comingSoon = new ArrayList<String>();
		comingSoon.add("2 Guns");
		comingSoon.add("The Smurfs 2");
		comingSoon.add("The Spectacular Now");
		comingSoon.add("The Canyons");
		comingSoon.add("Europa Report");

		listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
		listDataChild.put(listDataHeader.get(1), nowShowing);
		listDataChild.put(listDataHeader.get(2), comingSoon);
	}
}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • baha_odeh

    first comment , thank you

    • Third comment ….. you are welcome ๐Ÿ™‚

      • Siddhu Vydyabhushana

        forever comment @ravi8x:disqus is great great great …

  • Balakrishnan

    HI Ravi..i understood this example..How can i add Edittext an Button in childview?

    • You can add them in list_item.xml file

      • Lorenzo Volponi

        yes but..when in the adapter i set the listener it wont listen!!! you know why?

  • Filipe Tagliacozzi

    Ravi… excellent work… Anyone can make great apps relying on codes presented here. Through people like you we will be increasing the overall quality of android apps. I particularly have a easier learning when altering ready codes and making changes to see the behavior .. Congratulations…. I will click all the sponsors that I can.

    • Thank you Filipe for your support ๐Ÿ™‚

  • saladi krishna chaitanya

    Hi ravi u r doing a great job. Its very helpful for every one start doing their apps.
    Try to update daily one concept even it is small also no problem.It will also be helpful for someone..Keep doing.

  • LloydBlv

    Thanks,But how to anmiate expand and collapse?

    • ‘e’

      Any way to animate expanding the list items?

  • Excellent explanation, thanks ๐Ÿ˜‰

  • james

    Thank you for the tutorail, God bless you

  • Ines Belhouchet

    Parfait :))))

  • Ramiz Mohamed

    As good as always, well done.

  • Ayush

    Hey can u add the code to “auto close the all previous opened list and only opens the currently expandable list “??

  • vignes

    wow.. wow wow.. what an excellent tutorial..

  • Chinthaka Devinda

    Great Work Ravi this is really helpful thanks ๐Ÿ™‚

  • Katia Zanotti

    Hi, your tutorial is great!

    but when I run the project it doesn’t show the indicators.
    If I try to click the header this action generate the following error:

    Unexpected error while launching logcat. Try reselecting the device.] device not found
    com.android.ddmlib.AdbCommandRejectedException: device not found
    at com.android.ddmlib.AdbHelper.setDevice(AdbHelper.java:752)
    at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:373)
    at com.android.ddmlib.Device.executeShellCommand(Device.java:462)
    at com.android.ddmuilib.logcat.LogCatReceiver$1.run(LogCatReceiver.java:109)
    at java.lang.Thread.run(Thread.java:724)

    any help?
    Thanks

    • Ben

      Seems like your device is not detected by your Operating system,try to install appropriate device drivers first

  • Nishu

    Sir ! i wana get record from data base ,how can i?

  • how to start new activity in child data using expandablelist.?

  • Beatriz Hernรกndez

    Dear Ravi,

    My name is Beatriz Hernรกndez and I get in touch
    with you because we are developing an advertising campaign which we would like
    to count on you.

    If you are interested , please write me
    back and I will tell you more about the project.

    Best regards,

    Beatriz

  • Kunwar Abhishek

    Hey Ravi
    I want to add an element in expandable list
    as we do in listview by using adapter.addall(arraylist)
    how to perform this in Expandable list view

  • Cรดng Bรฌnh Trแบงn

    thank you!

  • Sk Ahmed Hossain

    awesome awesome awesome……………………

  • Fernando

    Excellent tutorial! Is just what I was looking for, I want to modify a bit your listview, I pretend to put some buttons in the listview or set an onclick event, Could you help me with that? I need to develop a menu for a restaurant and it’s necessary for me that the program counts the clicks on each product. I hope you can help me with this task .

  • akhil nair

    Hey Ravi good tutorial i want to know how to create ExpandableListView with image and text else a coustom ExpandableListView

    Thank You

  • Andy

    how to set onClickListener(intent) for any particular child option

  • rahul

    nice tutorial..please keep it up…

  • Angel

    Hi!

    First, thank you for a very great tutorial. As a beginner in Android, you have been a great help to me.

    I am currently trying to make your program into a dynamic expandable listview with data coming from a remote server accessed through PHP and JSON (using your other tutorial as reference). However, I’m having problems trying to save the data on the listDataHeader and listDataChild. Could you please share some tips on how to resolve it?

    Thanks again and more power!

  • Joseph

    hi, what if I there is a add button? do you have source code for this? thanks a lot! ๐Ÿ™‚

  • sravani

    hi nice blog spot , how to implent Expandable List view up to Four levels

  • Daan Dawud

    Fantastic dude! Im going to attempt to use this with the Navigation drawer. Hopefully it shouldn’t be too bad.

  • Mike

    Ravi => Android Sensei !!!

  • Der ร„รคl

    1st thing: great work, thank you so much!
    2nd thing: i tried to put a 2nd textview into my childrow.xml but it doesn’t work. i think i’ve made a mistake in the getChildView or in prepareListData… can you (or maybe anybody else) please help me?
    would be great!
    thank you

  • MrBoomBostic

    “No Empty Constructor” ???

  • Helmer Plaza

    Hi..how do i apply this on a fragment?? where do i put it?on the onCreate or onActivityCreated?

  • mike20122012

    Awesome tutorial..:)..This really helps a lot.
    How can I implements this when using fragments? Help would be really appreciated..:)

  • Ashish

    Very useful article but there is one problem in each article. Problem is that the width of code box is very less so we have to scroll horizontally again and again. so please make it wider if possible

  • systemz

    The best tutorial !!
    When i scroll the list item i have a white background. To fix it add the following attribute android:cacheColorHint=”#00000000″ in the xml file : activity_main.xml in ExpandableListView view

  • Lisa

    How can you add a third level to this? All of the other examples use a completely different form.. this is the best one, but need to add a 3rd level

  • Jean Hewetson

    hardcoded values into expandablelistview. I want to know how do you get generic database values into it?

  • sasa

    I stuck badly in my code to implement ExpandableListView and your code can help me A LOT,but when I try your code it gives me an error in this part:
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    which the error is “Cannot instantiate the type ExpandableListAdapter”
    could you please help me to solve it?
    Thanks a lot

    • Naganji Polam

      same error i’m also getting now.

      • Furkan Kurt

        Yes, same error i’m also getting now. But, I don’t find it ๐Ÿ™

        • Furkan Kurt

          Hey, I find it ๐Ÿ™‚ you make a class by “ExpandableListAdapter” name.
          This class is adapter class ๐Ÿ™‚

    • GokulakrishnanM

      Change the class name
      “ExpandableListAdapter” to some other. Android have interface class in this name…

  • Naganji Polam

    Hi, The best tutorial.

    I like your tutorials.

    I’ve a small doubt, you actually used same image for all list items. But, how to add diff images for list items.

    And one more is , can you implement some non expandable list items and some expandable list items like this

    http://i.stack.imgur.com/vilHb.png

    Thanks,

    Siva

  • Naganji Polam

    Hi Sasa,

    I also get the same error, but finally solved.

    Just change that a line as

    listAdapter = new packageName.ExpandableListAdapter(this, listDataHeader, listDataChild);

    instead of listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Thanks,
    Siva

  • needhelp

    Hi,

    Nice tutorial thankyou but how do i add a second textview to the childview.I mean adding it is easy (you just have to edit the XML) but i don’t understand how to set the adapter to make text appaer in the second textview.

    • systemz

      I want a second childview too and a textview in every group please…

  • amala ray

    Hey nice tutorial, can you tell me how to add empty views as children of every listview element. So that when i click on an item which does not have children, the application does not crash.

  • Abdullah

    Thank a lot for this codes, works perfectly, it was soooo helpful for me, I was desperately looking for codes, thanks again. ๐Ÿ™‚

  • Senjo

    Thanks a lot.

  • ALB

    Thanks for this super helpful tutorial!! For those asking about putting in a fragment, I managed to get that working, so thought I would share: (1) fragment extends ListFragment, (2) create a new layout for the fragment with same code as described above for activity_main.xml except change to “android:id=@android:id/list” and inflate this layout in onCreateView in the fragment (3) put this in onActivityCreated:

    expListView = (ExpandableListView) getListView();
    prepareListData();
    adapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
    expListView.setAdapter(adapter);

    • an

      Thanks so much, you are a lifesaver!

      • Guest

        I dont understand what number 3 is, where is it being added exactly? in OnCreate of the Activity that the frag is being created from?

  • Riadh Karchoud

    How can i take off the arrow on the left (the one that indicates if the list is expanded or not ) .. i created my own arrow on the right that’s why i wanna take off the one on the left !!

  • Shubham Singh

    is it possible to collapse items other than the clicked one

    • Rishil

      Do you want to expand and collapse all the items at once ?

      • Shubham Singh

        nope to collapse other groups when a group is clicked. ie expand the clicked and collapse the others.

        • Rishil

          Hello Shubham,

          Try this code. It worked for me.

          private int lastExpandedPosition = -1;
          private ExpandableListView lv; //your expandable listview

          lv.setOnGroupExpandListener(new OnGroupExpandListener() {

          @Override
          public void onGroupExpand(int groupPosition) {
          if (lastExpandedPosition != -1
          && groupPosition != lastExpandedPosition) {
          lv.collapseGroup(lastExpandedPosition);
          }
          lastExpandedPosition = groupPosition;
          }
          });

          • Shubham Singh

            thanks mate it worked well

          • Rishil

            Your welcome buddy…

            But there is one problem when changing the orientation.
            Follow this step to reproduce it :
            keep one tab expanded. Now change the orientation of your phone.
            Now try to expand another tab. So it won’t collapse the previously selected tab and. So at a time 2 tabs will be expanded….lol

  • Rishil

    @ravi8x:disqus : How can i implement Search filter Functionality to Expandable listview. ?

    • MRK

      Hi Rishil,
      Do you implement filter ?

  • ะ—ะฐะผะธั€ะฐ ะะพั€ะพะฒะฐ

    Guys, i have a problem on lines

    drawerListView = (ExpandableListView) findViewById(R.id.left_drawer);
    listAdapter = ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
    drawerListView.setAdapter(listAdapter);

    error is “The method setAdapter(ListAdapter) in the type ListView is not applicable for the arguments (ExpandableListAdapter)”. What i’m doing wrong?

    • systemz

      “New” is missing after “listAdapter =”

  • Richard

    Ok so after taking a good look on this one I was wondering if we could integrate this project on the Drawer navigation. Like for example; we have five default items on the drawer navigation and below that are set of expandable items. Hey Ravi is that possible to integrate this in a Drawer Navigation? I mean both of them are list views right?

  • Ivelfan

    Awesome article !

    Many thanks !

  • Harish

    Hi
    I want to do expandable listview like tree view..
    It is possible to do?

  • prabhakaran

    very nice tutorial………. but i want, if suppose open a group once at a time, other groups are collapse

  • Tharaka Nirmana

    Thanks a lot, great tutorial. After 2 days of research this tutorial helped me to get what I want finally. Thank you!

  • Sohail Zahid

    Again Thanks A lot Ravi………..

  • Nadir Ali

    brilliant code to help me, and solve the problem

  • Developer

    How do i insert a radio button in the child item of the list view?

  • Guest

    Hi Ravi, Thanks for this, how can I put subtitle in the parent header?

  • Aj

    Hi Ravi, Thanks for this, how can I put subtitle in the parent header?

  • Illuminate

    how would i open the list item up in a fragment, or another window, where it would display images and possibly a write up

  • JP

    Great tutorial..How could you add checkboxes to the children?

  • Luis Alberto Romero Calderon

    Awesome tutorial. very clear. Thanks

  • Pradeep

    This is great…. Very clear and usefull items, Thanks much for doing this….

  • silver

    I have tried to use a EditText inside ExpandableListView but after adding this Group is not expanding on click. Anyone has any idea about this?

  • Gold

    $(“article”).css(“width”,”1000px”);
    Run this in the browser’s dev tools to expand the article’s width. Easier to read code this way.

  • Vick

    Trying to hide and embed the database primary key behind the values that are being used to populate the children data. Want to create and Edit item page similar to how you did on list view. How do I store and send that?

    • Vick

      Answered my own question. Do it all in your getChildView

      @Override

      public View getChildView(int groupPosition, final int childPosition,

      boolean isLastChild, View convertView, ViewGroup parent) {

      final String childText = (String) getChild(groupPosition, childPosition);

      if (convertView == null) {

      LayoutInflater infalInflater = (LayoutInflater) this._context

      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      convertView = infalInflater.inflate(R.layout.list_item, null);

      }

      String SubChildText = childText.substring(childText.lastIndexOf(“—“) + 3);

      String SubChildTextID = childText.substring(0,childText.lastIndexOf(“—“));

      TextView txtListChild = (TextView) convertView

      .findViewById(R.id.lblListItem);

      TextView txtListChildID = (TextView) convertView

      .findViewById(R.id.pid);

      txtListChild.setText(SubChildText);

      txtListChildID.setText(SubChildTextID);

      return convertView;

      }

  • Kiba

    if i want to display a JSONArray, what would be the code?

    • Kiba

      i’m starting to code on android

      • Peter Mageto

        Hi Kiba…did u manage to post using JSONArray? please assist

  • Siavash

    hi,ihave a problem with id : “id cannt be resolved or is not a field “

  • sravan

    thanks it was nice post , helped me a lot ๐Ÿ™‚

  • Hi I have a problem
    When I open a new page when I click on a child, not a tost

  • izzy

    i click on a child and dont get a toast, anyone knows why?

    • Brandon

      You need to put the code blocks:

      // Listview on child click listener
      expListView.setOnChildClickListener(new OnChildClickListener() { … }

      WITHIN the “onCreate(…)” method. Then they will run properly (import the proper functions that eclipse says or do a Ctrl+shift+O and it will import the necessary files.

      But put those 3 listener methods with the toasts functions in the onCreate function.

  • Peter Mageto

    Ravi, Guys…please assist. I need to use JSON approach to fetch my parent and child nodes. Please assist…

    • Coder

      Hi, had you solve this problem please ?? i need it . Please assist

  • Brad

    Another great tutorial. Thanks!

  • Brandon

    I just want you to know, that after hours of looking for a tutorial on how to do this.. I finally navigated back to you, my default android tutorial man… and my god. Your code is beautiful, it’s explanations are great and its easy to follow. THANK YOU SIR.

  • amit

    Nice Tutorial Thanx

  • Suare

    Nive Tutorial man! I implemented it with Fragments

  • Lisa

    You are a good writer. Clear and straight to the point tutorials. You should compile all your work into a book. Be blessed.

  • Fedro

    Thanks for this. You are a good programmer and an excellent teacher. Your tutorials are very clean and easy to understand.
    Has anyone an example of how to implement ExplandableListview retrieving data from a JSON array?
    I suppose that it will be useful if update this example explaining how to work with dynamic data.

  • JJ

    Hi, can I do multiline textview for children?
    Thanks

  • Hung Tran

    i don’t see icon of expand listview?

  • anusha

    can u tell me how to make auto close of one list when other one is clicked…..

  • Juwar74

    Can you extend this article to include moving to another screen when one of the children are clicked. I’m not sure how that works actually. I would need it to move to another screen

  • Hardik Trivedi

    Thanks a ton.. It helped me a lot!!

  • Kalu Khan Luhar

    Thanks Ravi , your tutorials helped me a lot. One question is that how to expend/collapse list with smooth animation.

  • Krits

    Hello and thanks for the nice tutorial! I am using this layout for a project and I am experiencing a problem! I have managed to change the background colour of each parent(and child) to transparent but when I click on the parent(or the child) I am getting that yellowish colour(only during the click) which doesn’t match the blue theme of my app. I’ve searched everywhere and cannot find how to change it to transparent as well. Any help would be much appreciated!

  • Wasim Amin

    @Krits: use this in your listview
    android:cacheColorHint=”@android:color/transparent”

  • Vladimir Topalovic

    hi Ravi. I am looking to learn how to use expanable list, for some time and this exampe is the best one, that i can find on net. Can you please help me?

    for a week i am trying to animate expand and colapse for Expandable list and i done all exept for moment when auto-scroling is activated. when i expand list on bottom off screen, list auto-scroll on bottom of group and it totaly mess my animation. how can i stop that auto-scroll. I alredy tryed android:transcriptMode and setTranscriptMode(0). Please help me i do not have any other way of reseach it more.

  • Sino

    how can i set images to parents and childs?

    • Guest

      To add images to either parents or children or both you would have to add an ImageView into their respective xml layout files – list_group.xml for parents, list_item.xml for children.
      Here don’t forget to use margins to place the image where you need it.
      You can also place a drawable in the xml thus making all your items have the same images. Alternatively, you could assign image resources to each through code, which might add a little more flavour to your project, but is more involving.
      Good Luck!

  • Jake

    how to parse names from json file to expandable list? thanks.

  • saravanan

    How to give scroll to group items instead of whole exapndable listview

  • Anon

    I keep getting, “ExpandableListAdapter” is abstract can’t be instantiated. On this line, “listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);” Any solutions?

    • Sam Soo

      How do you declare your Adapter class? i declare my as below

      public class MenuExpandableAdapter extends BaseExpandableListAdapter {

      Notice its, BaseExpandableListAdapter

    • Shuvo Joseph

      Your Fragment is importing android.widget.ExpandableListAdapter, Remove that.
      First create the class ExpandableListAdapter then Write
      ExpandableListAdapter listAdapter;
      listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
      May be Class ExpandableListAdapter is clashing with interface android.widget.ExpandableListAdapter or change the name of the class ExpandableListAdapter to something else.

  • nishant

    #Help

    Hello friends , can any one tell me how to add expandable list view in existing fragment(As in case of Navigation drawer I’ve fragment class ).Do I need to create new activity or can I add the above MainActivity code to
    the existing fragment class.

    • Aleksandar Petrovic

      Incorporating this into your project will not be as straight forwards as simply pasting the code into your fragment.
      You need to create the class, per Ravi’s example. Once you have the class made, you can then add the listeners from his MainActivity into your fragment. Do note because Ravi extends an activity and not a fragment there will be some minor changes that you will have to handle. This is not hard and the errors should clue you in as to what changes have to be made.
      (Hint: in the listadapter line instead of ‘this’ you will most likely need to replace it with ‘getActivity()’) or something to that effect.

  • Aleksandar Petrovic

    Thank you for this wonderful project! It works like a charm!
    I added a bit I found that I wanna share:
    public void onGroupExpand(int groupPosition) {
    int len = listAdapter.getGroupCount();

    for (int i = 0; i < len; i++) {
    if (i != groupPosition) {
    expListView.collapseGroup(i);
    }
    it will allow for one group to collapse as another is clicked to expand!
    Sweet functionality!

  • Hanu

    I want to declare two dates like start date and end date in one list view,how to declare?

    • Sam Soo

      put 2 TextView in your Item Layout and name them like tvStartDate and tvEndDate,

      in Adapter, get them with

      TextView tvStartDate = (TextView)convertView.findViewById(R.Id.tvStartDate);

      TextView tvEndDate = (TextView)convertView.findViewById(R.Id.tvEndDate);

  • ahtsham

    i want a button in group_item.xml class.listview should expand when i press the button not by clicking the listrow.i added my button in xml but dont know how to set clicklistener.kindly help me by writing code…..

  • Prasanna Kumar

    Thanks buddy…it helped me alot..

  • Alex Monari

    Awesome .. super helpful !!!!!

  • Clay Martin

    Great job. Very helpful to get my exandablelistview up and running.

  • Alireza saemi

    thanks man , ๐Ÿ™‚
    do u think we can have exandable list inside navigation drawer ?

    • Edu App

      yep surely.

      • Alireza saemi

        Can u do us great favour and learn us how to do it ? Sry if im asking alot .

  • wade

    thanks

  • Abdoul Doulab

    hi! ravi thanks for this… i want add a checkbox on Group and child and when i select checkbox Group all the checkbox child will be selected… Thans again…

  • fuck me too

    I love Android HIVE. Helped me many times! Keep on this good work.

  • Sudheesh Mohan

    Hey if therre are 10 headings, do we need to create 10 arraylists? Is there any way to avoid this?

  • Ferry Fernandez

    Hi Ravi,
    1. i add CheckedTextView, to childlistitem. how to make it checked onchildclick?
    2. i need to change the header group label when onchildclick?

    can anyone tell me how to do ?

  • Mahmoud Badr

    ุงู†ุช ุฌุงู…ุฏ ูุดุฎ ๐Ÿ˜€

  • hackerGK

    It working nice ๐Ÿ™‚ thanks

  • Jonathan

    It doesn’t work for me, I have a trouble in this line

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Exactly in ExpandableListAdapter, it says it cannot be instantiate.

    • Jonathan

      I’ve already read the comments and I found the solution, now it works good!!

      Thank you so much!!

      • Riddhi Patel

        if you got solution thn pls kindly inform me bcs i also get same trouble in

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

  • SparkleIshan

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Error:(35, 23) error: ExpandableListAdapter is abstract; cannot be instantiated

  • Siva Bala

    Hi thanks for ur code. I need to navigate to another page when child item is clicked. Can any one help me plz??

    • Guest

      Same question . Please if you found a solution let me know and vice versa if a found a solution i will tell you .

    • mohamed

      // Listview on child click listener
      expListView.setOnChildClickListener(new OnChildClickListener() {

      @Override
      public boolean onChildClick(ExpandableListView parent, View v,
      int groupPosition, int childPosition, long id) {
      /*
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition)
      + ” : “+ listDataChild.get(listDataHeader.get(groupPosition))
      .get(childPosition), Toast.LENGTH_SHORT).show();
      */
      switch (childPosition) {

      case 0:
      mycostumeactivity();

      break;
      case 1 :

      Intent a = new Intent(getApplicationContext(), AboutActivity.class);
      startActivity(a);
      break;

      case 2 :

      break;
      case 3 :

      break;
      case 5 :

      break;

      }

      return false;

      }
      });
      }

      • Siva Bala

        Thanks a lot #Mohamed

      • nasznjoka

        what if i dont know the number of child items how select them dynamically without using switch

        • mohamed

          Sorry for late reply but hope this will help you

          Use something like that

          // Listview on child click listener
          expListView.setOnChildClickListener(new OnChildClickListener() { @Override
          public boolean onChildClick(ExpandableListView parent, View v,
          int groupPosition, int childPosition, long id) {
          switch (groupPosition) { // Expandable parent 1
          case 0:
          Intent i = new Intent(this, LastActivity.class);
          i.putExtra(“position”, childPosition);
          startActivity(i);
          break
          case 1:

          break

          }

          In LastActivity.java
          Get extra and go

          • nasznjoka

            thanks but i already finished that project and I decided to activate onlick on an entire row but i got a new project which i think such functionality is required(clicking on list item child views) I’ll check on it thanks

          • MRK

            Hi Mohamed,

            In LastActivity.java with getExtra() its work fine

            BUT

            I want to show child name clicked in a textView dynamically

            And something is wrong !

            I can`t get(id) return NULL

            see my code in below :

            id = getIntent().getLongExtra(“id”, 0);
            HashMap<string, list> map = new HashMap<string, list>(MainActivity.categoryName);
            TextView title = (TextView) findViewById(R.id.articleListHeaderTextView);
            for(Entry<string, list> entry : map.entrySet()){
            map.get(id);
            title.setText(entry.getValue().toString());
            }

            Please Help me, Thanks.

          • Marco De Roni

            Is this what you are thinking of ?
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            switch (groupPosition) { // Expandable parent 1
            case 0:
            Intent i = new Intent(this, LastActivity.class);
            i.putExtra(“position”, childPosition);
            startActivity(i);
            break;
            case 1:

            break;

            }
            }
            });

            If yes, it turns out wrong to me ๐Ÿ™

  • R

    how do i customise the listview? i want to change the colour and background of the listdataheader

  • Eduardo

    the list indicator are not displayed in api 10. How do I solve it?

  • Luzi

    Hey ! Thanks a lot for this example ! I used it for my application and it works fine ๐Ÿ™‚

    But (there is alway a but ๐Ÿ˜€ ), I would like to implement a filter only on the Header Datas, but I don’t know how. I tried different code founded on the web, and adapted it to my code, but it didn’t work.

    Can you help me, please ?

    Thx, Nico ๐Ÿ™‚

    • MRK

      Hi Luzi,
      Do you have any solutions for this ?
      I have same problem and don`t find useful issue in internet.
      So I want to implement filter for child data
      Can you help me ?
      Tnx ๐Ÿ™‚

  • arun

    Nice Example.. Thanku.. I need show some items (for example 2) on collapse instead hiding all items. What to do?

  • yash sharma

    Its not Working for me the logcat says “Your Content must have listView”

  • J Bala Prakash

    how to use expandable view in sqliet db help me…..

  • Vijayadhas

    Hai.. Is there any example for sliding menu with expandable view??

  • rahul

    how can i do same thing when click on slidenavigation menu after that i want to see expandable view

  • Bharath Reddy

    Excellent.thanks

  • manvi gautam

    heyyyy .. i wannna use multi line text how can i use in this …
    GA-KHYIL HOUSE

    2-3Fl.House No.39, Block-12 , New Camp, New Aruna Nagar, Majnu Ka tila, Delhi-110054, India

    Tel: 0091-11238-111-47

    Fax: 0091-11-238-111-49
    how to use this under a single header….
    plzz rply asap …..
    thankssss a lot in advance

  • ancy

    hi wan know is that possible to expand child data ?

  • Sivan Kumar

    Thanks … Good Work

  • Salman Mohammed

    Is it possible to add children strings from (R.string) or Arrays(R.array) in order to support other languages, instead of using (” “)?

  • Vฤƒn Lรฝ Vลฉ

    Thanks for this post, it’s very helpful. I did it and it worked. But i want to extend a little bit. That i want to add a footerView to childView. Now what i do is:
    1. I create a layout file name footer_view.xml
    2. Then for each parent item, i add one more element to listChild.
    3. In getChildView method, i check
    if (childPosition == getChildrenCount(groupPosition) – 1){

    //render footerView here
    }else{
    //render normal child item
    }

    But seem it doesn’t work. When i click the parent first time, it works, but the second time it show error: NullPointerException.
    Did i do anything wrong?
    Thanks for your time.

  • ati’atul maula

    It’s good tutorial. I have trouble to make arrow icon on ExpandableListview, I have used android:groupIndicator but the image result is too large. Can you tell me how to set height and width it?

    Thanks for your time.

  • vahid

    One of the best tutorials ever

  • Ancy Murikupudi

    can we do multi-layered expandablelistview with Json response array data.?

  • Steve

    Why are you mixing fill and match_parent that often?

  • jayant rawat

    What to do if data is coming through json please suggest me

  • Ion Popescu

    I followed the “How to connect Android with PHP, MySQL” tutorial. I successfully populated a database with some test values. Now I need to make a list like this above, with “name” as List header, and ‘price” and “description” as Child, (to appear when I touch the “name” and list is expanded). I preserved tags from the other tutorial, so it will be more clear what i want to achieve. I am a very beginner at android, so I have no idea how to fetch those data, and populate the list with all the names, prices, etc. Can someone help me? ๐Ÿ™‚

  • Animis

    how do I add a LongClick listener to the Group and CHildren? I want to be able to add items to the list by long clicking on the group and then typing something in

  • Aayushi

    hey hi ,Android hive is a great site.Hats off to writer.
    I made the expandable list view acc to your tutorial but what i have to do if I want to populate Expandable List View with values from database?Means what changes I have to do in MainActivity.java add() .Will be of great help.Waiting for your reply

  • Mike

    @Override
    public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
    .size();
    }

    How does this work? Doesn’t get() take in an int?

  • Prajwal

    How to add onClick to items inside the row.
    for eg TextView and Button in inside RelativeLayout

    • Lily

      you can add onclick listener inside getchildview method

  • Gilgw

    I just tried this tutorial with Android Studio 1.1. RC1 but running the application throws me the following error:
    java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
    Any idea why?

  • Shuvo Joseph

    Attempt to invoke virtual method
    ‘void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)’ on a null object reference at
    com.XXX.YYY.ZZZ.NavigationDrawerFragment.onCreate(NavigationDrawerFragment.java:159)
    Which is
    expListView.setAdapter(listAdapter); // line 159
    where expListView is ExpandableListView and listAdapter is ExpandableListAdapter.
    //listAdapter initialize
    listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
    This is written in NavigationDrawerFragment which extends Fragment.

    • Shuvo Joseph

      Solved it. Thanks for the tutorial ๐Ÿ™‚

      • aman mehta

        how?? i am facing the same issue

  • mortenslotthansen

    Consider moving inflator instantiation to constructor and then use parent as 2 argument when calling inflate ie.

    convertView = this.infalInflater.inflate(R.layout.list_item, parent, false);

    • Marco De Roni

      Hi, what if I wanted to implement the inflate method in the onChildClick?

  • Benny

    have problem copy&pasting onto Android Studio. Use this command line perl -pe ‘s/xC2xA0/ /g’ infile > outfile

  • MuerteAlosP3n3s

    Nice job. Thanks you for your tutorial.

  • Thank you!

  • srujan

    so much of thanks to you ..

  • ghiles64

    thank you great job

  • Karthikeyan V

    Is it mandatory that the both child and parent/header list should be equal in size ?

    • Mike Michaels

      Do you mean text size? No. modify list_group.xml, add some sample text, this text gets replaced in the code but you can use the preview panel to see you changes.
      android:text=”Test Group”
      android:textSize=”40sp”

  • Mrinal

    This is awesome! Just wanted to know how to make it scrollable when my screen has few linear layout along with one explandable list view.

    • Mike Michaels

      android:smoothScrollbar=”true”
      in the activity_main.xml under ExpandableListView

  • Abdullah

    Hi ravi , i want to know if i have second text view in the child, how can insert data to that, how can i customize the adapter

  • Dheeraj Bansal

    I want to make slide menu with expandable list like as flip cart app slide menu.Please guide me.

  • Ajinkya

    Can you please tell something about the Check boxes in Expandable List View and how to give functionality to them means how to get the checked states of those check boxes and use their values. This is only doubt i am facing ๐Ÿ™ ….

  • Kenny

    Hi All,

    I am going through this tutorial, and everything is working fine, However i am stuck at the following:

    I want to pull my listview items from a JSON feed as in Ravi’s tutorial “android-json-parsing-tutorial” where i would like the heading as the Persons name and on expand the persons info.

    I really don’t know how to change from a typed array to a dynamic array, any pointers will be appreciated

    Kenny

  • MRK

    Beautiful code !

    Hi Guys ,
    Can any help about ” Implement Filterable on Child ” for this code ?
    Thanks a lot .

  • usarrr

    why cannot resolse symbol ‘R’ ?

    Please Help Me.. :'(

    • Jose Pablo MB

      Usually this happens when there’s an error in any of your XML files. Try looking for an error in any of your XML files, to check if there’s an error
      Hope this helps!

    • GregKorman

      Other possible solutions include cleaning and then rebuilding your project. Also, try restarting your IDE. Sometimes it can be caused by files getting out of sync with the IDE.

    • Erich M.

      USARR, make sure your project or package path is correct. That is where the problem is. Try re-importing the class paths by right-clicking on the “R” code that is give the error and clicking “import”. This should fix the problem.

    • Kishor Ramani

      go to project->clean..

      and see the result.
      may be it will help.

  • Niso

    I am trying to get the Child’s position, how can I get it?

    • Jose Pablo MB

      You have to set the onChildClick listener for the ExpandableList. The attribute called “childPosition” is the one you’re looking for.
      Hope this helps!

  • Omega

    Friends plz help
    * i build restaurant app
    * i have 1 text editor and 1 button
    * text editor 4 postal code
    * when user enter postal code nearest restaurant show my app
    * i want to help database connectivity

    • Kishor Ramani

      for this you have to use auto complete text view rather than edit text.
      when customer start enter your postal code he/she see some list of postal code.

      and on button click event
      you have to match this postal code with your database and retrieve list of restaurant which is in this area.

  • prasanna

    Excellent.. Nice

  • The Pen is Therapist

    So, I want to click on what you have as movie titles and have it go to text. Something like:

    Title
    Name1
    Name2
    Phone 1: 555-555-5555
    Phone 2: 555-555-5555

  • amit sharma

    Thanks for the post, this is very nice. But what i have to do if I want to add custom list_item like textview with image.
    Please Help me regarding this, thanks in advance

    • Josh F

      To add an image to your groups, in the list_group.xml file just add the layout that you want that cell to be. In your case you could just add an ImageView next to the TextView. Then, in the getGroupView method add whatever image you like to the ImageView you just added to the xml. Do it the exact same way for adding images to the child views except you will edit the list_item.xml and the getChildView method instead.

      • jerofad

        Hello Josh. How can I add different images to the child views. Since I have more than one list item and they are to have different images. please help me out. Thanks

  • Berni

    Hallo, I have one question:

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    For this code line I got the following error:
    ExpandableListView is abstract; cannot be instantiated

    How can I solve that? Thank you for any help!

    • Patrick Messina

      It’s ExpandableListAdapter, not ExpandableListView

  • vijay maddhesiya

    hello i have aproblem

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    error anyone two solve it please

    • Ravishankar Yadav

      replace this with mainactivity(current_class_name).this

  • arpit

    please anyone guide me how to apply the json in expandable view..

  • Azizi Musa

    Hi, great tutorial. I would like to implement an animation of expanding and collapsing. How can I achieve that?

  • Luciano Candiani

    Thanks for your great tutorial.

  • Joehamir Balabadan

    hi,

    Thanks for this tutorial this is very simple and nice..
    just want to know why im getting error when i remove the child in one of the group..

    because i want to do thing like this

    Home
    Category
    category 1
    category 2
    category 3
    About

    please help me..
    email me at joehamir_balabadan@yahoo.com

  • Ravishankar Yadav

    hello,ravi..my listgroup is not expanding items…y?

    • bigfire

      make the size wrap_content or (whatever )dp

  • MikeCoding

    getting a null error exception from java.

    java.lang.RuntimeException: Unable to start activity ComponentInfo{mikecoding.nl.mynewcleanapp/mikecoding.nl.mynewcleanapp.MainActivity}: java.lang.NullPointerException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)

    at android.app.ActivityThread.access$900(ActivityThread.java:172)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:146)

    at android.app.ActivityThread.main(ActivityThread.java:5694)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: java.lang.NullPointerException

    at mikecoding.nl.mynewcleanapp.MainActivity.onCreate(MainActivity.java:51)

    at android.app.Activity.performCreate(Activity.java:5541)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)

    at android.app.ActivityThread.access$900(ActivityThread.java:172)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:146)

    at android.app.ActivityThread.main(ActivityThread.java:5694)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)

    at dalvik.system.NativeStart.main(Native Method)

  • Anand

    I want to add one more level can you describe me how can this possible

  • Ullas Ms

    Hi .how to implement onclick lIstner on listAdapter.My data is coming from squlite I want show half the data in first activity and reamining in second activty using onclick lIstner in list adapter

  • Marco De Roni

    Hi, fine and smooth. What if I wanted to inflate a layout once a child is selected?

  • ร…รญshรฅ Hรฅmรฉรจรฐ

    I want to remove the childitems alongwith the group em removing.. i have removed the groups but unable to remove childs.. and childs are shuffling dont knw why ๐Ÿ™

    • ร…รญshรฅ Hรฅmรฉรจรฐ

      please Ravi help

  • Ajay Panchal

    Is that possible to use radioGroup as a child instead of TextViews?

  • Dantalion

    Hi whenever I add an header entry with the same name as another header, All the child items will have the values of the first header entry how do I prevent this?

  • rotexhawk

    Is it possible to add the default group indicator. My emulator doesn’t show the indicator ?

  • Akshay kumar

    Is it possible to add a html file in the child list.

  • Saurabh Panchal

    Can you please tell how to implement search feature to this expandable listview ? I have been trying but not successful till now.Please share some tips.Thanks.

    • Vinayak Parab

      I Also want to add search option for this example

  • jhansi laxmi

    nice example ravi

  • Lalith Narayan Kashyap

    Hi Can anyone help how to move the icon to the right ?

  • Akshay Patil

    How to hide the dropdown indicator when no child element is present

    • James

      expandableListView.setGroupIndicator(null); // hides the arrow

      • Akshay Patil

        I already tried that…what i wanted was to hide arrows for only non-child groups and not all groups. I used custom png arrows as indicators in the end. But still if theres a solution for using inbuilt indicators, i would like to hear it from you. Thanks.

  • Hi admin,
    its really a nice example. Thanks for sharing. But if I want to extend the list further for one more hierarchy then what I have to do?

  • Kiran Vinnakota

    hi ravi if may possible to add navigation drawer with 3 level expandable list view

  • Kiran Vinnakota

    hi

  • Kiran Vinnakota

    Hai Ravi…..
    I want to display Navigation Drawer with 3 levels of expandable listviews(category,sub,and sub sub category) Please help me.thank u…………

  • Jello

    Hello! Got error, ExpandableListAdapater is abstract; cannot be instantiated

    • Rodrigo

      U’re importing ExpandableListAdapater from android. U have to import the custom ExpandableListAdapater that u wrote.

  • sameer

    Hi Ravi..
    how can i remove arrow mark for non Expandable listview.
    There is any Example….

  • Kaiko

    Hi,

    Can someone tell me if it is possible to have several columns in an ExpandableListView?

    Thanks ๐Ÿ™‚

    • mooi

      you can add multiple ExpandableListView

  • Dhaval Chheda

    Hi ,

    I added some more list data to be shown in the expandableListView but that data is not getting expanded so please assist

    do i need to use notifyDataSetChanged() ?

    I tried to use it but it did not work

    Please assist

    • CSP

      see above^

  • CSP

    if you use Checkbox into Expandable view, add focusable = false

    • Johnny Dude

      Why? The purpose of adding a checkbox would be to let the user select one or more items. What is the issue your addressing? Thanks.

  • Rishabh Maurya

    Hey Ravi ,
    I want to use searchview functionality in expandable listview similar to you .
    Whenever the user types any term , the group should automatically inflate and highlight the matching child item .

  • Dinesh Bhat

    Hi All, I extended this sample to support checkboxes in the expandable List View. It was hard to find any samples with checkboxes.

    https://github.com/bhat-dinesh/ExpandableListViewWithCheckBox

  • Christian Volet

    Thank you for the tutorial.

    Note: You misspelled childPosition in @Override getChild causing an error.

  • manisha

    public class PDS_FamilyDetailsFragment extends Fragment implements

    PDS_Constants {

    SHSFW_InputInterface passer;

    PDS_DBHelper db;

    RelativeLayout rlContent;

    TextView tvRCNo, tvValidity, tvAgencyNo, tvCategory, tvMemberCount;

    ExpandableListView exMemberList;

    PDS_FamilyMembersAdapter adapter;

    ArrayList memberList;

    String rcNum = null;

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

    Bundle savedInstanceState) {

    RelativeLayout baseLayout = new RelativeLayout(getActivity());

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

    baseLayout.setLayoutParams(params);

    container = (ViewGroup) inflater.inflate(

    R.layout.pds_familydetails_fragment, container, false);

    baseLayout.addView(container);

    // extract the response from the fragment

    //String response = getArguments().getString(“response”);

    initializeViews(baseLayout);

    rcNum = PDS_SavedValues.getPDS_rcNum();

    // prepareTestData();

    setupDisplay();

    //setupDisplay(response);

    exMemberList.setOnChildClickListener(new OnChildClickListener() {

    @Override

    public boolean onChildClick(ExpandableListView parent, View v,

    int groupPosition, int childPosition, long id) {

    PDS_FamilyDetails family = memberList.get(groupPosition);

    PDS_SavedValues.setPDS_beneficiary(family.getFst_name()+” “+family.getLst_name());

    PDS_SavedValues.setPDS_rcNum(rcNum);

    if(family.getTypeofidenty().get(childPosition).equalsIgnoreCase(“1”)){

    PDS_AadhaarDataFragment aadhaarFrag = new PDS_AadhaarDataFragment();

    getActivity().getSupportFragmentManager()

    .beginTransaction()

    .replace(SHSFW_FrameWorkActivity.child.getId(), aadhaarFrag)

    .addToBackStack(“PDS_FamilyDetails”).commit();

    }

    return true;

    }

    });

    return baseLayout;

    }

    private void setupDisplay() {

    // get the ration card details

    PDS_CardDetails cardDetails = db.getRationCardDetails(rcNum);

    System.out.println(“****** TEST ******”);

    System.out.println(cardDetails.toString());

    System.out.println(“******************”);

    tvRCNo.setText(rcNum);

    tvValidity.setText(cardDetails.getRc_valid_from() + ” to ”

    + cardDetails.getRc_valid_upto());

    tvAgencyNo.setText(cardDetails.getAgency_name());

    tvCategory.setText(cardDetails.getCategory());

    tvMemberCount.setText(cardDetails.getFamily_size());

    // get the family details

    memberList = db.getFamilyDetails(rcNum);

    if (memberList != null || memberList.size() > 0) {

    adapter = new PDS_FamilyMembersAdapter(getActivity(), memberList);

    exMemberList.setAdapter(adapter);

    }

    }

    private void setupDisplay(String response) {

    FamilyDetailsDisplayAsyncTask task = new FamilyDetailsDisplayAsyncTask(

    response);

    task.execute();

    /*// get the family details

    memberList = db.getFamilyDetails(rcNum);

    if (memberList != null || memberList.size() > 0) {

    adapter = new PDS_FamilyMembersAdapter(getActivity(), memberList);

    exMemberList.setAdapter(adapter);

    }*/

    }

    public class FamilyDetailsDisplayAsyncTask extends

    AsyncTask {

    ProgressDialog dialog;

    ArrayList data = null;

    String response;

    PDS_CardDetails card;

    public FamilyDetailsDisplayAsyncTask(String response) {

    this.response = response;

    card = new PDS_CardDetails();

    }

    @Override

    protected void onPreExecute() {

    super.onPreExecute();

    dialog = new ProgressDialog(getActivity());

    dialog.setMessage(“Preparing display. Please wait…”);

    dialog.show();

    }

    @Override

    protected String doInBackground(String… params) {

    try {

    String resp = SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “Resp”);

    if (resp.equalsIgnoreCase(“Y”)) {

    extractCardDetails(response);

    extractMemberDetails(response);

    } else {

    // operation failure

    }

    } catch (Exception e) {

    }

    return “”;

    }

    private void extractCardDetails(String response) {

    card.setRc_number(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “rc_num”));

    card.setAgency_name(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “agency_name”));

    card.setRc_date_of_issue(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “date_of_issue”));

    card.setRc_valid_from(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “valid_from”));

    card.setRc_valid_upto(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “valid_to”));

    card.setEmail_primary(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “email_pri”));

    card.setEmail_secondary(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “email_sec”));

    card.setMobile_primary(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “mobile_pri”));

    card.setMobile_secondary(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “mobile_sec”));

    card.setPhone(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “phone”));

    card.setCategory(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “category”));

    card.setFamily_size(SCIDR_DataParser.SCIDR_parseXml(response,

    “PDS-resp”, “family_size”));

    }

    private void extractMemberDetails(String response2) {

    memberList = new ArrayList();

    NodeList nodeList = SCIDR_DataParser.PDS_parse(response,

    “/PDS-resp/member_details”);

    for (int i = 0; i < nodeList.getLength(); i++) {

    Node nNode = nodeList.item(i);

    System.out.println("nCurrent Element :" + nNode.getNodeName());

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

    Element element = (Element) nNode;

    PDS_FamilyDetails family = new PDS_FamilyDetails();

    family.setFst_name(element.getElementsByTagName("name").item(0).getTextContent());

    family.setAdrs_name(element.getElementsByTagName("addr_name").item(0).getTextContent());

    family.setFh_name(element.getElementsByTagName("fh_name").item(0).getTextContent());

    family.setDob(element.getElementsByTagName("dob").item(0).getTextContent());

    family.setAge(element.getElementsByTagName("age").item(0).getTextContent());

    family.setGender(element.getElementsByTagName("gender").item(0).getTextContent());

    byte[] photo = Base64.decode(element.getElementsByTagName("photo").item(0).getTextContent(), Base64.DEFAULT);

    family.setPhoto(photo);

    family.setRelation(element.getElementsByTagName("relation").item(0).getTextContent());

    family.setSpl_entitlement(element.getElementsByTagName("spl_entitlement").item(0).getTextContent());

    ArrayList ids = new ArrayList();

    String idTypes = element.getElementsByTagName(“id_types”).item(0).getTextContent();

    String[] parts = idTypes.split(“:”);

    for (String id : parts) {

    ids.add(id);

    }

    family.setTypeofidenty(ids);

    memberList.add(family);

    }

    }

    }

    @Override

    protected void onPostExecute(String result) {

    super.onPostExecute(result);

    tvRCNo.setText(card.getRc_number());

    //PDS_SavedValues.setPDS_rcNum(card.getRc_number());

    tvValidity.setText(card.getRc_valid_from() + ” to ”

    + card.getRc_valid_upto());

    tvAgencyNo.setText(card.getAgency_name());

    tvCategory.setText(card.getCategory());

    tvMemberCount.setText(card.getFamily_size());

    if (memberList != null || memberList.size() > 0) {

    adapter = new PDS_FamilyMembersAdapter(getActivity(), memberList);

    exMemberList.setAdapter(adapter);

    }

    dialog.dismiss();

    }

    }

    private void initializeViews(RelativeLayout baseLayout) {

    memberList = new ArrayList();

    db = new PDS_DBHelper(getActivity());

    rlContent = (RelativeLayout) baseLayout

    .findViewById(R.id.rl_family_content);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

    LayoutParams.MATCH_PARENT,

    SHSFW_FrameWorkActivity.SCROLLVIEW_HEIGHT);

    rlContent.setLayoutParams(params);

    tvRCNo = (TextView) baseLayout.findViewById(R.id.tv_family_cardno);

    tvValidity = (TextView) baseLayout

    .findViewById(R.id.tv_family_validity);

    tvAgencyNo = (TextView) baseLayout.findViewById(R.id.tv_family_agency);

    tvCategory = (TextView) baseLayout

    .findViewById(R.id.tv_family_category);

    tvMemberCount = (TextView) baseLayout

    .findViewById(R.id.tv_family_count);

    exMemberList = (ExpandableListView) baseLayout

    .findViewById(R.id.ex_family_list);

    }

    @Override

    public void onAttach(Activity activity) {

    super.onAttach(activity);

    try {

    passer = (SHSFW_InputInterface) activity;

    } catch (ClassCastException e) {

    throw new ClassCastException(activity.toString()

    + ” must implement SHSFW_InputInterface”);

    }

    }

    @Override

    public void onStart() {

    super.onStart();

    SUIRES_ROUTINE_Resources resource = SUIRES_ROUTINE_Resources

    .SUIRES_getResourceInstance(getActivity());

    String msg1 = resource.SUIRES_getMessage(60).getSUIRES_message();

    String msg2 = resource.SUIRES_getMessage(67).getSUIRES_message();

    String msg3 = “”;

    passer.SHSFW_IConfigMessages(msg1, msg2, msg3, 2);

    }

    private void prepareTestData() {

    ArrayList typeOfIdentity = new ArrayList();

    typeOfIdentity.add(“1”);

    typeOfIdentity.add(“2”);

    typeOfIdentity.add(“3”);

    Drawable d = getResources().getDrawable(R.drawable.ic_launcher);

    Bitmap bitmap = ((BitmapDrawable) d).getBitmap();

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

    byte[] photo = stream.toByteArray();

    PDS_FamilyDetails member1 = new PDS_FamilyDetails(“1234567890”, “111”,

    “#27, 1st Main Road Nehrunagar”, “Ashwin”, “”, “Venkat”,

    “Ramachandra Rao”, “09/04/1990”, “25”, “M”, photo, “Son”,

    “N/A”, typeOfIdentity);

    PDS_FamilyDetails member2 = new PDS_FamilyDetails(“2345678901”, “222”,

    “#28, 2st Main Road Nehrunagar”, “Hari”, “Krishna”, “Prasad”,

    “Ramachandra Rao”, “09/04/1990”, “50”, “M”, photo, “Son”,

    “N/A”, typeOfIdentity);

    PDS_FamilyDetails member3 = new PDS_FamilyDetails(“3456789012”, “333”,

    “#29, 3st Main Road Nehrunagar”, “Ramachandra”, “”, “Rao”,

    “Ramachandra Rao”, “09/04/1990”, “75”, “M”, photo, “Head”,

    “N/A”, typeOfIdentity);

    memberList.add(member1);

    memberList.add(member2);

    memberList.add(member3);

    }

    }

    Sir these code i am trying. Issue is that when i am using the onclickchild it shows the details in jelly bean version when i am working in kitkat version it is not working. Means i can’t able to scroll to see the list.

  • Zen Bhatt

    Hi Ravi, thanks for this great tutorial. I want to apply some style on some of the child views based on some condition. Like this,

    imgview.setVisibility(View.VISIBLE);
    layout.setBackgroundColor(Color.parseColor(“#f8f8f8”));

    This style applies,but when I scroll the list, this style also applies to other some of the childrens and works unexpectedly…So please help me with this!

    • You need to write if else. If condition apply your style, else apply the other style. Then the problem solves.

      • shakeel

        list view expanded like animation but on collapse i am using hide visibility. is there any method that on collapse it close like animation.?

  • Jaeho Ju

    ExpandableListAdapter class already exists. is there no problems?

  • Venkatesh Nani

    super tutorial sir in that i added child items to check boxes and when i checked child items will be appear next activity how to code that. sir please tel me sir .thanks for advance

  • Venkatesh Nani

    sir how to save this prepareListData() in sqlite database

  • Venkatesh Sundarrajulu Ravee

    I want to add items to the list from application manager(settings -> application manager) to my application please suggest – Android

  • Aries de Leon

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
    Hi. i have an error on this one saying it is abstract and cannot be instatiated. what should i do?

  • Raja Malik

    I make multilevel Expandable list view with dynamic bulk of json data …but data is show all groups, chides and sub childes correctly. but issue is child data repeat.if child have ten item then child data repeat ten time.. the problem is not found….can you help me…

  • Raja Malik
  • Ashok

    how can i create expendable list view with gridView…

  • muzlin

    hi.. can you help me.. i am beginner.. how to create an intent for expendable list view.. im trying add on this code.. however there is an error.. anyone can help me.

    @Override

    public boolean onChildClick(ExpandableListView parent, View v,

    int groupPosition, int childPosition, long id) {

    // TODO Auto-generated method stub

    Inten intent;

    final String pilih = (String)expListView.getChild(groupPosition,childPosition);

    Toast.makeText(

    getApplicationContext(),

    listDataHeader.get(groupPosition)

    + ” : ”

    + listDataChild.get(

    listDataHeader.get(groupPosition)).get(

    childPosition), Toast.LENGTH_SHORT)

    .show();

    return false;

    }

    });

    The problem at this code :
    final String pilih = (String)expListView.getChild(groupPosition,childPosition);

    an error at getChild

  • Hello Ravi,
    I am using the code above, trying to load the data dynamically from a csv file. The csv has 2 columns, term-definition pairs. I changed the prepareListData() to

    listDataHeader = new ArrayList();

    InputStream inputStream = getResources().openRawResource(R.raw.chronology);

    CSVReader csv = new CSVReader(inputStream);

    List termDefinition = csv.read();

    for (String[] term : termDefinition) {

    listDataHeader.add(term[0]);

    listDataChild.add(term[1]);
    }

    But now the listDataChild is added as many times as the size of the ArrayList is (9 in the case). May you help me figure it out? Thanks!

  • ravikiran

    Hello Ravi,

    i am using the code above, in that list group i added a button. i cant abele to give that button action or that button intent . in expandable list one row one button we added only one button. that buttons to next activities i have to give cunnection. help me thank you

  • Sankar Santhanaraman

    Hi Ravi – Thanks, this code works like a charm. Appreciate you adding the code for click, collapse and expand group. Can you also add the piece of code for adding an edit text as a means to filter this expandable list view? Thanks.

  • Hello, does anyone know how the expandable listview may be closed on child click? Thank you!

  • MyintMyatThurein

    Sir .. I want to know seriously how to add data with Myanmar font in Expandable List View.Please help me.

  • jusAskin

    how to add buttons for edit or add items?

    • justAskin

      i’d like the add buttons to be on the parentRow then the edit or delete in the childRow.

  • Valentin Cerneanu

    Hello! How can i do to replace the ArrayList with a String [] ? I want the second parameter of listDataChild.put(listDataHeader.get(0), top250); to be a String [].

  • Valentin Cerneanu

    Hello! How can i change the color of the selected item ?

  • Lakshman Bodduluru

    hello ravi, Please make tutorial on expandable RecyclerView.

  • my list is getting nullpointerexception error at

    @Override
    public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
    .size();
    }

    if child is empty. it give an error at size of child. how to rectify the code.

    In my list some items have child but some is empty.

    Also how do i make it already expanded if having child.
    Please Help
    and thanks for this tutorial
    Thanks in advance.

  • savy

    I have tried above program but it does not show any output because app has been crash and it android monitor shows this problem
    Caused by: java.lang.NullPointerException
    at com.example.hp.kludge.ProgramList.onCreate(ProgramList.java:36)

    please tell me sir how to resolve this problem….its very urgent for me please help…please!!

    • aman mehta

      did you find any solution , i am having same issue

  • prasad Vdv

    Hi its working fine, Thanks for the code
    Can we expand the all groups by default.
    Please let me know..

  • Prathibha Nandini

    Hi @ravi8x:disqus I wanna do this in fragments. Fragments of your material design. Could you help please

  • plu9in

    Hi,
    You don’t need to keep a reference on the context in ExpandableListAdapter class. Apparently, you keep it to access the inflater service. You can just do this: LayoutInflater.from(parent.getContext())
    Like this, you avoid a memory leak ๐Ÿ˜‰
    Have fun coding !

  • aravind n

    i want to close other header when selected new one pls help me….

  • Srinivas Dadi

    Hi I need custom Expandable listview with radio button and textview

    • Mayank Sahai

      did you find the answer?

  • Srinivas Dadi

    Ravi Tamada Pls help me I want show expandable listview with radiobutton and textview in my project pls give guidance for it

  • Kiran Vinnakota

    hi ravi,Each child item while clicking went to frgaments is possible?

  • Mohan kumar

    Hi Ravi, How to update child items dynamically on setOnGroupClickListener .?

  • james jonathan

    hi ravi how to use expandable list view for item and menu for showing single item in navigation drawer like snapdeal navigation drawer same to same create

    https://uploads.disquscdn.com/images/110fb67eaaec567e2526fcdaed09945bf024a4c2d522fa391dd952e43bc17d65.png

    • Girl Candy (Girlcandy)

      hi did you manage to resolve your problem? would you mind to share what you did because I have the same problem. Thanks!

      • Philips

        Hi @girlcandygirlcandy:disqus , Hi @disqus_xD798ZBpu4:disqus Did you solve the problem? I need to use expandable list view inside a navigation drawer. I’ll be so grateful if you share your solution ๐Ÿ™‚

  • pranav m.s

    hi thanks for this. I have one doubt how can i add some more field or values in child and header section please help me.

  • Adithya

    Hi

    Thanks for the excellent article!

    • You are welcome:)

      • Welcome

        >You are welcome:)
        You are welcome:)
        >You are welcome:)

  • omkar

    thanks got it

  • priya

    Not workin plss help…

    expListView.setOnGroupClickListener(new android.widget.ExpandableListView.OnGroupClickListener() {

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v,
    int groupPosition, long id) {

    if(groupPosition==0)
    {
    Intent i = new Intent(DrawerActivity.this,DashboardFragment.class);
    startActivity(i);
    }
    if(groupPosition==3)
    {
    Intent i = new Intent(DrawerActivity.this,LogoutFragment.class);
    startActivity(i);
    }
    return false;
    }
    });

  • Mazullah

    List top250 = new ArrayList();
    top250.add(“The Shawshank Redemption”);
    top250.add(“The Godfather”);
    top250.add(“The Godfather: Part II”);
    top250.add(“Pulp Fiction”);
    top250.add(“The Good, the Bad and the Ugly”);
    top250.add(“The Dark Knight”);
    top250.add(“12 Angry Men”);

    Sir i want That To make Certian Activities Linking with The CHilds of List,
    i mean That if i Click on a Child It Directly Takes Me To There Reference Activity,
    Tell Me How To Do That,?

  • dhaval

    please help me how to get json data in exapndable list view help me fast

  • Vivek

    hey Ravi,
    I am getting errors

    01-27 09:03:05.477: E/AndroidRuntime(6063): java.lang.NullPointerException

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.LayoutInflater.inflate(LayoutInflater.java:435)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.LayoutInflater.inflate(LayoutInflater.java:372)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at com.login.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:92)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:446)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.AbsListView.obtainView(AbsListView.java:2159)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.ListView.onMeasure(ListView.java:1158)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.RelativeLayout.measureChild(RelativeLayout.java:666)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.View.measure(View.java:15518)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.Choreographer.doCallbacks(Choreographer.java:562)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.Choreographer.doFrame(Choreographer.java:532)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.os.Handler.handleCallback(Handler.java:725)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.os.Handler.dispatchMessage(Handler.java:92)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.os.Looper.loop(Looper.java:137)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at android.app.ActivityThread.main(ActivityThread.java:5041)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at java.lang.reflect.Method.invokeNative(Native Method)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at java.lang.reflect.Method.invoke(Method.java:511)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

    01-27 09:03:05.477: E/AndroidRuntime(6063): at dalvik.system.NativeStart.main(Native Method)

    Help me out please @

  • Wild

    Thanks Ravi for your clean and concise example. Works like charm ๐Ÿ™‚

  • Hitesh

    Hi Ravi,

    Do you have any solution for this?
    http://stackoverflow.com/questions/42274452/expandable-listview-blank-space-at-the-bottom

    Thanks in Advance.
    Reply awaited…

  • HP Software Technology

    how to highlight the selected child item in Expandable
    listview ?

  • Akshay kumar

    Hi Ravi, I have one issue.
    How to handle the header item click when it is not having any child inside it.
    Please help.

  • raj

    how to implement multi level expandable list view

  • Nikhil Gupta

    hello sir, i am new in android so please help me. I am developing the Basic Activity in which i create the 4 layout file.
    1. activity_main.xml -(create an expandable list view)
    2.child.xml
    3.prent.xml
    4.number_picker.xml
    and One is MainActivity.java file and Second is MyAdapter.java.
    i want when number is Select in number picker data will be show According to the number in number picker like when select 2 then only two parent show and with also child. and i have Edit text – Patient Name , Patient Age and Patient Gender. and when Focus change then data save in listview( means i want to save temporary data in list items)
    please help – nikhilgniit@gmail.com

  • Nicky Apriliani

    How to make multiple selection in the childview then?

    • Mayank Sahai

      did you found the answer for that?

  • Suman Ghimire

    Within ListView i have to use TextView,TextView,ListView.I am not able to work list Within List.Can this Problem be solved Through Expandable ListView????

  • Noob

    Great tutorial man, I copied your ExpandableListView code, passed in a different set of input, but the list view didn’t expand, found out that the checkbox I had in my list_group.xml was causing the problem somehow

  • Jacek Budzynski

    Hi, great tutorial but I have a question.
    How can you display just a single item from a child list under corresponding header? So let’s say that in your example you’d for example use listDataChild.put(listDataHeader.get(2), comingSoon.get(2); which obviously doesn’t work because of the ExpandableListAdapter constructor that can’t be changed because then getChildrenCount and getGroup methods from that class won’t work. Any help would be much appreciated.

  • viavitaeapps test

    your code is awesome bro….

  • hi everyone, is there anyway i can visit another site by clicking the childlist to be display inside webview

  • Muhammad Hassan

    Please tell me that how can I add items in child on run time in a specific parent using.

    Scenario is I’m using a spinner in which all parent are saved I select any specific parent the add any thing in textBox and press the Button …… ad it should be shown in that specific parent category.

  • Fritz Quaye

    How about having 3 levels. Having a grandparent, with a parent and it’s children?

  • Thenextgen 22

    how can i make them clickable

  • Nitin Jadhav

    well explained

  • Omar Ozbek

    Hi Ravi.

    First and foremost, thank you very much for this. It is very helpful.

    My question is this. I want to dynamically add the parent and also dynamically add children for each parent. Do you know how to do that?

    Thanks.

  • Damjan Miloshevski

    Thanks a lot. It helped me to achieve what I wanted. You rock. Cheers!

  • fazeel zama

    very thanks to one and only @ravi8x:disqus ..you are the best…

  • Ucen

    Thanks Bro ๐Ÿ™‚ . I like ur tutorial ….

  • Unable to download code….. please check link

  • Sandeep Reddy

    how to retrieve data for sql and display in expandablelistview

  • chethan

    Getting problem in retrieving the data from retrofit on to Expandable list view

  • alok singh

    M working on p2p modulation and getting problem on streaming video plz help….

  • supriya babar

    how to add dynamic child item in expandable listview .please help me #Ravi

  • Sayooj KC

    How to add child dynamically in grid format

  • Rahul P

    How to add search for the above listview