简体   繁体   English

如何在Android中解决java.lang.IndexOutOfBoundsException?

[英]How to resolve java.lang.IndexOutOfBoundsException in android?

I have created an expandable list view,On clicking the child element another activity is started.But this happens only for the first three child elements in first parent group, when i click on the subsequent child elements the app crashes an the error 我创建了一个可扩展的列表视图,单击子元素时会启动另一个活动。但这仅发生在第一个父组中的前三个子元素上,当我单击后续子元素时,应用程序崩溃并报错

java.lang.IndexOutOfBounds:Invalid index 3,size is 3. java.lang.IndexOutOfBounds:无效的索引3,大小为3。

I don't know where I have gone wrong. 我不知道哪里出了问题。

This is MainActivity.java file 这是MainActivity.java文件

    package com.example.expandablelistview;

    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.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);

    expListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View view,
                int groupPosition, int childPosition, long id) {

            // selected item

            if(listDataHeader.get(groupPosition)=="Catalog"){
             Intent i = new Intent(MainActivity.this, SingleListItem.class);
       // sending data to new activity
          startActivity(i);
            }

            if(listDataHeader.get(groupPosition)=="My Account"){

                    Intent i1 = new Intent(MainActivity.this,CheckHolds.class);
                    startActivity(i1);
            }
             if(listDataHeader.get(groupPosition)=="Library Info"){

                Intent i2 = new Intent(MainActivity.this,LibraryHours.class);
                startActivity(i2);
            }

         return false;
        }

       });
      }
       /*
       * Preparing the list data
       */
      private void prepareListData() {
      listDataHeader = new ArrayList<String>();
      listDataHeader.add("Catalog");
      listDataHeader.add("My Account");
      listDataHeader.add("Library Info");

       // Adding child data
       List<String> catalog = new ArrayList<String>();
       catalog.add("Automobile");
       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);
       }
      }

And this is the ExpandableListAdapter.java file 这是ExpandableListAdapter.java文件

    package com.example.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;
     }
    }

Please suggest me what changes should I do to solve the error. 请建议我应该做些什么来解决该错误。

Lets consider this if condition: 让我们考虑一下以下条件:

if(listDataHeader.get(groupPosition)=="My Account"){

Here you should first check whether the groupPosition is inside the size of the list listDataHeader to avoid this Exception . 在这里,您应该首先检查groupPosition是否在列表listDataHeader的大小之内,以避免此Exception For example groupPosition < listDataHeader.size() 例如groupPosition < listDataHeader.size()

Also here you are doing the string comparison in a wrong way. 同样在这里,您以错误的方式进行字符串比较。 Java doesn't support such comparision. Java不支持这种比较。 You should use either .equals("My Account") or .equalsIgnoreCase("My Account") for this instead of == 您应该.equals("My Account")使用.equals("My Account").equalsIgnoreCase("My Account")而不是==

So finally it will be: 所以最终它将是:

if(groupPosition < listDataHeader.size() && 
   listDataHeader.get(groupPosition).equalsIgnoreCase("My Account")){

Try to access the Group elements as below: 尝试按以下方式访问组元素:

listDataHeader.get(groupPosition).equalsIgnoreCase("My Account")

Also to access the child elements you can get it as below: 另外,要访问子元素,您可以如下所示:

  listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).equalsIgnoreCase("Automobile");

Change your child Click listener as below: 更改您的孩子的Click监听器,如下所示:

  expListView.setOnChildClickListener(new OnChildClickListener() {

    @Override
    public boolean onChildClick(ExpandableListView parent, View view,
            int groupPosition, int childPosition, long id) {

        // selected item

        if(listDataHeader.get(groupPosition).equalsIgnoreCase("Catalog")){
             Intent i = new Intent(MainActivity.this, SingleListItem.class);
             // sending data to new activity
              startActivity(i);
        }

        if(listDataHeader.get(groupPosition).equalsIgnoreCase("My Account"){

                Intent i1 = new Intent(MainActivity.this,CheckHolds.class);
                startActivity(i1);
        }
         if(listDataHeader.get(groupPosition).equalsIgnoreCase("Library Info"){

            Intent i2 = new Intent(MainActivity.this,LibraryHours.class);
            startActivity(i2);
        }

     return false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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