2014-01-14 2 views
0

Вот класс AsyncTask внутри моего фрагмента, и когда я нажимаю на фрагмент, я получаю эту ошибку: NetworkOnMainThread Exception (я не могу опубликовать изображение, потому что моя репутация недостаточно высока)NetworkOnMainThread Exception Брошено даже с AsyncTask

private class me extends AsyncTask<Object,Void,Boolean>{ 
      DisplayMetrics dm = new DisplayMetrics(); 

      protected void onPreExecute(){ 
       String sess = SignIn.giveSession().getSession().getToken(); 


       deviceId = device.getDeviceId(); 
       data = RestQuery.profileImage(sessionToken, deviceId, username); 
       bm = BitmapFactory.decodeByteArray(data,0,data.length); 
       getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); 


       username = reWiPr.getName(); 



      } 

      protected Boolean doInBackground(Object... stuff){ 
       if(reWiPr == null){ 
        return false; 
       } 

       return true; 
      } 

      protected void onPostExecute(Boolean results){ 
       if(results){ 
        image.setMinimumHeight(dm.heightPixels); 
        image.setMinimumWidth(dm.widthPixels); 
        image.setImageBitmap(bm); 

        uName.setText(reWiPr.getName()); 
        rName.setText(reWiPr.getRealName()); 
        safety.setText("Safety: " + reWiPr.getRating().getSafe()); 
        time.setText("Time: " + reWiPr.getRating().getTime()); 
        courteous.setText("Courteous: " + reWiPr.getRating().getCourteous()); 
        cleanliness.setText("Cleanliness: " + reWiPr.getRating().getClean()); 
        overall.setText("Overall: " + reWiPr.getRating().getOverall()); 
        average.setText("Average: " + reWiPr.getRating().getAverage()); 
        ve.setText("Vehicles: " + reWiPr.getVehicle()); 


       } 
      } 

Как исправить это? Мне нужен этот AsyncTask, чтобы сделать фрагмент, и я выполняю его в методе onCreate(). Любая помощь была бы признательна. *

ответ

3

Вы не выполняете сетевой вызов в правильном методе. Вы должны перевести свой сетевой вызов в doInBackground, который я вижу сейчас в onPreExecute.

Из документации:

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
+0

Мой сетевой вызов - это с RestQuery, и я переместил его на doInBackground, но я все равно получаю ту же ошибку. – shreyashirday

+0

@ user3140562: можете ли вы опубликовать свой новый код? – Nerd

+0

Оказывается, я использую метод из другого класса, который использует вызов данных вне doInBackground. Есть ли способ создать метод внутри doInBackground для AsyncTask, а затем вызвать этот метод в другом отдельном классе (а не в родительском классе)? – shreyashirday

0

Вы должны сделать свои сетевые задачи в методе doInBackground. На данный момент у вас есть onPreExecute, который работает в потоке графического интерфейса пользователя.

Смежные вопросы