2017-02-18 15 views
0

Ошибка указывает на строку String groceryName = recipeNames.get(parentPosition); Я понимаю, что означает ошибка, но я не совсем понимаю, что вызывает ее. Как ни странно, это действительно происходит, когда некоторые из групп расширяются. Когда я нажимаю кнопку «Удалить», она не удаляет правильный элемент, что означает, что он читает неверный индекс. Если все группы свернуты, он просто прекращается. Буду признателен за любую оказанную помощь.Расширяемый список Просмотр Group Position variable вызывает индекс за пределами

package groceryproject.jacob.com.recipelist; 

import android.content.Context; 
import android.content.Intent; 
import android.database.sqlite.SQLiteDatabase; 
import android.graphics.Typeface; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseExpandableListAdapter; 
import android.widget.Button; 
import android.widget.ExpandableListView; 
import android.widget.TextView; 
import java.util.List; 

public class ExpandableIngredientListAdapter extends BaseExpandableListAdapter{ 
private Context mContext; 
private List<String> recipeNames; // header titles 
private HashMap<String, List<String>> recipeIngredients; 
private Button mDeleteButton; 

public ExpandableIngredientListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listChildData) { 
    this.mContext = context; 
    this.recipeNames = listDataHeader; 
    this.recipeIngredients = listChildData; 
} 

@Override 
public Object getChild(int groupPosition, int childPosititon) { 
    return this.recipeIngredients.get(this.recipeNames.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) { 
    //Changed from groupPosition to groupPosition - 1 
    final String childText = (String) getChild(groupPosition, childPosition); 

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

    TextView txtListChild = (TextView) convertView.findViewById(R.id.expandable_list_recipe_ingredient_item); 
    txtListChild.setText(childText); 
    return convertView; 
} 

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

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

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

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

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

     mDeleteButton = (Button) convertView.findViewById(R.id.delete_recipe_from_grocery_list_button); 
     //TODO: Add a dialog to ensure user wants to delete the recipe 
     mDeleteButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       int parentPosition = groupPosition; 
       //This is where the error is 
       String groceryName = recipeNames.get(parentPosition); 
       RecipeDB dbHelper = new RecipeDB(parent.getContext()); 
       recipeNames.remove(parentPosition); 
       recipeIngredients.remove(parentPosition); 
       dbHelper.deleteGrocery(groceryName); 
       notifyDataSetChanged(); 

      } 
     }); 
    } 

    TextView lblListHeader = (TextView) convertView.findViewById(R.id.expandable_list_recipe_header); 
    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; 
} 
} 

Редактировать: Это ошибка logcat, которую я получаю.

02-17 23:55:19.558 11403-11403/groceryproject.jacob.com.recipelist E/AndroidRuntime: FATAL EXCEPTION: main 
                       Process: groceryproject.jacob.com.recipelist, PID: 11403 
                       java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2 
                        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 
                        at java.util.ArrayList.get(ArrayList.java:308) 
                        at groceryproject.jacob.com.recipelist.ExpandableIngredientListAdapter$1.onClick(ExpandableIngredientListAdapter.java:98) 
                        at android.view.View.performClick(View.java:5204) 
                        at android.view.View$PerformClick.run(View.java:21153) 
                        at android.os.Handler.handleCallback(Handler.java:739) 
                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                        at android.os.Looper.loop(Looper.java:148) 
                        at android.app.ActivityThread.main(ActivityThread.java:5417) 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
+0

добавить свой журнал ошибок –

+0

share logcat/error –

+0

Добавлена ​​ошибка logcat. Я не уверен, что все будет сделано, но я переписал конструктор, чтобы я мог напрямую вытащить из базы данных вместо передачи информации в качестве параметра. Я также хочу удалить необходимость хэш-карты с arraylist, напрямую обращаясь к моему пользовательскому объекту. Я знаю, что это ничего не исправит, но мне будет легче проследить, где он ломается. Я обновлю прогресс. – knokout1

ответ

0

Так что, похоже, я наконец-то нашел решение. По какой-то причине, удаление строки:

if (convertView == null){ 

как от getGroupView и getChildView зафиксировал его. Я не уверен, что удаление его из getChildView на самом деле ничего не сделало, но я сделал это для хорошей меры. Я понятия не имею, почему это было исправление, но оно еще не разбилось в моих попытках воспроизвести проблему.

 Смежные вопросы

  • Нет связанных вопросов^_^