Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android ArrayAdapter中的IndexOutOfBoundsException_Android - Fatal编程技术网

Android ArrayAdapter中的IndexOutOfBoundsException

Android ArrayAdapter中的IndexOutOfBoundsException,android,Android,我得到了一个简单的代码,包括一个ListView和一个ArrayAdapter,它在一些设备上抛出一个IndexOutOfBoundsException。问题是:我不知道这个异常是如何发生的,我只从Android的开发者控制台获取stacktraces 简化的代码示例如下所示。对于位置元素,ArrayAdapter的getItem操作如何失败?ArrayAdapter从未更改,在活动中没有其他方法 我知道什么是indexootfboundsexception,我知道我可以通过先检查长度来防止它。

我得到了一个简单的代码,包括一个
ListView
和一个
ArrayAdapter
,它在一些设备上抛出一个IndexOutOfBoundsException。问题是:我不知道这个异常是如何发生的,我只从Android的开发者控制台获取stacktraces

简化的代码示例如下所示。对于
位置
元素,
ArrayAdapter
getItem
操作如何失败?
ArrayAdapter
从未更改,在
活动中没有其他方法

我知道什么是
indexootfboundsexception
,我知道我可以通过先检查长度来防止它。但我很好奇:这个例外怎么会发生在这里?如何单击数据结构中不存在的事件?

简化代码:

public class EventListActivity extends Activity {
    public void onStart() {
        final ListView listview = new ListView(this);
        final Event[] events = [Retrieve a Array from somewhere]
        final ArrayAdapter<Event> a = new ArrayAdapter<Event>(this, R.layout.eventlistitem, events);
        listview.setAdapter(a);
        listview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Event event = a.getItem(position);
                                ^^^^^^^ throws Exception
            }
        });

好的,我调试了它,如果有人有相同的错误,下面是解决方案:

如果使用
ListView.addHeader
,则
onItemClick
position
参数将移位1。看起来很奇怪,因为位置与阵列适配器中的位置无关。包含相同的结论,您必须注意作为标题添加的内容


事实上,我上面的问题不是很有帮助,因为整个
addHeader
部分缺失,其他人无法回答这个问题,对不起。然而,这个答案可能对其他人有帮助。

它意味着。。。数组中不存在该元素。先检查长度。好的,我的问题不清楚,我改了。我已经修复了错误,这只是一个为什么会发生在这里的问题。请将您的答案标记为正确,这样它将位于已回答的一侧而不是未回答的一侧。那么为什么它“在某些”设备上呢?BillGary:目前无法将我的答案标记为已接受,此限制为两天!朝日:你是对的,它不依赖于设备,这是我没有在正确的地方搜索的错误。你可能应该纠正你的问题,并添加缺失的细节-这将使问题和答案都完全有效我也经历了这一点。但我添加了两个页脚,可以在需要时切换View.Visible和View.GONE。这也能回答我的例外吗。(我永远无法复制异常以进行测试,只能复制崩溃报告)
java.lang.IndexOutOfBoundsException
at java.util.Arrays$ArrayList.get(Arrays.java:75)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:298)
at xxx.EventListActivity$3.onItemClick(EventListActivity.java:130)