jcvandan
jcvandan

Reputation: 14314

android.os.NetworkOnMainThreadException in AsyncTask

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.

Upvotes: 9

Views: 8461

Answers (2)

tw2050
tw2050

Reputation: 19

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;

Upvotes: 1

dmon
dmon

Reputation: 30168

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.

Upvotes: 23

Related Questions