Android.Os.Networkonmainthreadexception . Need to Use Async Task

Why I am getting android.os.NetworkOnMainThreadException with AsyncTask?

public class Background_confirmation extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();

progressDialog = ProgressDialog.show(Confirmation.this, "Please wait...", "Retrieving data ...", true);

}

@Override
protected String doInBackground(Void... params) {

try {
HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://68.121.167.160/sip_chat_api/create_account.php?useralias=" + useralias + "&cntname=" + cntcode + "");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
e.printStackTrace();
}
if (backgroung_flag == 1) {

} else {
if (is != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();

result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
return result;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}

Your code should change like above. Things you have to consider

  • Connectivity should code inside doInBackground()
  • If you want to get the result of the doInBackground(), you have to take it in onPostExecute()
  • That means you have to return a String value in doInBackground() where your third parameter of AsyncTask class should be String too (which is not in Wayne's answer)

In your code, you are calling a InputStream that we cannot see except in the "else" part. If you are using only that InputStream, make sure code always reach the else part.

Using AsyncTask and still getting NetworkOnMainThreadException

Use this

NetworkRequest networkRequest = new NetworkRequest();
networkRequest.execute(API_URL);

Instead of this

NetworkRequest networkRequest = new NetworkRequest();
networkRequest.doInBackground(API_URL);

NetworkOnMainThreadException in AsyncTask

I think you are getting the error because although you get a reference to the InputStream in your background thread, you actually read from the stream when you call decodeStream in onPostExecute, which runs on the main thread

Move the call:

Bitmap bitmap = BitmapFactory.decodeStream(inputstream);

into doInBackground and pass the bitmap back rather than the inputstream

android.os.NetworkOnMainThreadException in AsyncTask's doInBackground

By calling doInBackground() directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.

NetworkOnMainThreadException even with AsyncTask

I figured it out, finally. Apparently when a variable is given a value in the main thread from a method, it doesn't matter if the method used, in my case NetworkHandling.getOptions(), uses AsyncTask to temporarily open a new thread. It will still see this as using networking in the main thread.

I solved it by removing the AsyncTask from my NetworkHandling class and replacing it with a regular method that does the networking. Then in the fragment, I created a method in which i put an AsyncTask that called on the network handling methods, like so:

private ArrayList<String> options;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ListView listView = new ListView(getActivity());
options = new ArrayList<>();
getOptions();
adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, options);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return listView;
}

private void getOptions(){
new AsyncTask<Void,Void,ArrayList<String>>(){
@Override
protected ArrayList<String> doInBackground(Void... params) {
String input = NetworkHandling.getJsonInput("http://tddd80-afteach.rhcloud.com/api/groups");
return JsonParser.getGroups(input);
}

@Override
protected void onPostExecute(ArrayList<String> groups) {
options.addAll(groups);
adapter.notifyDataSetChanged();
}
}.execute();
}

android.os.NetworkOnMainThreadException inside AsyncTask

Move the JSON code into doInBackground():

@Override
protected HttpResponse doInBackground(String... params) {
...
Your current HttpPost code...
...
Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
...
}

Android NetworkOnMainThreadException AsyncTask

Pass your point as parameter to AsyncTask.

@Override
public void onCreate(Bundle savedInstanceState) {
mMapView.setOnSingleTapListener(new OnSingleTapListener() {
public void onSingleTap(float x, float y) {
Point point = mMapView.toMapPoint(x, y);
Log.e("Coord", point.toString());
new MyAsyncTask().execute(point);
}
});
}

private class MyAsyncTask extends AsyncTask<Point, Integer, Double> {
@Override
protected Double doInBackground(Point... params) {
if(params.length == 1) {
try {
eventCtrl.createEvent(params[0].toString());
eventCtrl.retrieveEventJSON();
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}

protected void onPostExecute(Double result) {
}

protected void onProgressUpdate(Integer... progress) {
}
}

android.os.NetworkOnMainThreadException in AsynkTask Class

You merely getting a reference of HttpResponse in doInBackground. but all the read/write operations on HttpResponse also involves network operation. and you are reading from HttpResponse in onPOstExecute() which runs in UI Thread. and try this...

public class NetworkDocStateThread extends AsyncTask<String, Void, Void> {

@Override
protected Void doInBackground(String... params) {

try {
HttpResponse responseState = JsonDocumnet
.SendDocumentState(Financial.selectedGuId);
Financial.documnetStateDs = JsonDocumnet
.DocumentState(responseState);
} catch (Exception ex) {
ex.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void post) {
try {

documentStateSpinner.add(Financial.documnetStateDs.get(i)
.getTitle());

SpinnerStateAdapter = new ArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid,
documentStateSpinner);

SpinnerNumAdapter = new ArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid, getResources()
.getStringArray(R.array.numPerPage));

SpinnerSortAdapter = new ArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid, getResources()
.getStringArray(R.array.SortBy));

new NetworkDocThread().execute(Financial.selectedGuId, "5",

"0", "Id", "-1");

docStateSpinner.setAdapter(SpinnerStateAdapter);
NumberPerPageSpinner.setAdapter(SpinnerNumAdapter);
SortBySpinner.setAdapter(SpinnerSortAdapter);

} catch (IllegalStateException e) {

e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

super.onPostExecute(post);
}

}


Related Topics



Leave a reply



Submit