I want to get json data and parse them through gson. I am able to do the correct parsing, but for one example that I did, I got this error:
android.os.NetworkOnMainThreadException
I know that using internet
on UI thread is not allowed.
My example is simple:
In onCreate
of the activity is the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kategoriListView =(ListView)findViewById(R.id.kategoriListView);
new GetPlacesAsync().execute(placesUrl);
}
And on the 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());
}
}
}
My error is on the lines where I have used try
catch
block.
onPostExecute in executed on the UI thread.
Read your InputStream in doInBackground.