我想获取json数据并通过gson解析它们。我能够做正确的解析,但是对于我做的一个例子,我得到了这个错误:
android.os.NetworkOnMainThreadException
我知道不允许在UI线程上使用internet
。
我的例子很简单:
在活动的onCreate
中是代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kategoriListView =(ListView)findViewById(R.id.kategoriListView);
new GetPlacesAsync().execute(placesUrl);
}
在AsyncTask上:
class GetPlacesAsync extends AsyncTask<String, Void, InputStream>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected InputStream doInBackground(String... params) {
DefaultHttpClient client = new DefaultHttpClient();
String url = params[0];
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
@Override
protected void onPostExecute(InputStream inputStream) {
super.onPostExecute(inputStream);
Reader reader = new InputStreamReader(inputStream);
Gson gson = new Gson();
try
{
PlacesContainer places = gson.fromJson(reader, PlacesContainer.class);
Toast.makeText(MainActivity.this, Integer.toString(places.getCountPlaces()), Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, places.message , Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e("READ_PLACES_ERROR", e.toString());
}
}
}
我的错误出现在我使用try
catch
阻止的行上。
答案 0 :(得分:1)
onPostExecute在UI线程上执行。
在doInBackground中读取您的InputStream。