Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView and null pointer exception

Why is

TextView test = (TextView) findViewById(R.id.testTextView);
test.getText();

generating a null pointer exception? The id is correct, testTextView is correctly declared in my XML layout file.

like image 535
SK9 Avatar asked Jan 31 '11 04:01

SK9


People also ask

How do I fix NullPointerException in Android?

How to fix the NullPointerException? To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.

How to resolve the Java lang NullPointerException?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What is NullPointerException in Kotlin?

In short, NullPointerException is thrown when a program attempts to use an object reference, which has the null value. For example: public class SampleClass{ public static void main(String[] args){ String sampleString= null; System. out.

What does NullPointerException mean in Java?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.


2 Answers

The only reason for findViewById to return null if you are passing a valid id is that you are either setting the wrong content view (with setContentView) or not setting a content view at all.

like image 150
Cristian Avatar answered Nov 08 '22 21:11

Cristian


I think you might have written setContentView(..) after defining the TextView. Reverse these, and it should work.

Change:

TextView test = (TextView) findViewById(R.id.testTextView);
.
.
setContetView(..)

To:

setContetView(..)
.
.
TextView test = (TextView) findViewById(R.id.testTextView);
like image 23
Piyush Agade Avatar answered Nov 08 '22 22:11

Piyush Agade