@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://domain.com");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(getActivity(), line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getActivity(), "Caught Exception", Toast.LENGTH_SHORT).show();
}
//Log.i("DATA FROM MYSQL", output);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,countries);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
每次我得到&#34;抓住异常&#34;输出,什么错?
答案 0 :(得分:2)
我敢打赌,你得到的例外是NetworkingOnMainThreadException
。网络操作往往需要一些时间,这就是为什么禁止在Android的主(ui)线程上执行此类操作的原因。这会使UI无响应,从而导致非常糟糕的用户体验。
查看AsyncTask
以便将操作优雅地移动到后台线程。