March 31, 2010

254 words 2 mins read

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.