-1

I have 10 textviews each with the following id(s) tv1, tv2, tv3, etc. and each have text in them. These textviews are clickable, I saved the resource ID of the clicked textview in sharedprefrence. This ID is an int.

Now using this resource ID, can I somehow get text attached to this resource(TextView here). Below is code the code I am trying to use, but it gives a null pointer exception.

if (!sharedPref.getString(String.valueOf(i), "error").equals("error")) {
int u = Integer.parseInt (sharedPref.getString(String.valueOf(i), "error"));
System.out.println("For "+i+" object Value of id retrieved is-"+u);
String dohass= ((TextView) findViewById(u)).getText().toString();
}

I have checked value of u and is correct(correct resource id), but the above code says I am using getText on a null object.

Here are the logs

java.lang.RuntimeException: Unable to start activity ComponentInfo{dhritiapps.tulsiramayan/dhritiapps.tulsiramayan.Fav}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference 
Phantômaxx
  • 36,442
  • 21
  • 78
  • 108
  • Here are logs- java.lang.RuntimeException: Unable to start activity ComponentInfo{dhritiapps.tulsiramayan/dhritiapps.tulsiramayan.Fav}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference – Pankaj Bhardwaj Aug 10 '16 at 11:04
  • Possible 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) – Phantômaxx Aug 10 '16 at 11:20

2 Answers2

1

First you have to get reference of your textview.

TextView textview= ((TextView) findViewById(R.id.youtextviewid));

then you can get the string value by calling getText on TextView reference.

String yourtext= textview.getText().toString();
Amit Bhandari
  • 2,319
  • 4
  • 10
  • 30
eleduarr
  • 11
  • 3
  • Not working, Tried this but same problem. TextView textview1= ((TextView) findViewById(u)); String str=textview1.getText().toString(); – Pankaj Bhardwaj Aug 10 '16 at 11:25
  • 1
    @PankajBhardwaj The answer is **correct**. Currently, you are not finding the correct view: `findViewById(u)` should actually be `findViewById(R.id.yourtextviewid)` – Phantômaxx Aug 10 '16 at 11:32
0

Make sure you perform this step after setContentLayout() method call in onCreate. If tried before that, it will give null pointer exception because it will not be able to find your textview.

Get reference of texview.

TextView textview= (TextView) findViewById(R.id.textviewid);

call this method

String yourtext= textview.getText().toString();

Amit Bhandari
  • 2,319
  • 4
  • 10
  • 30