我正在尝试使用Android中的HttpClient从远程站点获取资源。我一直在尝试以下
public class Engine {
public String test(){
String engineUrl = "http://site/path"; //I used legit site and path here
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet req = new HttpGet(engineUrl);
HttpResponse response = httpclient.execute(req); <<----this
//is = response.getEntity().getContent();
}catch(Exception e){
e.printStackTrace();
Log.e("error", "err");
}
return result;
}
每当我尝试执行给定的标记方法时,我都会收到错误。如果我不执行.execute()方法,一切正常。
我的调用片段是:
public class mainFragment extends Fragment{
View view = null;
Context context = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_main, container, false);
context = getActivity().getApplicationContext();
final TextView v = (TextView)view.findViewById(R.id.hello);
Thread t = new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
Engine e = new Engine();
v.setText(e.test());
}
};
t.run();
return view;
}
}
非常感谢!!
谢谢大家,我想我解决了这个问题。我必须使用AsyncTask&lt;&gt;对于网络操作而言不是线程类。再次感谢
答案 0 :(得分:1)
你不能打电话
v.setText(e.test())
在
run().
由于UI更改必须在UI线程中完成。试试
final String result = e.test():
runOnUiThread(new Runnable(){
private void run (){
v.setText(result);
}
}).