2012-08-28 16 views
6

मुझे android.os.NetworkOnMainThreadException मिल रहा है, जबकि मैंने AsynkTask में नेटवर्किंग ऑपरेशन का कोड लिखा है। क्या इस अपवाद को फेंकने का कोई अन्य कारण है?मुझे एंड्रॉइड.ओएस.नेटवर्कऑनमेन थ्रेड अपवाद क्यों AsyncTask के साथ मिल रहा है?

यहाँ मेरी कोड है:

public class Background_confirmation extends AsyncTask<Void, Integer, Void> { 
     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      progressDialog = ProgressDialog.show(Confirmation.this, 
        "Please wait...", "Retrieving data ...", true); 
      try { 
       HttpClient httpclient = new DefaultHttpClient(); 

       HttpPost httppost = new HttpPost(
         "http://68.121.167.160/sip_chat_api/create_account.php?useralias=" 
           + useralias + "&cntname=" + cntcode + ""); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 


      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      if (backgroung_flag == 1) { 

      } else { 
       if (is != null) { 
        try { 
         BufferedReader reader = new BufferedReader(
           new InputStreamReader(is, "UTF-8")); 
         StringBuilder sb = new StringBuilder(); 
         String line = null; 
         while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
         } 
         is.close(); 

         result = sb.toString(); 
        } catch (Exception e) { 
         Log.e("log_tag", 
           "Error converting result " + e.toString()); 
        } 
       } 

      } 
      super.onPreExecute(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      // TODO Auto-generated method stub 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 
      if (progressDialog.isShowing()) { 
       progressDialog.dismiss(); 
       // progressDialog.setCancelable(true); 
      } 
      super.onPostExecute(result); 
     } 

    } 

और मुझे OnCreate में इस वर्ग()

new Background_confirmation().execute(); 

बोल रहा हूँ लेकिन यह हमेशा पकड़ने ब्लॉक में चला जाता है और मुझे this अपवाद LogCat
देता है किसी भी सुझाव और विचार की सराहना की जाएगी।
धन्यवाद

+0

इन Async कार्य के लिए Android क्वेरी बाहर की जाँच करें, यह सब सरल करता है। – jasonflaherty

उत्तर

4
public class Background_confirmation extends AsyncTask<Void, Integer, String> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      progressDialog = ProgressDialog.show(Confirmation.this, "Please wait...", "Retrieving data ...", true); 

     } 

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

      try { 
       HttpClient httpclient = new DefaultHttpClient(); 

       HttpPost httppost = new HttpPost("http://68.121.167.160/sip_chat_api/create_account.php?useralias=" + useralias + "&cntname=" + cntcode + ""); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      if (backgroung_flag == 1) { 

      } else { 
       if (is != null) { 
        try { 
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
         StringBuilder sb = new StringBuilder(); 
         String line = null; 
         while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
         } 
         is.close(); 

         result = sb.toString(); 
        } catch (Exception e) { 
         Log.e("log_tag", "Error converting result " + e.toString()); 
        } 
       } 
      } 
      return result; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      if (progressDialog.isShowing()) { 
       progressDialog.dismiss(); 
       // progressDialog.setCancelable(true); 
      } 
     } 
    } 

आपका कोड ऊपर की तरह बदलना चाहिए। चीजें आप आप doInBackground() का परिणाम प्राप्त करना चाहते हैं पर विचार करने के

  • कनेक्टिविटी के अंदर doInBackground()
  • कोड चाहिए है, तो आप onPostExecute()
  • में ले जाने के लिए इसका मतलब है कि आप में एक स्ट्रिंग मान वापस लौटाना होगा है doInBackground() जहां AsyncTask वर्ग के अपने तीसरे पैरामीटर स्ट्रिंग भी (जो वेन के जवाब में नहीं है)

अपने कोड में किया जाना चाहिए, तो आप एक InputStream बुला रहे हैं कि हम "अन्य" भाग को छोड़कर नहीं देख सकते हैं। यदि आप केवल InputStream का उपयोग कर रहे हैं, तो सुनिश्चित करें कि कोड हमेशा दूसरे भाग तक पहुंच जाए।

+0

