【问题标题】:IndexOutOfBoundsException in my Android Listview adapter我的 Android Listview 适配器中的 IndexOutOfBoundsException
【发布时间】:2015-05-14 23:24:00
【问题描述】:

我不断收到此 IndexOutOfBoundsException,但似乎无法弄清楚是什么原因造成的。我的列表视图有一个带有对象列表的适配器,并且这些对象根据时间戳被删除。删除是在 getView 方法中完成的。删除项目后,我调用 notifyDataSetChanged()。

完整的源代码在github上,这里是listview适配器代码的链接:https://github.com/kenneho/run-for-the-bus/blob/master/app/src/main/java/net/kenneho/runnow/adapters/TravelsAdapter.java

这是我不断得到的堆栈跟踪的开始:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)
at android.widget.ListView.dispatchDraw(ListView.java:3307)
at android.view.View.draw(View.java:15213)
<snip>

我看到 getView 中的位置值通常可以高达六或七。

这里有人能发现这个错误吗?任何帮助将不胜感激。

问候, 肯尼斯

编辑 1: * 链接到使用 https://github.com/kenneho/run-for-the-bus/blob/master/app/src/main/java/net/kenneho/runnow/InfoActivity.java 的活动代码 * 我在这里粘贴了最相关的 logcat 部分:http://pastebin.com/5FtU4EaM

【问题讨论】:

  • 您试图在 ArrayList 为空时访问它。贴一些代码。
  • 您可以发布您的活动代码吗? size 为 0 表示您的列表为空。
  • 删除是在 getView 方法中完成的。 这里的问题是适配器的删除方法已经调用 notifyDataSetChanged ...
  • 您也应该发布 LogCat,因为代码进行了有用的 Log 调用。如果您通过调试器单步执行代码,那么您应该知道哪个代码导致了异常。
  • @Selvin,你建议我如何放置从适配器中删除条目的代码?

标签: android listview indexoutofboundsexception


【解决方案1】:

终于修复了这个错误。首先,我按照@Selvin 的建议重构了代码。其次,我添加了一个“removecallback”语句来在创建新的 Runnable 之前停止任何 Runnable:

// Make sure we stop existing timers, if any.
timerHandler.removeCallbacks(timerRunnable);

timerRunnable = new Runnable() {

   @Override
   public void run() {
      removeExpiredTravels(myAdapter);
      myAdapter.notifyDataSetChanged();
      timerHandler.postDelayed(this, 1000);
   }
};

timerHandler.postDelayed(timerRunnable, 0);

感谢您帮助我追踪此错误。

【讨论】:

  • 这个getView()是你写的吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多