2011-10-16 117 views
0

誰能告訴我爲什麼我在下面的代碼中得到錯誤信息java.lang.NullPointerException更改onCreate函數中的textView文本

package firstApp.hangman; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.widget.TextView; 

public class HangmenActivity extends Activity 
{ 
    private String word_to_guess; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     this.set_random_word(); 
     TextView wordToGuess = (TextView) findViewById(R.id.word_to_guess); 
     try 
     { 
      wordToGuess.setText(this.word_to_guess); 
     } 
     catch(Exception e) 
     { 
      AlertDialog alertDialog = new AlertDialog.Builder(this).create(); 
      alertDialog.setTitle("error"); 
      alertDialog.setMessage(e.toString()); 
      alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        // here you can add functions 
       } 
      }); 
      alertDialog.setIcon(R.drawable.icon); 
      alertDialog.show(); 
     } 

     setContentView(R.layout.main); 
    } 

    private void set_random_word() 
    { 
     this.word_to_guess = "abcdef"; 
    }  

} 

回答

2

你應該在訪問它的一個孩子之前定義你的contentView,在你的情況下是一個textview。 contentView尚未初始化,所以findViewbyId返回Null。

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); //Initialize the view 
    this.set_random_word(); 
    TextView wordToGuess = (TextView) findViewById(R.id.word_to_guess); 
    try 
    { 
     wordToGuess.setText(this.word_to_guess); 
    } 
    catch(Exception e) 
    { 
     AlertDialog alertDialog = new AlertDialog.Builder(this).create(); 
     alertDialog.setTitle("error"); 
     alertDialog.setMessage(e.toString()); 
     alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       // here you can add functions 
      } 
     }); 
     alertDialog.setIcon(R.drawable.icon); 
     alertDialog.show(); 
    } 
} 

此外,提供有關問題的更多信息,即通過顯示問題出現在哪條線上。學習使用DDMS(谷歌它),不要發佈你的代碼,並要求我們解決它。