धन्यवाद यह बहुत बढ़िया काम किया! अगर मैं सख्त मोड नीति को अक्षम करने के लिए दीपक केशरिया के कोड का उपयोग करता हूं तो क्या यह मेरे आवेदन के प्रदर्शन को धीमा कर देगा? चूंकि स्ट्रिक्टोड को अक्षम करते समय यह लॉग में बहुत सी रेखा दिखाता है। आपकी राय क्या है> – juned

+1

'सख्त मोड' का उपयोग करते समय बहुत सारे कोडिंग को दिखाने के लिए सामान्य है। कुछ हद तक रनटाइम पर प्रदर्शन की जांच करने के लिए आप ** ग्रहण ** ** ** आवंटन ट्रैकर ** ** अपने ग्रहण में ** डीडीएमएस ** मोड में विचारों का उपयोग कर सकते हैं। – AnujAroshA

4

आपने अपने नेटवर्क से संबंधित कोड को रखने के लिए गलत AsyncTask विधि का उपयोग किया है। कृपया इसे doInBackground पर ले जाएं, क्योंकि onPreExecute मुख्य धागे पर होता है। तो, अपवाद हुआ। विवरण here हैं।

+0

प्रतिक्रिया के लिए धन्यवाद लेकिन अगर मैं कोड को doInBackground() में डालता हूं तो मुझे वांछित परिणाम नहीं मिल रहा है – juned

+0

'वांछित परिणाम' से आपका क्या मतलब है? – sandrstar

1

अपने सभी नेटवर्क अनुरोध कोड को doInBackground पर रखें। onPreExecute और onPostExecute यूआई थ्रेड (मुख्य थैड) पर चलेंगे, इसलिए यदि आप इन 2 विधियों पर नेटवर्क का अनुरोध करते हैं तो आपको एक एक्सपशन मिलेगा।

