Reputation: 683
I tried to show a alert dialog in handler, but i could not show the alert. Could you help me have a look where is the bug?
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
myDialog.show();
super.handleMessage(msg);
}
};
class myThread implements Runnable {
public void run() {
try {
myHandler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In onCreate:
myDialog= new AlertDialog.Builder(this).create();
myDialog.setTitle("hi");
myDialog.setMessage("thanks");
myDialog.setButton("Next...",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
new Thread(new myThread()).start();
....
I defined myHandler and myThread. Then in onCreate, I defined a dialog. And then call the mythread to run. I suppose the mythread will send a message to myHandler. Myhandler will then trigger the dialog. What is wrong with the logic? thanks.
Upvotes: 0
Views: 1379
Reputation: 6925
Update you handler like this
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
//Show dialog
myDialog.show();
}
else{
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"No message from Thread",
Toast.LENGTH_SHORT).show();
}
}
};
and in your thread update like this
class myThread implements Runnable {
public void run() {
try {
Message msgObj = myHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
myHandler.sendMessage(msgObj);
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 1