HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

AsynTask example

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
exampleasyntaskstackoverflow

Problem

As I was trying to demystify the Android AsyncTask functionalities, I wrote this sample app to test it. Please review my code and suggest possible improvements:

```
public class AsyncTaskExampleActivity extends Activity implements OnClickListener{

private Boolean success = true;
private static AsyncTaskExampleActivity MainActivityInstance;
private CallBack c;
ProgressDialog progressDialog;
Button startAsyncTask;
MyAsyncTask aTask;
Button cancelAsyncTask;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startAsyncTask = (Button)findViewById(R.id.button1);
cancelAsyncTask = (Button)findViewById(R.id.button2);
startAsyncTask.setOnClickListener(this);
cancelAsyncTask.setOnClickListener(this);
MainActivityInstance = this;

//ProgressDialog progressDialog;
progressDialog = new ProgressDialog(this.getApplicationContext());
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("On Progress...");
progressDialog.setCancelable(false);

c = new CallBack() {
public void onProgress(){
//progressDialog.show();
Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Progress!!", 1000);
toast.show();
}

public void onResult(Boolean result){
if(result.equals(true)){
Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Bingo...Success!!", 1000);
toast.show();
}

else {
Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Alas!! Failure", 1000);
toast.show();
}
}

public void

Solution


  • If you rotate the screen, the activity will be restarted, which will restart the task as well (it might even crash because of the ProgressDialog). Eventually, I have found that only services can correctly handle long running operations. But they are more complicated to code.



  • You don't follow naming conventions from Android, and several names make no sense at all. For instance AsyncTaskExampleActivity.c should be named AsyncTaskExampleActivity.mCallback

Context

StackExchange Code Review Q#5191, answer score: 2

Revisions (0)

No revisions yet.