I have a function that requires a lot of calculation, so I try to call that function inside a thread. This is how I do it:
submit.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(!(fromAdress.getText().toString().length() > 0) || !(toAdress.getText().toString().length() > 0)) {
Toast.makeText(this, "ERROR IN INPUT", Toast.LENGTH_LONG).show();
}
else {
if(connected) {
final ProgressDialog dialog = ProgressDialog.show(this, "Calculating",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
measureDistanceAndTime(fromAdress.getText().toString(), toAdress.getText().toString());
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
else
Toast.makeText(this, "No network!", Toast.LENGTH_LONG).show();
}
When I open the application, it shows the progressdialog, but after like 4 seconds, it stops responding. I cant figure out this problem, cuz when I remove the code for the thread and progressdialog, it works fine!
Isn’t this the way to do it?
The easiest way to do this is with an
AsyncTask. Read this article entitled Painless Threading.