1

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

sfmirtalebi
  • 370
  • 7
  • 16
Tarikh Chouhan
  • 425
  • 3
  • 5
  • 15

2 Answers2

2

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);

    ...
}
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
  • Oh okay, Thanks that fixed it. Do you know if we can reference other View objects if its not in the layout from the current avctivity? E.g. if there was a textview in layout A.xml and my current activity, C.java sets the content as B.xml, would be able to get the reference of the rextview from A.xml – Tarikh Chouhan Feb 09 '16 at 15:18
  • That's not typically what you should be trying to do. It can be done if you inflate the other layout, take a look at: https://stackoverflow.com/questions/4211189/how-to-get-id-in-different-layout – Andrew Brooke Feb 09 '16 at 17:32
  • So do you recommened inflating other layouts? – Tarikh Chouhan Feb 09 '16 at 23:43
  • It really depends, what exactly are you trying to accomplish? It may be best to ask a new question entirely – Andrew Brooke Feb 09 '16 at 23:49
0

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
Swag
  • 2,090
  • 9
  • 33
  • 63