Apologies if this is a simple question but I am very new to this and still learning.
I have an app and when my users click the button to login after entering their d
It would be something like this
public class TalkToServer extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
/*
* do things before doInBackground() code runs
* such as preparing and showing a Dialog or ProgressBar
*/
}
@Override
protected void onProgressUpdate(Void... values) {
/*
* updating data
* such a Dialog or ProgressBar
*/
}
@Override
protected Void doInBackground(Void... params) {
//do your work here
return null;
}
@Override
protected void onPostExecute(Void result) {
/*
* do something with data here
* display it or send to mainactivity
* close any dialogs/ProgressBars/etc...
*/
}
}
Then you can execute it with
TalkToServer myTask = new MyTask(); // can add params for a constructor if needed
myTask.execute(); // here is where you would pass data to doInBackground()
You may not need onProgressUpdate()
or onPreExecute()
if you aren't using them to show a Dialog
, progress, or other tasks before or during doInBackground()
.
onPreExecute() can be used to initialize and show a ProgressDialog
. Then it could be dismissed in onPostExecute()
After a task finishes
onPostExecute()
will be called. If the class is an inner-class of your Activity
then you can update UI
elements there or call a function to run code once the task finishes. If it is a separate file than the Activity
then you can use an interface
and create a callBack
to the Activity
and run code there once the task finishes.
This answer talks about using an interface for a callback if you need
Make sure any UI
updating is done in any method besides doInBackground()
or sent back to the Activity
in any function besides doInBackground()
. Heavy-lifting such as network operations should be done in doInBackground()
.
Also, be sure to read through the AsyncTask Docs completely. Especially the Threading Rules