Skip to content

Obviate.io

To anticipate and prevent

AndroiDev: TextView.setText crash

Posted on 2010-03-31 By Jon No Comments on AndroiDev: TextView.setText crash

One thing I yearn for when I am programming is a debugger like Perl’s interpreter. If you had a bug in your code, it would tell you almost exactly where it was, and even suggest fixes sometimes (Ex: You probably forgot a semicolon at the end of line X). Unfortunately, that isn’t the case with most languages. In the case of Android, it throws typically Java error messages, which 90% of the time are useful, but 10% of the time you get stuff like this:

03-26 06:08:13.068: ERROR/AndroidRuntime(426): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snowulf.quickclick/com.snowulf.quickclick.QuickClick}: java.lang.NullPointerException

I realize what a Null Pointer Exception is, but it isn’t very helpful. Here’s the (stripped down) code I was using:

`
public class QuickClick extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   String userName = settings.getString(“userName”, null);

   final TextView txtHi = (TextView) findViewById(R.id.greeting_message);
   txtHi.setText(“Greetings ” + userName);

   setContentView(R.layout.main);
  }
}
`

If you were to try and debug this the good old fashion way (as I did), commenting out blocks/lines of code , recompiling and rerunning until the problem goes away you’d (eventually) find out that the problem line is **txtHi.setText()**. This really shouldn’t be a shock as that is the topic of this post. Actually, the real problem is **setContentView()** in combination. You must setContentView() before you try to manipulate the value of the objects it creates. Quite simply, R.id.greeting_message (and by proxy txtHi) doesn’t exist until you use setContentView.

So quick fix, put setContentView() way up at the top.

Android, Code

Post navigation

Previous Post: Bad Company 2: Easy ‘Demolish Part 2′ Achievement
Next Post: I Hate April Fools

Related Posts

Android Pay shows Apple how it’s done Android
Why Slack when you can Rocket.chat? Cloud
AndroiDev: The project so far – Wikinews Reader Android
Exploring PHP IDEs: Sublime Text Code
(Re-)Introducing PDNSOps Code
Getting to know the Google Nexus 7 Android

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2026 Obviate.io.

Powered by PressBook Masonry Dark