AsyncTask中的ConcurrentModificationException

时间:2013-08-08 13:48:49

标签: android exception android-asynctask concurrentmodification listiterator

我在循环期间遇到onPostExecute()方法内的异常问题。以前我使用过foreach循环,但我读到我应该使用ListIterator。没希望它没有修复它。关键代码的片段:

public void search(final String query) {
        this.query = (!query.trim().isEmpty()) ? query : null;
        loadItemsTask2 = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                ...
            }

            @Override
            protected void onPostExecute(Void result) {
                progress.setVisibility(View.GONE);
                lView.setVisibility(View.VISIBLE);

                adapter.clear();

                for (ListIterator<LoyaltyProgramsListItem> iter = searchItems.listIterator(); iter.hasNext();) {
                    LoyaltyProgramsListItem si = iter.next();
                    adapter.add(si);
                }

                adapter.notifyDataSetChanged();
            }

        };
        loadItemsTask2.execute();

    }

此行中出现异常:

for (ListIterator<LoyaltyProgramsListItem> iter = searchItems.listIterator(); iter.hasNext();) {

logcat的:

08-08 15:26:40.069  18277-18277/******* E/AndroidRuntime: FATAL EXCEPTION: main
        java.util.ConcurrentModificationException
        at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
        at pl.freebee.android.ui.fragments.LoyaltyProgramsListFragment$4.onPostExecute(LoyaltyProgramsListFragment.java:328)
        at pl.freebee.android.ui.fragments.LoyaltyProgramsListFragment$4.onPostExecute(LoyaltyProgramsListFragment.java:289)
        at android.os.AsyncTask.finish(AsyncTask.java:417)
        at android.os.AsyncTask.access$300(AsyncTask.java:127)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:3687)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

我的解决方案:在循环之前复制数组,然后在内部循环中对此副本进行操作。