public class Background_confirmation extends AsyncTask<Void, Integer, Void> { 
    @Override 
    protected void onPreExecute() {    
     progressDialog = ProgressDialog.show(Confirmation.this, 
       "Please wait...", "Retrieving data ...", true);    

    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 

     try { 
      HttpClient httpclient = new DefaultHttpClient(); 

      HttpPost httppost = new HttpPost(
        "http://68.121.167.160/sip_chat_api/create_account.php?useralias=" 
          + useralias + "&cntname=" + cntcode + ""); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     if (backgroung_flag == 1) { 

     } else { 
      if (is != null) { 
       try { 
        BufferedReader reader = new BufferedReader(
          new InputStreamReader(is, "UTF-8")); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        is.close(); 

        result = sb.toString(); 
       } catch (Exception e) { 
        Log.e("log_tag", 
          "Error converting result " + e.toString()); 
       } 
      } 

     } 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     if (progressDialog.isShowing()) { 
      progressDialog.dismiss(); 
      // progressDialog.setCancelable(true); 
     } 

    } 

} 
0

दोस्तों मैं doInBackground में मेरे नेटवर्क काम() अभी भी इस लाइन BitmapFactory.decodeStream पर यह त्रुटि मिलती मेरे बारे में क्या कर रहा हूँ (url.openConnection() getInputStream()।);
मेरी कोड

नीचे
@Override 
    protected Void doInBackground(Void... voids) { 
     try { 
      RequestQueue queue = Volley.newRequestQueue(con); 
      StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        Log.e("Response: ",response.toString()); 
        //mProgressDialog.dismiss(); 

        try{long count; 
         String[] projection = { 
           columnid, 
           columnimage, 
           columnttitle, 
           columndesription, 
           columnurl 
         }; 
         SQLiteDatabase db=mdbHelper.getReadableDatabase(); 
         Cursor cursor=db.query(tablename, 
           projection, 
           null, 
           null, 
           null, 
           null, 
           null); 
         count=cursor.getCount(); 
         JSONObject jObject=new JSONObject(response); 
         String status=jObject.getString("status"); 
         String sortby=jObject.getString("sortBy"); 
         if(status.equals("ok")){ 
          JSONArray jsonArray= jObject.getJSONArray("articles"); 
          for(int i=0;i<jsonArray.length();i++){ 
           JSONObject jsonobject=jsonArray.getJSONObject(i); 
           Log.e("InnerData: ",jsonobject.toString()); 
           //NewsModel mDataList = new NewsModel(); 
           //mDataList.setDescription(jsonobject.getString("description")); 
           //mDataList.setTitle(jsonobject.getString("title")); 
           //mDataList.setUrl(jsonobject.getString("url")); 
           //mDataList.setUrltoimage(jsonobject.getString("urlToImage")); 
           cursor.moveToFirst(); 
           if(cursor.moveToFirst()){ 
            Log.d("yes cursor is null", cursor.toString()); 
           }else { Log.d("NO cursor is not null", cursor.toString());} 
           for(int j=0;j<=jsonArray.length();j++){ 
            SQLiteDatabase db1=mdbHelper.getWritableDatabase(); 
            if(count<=0){ 
             Id=1; 
             try { 
              URL url = new URL(jsonobject.getString("urlToImage")); 
              bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
             }catch (IOException e){e.printStackTrace();} 
             byte[] byteimage1=getBytes(bmp); 

             ContentValues values= new ContentValues(); 
             values.put(columnid,Id); 
             values.put(columnimage,byteimage1); 
             values.put(columnttitle,jsonobject.getString("title")); 
             values.put(columndesription,jsonobject.getString("description")); 
             values.put(columnurl,jsonobject.getString("url")); 
             long currentRow_ID=db1.insert(tablename,null,values); 
             if(Id!=currentRow_ID){ 
              Toast.makeText(con,"Error with saving news",Toast.LENGTH_LONG).show(); 
             } 
             else { 
              Toast.makeText(con,"You are having "+currentRow_ID+" News",Toast.LENGTH_LONG).show(); 
             } 
            } 
            if(count>0 && count<40){ 
             cursor.moveToPosition(j); 
             if((!(cursor.getString(cursor.getColumnIndex(columnttitle)).equals(jsonobject.getString("title")))) || (cursor.getInt(cursor.getColumnIndex(columnid))==0) || (cursor.getInt(cursor.getColumnIndex(columnid))==-1)){ 

              try { 
               URL url = new URL(jsonobject.getString("urlToImage")); 
               bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
              }catch (IOException e){e.printStackTrace();} 
              byte[] byteimage1=getBytes(bmp); 
              cursor.moveToLast(); 
              if(cursor.getInt(0)<=0) 
              {Id=1;} 
              else {Id=cursor.getInt(cursor.getColumnIndex(columnid))+1;} 
              ContentValues values= new ContentValues(); 
              values.put(columnid,Id); 
              values.put(columnimage,byteimage1); 
              values.put(columnttitle,jsonobject.getString("title")); 
              values.put(columndesription,jsonobject.getString("description")); 
              values.put(columnurl,jsonobject.getString("url")); 
              long currentRow_ID=db1.insert(tablename,null,values); 
              if(Id!=currentRow_ID){ 
               Toast.makeText(con,"Error with saving news",Toast.LENGTH_LONG).show(); 
              } 
              else { 
               Toast.makeText(con,"You are having "+currentRow_ID+" News",Toast.LENGTH_LONG).show(); 
              } 

             } 

            }else { cursor.moveToPosition(j); 

             if(!cursor.getString(cursor.getColumnIndex(columnttitle)).equals(jsonobject.getString("title"))){ 
              //cursor=db.rawQuery(" SELECT "+columnttitle+" FROM "+tablename+" WHERE "+columnid+" =?",new String[]{ String.valueOf(1) }); 
              db1.delete(tablename,columnid+"=?", new String[] { String.valueOf(1) }); 
              Log.d("record has been deleted",cursor.getString(cursor.getColumnIndex(columnttitle))); 
              long counttt=cursor.getCount(); 
              for(int k=2;k<=counttt;k++){ 
               ContentValues values= new ContentValues(); 
               values.put(columnid,--k); 
               db1.update(tablename,values,columnid +"="+k,null); 
              } 

              cursor.moveToLast(); 
              if(cursor.getInt(cursor.getColumnIndex(columnid))<40) {Id=cursor.getInt(cursor.getColumnIndex(columnid))+1;} 
              else {Toast.makeText(con," Record is not deleted",Toast.LENGTH_LONG).show(); 
               db1.delete(tablename,columnid+"=?", new String[] { String.valueOf(1) }); 
               for(int k=2;k<=counttt;k++){ 
                ContentValues values= new ContentValues(); 
                values.put(columnid,--k); 
                db1.update(tablename,values,columnid +"="+k,null); 
               } 
               Id=cursor.getInt(cursor.getColumnIndex(columnid))+1; 
              } 
              try { 
               URL url = new URL(jsonobject.getString("urlToImage")); 
               bmp1 = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
              }catch (IOException e){e.printStackTrace();} 
              byte[] byteimage1=getBytes(bmp1); 
              ContentValues values= new ContentValues(); 
              values.put(columnid,Id); 
              values.put(columnimage,byteimage1); 
              values.put(columnttitle,jsonobject.getString("title")); 
              values.put(columndesription,jsonobject.getString("description")); 
              values.put(columnurl,jsonobject.getString("url")); 
              long currentRow_ID=db1.insert(tablename,null,values); 
              if(Id!=currentRow_ID){ 
               Toast.makeText(con,"Error with saving news",Toast.LENGTH_LONG).show(); 
              } 
              else { 
               Toast.makeText(con,"You are having "+currentRow_ID+" News",Toast.LENGTH_LONG).show(); 
              } 

             } 
            } 
            if(j>=count){cursor.close(); 
             db1.close();} 
           } 
            /*for(int j=1;j<=count;j++){ 
             NewsModel model=new NewsModel(); 
             Cursor cursor1=db.rawQuery(" SELECT * FROM "+tablename+" WHERE "+columnid+"=?",new String[]{String.valueOf(j)}); 
             model.setTitle(cursor1.getString(cursor1.getColumnIndex(columnttitle))); 
             model.setDescription(cursor1.getString(cursor1.getColumnIndex(columndesription))); 
             model.setUrl(cursor1.getString(cursor1.getColumnIndex(columnurl))); 
             byte[] img = cursor1.getBlob(cursor1.getColumnIndex(columnimage)); 
             Bitmap bitmapimage= BitmapFactory.decodeByteArray(img,0,img.length); 
             model.setimage(bitmapimage); 
             mModelList.add(model); 
            } */ 

          } 

          //recyclerView.setAdapter(new Adapter(MainActivity.this,mModelList)); 

         } 

        }catch (NullPointerException ex){ 
         Log.e("Error ",ex.toString()); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        //mProgressDialog.dismiss(); 
        if (error instanceof TimeoutError || error instanceof NoConnectionError) { 
         Toast.makeText(con, "Failed to fetch data." + 
           " Please check your network connection", Toast.LENGTH_SHORT).show(); 
        } else if (error instanceof AuthFailureError) { 
         //TODO 
        } else if (error instanceof ServerError) { 
         //TODO 
         Log.e("Server error",error.toString()); 
        } else if (error instanceof NetworkError) { 
         //TODO 
         Log.e("Network error",error.toString()); 
        } else if (error instanceof ParseError) { 
         //TODO 
         Log.e("Parse Error ",error.toString()); 
        } 
       } 
      }) { 

       @Override 
       protected Response<String> parseNetworkResponse(NetworkResponse response) { 
        if (response.headers == null) 
        { 
         // cant just set a new empty map because the member is final. 
         response = new NetworkResponse(
           response.statusCode, 
           response.data, 
           Collections.<String, String>emptyMap(), // this is the important line, set an empty but non-null map. 
           response.notModified, 
           response.networkTimeMs); 
        } 

        return super.parseNetworkResponse(response); 
       } 
      }; 

      //*********To Retry sending********************************************* 
      jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(8000, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 

      queue.add(jsonArrayRequest); 

     }catch (NullPointerException ex){ 

     }catch (IllegalFormatException ex){} 
     return null; 
    } 
+0

यदि आपके पास कोई नया प्रश्न है, तो कृपया [प्रश्न पूछें] (https://stackoverflow.com/questions/ask) बटन पर क्लिक करके इसे पूछें। इस प्रश्न का एक लिंक शामिल करें यदि यह संदर्भ प्रदान करने में मदद करता है। - [समीक्षा से] (/ समीक्षा/कम गुणवत्ता वाली पोस्ट/18856472) – rollstuhlfahrer

+0

मेरा प्रश्न इस प्रश्न से संबंधित है इसलिए मैं अपना प्रश्न –

+0

जोड़ता हूं, मुझे इस 'if (android.os.build.VERSION.SDK_INT> 9) { StrictMode.ThreadPolicy नीति = नया StrictMode.ThreadPolicy.builder()। PermitAll()। Build(); StrictMode.setThreadPolicy (नीति); } 'setContentView() के बाद इसे अपने ऑनक्रेट() में जोड़ें; –

संबंधित मुद्दे