Android : Network On Main Thread Exception Even When Using Asynctask
Solution 1:
executeRestLogin.doInBackground();
Call execute()
to execute an async task on a background thread. Calling doInBackground()
directly just runs the method on your current thread.
how can I get custom objects back as response from async task
Put the code that deals with async task results in onPostExecute()
. It gets run on the UI thread.
Solution 2:
You are calling doInBackground form the UI therad! In order to start an AsyncTask you need to call execute. executeRestLogin.execute()
Edit:
Dont forget conventions a class starts with an upper case.
Call execute on the AysnTask object will start the task. This tutorial will make it clearer.
Solution 3:
You should replace the doInBackground() by execute(). With that the code in doInBackground method will be executed in another thread.(you should not create a new thread, Android does it for you.)
Solution 4:
Change your code like:
privateclassExecuteRestLoginextendsAsyncTask<Void,Void,Boolean> {
@OverrideprotectedBooleandoInBackground(Void... params) {
HttpHeaders requestHeaders = newHttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
HttpEntity<String> requestEntity = newHttpEntity<>(requestHeaders);
HttpEntity<String> rssResponse = rest.exchange(
"http://192.168.178.60:8080/dashboard",
HttpMethod.GET,
requestEntity,
String.class);
StaticRestTemplate.jsessionid = rssResponse.getBody();
result = StaticRestTemplate.jsessionid; // result is a global String.returntrue;
}
@OverrideprotectedvoidonPostExecute(final Boolean success) {
if (success) {
//You can use your result string now.
}
}
}
Post a Comment for "Android : Network On Main Thread Exception Even When Using Asynctask"