I am currently working on an Android application where I am changing the text in a TextView object while my app is running, from within the MainActivity class. To do this, I am using the setText(CharSequence text)
method. This method's documentation on the Android Studio website explicitly states that the purpose of the method "Sets the string value of the TextView." However, whenever I try to pass a referenced string from my Strings.xml file as a parameter for this method, I get a NullPointerException with the message "Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference." Can somebody please guide me as to why this error is occurring and how use the setText(CharSequence text)
method with a referenced String as a parameter? Thank you so much!
Asked
Active
Viewed 337 times
-5

Darth Vader
- 31
- 4
-
add your mainActivity code. – W4R10CK Feb 02 '17 at 05:12
-
1First you need to initialize your textView , second if you ask a question you need to show what you have done – Charuක Feb 02 '17 at 05:13
-
Post your code so we can make changes – Akshay Feb 02 '17 at 05:13
-
1Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Charuක Feb 02 '17 at 05:17
-
Have you initialize your textview? – AbhayBohra Feb 02 '17 at 05:18
-
Can't you put your code here? Is setting a text on `TextView` is that much confidential? – Devendra Singh Feb 02 '17 at 05:33
2 Answers
1
Make sure to initialize textview
TextView tvName = (TextView) findViewById(R.id.tv_name);
tvName.setText(getResources().getString(R.string.name_xml));
Also make sure in your setContentView xml the tv_name is declared as TextView in the layout.

Mike
- 1,313
- 12
- 21
-
-
1Hey without knowing where OP went wrong how-come you post an answer ? and can you explain which avoids his null pointer from your answer? – Charuක Feb 02 '17 at 05:15
-
1@Mike, Please add a resource full body to make sure OP can understand what went wrong with his code. Make sure to add a brief body to your answer. – W4R10CK Feb 02 '17 at 05:17
-
Simple he is attempting to parse the String on xml as he stated but it is failing, and it is pointing to a parsing an int of a null object reference – Mike Feb 02 '17 at 05:18
-1
another way to do this
TextView textview = (TextView)findViewById(R.id.text);//get the view of textview
//set the text for textview
textview.setText("text you want to set");

Rehan Shikkalgar
- 1,029
- 8
- 16