2011-10-03 75 views
0

好吧我試着調試我的代碼,使用DDMS,我無法趕上它的竅門。我認爲這是因爲我的程序在啓動時崩潰。無論如何,我向一個朋友展示了這一點,他無法弄清楚我做錯了什麼。有人能指出爲什麼我的應用程序在啓動時崩潰嗎?新應用程序在啓動時崩潰,調試沒有幫助

感謝:

http://pastebin.com/ZXxHPzng

+0

Android不處理的編程問題,所以我SO遷移這這裏。 –

+0

有什麼樣的錯誤信息?在您的鏈接中,我只能看到一個活動文件。你的清單是否正確設置? – Jlange

回答

4

你是要創建在全球區域的UI元素的問題。如果您希望它成爲全局對象,則可以在那裏聲明它們,但只有在設置了內容視圖後才能實例化它們。例如:

private RadioButton rockRB; 
    private RadioButton paperRB; 
    private RadioButton scissorsRB; 
    private TextView result; 



    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // Content View Must be set before making UI Elements 
     rockRB = (RadioButton)findViewById(R.id.radioRock); 
     paperRB = (RadioButton)findViewById(R.id.radioPaper); 
     scissorsRB = (RadioButton)findViewById(R.id.radioScissors); 
     result = (TextView)findViewById(R.id.result); 
+0

不在onCreate之前執行任何操作嗎?我必須把它放在onCreate範圍內嗎?是的,這個想法是在這個時候儘可能全球化。 – BloodyIron

+0

類定義在OnCreate方法之前觸發,這是有道理的,否則它的定義在OnCreate中不可用。如果您在全局聲明它並在OnCreate中實例化它,它將在整個課程中都可用。 – Pyrodante

+0

記住:所有UI元素必須初始化setContentView – Pyrodante

1

其實很簡單。在初始化課程時,初始化變量rockRB,paperRB,scissorRB和結果。在調用findViewById(...)時,佈局尚未加載,因此沒有找到具有指定標識的視圖。函數findViewById因此返回null來指示。當你以後嘗試使用存儲的id(它是空的)時,你會得到一個空指針異常,因此整個應用程序崩潰。

要解決您的問題,請使用findViewById(...)將變量的初始化移動到setContentView語句下面的函數onCreate中,但在setOnClickListener語句之前。

像這樣:

公共類RockPaperScissorsActivity延伸活動實現Button.OnClickListener { /**當首先創建活動調用。 */

private RadioButton rockRB; 
private RadioButton paperRB; 
private RadioButton scissorsRB; 
private TextView result; 



@Override 
public void onCreate(Bundle savedInstanceState) { 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    rockRB = (RadioButton)findViewById(R.id.radioRock); 
    paperRB = (RadioButton)findViewById(R.id.radioPaper); 
    scissorsRB = (RadioButton)findViewById(R.id.radioScissors); 
    result = (RadioButton)findViewById(R.id.result); 

    rockRB.setOnClickListener(this); 
    paperRB.setOnClickListener(this); 
    scissorsRB.setOnClickListener(this); 
} 

等等...