2016-07-13 2 views
-3

AsyncTask 및 미리 정의 된 HashMap의 정보를 사용하여 확장 가능한 목록에 표시되는 코드를 작성하고 있습니다. 그러나 그것은 java.util.ConcurrentModificationException을 던지고있다.Android의 java.util.ConcurrentModificationException

AsnycTask

private class BackTask extends AsyncTask<Void, Void, Void> { 
     ProgressDialog pd; 
     ArrayList<String> name; 
     ArrayList<Integer> quantity; 
     Map<String, Map<String, Integer>> cart_names1 = new HashMap<String, Map<String, Integer>>(); 

     public BackTask(ArrayList<String> name, ArrayList<Integer> quantity) { 
      this.name = name; 
      this.quantity = quantity; 
     } 

     protected void onPreExecute() { 

      super.onPreExecute(); 

      pd = new ProgressDialog(ha); 

      pd.setTitle("Retrieving data"); 

      pd.setMessage("Please wait."); 

      pd.setCancelable(true); 

      pd.setIndeterminate(true); 

      pd.show(); 


     } 

     protected Void doInBackground(Void... arg0) { 
      InputStream is = null; 
      String result = ""; 
      try { 
       String link = "http://chutte.co.nf/get_item_prices.php?"; 
       for (int b = 0; b < name.size(); b++) { 
        link += "names[]" + "=" + name.get(b) + "&"; 

       } 
       for (int a = 0; a < quantity.size(); a++) { 
        link += "quantities[]" + "=" + quantity.get(a); 
        if (a != quantity.size() - 1) { 
         link += "&"; 
        } 
       } 
       Log.e("ERROR", link); 
       URL url = new URL(link); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
       is = urlConnection.getInputStream(); 
      } catch (Exception e) { 
       if (pd != null) pd.dismiss(); 


       Log.e("ERROR", e.getMessage()); 
      } 
      try { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
       StringBuilder builder = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        builder.append(line + "\n"); 

       } 
       is.close(); 
       result = builder.toString(); 
      } catch (Exception e) { 
       Log.e("ERROR", "Error converting result " + e.toString()); 
      } 
      try { 
       result = result.substring(result.indexOf("[")); 
       JSONArray jsonArray = new JSONArray(result); 
       for (int i = 0; i < jsonArray.length(); i++) { 
        JSONObject jsonObject = jsonArray.getJSONObject(i); 
        Map<String, Integer> temmap = new HashMap<>(); 
        String temname = jsonObject.getString("Name"); 
        temmap.put("First", jsonObject.getInt("First")); 
        temmap.put("Second", jsonObject.getInt("Second")); 
        temmap.put("Third", jsonObject.getInt("Third")); 
        Log.e("ERROR", temmap.get("First").toString()); 
        cart_names1.put(temname, temmap); 

       } 
       strhold2.clear(); 
       strhold2.add("First"); 
       strhold2.add("Second"); 
       strhold2.add("Third"); 


       String[] strhold1 = new String[strhold2.size()]; 
       for (int i56 = 0; i56 < strhold2.size(); i56++) { 
        strhold1[i56] = strhold2.get(i56); 
       } 
       System.out.println(cart_names1); 
       Log.e("ERROR", Integer.toString(cart_names1.size()) + "IN LATEST"); 
       if (cart_names1.size() > 1) { 
        System.out.println(cart_names1.size()); 
        System.out.println(strhold2.size()); 
        Combination.printCombination(cart_names1, strhold1, strhold2.size(), cart_names1.size(), 2); 
        ArrayList<String> wrong = Permutation.getlist(); 
        System.out.println(wrong + "this is final"); 
        setalldata(wrong); 
        System.out.println(wrong); 
        couldthis.clear(); 
        couldthis.addAll(wrong); 
       } else { 
        Single_Permutation.getpermute(cart_names1); 
        System.out.println(Single_Permutation.singlelist); 
        couldthis.clear(); 
        couldthis.addAll(Single_Permutation.singlelist); 
        setalldata(Single_Permutation.singlelist); 
        Log.e("ERROR", "thisis the list 1" + getdataformap()); 
       } 

      } catch (Exception e) { 
       Log.e("ERROR", "Error pasting data " + e.toString()); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      /*SetMap setMap = new SetMap(getdataformap()); 
      setMap.execute();*/ 
      if (pd != null){ pd.dismiss();} 
       ListFragment.addtolist(getdataformap()); 
       Log.e("ERROR", "This is putmap i" + getdataformap()); 
       SetMap setMap =new SetMap(getdataformap()); 
       setMap.execute(); 
      } 
     } 

    } 

조각을 (확장 목록)

