The AsyncTask class implements a best practice pattern for moving time consuming (but short lived) processing to a background thread and synchronising back to the UI thread, to apply updates to the UI, when complete. Note that such tasks do not persist across Activity restarts so for example will be cancelled if the orientation of your device changes.
However, if you don't need to update the UI as part of your background task (which appears to be the case here), then just use the normal Thread class which is much simpler to implement (edit: code added for updating the UI from a background thread):
Handler handler = new Handler(); //Optional. Define as a variable in your activity.
Runnable r = new Runnable()
{
@Override
public void run()
{
// your code here
handler.post(new Runnable() //If you want to update the UI, queue the code on the UI thread
{
public void run()
{
//Code to update the UI
}
});
}
};
Thread t = new Thread(r);
t.start();
Note that this type of threading does persist across activity restarts so it should usually run to completion.
To do this as an AsyncTask (which may be a better choice if the UI needs to be updated) the same thing can be achieved by:
In your activity, create an instance of your Async class and execute.
SaveData save = new SaveData();
save.execute();
Subclass AsyncTask as a private class within your activity
private class SaveData extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... params) {
// your background code here. Don't touch any UI components
if(your code worked...)
return true;
else
return false;
}
protected void onPostExecute(Boolean result) {
//This is run on the UI thread so you can do as you wish here
if(result)
Toast successful
else
Toast unsuccessful
}
}