I Have searched for a few hours on google and on here. I have been unable to find a solution to my problem. I want the thread to stop when the user presses the back button. So for example the user will press the back button and the loop will stop flipping coins. Then the textviews will be populated with the number of heads and tails that the loop managed to complete before the user canceled the operation.
I know i have to set
dialog.setCancelable(false);
to
dialog.setCancelable(true);
and that i need to implement
progressDialog.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog) {
background.setRunning(false);
}});
But when i try to do this it ends up killing my entire app force closing it.
Can you please help. Im still kind of new to android programming and I am eager to learn more so if you notice any other things in the code i can improve it would be appreciated.
package com.michaelpeerman.probability;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class ProbabilityActivity extends Activity implements OnClickListener {
private Button submit;
ProgressDialog dialog;
int increment;
Thread background;
int heads = 0;
int tails = 0;
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.main);
submit = ((Button) findViewById(R.id.submit));
submit.setOnClickListener(this);
}
public void onClick(View view) {
increment = 1;
dialog = new ProgressDialog(this);
dialog.setCancelable(false);
dialog.setMessage("Flipping Coin...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.number);
int maximum = Integer.parseInt(max.getText().toString());
dialog.setMax(maximum);
dialog.show();
background = new Thread(new Runnable() {
public void run() {
for (int j = 0; j < dialog.getMax(); j++) {
int i = 1 + new Random().nextInt(2);
if (i == 1)
heads++;
if (i == 2)
tails++;
progressHandler.sendMessage(progressHandler.obtainMessage());
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
if (dialog.getProgress() == dialog.getMax()) {
dialog.dismiss();
TextView result = (TextView) findViewById(R.id.result);
result.setText("heads : " + heads + "\ntails : " + tails);
}
}
};
}
I’m curious how your code compiles, since
setRunning(boolean)is not part of the api forThread.Regardless of that, here’s one way to exit a thread cleanly. Change your background thread definition to this:
Then cancel your thread with: