2012-04-02 46 views
-2

我做了一個簡單的應用程序,它將count加1,並在TextView上顯示計數。它編譯和安裝的很好,但是當我運行它時,一條消息立即說:「不幸的是,Counter已經停止。」Android應用程序不運行

package com.android.counter; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 


public class CounterActivity extends Activity { 
/** Called when the activity is first created. */ 

private static int count = 0; 
Button increment = (Button) findViewById(R.id.inc); 
TextView tv = (TextView) findViewById(R.id.CountDisp); 


Runnable update = new Runnable() 
{ 
    public void run() { 
     increment.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       count++; 
       tv.setText("Count:" + count); 
      } 
     }); 
    } 
}; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Thread thr = new Thread(update); 
    thr.start(); 

} 

} 

回答

1

在嘗試查找任何視圖之前,您需要設置Activity的內容。這樣做......

Button increment = (Button) findViewById(R.id.inc); 
TextView tv = (TextView) findViewById(R.id.CountDisp); 

...您當前所在,將意味着雙方incrementtvnull。改變這些行...

Button increment; 
TextView tv'; 

onCreate(...)然後使用findViewById(...)之後,你有叫setContentView(...)

而且,使用單獨的Thread(Runnable接口)來處理onClick(...)監聽器是在複雜的事情,而不是必要。只需在onCreate(...)內創建您的onClick(...)偵聽器,並忘記其他線程代碼。

+0

實際上'tv.setText(...)'不會失敗,因爲它將在UI線程中被調用......在UI線程上未調用的唯一部分是'increment.setOnClickListener' – Selvin 2012-04-02 15:54:33

+0

@Selvin:好點和我我編輯了我的答案。我的大腦放慢速度 - 我想我需要另一杯咖啡。 – Squonk 2012-04-02 16:03:04

0

您需要查看LogCat。你可以用Eclipse或DDMS工具來完成。該logcat的日誌會告訴你:

  • 什麼例外是
  • 凡在它的代碼發生

利用這些信息,那麼你可以找到原因。從源代碼單獨做就是受虐狂。