Using A Handler / Asynctask Or Similar To Run A Networking Task
i am aware that the error is occurring because im trying to put a network call on the main thread so i need to use a handler or asynctask however i dont seem to be able to get it r
Solution 1:
Something like
publicclassTalkToServerextendsAsyncTask<String, String, String> {
@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();
}
@OverrideprotectedvoidonProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@OverrideprotectedStringdoInBackground(String... params) {
//do your work herereturn something;
}
@OverrideprotectedvoidonPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
Do all heavy-lifting in doInBackground()
and you can update the UI in the other 3 methods.
Here is the documentation on AsyncTask
Solution 2:
Create and instantiate the AsyncTask in the onClick method. Put the call (and the wait) for the url call in the doOnBackground method and do whatever you want with the response in the onPostExecute (which happens in the main thread again).
Post a Comment for "Using A Handler / Asynctask Or Similar To Run A Networking Task"