2012-08-28 23 views
6

Obtendré android.os.NetworkOnMainThreadException mientras escribo el código de la operación de red en AsynkTask. ¿Hay alguna otra razón para lanzar esta excepción?¿Por qué obtengo android.os.NetworkOnMainThreadException con AsyncTask?

Aquí está mi código:

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); 
     } 

    } 

Y estoy llamando esta clase en OnCreate()

new Background_confirmation().execute(); 

Pero siempre va en bloque Catch y me da this excepciones LogCat
Cualquier sugerencia e idea será apreciada.
Gracias

+0

Salida Android de consulta para estas tareas asíncronas, simplifica todo. – jasonflaherty

Respuesta

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); 
      } 
     } 
    } 

El código debería cambiar como la de arriba. Cosas que tienen que considerar

  • Conectividad deberá codificar el interior doInBackground()
  • Si desea obtener el resultado de la doInBackground(), hay que tomarlo en onPostExecute()
  • Eso significa que tiene que devolver un valor de cadena en doInBackground() donde su tercer parámetro de AsyncTask clase debe ser cadena demasiado (que no está en la respuesta de Wayne)

en su código, está llamando a un InputStream que no podemos ver, excepto en la parte "else". Si solo está usando ese InputStream, asegúrese de que el código siempre llegue a la parte else.

+0

¡Gracias funcionó increíble! Si utilizo el código de Dipak Keshariya para desactivar la política strictMode, ¿ralentizará el rendimiento de mi aplicación? Porque al deshabilitar StrictMode, muestra muchas líneas en el registro. ¿Cuál es tu opinión? – juned

+1

Es normal mostrar mucha codificación al usar 'StrictMode'. Para comprobar el rendimiento en tiempo de ejecución en cierta medida, puede utilizar ** Heap **, ** Allocation Tracker ** como las vistas en el modo ** DDMS ** en su Eclipse. – AnujAroshA

4

Has usado el método AsyncTask incorrecto para colocar el código relacionado con tu red. Mueva el archivo al doInBackground, porque onPreExecute se lleva a cabo en el hilo principal. Entonces, la excepción ocurrió. Los detalles son here.

+0

Gracias por responder, pero si pongo el código en doInBackground(), entonces no obtengo el resultado deseado – juned

+0

¿qué quiere decir con 'resultado deseado'? – sandrstar

1

Ponga su código de solicitud de red en doInBackground. onPreExecute y onPostExecute se ejecutará en UI Thread (thead principal) por lo que recibirá una excepción si solicita la red en estos 2 métodos.

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

Guys ¿y yo estoy haciendo mi trabajo en red doInBackground() sigue recibiendo este error en esta línea BitmapFactory.decodeStream (url.openConnection() getInputStream().);
mi código está por debajo

@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

Si tiene una nueva pregunta, por favor, haga clic en el botón [Ask Question] (https://stackoverflow.com/questions/ask). Incluye un enlace a esta pregunta si ayuda a proporcionar contexto. - [De la crítica] (/ review/low-quality-posts/18856472) – rollstuhlfahrer

+0

mi pregunta está relacionada con esta pregunta, así que agrego mi pregunta –

+0

encontré una respuesta a esto 'if (android.os.Build.VERSION.SDK_INT> 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder(). PermitAll(). Build(); StrictMode.setThreadPolicy (política); } 'agregue esto a su onCreate() después de setContentView(); –

Cuestiones relacionadas