-5

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!

2 Answers2

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
  • Thanks forgot the coding block – Mike Feb 02 '17 at 05:14
  • 1
    Hey 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