Reputation: 727
I have some code that converts my HTTPResponse
Object into a JSONObject
, which works fine most of the time:
public static JSONObject httpResponseToJson(HttpResponse response) {
if (response != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));
String json = reader.readLine();
if (json != null) {
JSONObject jsonObject = new JSONObject(json);
printStatus(jsonObject);
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
However, sometimes it throws a the Android NetworkOnMainThread exception
. I cannot figure out why, because the response is already finished and there should not be any more network IO involved in that call. For test reasons, if I allow NetworkOnMainThread
, this method works fine all the time.
Note that all the HTTPResponse
is fetched with an AsyncTask
and this is working fine.
I am very interested in any suggestions.
Upvotes: 1
Views: 163
Reputation: 13761
Reading the response from a HttpResponse
object also involves a Network Operation
. Simply process that also in the doInBackground()
method and modify your AsyncTask
to pass to the onPostExecute()
the real result once processed.
Upvotes: 1
Reputation: 5068
its mean you are performing some network operation on main thread.The point here is Unless the stream is not closed, you are still performing network operation so move that part into doInBackGround()
too.
Upvotes: 0