How to get the value of a textview?

1.1k views Asked by At

I tried:

    TextView textView1 = (TextView) getActivity().findViewById(R.id.date);
    String s1 = textView1.getText().toString();

but on the second line falls error:

java.lang.NullPointerException
at com.ancort.cryptophone.guitest.CAMyTest.testMail_000(CAMyTest.java:94)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:177)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1619)

Also, I tried

    TextView textView1 = (TextView)findViewByID(R.id.date);
    String s = textView1.getText().toString();

But in this case "findViewByID" red highlights with error"cannot resolve method findViewById(int)". I understandthat the class must be extends from Activity class, but my class extends from another class. How to get the value of a textview?

3

There are 3 answers

0
Blackbelt On

you are inside a Fragment if you are using getActivity, and probably, the view, is only part of the fragment itself.

change

 TextView textView1 = (TextView) getActivity().findViewById(R.id.date);

with

 TextView textView1 = (TextView) getView().findViewById(R.id.date);

if you are using that line after onCreateView

0
Sudheesh Mohan On

I think you are using Fragment. Inside onCreateView write

View view = inflater.inflate(R.layout.your_fragment_layout,container, false);                                                                         
TextView textView1 = (TextView) view.findViewById(R.id.date);  

Hope this will work. :)

0
Игорь Кожин On

I wanted get a value that was in TextView. The decision was simple:

TextView textView1 = (TextView) solo.getView(R.id.date); String s1 =
textView1.getText().toString();

Thank you all.