Android.os.networkonmainthreadexception In Asynktask Class
i want to get data from the internet with JSON, i'm using an AsynkTask class to do that and its working, but if i add or change any code and run my program again it stops working
Solution 1:
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...
publicclassNetworkDocStateThreadextendsAsyncTask<String, Void, Void> {
@OverrideprotectedVoiddoInBackground(String... params) {
try {
HttpResponse responseState = JsonDocumnet
.SendDocumentState(Financial.selectedGuId);
Financial.documnetStateDs = JsonDocumnet
.DocumentState(responseState);
} catch (Exception ex) {
ex.printStackTrace();
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(Void post) {
try {
documentStateSpinner.add(Financial.documnetStateDs.get(i)
.getTitle());
SpinnerStateAdapter = newArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid,
documentStateSpinner);
SpinnerNumAdapter = newArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid, getResources()
.getStringArray(R.array.numPerPage));
SpinnerSortAdapter = newArrayAdapter<String>(Documnet.this,
R.layout.spinnlayout, R.id.docstateid, getResources()
.getStringArray(R.array.SortBy));
newNetworkDocThread().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);
}
}
Solution 2:
Try to add this below code on onCreate(Bundle bundle)
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your code
}
Solution 3:
When you perform Network Connection task like fetching data from Server in Main Thread then this issue comes. It is recommended to perform such tasks in doInbackground()
method of AsyncTask
or you can also avoid this issue by putting the code below in onCreate()
of Activity :
StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
I hope it would solve your problem when you have already written lots of code in Main Thread.
Post a Comment for "Android.os.networkonmainthreadexception In Asynktask Class"