2011-01-07 2 views
0

私はここに愚かな何かをやっていると確信しているが、次のコード:Androidのハンドラの問題

... 

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(); 
    } 
}; 

まだこれがあるにもかかわらず、ラインbuilder.create().show();

01-07 11:55:02.791: ERROR/AndroidRuntime(18791): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 

を得ています私のメインスレッドhandleMessageの中のハンドラの中で呼び出されます。私は間違って何をしていますか?

答えて

2

Activityクラスに投稿したコードはありますか?

また、私はむしろ、新しいメッセージを作成するよりも

Message msg = Message.obtain(); 

を使用します。また、あなたはちょうどそのStringを渡したい場合:

private static final int HANDLER_MESSAGE_RESULT = 0; 
... 
msg.what = HANDLER_MESSAGE_RESULT; 
msg.obj = "result"; 

Bundleを渡すよりも効率的です。 Handlerでは、whatswitchを使用して、今後新しいメッセージタイプを追加することができます。

extractHandler.sendMessage(m); 

ではなく

extractHandler.dispatchMessage(m); 

ないことのいずれかががあなたの問題を修正することを確認した:私はあなたにも使用されるべきだと思います!

+0

ありがとう、非常に有用なアドバイス、それは問題だった 'dispatchMessage()'の使用でした。 – fredley

1

はい、それは何かばかげたものでした。私はextractHandler.dispatchMessage(m);の代わりにextractHandler.sendMessage(m);を使用していたはずです

+1

違いは何ですか? – waqaslam