Reputation: 21
the application crashes when I make a toast but I do not understand why. This is the code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mvc = (Button) findViewById(R.id.button1);
mvc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"START!" ,Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
public void run() {
long startTime = System.currentTimeMillis();
while( startTime + 5000 > System.currentTimeMillis())
{
// }
// while (progressStatus < 1000) {
if (k > progressStatus){
progressStatus = k;
}
else {
progressStatus = progressStatus;
}
// Update the progress bar and display the current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
// Sleep for 10 milliseconds. Just to display the progress slowly
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast mioToast = Toast.makeText(BluetoothChat.this,
"STOP!",
Toast.LENGTH_LONG);
mioToast.show();
}
}).start();
}
});
the first toast executes it perfectly but in the second, where there is the word "STOP", the application crashes. How so? Thank you.
Upvotes: 0
Views: 81
Reputation: 12919
You are trying to display a Toast
in a background thread. The UI can only be modified from the UI thread, and that's what crashes your app.
Use this instead:
handler.post(new Runnable() {
public void run() {
Toast.makeText(BluetoothChat.this,
"STOP!",
Toast.LENGTH_LONG).show();
}
};
This will run on the UI thread and thus won't crash the app.
Upvotes: 1
Reputation: 953
try to replace "getApplicationContext()" with "this" or "your_class_name.this"
Upvotes: 0