简体   繁体   中英

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 onCreate):

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM