我写了一个类,它在文件夹中查找特定文件并将其地址(加上3个其他属性)保存到共享首选项,然后在我的自定义适配器中调用方法(方法(即named getAllItems )从共享首选项中读取数据,实例化新的自定义对象并将它们添加到列表中并返回列表。这是最大加载发生的部分)然后适配器使用该项列表从每个项目中检索地址,生成一个位图并在recyclerView中显示它们 这是我得到的错误:
E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
Process: com.amir.example, PID: 4968
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$KeyIterator.next(HashMap.java:814)
at com.android.internal.util.XmlUtils.writeSetXml(XmlUtils.java:355)
at com.android.internal.util.XmlUtils.writeValueXml(XmlUtils.java:693)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:300)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:269)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:235)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:192)
at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:600)
at android.app.SharedPreferencesImpl.-wrap2(SharedPreferencesImpl.java)
at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
现在当文件数量很少时(比如100个文件中的20个匹配),应用程序运行正常,但是当有太多文件时(如8000个文件中的200个项目)应用程序崩溃
我试图异步加载项目到适配器:这是在 MainActivity.java
public class AsyncAdapter extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//This line will load the files into shared preferences (DataSource is my sharedPreferences)
Loader.loadPhoneStickers(adapter.getDataSource());
//this will cause the list that the adapter is attached to, to get updated and load all the items that were added to shared preferences
//this method will make a call to getAllItems and notifyItemRangeChanged
adapter.refresh();
return null;
}
}
但是我是否异步设置适配器(设置适配器会导致所有加载发生)或同步
错误仍然相同我应该在哪里装载? otto会有什么帮助吗?
答案 0 :(得分:1)
您需要在asynctask中覆盖此方法,并在ui线程上运行的postexecute上覆盖此方法。您无法从ui Thread刷新适配器。
public class AsyncAdapter extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//This line will load the files into shared preferences (DataSource is my sharedPreferences)
Loader.loadPhoneStickers(adapter.getDataSource());
//this will cause the list that the adapter is attached to, to get updated and load all the items that were added to shared preferences
//this method will make a call to getAllItems and notifyItemRangeChanged
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.refresh();
}
}
通常,当您在不同的线程中工作时,您无法与ui元素进行交互。通常的做法是在Asynctask中使用postExecute.Post执行在doInbackground完成后立即调用,并在UI线程上调用,您可以在其中执行所有与Ui相关的操作。