public static class ListFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     public static ExpandableListView expandablelistview; 
     public static CustomExpandableListAdapter expandableadapter; 
     public static HashMap<Fitems, List<Fnitems>> datapforput = new HashMap<>(); 
     public static List<Fitems> mainforput = new ArrayList<>(); 
     public static View view; 
     public static Context getha; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      view = inflater.inflate(R.layout.activity_listfragment, container, false); 
      //doddata(); 
      expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView); 
      expandableadapter = new CustomExpandableListAdapter(((Result) getActivity()).getha(), mainforput, datapforput); 
      expandablelistview.setAdapter(expandableadapter); 
      getha = ((Result) getActivity()).getha(); 
      return view; 
     } 

     @Override 
     public void onStart() { 
      super.onStart(); 
      Permutation.finallist = new ArrayList<>(); 
      Single_Permutation.singlelist = new ArrayList<>(); 
    /* doddata(); 
    expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView); 
    expandableadapter = new CustomExpandableListAdapter(((Result)getActivity()).getha(),mainforput,datapforput); 
    expandablelistview.setAdapter(expandableadapter);*/ 
     } 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static void doddata() { 
      Fitems fitems1 = new Fitems(); 
      Fitems fitems2 = new Fitems(); 
      Fnitems fnitems1 = new Fnitems(); 
      Fnitems fnitems2 = new Fnitems(); 
      Fnitems fnitems3 = new Fnitems(); 
      Fnitems fnitems4 = new Fnitems(); 
      fitems1.setName("AAA"); 
      fitems2.setName("BBB"); 
      fnitems1.setName("AAAa"); 
      fnitems2.setName("AAAb"); 
      fnitems3.setName("BBBa"); 
      fnitems4.setName("BBBb"); 
      List<Fnitems> listfnitem1 = new ArrayList<>(); 
      List<Fnitems> listfnitem2 = new ArrayList<>(); 
      listfnitem1.add(fnitems1); 
      listfnitem1.add(fnitems2); 
      listfnitem2.add(fnitems3); 
      listfnitem2.add(fnitems4); 
      datapforput.put(fitems1, listfnitem1); 
      datapforput.put(fitems2, listfnitem2); 
      mainforput.add(fitems1); 
      mainforput.add(fitems2); 
      //Log.e("ERROR", "thisis the list for god's sake " + Result.couldthis+datapforput.toString()); 
      if (Result.couldthis.size() > 0) { 
       for (int i = 0; i < (Result.couldthis).size(); i++) { 
        for (Map.Entry<Fitems, List<Fnitems>> entry : datapforput.entrySet()) { 
         if (Result.couldthis.get(i).equals(entry.getKey().getName())){ 
          Fnitems fnitems5 = new Fnitems(); 
          fnitems5.setName(Search_multiple.cart_records.get(i).getName()); 
          entry.getValue().add(fnitems5); 
         }else { 
          Fitems fitems3 = new Fitems(); 
          fitems3.setName(Result.couldthis.get(i)); 
          Fnitems fnitems5 = new Fnitems(); 
          fnitems5.setName(Search_multiple.cart_records.get(i).getName()); 
          List<Fnitems> listfnitem3 = new ArrayList<>(); 
          listfnitem3.add(fnitems5); 
          datapforput.put(fitems3, listfnitem3); 
          mainforput.add(fitems3); 
         } 
        } 
       } 
      } 
     } 

     public static ListFragment newInstance() { 
      ListFragment fragment = new ListFragment(); 
      Log.e("ERROR", "man .... " + fragment.getTag()); 
      return fragment; 
     } 

     public static void addtolist(ArrayList<String> dataforputting) { 
      // Log.e("ERROR", "thisis the list 3" + (dataforputting)); 
      //if (expandableadapter != null){ 
      expandableadapter.clear();//} 
      //Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput); 
      doddata(); 
      //Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput); 
      expandableadapter = new CustomExpandableListAdapter(getha, mainforput, datapforput); 
      expandablelistview.setAdapter(expandableadapter); 
     } 


    } 

스택

07-13 18:16:11.955 17339-17339/nf.co.riaah.chutte E/ERROR: Inside populate Second 
07-13 18:16:11.986 17339-17339/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main 
                    Process: nf.co.riaah.chutte, PID: 17339 
                    java.util.ConcurrentModificationException 
                     at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787) 
                     at java.util.HashMap$EntryIterator.next(HashMap.java:824) 
                     at java.util.HashMap$EntryIterator.next(HashMap.java:822) 
                     at nf.co.riaah.chutte.Result$ListFragment.doddata(Result.java:199) 
                     at nf.co.riaah.chutte.Result$ListFragment.addtolist(Result.java:230) 
                     at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:1049) 
                     at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:967) 
                     at android.os.AsyncTask.finish(AsyncTask.java:636) 
                     at android.os.AsyncTask.access$500(AsyncTask.java:177) 
                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653) 
                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                     at android.os.Looper.loop(Looper.java:139) 
                     at android.app.ActivityThread.main(ActivityThread.java:5298) 
                     at java.lang.reflect.Method.invoke(Native Method) 
                     at java.lang.reflect.Method.invoke(Method.java:372) 
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
+0

아마도 대신 해시 테이블을 사용하십시오. HashMap은 동시 액세스에 안전하지 않습니다. – ManoDestra

답변

0

이 노력하는 동안 컬렉션을 수정하고 있다는 것을 의미 다음과 같이 내 코드는 그것을 반복 할 수 있습니다. 같은 장소에 모두있을 수도 있고 다른 스레드에서있을 수도 있습니다.

+0

나는 그것에 익숙하지만 코드에서 어디에서 일어나고 있는지 그리고 어떻게 멈출 수 있는지를 알 수는 없다. –

+0

코드를 살펴보고 컬렉션을 반복하면서 어디에서 추가 또는 제거하는지 살펴 본다. 그 수집 물에서 물건. 그런 다음 이들이 동시에 일어날 수있는 장소를 찾습니다. 불행히도 처음부터 이것을 염두에 두지 않으려한다면 추적하기가 어렵습니다. – CaseyB

+0

나는 수많은 장소에서 반복되지만 다른 컬렉션에서는 문제가 발생합니까 ??? –

0

은 일반적으로 오류가 빠르며 컬렉션을 변경할 수 없습니다 (내부적으로 반복자를 사용할 때마다).

사용하는 대신 "에 대한 (의 Map.Entry> 항목 : datapforput.entrySet을())"

는 반복자를 만든 다음 다시지도를 반복, 새로 만든 entrySet에 반복자 참조를 할당하는 것을 잊지 마세요 . while 루프를 반복 할 때마다 iterartor 참조를 매번 재 할당하면됩니다.

}

+0

위의 코드를 어떻게 수행 할 수 있습니까? –

관련 문제