在onCreate函数中更改textView文本

时间:2011-10-16 14:26:33

标签: android

任何人都可以告诉我为什么我会在以下代码中收到错误消息java.lang.NullPointerException

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";
    }    

}

1 个答案:

答案 0 :(得分: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(谷歌),不要发布你的代码,并要求我们解决它。