Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.os.NetworkOnMainThreadException in AsyncTask

Tags:

java

android

I realise that this error happens when you attempt to do some sort of network request on the UI thread, but as you can see in the code below I am actually calling the Http Get in an AsyncTask:

public class LeftPaneFragment extends Fragment {

    private ImageView _profileImage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(wj.tweetTab.R.layout.left_pane, container);

        _profileImage = (ImageView) view.findViewById(R.id.profileImage);

        setUpProfileInfo(view);

        return view;
    }

    private void setUpProfileInfo(View view) {          
        new SetUpUserInfo().doInBackground();
    }

    private class SetUpUserInfo extends AsyncTask<Void, Void, Drawable> {

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

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(_model.UserInfo.ProfileImageUrl);

            InputStream inputStream = null;

            try {
                HttpResponse response = httpClient.execute(request);        
                inputStream = response.getEntity().getContent();
            }
            catch (Exception e) {               
                Log.e("setUpUserInfo.doInBackground", e.getMessage());
            }

            return Drawable.createFromStream(inputStream, "src");
        }

        @Override
        protected void onPostExecute(Drawable result) {
            _profileImage.setImageDrawable(result);
        }
    }
}

Can anyone see any obvious problems here? Also can the NetworkOnMainThreadException exception be thrown for any other reason than doing a http request in the main thread?

I am a newcomer to Android, only been working with it a few days.

like image 894
jcvandan Avatar asked Sep 13 '11 20:09

jcvandan


People also ask

Is AsyncTask deprecated in Android?

This class was deprecated in API level 30.

What is Android AsyncTask?

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.

What are the three generic types of an AsyncTask?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Is it possible to start AsyncTask from background thread?

Methods of AsyncTaskwe can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods . doInBackground(Params) − In this method we have to do background operation on background thread.


2 Answers

but as you can see in the code below I am actually calling the Http Get in an AsyncTask

You're not, actually. You need to call execute() instead of calling doInBackground() directly, otherwise you're not using any of the plumbing provided by the AsyncTask, and you're just calling the method directly in the UI thread.

like image 68
dmon Avatar answered Nov 10 '22 08:11

dmon


Maybe Android SDK version is to high (version >= 3.0).

Try to add code

import android.os.StrictMode;

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
        .detectDiskReads()   
        .detectDiskWrites()   
        .detectNetwork()   // or .detectAll() for all detectable problems   
        .penaltyLog()   
        .build());  

in onCreateView() function;

like image 42
tw2050 Avatar answered Nov 10 '22 07:11

tw2050