【问题标题】:Custom Adapter for ListView and Thread safety用于 ListView 和线程安全的自定义适配器
【发布时间】:2013-07-22 20:24:37
【问题描述】:

我正在使用不同的Thread 来清除适配器的List,有时我会得到IndexOutOfBoundsException

我想问题是在自定义适配器填充ListView 的过程中的某个地方,第二个线程调用list.clear() 导致list.size() 返回0,导致某处越界。

如何使用同步使这个线程安全(如果这会解决它)?

//onCreate
fillList(list);  // fills the list
new AsyncTaskSubclass().execute(); // clear the list on a different Thread

编辑:我认为问题在于AsyncTask 正在清除ArrayAdapter 子类使用的列表,有没有办法改变适配器的List用途?

【问题讨论】:

    标签: java android android-asynctask thread-safety synchronized


    【解决方案1】:

    您可以使用同步列表:

    List<Item> list = Collections.synchronizedList(new ArrayList<Item>());
    

    【讨论】:

    • 我正在从服务器获取新数据,这就是列表被清除并在单独线程上重新填充的原因。此解决方案是否适用于那种情况?
    【解决方案2】:

    如果有更多代码就好了。

    如果使用AsyncTask,当你想清除丢失时,你应该在doInBackground()方法中调用publishProgress(),然后在onProgressUpdate()add()remove())中清除。您应该避免从 UI 线程外部操作 UI 元素。

    为什么不用新的列表设置一个新的适配器呢?因此,您可以异步处理您的列表,然后在 UI 线程中调用 ListView.setAdapter()(例如在 onProgressUpdate()onPostExecute() 中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多