Tarikh Chouhan
Tarikh Chouhan

Reputation: 435

Getting nullpointerexception despite assinging a value to it

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

Answers (2)

Swag
Swag

Reputation: 2140

You have 3 options:

  1. Use findViewById in the onCreate method
  2. Create a global variable for the textView and assign it in the onCreate method
  3. Pass the activity object, or get the activity object and use it like: activity.findViewById

Upvotes: 0

Andrew Brooke
Andrew Brooke

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

Related Questions