Reputation: 33861
I'm sure I'm doing something stupid here, but the following code:
...
public void onClick(View v) {
extractThread et = new extractThread();
et.start();
}
...
private class extractThread extends Thread{
public void run(){
expensiveOperation();
Message m = new Message();
Bundle b = new Bundle();
b.putString("message","result");
m.setData(b);
extractHandler.dispatchMessage(m);
}
}
private Handler extractHandler = new Handler(){
public void handleMessage(Message m){
Bundle b = m.getData();
String message = b.getString("message");
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
};
is still getting
01-07 11:55:02.791: ERROR/AndroidRuntime(18791): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at the line builder.create().show();
, despite the fact this is called inside a Handler in my main thread inside handleMessage
. What am I doing wrong?
Upvotes: 0
Views: 2438
Reputation: 10908
Is the code you posted within your Activity
class?
I would also use
Message msg = Message.obtain();
rather than creating a new message. Also if you just want to pass a String
then:
private static final int HANDLER_MESSAGE_RESULT = 0;
...
msg.what = HANDLER_MESSAGE_RESULT;
msg.obj = "result";
is more efficient than passing a Bundle
. In your Handler
you can then switch
on the what
which allows you to add new message types in the future. I think you should also be using:
extractHandler.sendMessage(m);
rather than
extractHandler.dispatchMessage(m);
Not sure that any of that fixes your issue though!
Upvotes: 2
Reputation: 33861
Yes, it was something stupid. I should have used extractHandler.sendMessage(m);
instead of extractHandler.dispatchMessage(m);
Upvotes: 1