简体   繁体   中英

How to add list item in expandable list view?

I have created an expandable list view with child items and it works fine. I want to add another item to the list which doesnt have any child item.I want this item to respond to clicks by opening new activity.I have tried by adding it as 4th item ,but the app crashes when i click this item.Please suggest me what changes I should do. Here is the code of my MainActivity

    package com.example.dashboard;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ExpandableListView;
    import android.widget.ExpandableListView.OnChildClickListener;

    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 on child click listener
    expListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            //selected item
                 if(listDataHeader.get(groupPosition).equalsIgnoreCase("Catalog")){
                 Intent i = new Intent(MainActivity.this, Departments.class);
                 // sending data to new activity
                  startActivity(i);
            }

            if(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).equalsIgnoreCase("Check Holds")){

                    Intent i1 = new Intent(MainActivity.this,CheckHolds.class);
                    startActivity(i1);
            }
            if(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).equalsIgnoreCase("Unreserve Books")){

                Intent i2 = new Intent(MainActivity.this,UnreserveBooks.class);
                startActivity(i2);
        }
            if(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).equalsIgnoreCase("Library Hours")){

                Intent i3 = new Intent(MainActivity.this,LibraryHours.class);
                startActivity(i3);
        }
            if(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).equalsIgnoreCase("Contact Library")){

                Intent i4 = new Intent(MainActivity.this,ContactLibrary.class);
                startActivity(i4);
        }
            if(listDataHeader.get(groupPosition).equalsIgnoreCase("Logout")){
                 Intent i5 = new Intent(MainActivity.this, Departments.class);
                  startActivity(i5);
            }
            return false;
        }
    });
}

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

    // Adding child data
    listDataHeader.add("Catalog");
    listDataHeader.add("My Account");
    listDataHeader.add("Library Info");
    listDataHeader.add("Logout");

    // Adding child data
    List<String> catalog= new ArrayList<String>();
    catalog.add("Automobile");
    catalog.add("Computer Science");
    catalog.add("Civil");
    catalog.add("Electronics and Communication");
    catalog.add("Electrical and Electronics");
    catalog.add("Information science");
    catalog.add("Industrial Production");
    catalog.add("Mechanical");
    catalog.add("Basic Sciences");

    List<String> myaccount = new ArrayList<String>();
    myaccount.add("Check Holds");
    myaccount.add("Unreserve Books");

    List<String> libraryinfo = new ArrayList<String>();
    libraryinfo.add("Library Hours");
    libraryinfo.add("Contact library");

    listDataChild.put(listDataHeader.get(0), catalog); // Header, Child data
    listDataChild.put(listDataHeader.get(1), myaccount);
    listDataChild.put(listDataHeader.get(2), libraryinfo);

}
   }

This is how the logcat looks

     03-22 02:13:38.814: I/Choreographer(2321): Skipped 251 frames!  The application may be doing too much work on its main thread.
     03-22 02:13:38.844: D/gralloc_goldfish(2321): Emulator without GPU emulation detected.
     03-22 02:13:39.004: I/Choreographer(2321): Skipped 84 frames!  The application may be doing too much work on its main thread.
     03-22 02:13:39.874: I/Choreographer(2321): Skipped 47 frames!  The application may be doing too much work on its main thread.
     03-22 02:13:40.894: D/AndroidRuntime(2321): Shutting down VM
     03-22 02:13:40.904: W/dalvikvm(2321): threadid=1: thread exiting with uncaught exception (group=0x41465700)
     03-22 02:13:40.934: E/AndroidRuntime(2321): FATAL EXCEPTION: main
     03-22 02:13:40.934: E/AndroidRuntime(2321): java.lang.NullPointerException
     03-22 02:13:40.934: E/AndroidRuntime(2321):    at com.example.dashboard.ExpandableListAdapter.getChildrenCount(ExpandableListAdapter.java:61)
     03-22 02:13:40.934: E/AndroidRuntime(2321):    at android.widget.ExpandableListConnector.refreshExpGroupMetadataList(ExpandableListConnector.java:563)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.widget.ExpandableListConnector.expandGroup(ExpandableListConnector.java:688)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:691)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:651)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.widget.AbsListView$1.run(AbsListView.java:3463)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at  android.os.Handler.handleCallback(Handler.java:730)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.os.Handler.dispatchMessage(Handler.java:92)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.os.Looper.loop(Looper.java:137)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at java.lang.reflect.Method.invokeNative(Native Method)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at java.lang.reflect.Method.invoke(Method.java:525)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    03-22 02:13:40.934: E/AndroidRuntime(2321):     at dalvik.system.NativeStart.main(Native Method)
    03-22 02:13:43.955: I/Process(2321): Sending signal. PID: 2321 SIG: 9

This is the ExpandableListAdapter.java file

   package com.example.dashboard;

   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.listitem, 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.listgroup, 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;
}

   }

In you expandable list adapter:

@Override
public int getChildrenCount(int groupPosition) {
    if(groupPosition == 3){
     return 0;
    }else{
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
    }
}

Since you want to listen to the clicks on the group use this instead of the childclick listner:

expListView.setOnGroupClickListener(new OnGroupClickListener() {            
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v,
                int groupPosition, long id) {
            //Catch the click that you want here.
            return false;
        }
    });

Previous answer:
In your prepareListData() :

listDataChild.put(listDataHeader.get(3), logout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM