Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Miles Torres
Miles Torres
2,316 Points

How do I solve this NullPointerException?

It keeps saying on the logcat that this strand is null:

factlabel.setText(fact);

how do I fix it?

1 Answer

Dina Climatiano
Dina Climatiano
10,862 Points

Can you please describe in detail where the exception is thrown, when (is it a run-time error or does your code not compile at all?), and include ALL of the relevant code?

In general, a Null Pointer Reference Exception is what happens when you reference a null object. When you create an object (like "fact" for example) you're really creating a reference to an object. If the reference is pointing to nothing (null) the exception occurs. In this case I'm betting that the culprit is the "fact" in setText(fact), but I need more information to know for sure. Since the function has to accept a non-nullable value it throws an exception.

One way to fix this is to test the value of "fact" before you pass it on using a conditional statement, and if it's a null set it to a default value that will at least keep your code from crashing for the time being. That way you're ensuring that the value is never null. Also, you can just throw the exception yourself and instead of having the app crash you can display some message to yourself or to the user. After you do that (just to keep your code running for testing purposes), try debugging:

Seeing as this particular exception will cause the app to malfunction as far as the user is concerned (meaning they will get some random string or error message instead of the "fact" they were expecting) a better approach is to run the code with the debugger and see exactly where the data fails to pass from one place to another. Try to determine which one of the components of that specific line is the null - is it the "fact" passed into the function? Is it the label that you maybe forgot to declare or set an id to elsewhere?

Also, a good practice is to Google your error. I got most of my answer from here: http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it which is like the first answer I got when googling your question. If you're new to programming chances are you're far from being the first one to make the same error.

Good luck!