2011-10-16 3 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를 정의해야합니다. findViewbyId가 Null을 반환하도록 contentView가 초기화되지 않았습니다.

@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 (google it)를 사용하여 배우고 코드를 게시하고 해결하도록 요청하십시오.

관련 문제