我意识到,当你试图做一些在UI线程网络请求的这种错误发生,但你可以在code见下面我实际调用HTTP GET在AsyncTask的:
公共类LeftPaneFragment扩展片段{ 私人ImageView的_profileImage; @覆盖 公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){ 查看查看= inflater.inflate(wj.tweetTab.R.layout.left_pane,集装箱); _profileImage =(ImageView的)view.findViewById(R.id.profileImage); setUpProfileInfo(视图); 返回视图。 } 私人无效setUpProfileInfo(查看视图){ 新SetUpUserInfo()doInBackground(); } 私有类SetUpUserInfo扩展的AsyncTask<无效,无效的,可绘制> { @覆盖 保护可绘制doInBackground(虚空...... PARAMS){ DefaultHttpClient的HttpClient =新DefaultHttpClient(); HTTPGET请求=新HTTPGET(_model.UserInfo.ProfileImageUrl); 为InputStream的InputStream = NULL; 尝试{ HTT presponse响应= httpClient.execute(请求); 的InputStream = response.getEntity()的getContent()。 } 赶上(例外五){ Log.e(setUpUserInfo.doInBackground,e.getMessage()); } 返回Drawable.createFromStream(InputStream中,SRC); } @覆盖 保护无效onPostExecute(可绘制结果){ _profileImage.setImageDrawable(结果); } }}
任何人都可以看到任何明显的问题吗?还可以在 NetworkOnMainThreadException
抛出异常其他任何理由这样做比在主线程的http请求?
我是一个新人到Android,只能一直用它几天。
解决方案但你可以在code见下面我实际调用的Http 获取在的AsyncTask
你不是,其实。你需要调用的execute()
不是调用 doInBackground()
直接,否则你不使用任何的所提供水暖的AsyncTask
,和你只是直接调用在UI线程的方法。
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.
解决方案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.