Reputation: 435
I am creating a basic android app. I am creating a TextView
object called mathexpresionTV
and assigning to the value of the id of the textview I want it to reference to.
TextView mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);
I also have a button in which if the user presses it, it displays 1 on the textview.
Button oneButton = (Button) findViewById(R.id.button1)
oneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mathExpressionTV.append("0");
}
});
I am will be using the mathExpressionTV
through the class hence I have delcared it as a global variable and not on my onCreate();
method but the oneButton
is declared in my onCreate();
.
This is the error output: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
Upvotes: 1
Views: 67
Reputation: 2140
You have 3 options:
findViewById
in the onCreate
methodtextView
and assign it in the onCreate
methodactivity.findViewById
Upvotes: 0
Reputation: 12173
You can declare it as a global, but you need to cast as a TextView
in onCreate
. You can't use findViewById
outside of a method in an activity
TextView mathExpressionTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourActivity);
mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);
...
}
Upvotes: 2