2014-06-28 24 views
0

這就是我想要做的:我有一個網站有一些按鈕。該網站連接到我的Android應用程序(通過太空船)。根據我點擊ImageButton的背景變化而定。但每次我點擊一個按鈕「setBackground」拋出異常。

這是我的代碼:

public class MainActivity extends Activity{ 
    ImageButton display; 
    SpacebrewClient client; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (savedInstanceState == null) { 
      getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit(); 
     } 
     ... 
     //calls the method "changeDisplay" 
     client.addSubscriber("changeDisplay", SpacebrewMessage.TYPE_STRING, "changeDisplay"); 
    } 

    public void changeDisplay(String input){ 
     if(input.equals("topay")){ 
      display = (ImageButton)findViewById(R.id.imageButton1); 
      display.setBackground(getResources().getDrawable(R.drawable.display_2)); 
     } 
     ... 
    } 
} 

我發現這個可能的解決方案:first answer。但這似乎並不適用於我。 我仍然得到相同的例外。

編輯: 試過第二種解決方案。現在「setBackground」拋出一個NullPointerException。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    if (savedInstanceState == null) { 
     getFragmentManager().beginTransaction() 
       .add(R.id.container, new PlaceholderFragment()).commit(); 
    } 
    display = (ImageButton)findViewById(R.id.imageButton1); 
} 
public void changeDisplay(String input){ 
    if(input.equals("topay")){ 
     runOnUiThread(new Runnable() { 
      public void run() {   
       display.setBackground(getResources().getDrawable(R.drawable.display_2)); 
      } 
     });} 
+0

您只能在UI線程中修改UI。您可以用'display'將一個Runnable發佈到UI線程。 (新的Runnable(){...});'。 –

+0

仍然得到一個空指針。也許問題不是「setBackground」,而是「findViewById」? –

+0

您應該總是在'onCreate()'中執行所有'findViewById()'並將引用保存爲'Views'作爲成員變量。但那不會解決你的問題,你確定這個ID是正確的嗎?這個佈局是否有你想要的'View'? –

回答

0

好吧,我設法解決我的問題。這是我做的:

我創建了一個Handler ...

Handler handler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      Bundle bundle = msg.getData(); 
      String input = bundle.getString("input"); 
      ImageButton display = (ImageButton)findViewById(R.id.imageButton1); 
      if(input.equals("topay")){ 
       display.setBackground(getResources().getDrawable(R.drawable.display_2)); 
      } 
      else if ... 
     } 
    }; 

...,然後一個新的Runnable,其傳遞的changeDisplayHandler輸入。

Runnable runnable = new Runnable() { 
      public void run() {   
       Message msg = handler.obtainMessage(); 
       Bundle bundle = new Bundle(); 
       String message = ""; 
       if(input.equals("topay")){ 
        message = "topay"; 
       } 
       else if ... 
       bundle.putString("input", message); 
       msg.setData(bundle); 
       handler.sendMessage(msg); 
      } 
     }; 
     Thread mythread = new Thread(runnable); 
     mythread.start(); 

現在它的工作! :-)

但是,感謝您的幫助,無論如何!

相關問題