Java android java.util.ConcurrentModificationException

标签 java android

我有一个服务,其中有一个 AsyncTask

if (s != null) {
                    if (!MainActivity.photoListSend.isEmpty()) {
                        if (MainActivity.photoListSend.size() > 0) {
                            File file = MainActivity.photoListSend.get(0);
                            if (file.exists())
                                file.delete();
                            MainActivity.photoListSend.remove(0);
                            Gson gson = new Gson();
                            String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
                            SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("TAG", jsonCurProduct);
                            editor.apply();
                            File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                            assert imagesFolder != null;
                        }
                    }

                }

在这一行:

String jsonCurProduct = gson.toJson(MainActivity.photoListSend);

我有 java.util.ConcurrentModificationException

这是我的全部类(class):

ublic class Sendrer extends Service {

    public static boolean running = false;
    private Timer timer = new Timer();
    private SendPhotoTask asyncSender;
    private Context context;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    public static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
        editor = sp.edit();
        Gson gson = new Gson();
        List<File> productFromShared = new ArrayList<>();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
        String jsonPreferences = sharedPref.getString("TAG", "");

        Type type = new TypeToken<List<File>>() {
        }.getType();
        productFromShared = gson.fromJson(jsonPreferences, type);
        MainActivity.photoListSend = null;
        MainActivity.photoListSend = new ArrayList<>();
        if (productFromShared != null)
            MainActivity.photoListSend.addAll(productFromShared);
        Log.e("tworzenie serwisu ", "tworzenie");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Dziełanie serwisu ", "Dziełanie");

        if (!running) {
            running = true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    asyncSender = new SendPhotoTask();
                    asyncSender.execute();
                }
            }, 1000 * 60 * 2);
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (running) {
            timer.cancel();
            asyncSender = new SendPhotoTask();
            asyncSender.cancel(true);
            running = false;
        }
        Log.e("service ", "nie działa");
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    class SendPhotoTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            running = true;
            if (MainActivity.photoListSend != null) {
                if (!MainActivity.photoListSend.isEmpty())
                    if (NetworkUtil.isNetworkAvailable(context)) {
                        if (MainActivity.photoListSend.size() > 0) {
                            MainActivity.isSend = true;
                            running = true;
                            InputStream responseInputStream = null;
                            Log.e("start wysłania ", "start");
                            try {
                                if (MainActivity.photoListSend.get(0).isFile()) {
                                    responseInputStream = HttpConnectionsUtil.sendPhotoRequest(getApplicationContext(), true, MainActivity.photoListSend.get(0).getName());
                                    if (responseInputStream != null) {
                                        String input = convertStreamToString(responseInputStream);
                                        if (input.equals("empty"))
                                            return "BAD";
                                        else {
                                            try {
                                                int tt = ResponseParser.getType(input);
                                                Log.e("TaG", tt + " ");

                                                if (tt == 0) {
                                                    return null;
                                                } else if (tt == -1) {
                                                    return null;
                                                }
                                            } catch (UnknownAnswerName e) {
                                                e.printStackTrace();
                                                return null;
                                            }
                                        }
                                    }

                                } else {
                                    return "BAD";
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                                return null;
                            }
//                    Log.e("Wysyłanie zdjęcia ", convertStreamToString(responseInputStream));
                            if (responseInputStream != null)
                                return convertStreamToString(responseInputStream);
                        }
                    }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (NetworkUtil.isNetworkAvailable(context)) {
                if (sp.getBoolean("workOffLine", false)) {
                    editor.putBoolean("workOffLine", false);
                    editor.commit();
                    isConnect.setVisibility(View.VISIBLE);
                    imgIsSend.setVisibility(View.VISIBLE);
                    imgIsNet.setVisibility(View.GONE);
                }
            }
            if (s != null) {
                if (!MainActivity.photoListSend.isEmpty()) {
                    if (MainActivity.photoListSend.size() > 0) {
                        File file = MainActivity.photoListSend.get(0);
                        if (file.exists())
                            file.delete();
                        MainActivity.photoListSend.remove(0);
                        Gson gson = new Gson();
                        String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
                        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("TAG", jsonCurProduct);
                        editor.apply();
                        File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        assert imagesFolder != null;
                    }
                }

            }
            if (s == null) {
                MainActivity.isSend = false;
            }
            if (!MainActivity.photoListSend.isEmpty()) {
                if (NetworkUtil.isNetworkAvailable(context)) {
                    if (MainActivity.photoListSend.size() > 0) {
                        asyncSender = new SendPhotoTask();
                        asyncSender.execute();
                        Log.e("Wysyłanie kolejnego ", "zdjecia");
                    } else {
                        context.stopService(new Intent(context, Sendrer.class));
                        asyncSender.cancel(true);
                        context.startService(new Intent(context, Sendrer.class));
                    }

                } else {
                    context.stopService(new Intent(context, Sendrer.class));
                    asyncSender.cancel(true);
                    context.startService(new Intent(context, Sendrer.class));
                }
            } else {
                MainActivity.isSend = false;
                context.stopService(new Intent(context, Sendrer.class));
                asyncSender.cancel(true);
                context.startService(new Intent(context, Sendrer.class));
            }
            running = false;
        }
    }
}

最佳答案

这是因为另一个线程正在同时修改MainActivity。您可以使用以下命令对线路进行分支

synchronized(MainActivity.this) {
    String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
}

但是您应该注意可能的性能问题,因为现在所有线程都将等待 toJson 方法结束

Read more about the exceptionhow to avoid this

关于Java android java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322387/

相关文章:

javascript - Headless Chrome 和 document.location.href 更改

java - 在 Java servlet 中,cookie.getMaxAge() 总是返回 -1

java - Java 中的 super 关键字给出编译错误

java - 有没有办法跟踪已发布的 Android 应用程序的日志

java - 定时器调度方法超过时间

java - 如何通过按钮启用 3G - android

java - Android - 带有 OPENGL + 纹理的 3D 立方体

android - 如何使 TextView 文本垂直

Java Hash Multi Map(键多值)实现

java - 使用 SimpleDateFormat 但小时值倒退 3 小时