I’ve got following code in my AsyncTask. The only thing I want the AsyncTask to do, is to sleep for 1000 ms, while showing a ProgressDialog.
package something.something.Logic;
import android.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class DeviceScan extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
Context _context;
public DeviceScan(Context context) {
_context = context;
dialog = new ProgressDialog(_context);
}
protected void onPreExecute() {
dialog = new ProgressDialog(_context);
dialog.setTitle("Please Wait");
dialog.setMessage("Searching for devices..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "";
}
protected void onPostExecute(Integer result) {
/*
* When the background thread is finished, do something here
*/
Toast.makeText(_context, "Done!!", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}
Then I call the AsyncTask this way:
import something.something.Logic.*;
public void onClick(View view){
switch(view.getId()) {
case R.id.button1:
new DeviceScan(getApplicationContext()).execute("");
break;
}
}
But my app just crashes when I hit the button, I cant find any information from the debugger. Can anyone give me a hint?
Thanks in advance.
You are creating the
ProgressDialogtwice. Remove the creation from theonPreExecute.Another thing is, pass the
thisreference of the theActivityas thecontextin the constructor ofDeviceScanAlso, change the signature of
onPostExecuteas suggested by other answers.