【问题标题】:IndexOutOfBoundException when I use notifyDataSetChanged当我使用 notifyDataSetChanged 时出现 IndexOutOfBoundException
【发布时间】:2012-08-16 15:17:04
【问题描述】:

我在这篇文章中发现了我的问题Updating ExpandableListView with notifyDataSetChanged()

“每次使用 setNotifyDatasetChanged 刷新视图时,适配器都会调用列表周围的循环。由于您所做的更改,适配器中的列表会获得空值。”

我是初学者,无法正确更改列表

我的资源

public class UrlArrayAdapter extends ArrayAdapter<UrlItem> {

    private LayoutInflater inflater;
    private ListView urlListView1;
    private ArrayList<UrlItem> urlItems1;

    public UrlArrayAdapter(Context context, ListView urlListView,
            ArrayList<UrlItem> urlLists) {
        super(context, urlListView.getId(), urlLists);
        this.urlItems1 = urlLists;
        this.urlListView1 = urlListView;


        inflater = LayoutInflater.from(context);

如何从基础适配器的 urlLists 中的列表中删除项目??

【问题讨论】:

标签: android baseadapter


【解决方案1】:

除了覆盖 public View getView(int position, View view, ViewGroup parent) 之外,请确保扩展 ArrayAdapter 的类覆盖这些方法:

public int getCount()
public UrlItem getItem(int position)
public int getPosition(Hold item)
public long getItemId(int position)

我相信notifyDataSetChanged() 会在您的适配器上调用getCount() 以确定有多少项目。如果您不使用return urlItems1.size(); 覆盖此方法,那么IndexOutOfBoundException 似乎迫在眉睫,因为您的自定义适配器将无法告诉客户其大小和内容。

【讨论】:

【解决方案2】:

删除项目:urlList.remove(item_index); 然后通知数据集已更改。

根据您在下面的评论,我正在更新我的答案。
remove() 方法接受被移除元素的索引,而不是元素本身。

因此,要从列表中删除特定数字,您应该首先找到它的索引,然后将该索引传递给remove() 方法。

例如:

public void deleteItem(int numberToDelete) {
    int index=-1;

    // Find the index of numberToDelete
    if(urlLists.contains(numberToDelete)){
        index = urlLists.indexOf(numberToDelete);
    }

    // Delete the number by spefying the index found.
    if(index!=-1){
        urlLists.remove(index);
    }

//...
}

【讨论】:

  • public void deleteItem(int nummer) { urlItems1.remove(nummer); notifyDataSetChanged(); } -- 而且它不起作用
  • 什么代表你的nummer?您要删除的号码?如果是这样,那么不,数组列表不能这样工作。 remove 方法接受一个index,该数字在列表中的位置。
  • 会从列表中删除,但是notifyDataSetChanged()会抛出异常
  • 请看链接 - 和答案,我认为这是我的情况
  • 好的,那么我可能误解了这个问题。对不起。
猜你喜欢
  • 1970-01-01
  • 2017-04-02
  • 2012-03-25
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 2011-05-23
  • 2017-05-11
相关资源
最近更新 更多