Reputation: 1478
Can anyone tell me why am i getting error message java.lang.NullPointerException
in following code??
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";
}
}
Upvotes: 0
Views: 5858
Reputation: 3652
You should put define your contentView before accessing a child of it, in your case a textview. The contentView hasn't been initialized so findViewbyId returns 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();
}
}
Also, provide more information on the problem, i.e. by showing on which line the problem is. Learn using DDMS (google it) and don't post your code and ask us to solve it.
Upvotes: 2