开发者

Android Development: java NullPointerException When Trying To getStringExtra()

In my main activity, I have the following code that calls my FileBrowser activity:

  Intent newFileIntent = new Intent(getBaseContext(), FileBrowser.class);
  newFileIntent.putExtra("action", "browseDirectories");
  startActivityForResult(newFileIntent, 2);

But when this code executes, my app force closes. I ran the app again this time with DDMS open to look for the error, and here's what it is:

11-06 22:01:04.892: ERROR/AndroidRuntime(28287): Caused by: java.lang.NullPointerException
11-06 22:01:04.892: ERROR/AndroidRuntime(28287):     at com.alexprice.devpad.FileBrowser.<init>(FileBrowser.java:17)

Here is line 17 (located outside of onCreat开发者_Python百科e):

private String action = getIntent().getStringExtra("action");

What's wrong? Can I not use putExtra with startActivityForResult? Can putExtra only be used with startActivity?


Try moving the declaration inside the onCreate(), or any method, this will ensure you have acess to the intent data. Declaring the variable before onCreate() and thus any other method, you won't have acess to the intent extras.

Leave line 17 as private String action;

And inside onCreate()

action = getIntent().getStringExtra("action");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