2013-10-03 87 views
1

嘗試使用線程時出現此錯誤。android無法在線程中創建處理程序,但尚未調用Looper.prepare

Can't create handler inside thread that has not called Looper.prepare()

Thread anOpenConnectionThread = new Thread(new Runnable() 
    { 
     @Override 
     public void run() 
     { 

      try 
      { 
       openConnection(); 
      } 
      catch (Exception err) 
      { 
        runOnUiThread(new Runnable() { 
         public void run() { 

          Toast.makeText(LaunchApp.this, "Opening connection with " + ip + " failed!", Toast.LENGTH_SHORT).show(); 
        } 
       }); 

       EneterTrace.error("Open connection failed.", err); 
      } 
     } 
    }); 

開始在OnCreate螺紋:

anOpenConnectionThread.start(); 

開放的連接代碼,以防萬一:

private void openConnection() throws Exception 
{ 
    // Create sender sending MyRequest and as a response receiving MyResponse 
    IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory(); 
    mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class); 

    // Subscribe to receive response messages. 
    mySender.responseReceived().subscribe(myOnResponseHandler); 

    // Create TCP messaging for the communication. 
    ip = sProfile.getIp(); 
    IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory(); 
    IDuplexOutputChannel anOutputChannel 
     = aMessaging.createDuplexOutputChannel("tcp://" + ip + ":8060/"); 
    Toast.makeText(this, ip, Toast.LENGTH_SHORT).show(); 

    // Attach the output channel to the sender and be able to send 
    // messages and receive responses. 
    mySender.attachDuplexOutputChannel(anOutputChannel); 
} 

sProfile被初始化! 這是IP被設置在哪裏(它顯示了土司的IP,所以我100%肯定它不是空)

 @Override 
     public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { 
      int pos = profileSpinner.getSelectedItemPosition() + 1; 
      currentIp = myDb.getIp(pos); 
      Toast.makeText(SelectProfile.this, currentIp, Toast.LENGTH_SHORT).show(); 
     } 

getIp在那裏返回的IP設置。

public String getIp() 
{ 
    return currentIp; 
} 
+0

什麼是EneterTrace? –

回答

1

在線程運行方法中,您有openConnection()。在openConnection()中,您有以下

Toast.makeText(this, ip, Toast.LENGTH_SHORT).show(); 

從線程無法更新ui。

+1

謝謝,現在已經修復。但它現在說ip = null? 在連接tcp時發生錯誤:// null:8060 – PrivateerGerrit

+0

請檢查此'ip = sProfile.getIp()'這是否爲'sProfile'初始化? – Raghunandan

+0

是 SelectProfile sProfile;在onCreate中有 我有:sProfile = new SelectProfile(); 另外:在SelectProfile類getIp功能我有以下幾點: \t公共字符串getIp() \t { \t \t回報currentIp; \t} 的IP被設置在這裏: \t \t @覆蓋 \t \t公共無效onItemSelected(適配器視圖 parentView,查看selectedItemView,INT位置,長的id){ \t \t \t INT POS = profileSpinner.getSelectedItemPosition() + 1; \t \t \t currentIp = myDb.getIp(pos); \t \t \t Toast.makeText(SelectProfile.this,currentIp,Toast.LENGTH_SHORT).show(); \t \t} 和敬酒工作正常,並顯示ip – PrivateerGerrit

相關問題