【问题标题】:IndexOutOfBoundsException in getItemId in Android baseAdapterAndroid baseAdapter 中 getItemId 中的 IndexOutOfBoundsException
【发布时间】:2014-03-11 22:21:09
【问题描述】:

我有一个自定义基础适配器来处理我的 customObjects ArrayList。当用户进入我的 listView 时,我的数据集在后台发生变化的可能性很小,这似乎导致了我的 IndexOutOfBoundsException。我目前正在做:

@Override
public long getItemId(int position) {

    return custom.get(position).getID();

}

我应该坚持从像 ArrayAdapter 这样的位置返回位置吗?

/**
     * {@inheritDoc}
     */
    public long getItemId(int position) {
        return position;
    }

我可以捕捉到这个错误,但我不确定在捕捉中要做什么。我需要返回一些东西,但我害怕返回 -1 或 0 之类的东西。

在这个问题中:What is the intent of the methods getItem and getItemId in the Android class BaseAdapter?

人们说 ArrayAdapter 返回 -1,但事实并非如此(至少截至 2014 年 3 月)。

【问题讨论】:

    标签: java android android-arrayadapter baseadapter


    【解决方案1】:

    只需检查您的位置是否小于数组的大小,如果是则返回 -1。

    @Override
    public long getItemId(int position) {
        if(position < custom.size()){
            return custom.get(position).getID();
        }
        return -1;
    }
    

    【讨论】:

    • 不要相信当它期望一个原语时你可以返回 null。
    • 有趣。你知道为什么这种方法存在吗?似乎什么都没有。
    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多