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.
You’re not, actually. You need to call
execute()instead of callingdoInBackground()directly, otherwise you’re not using any of the plumbing provided by theAsyncTask, and you’re just calling the method directly in the UI thread.