简体   繁体   English

Android开发:尝试获取getStringExtra()时出现java NullPointerException

[英]Android Development: java NullPointerException When Trying To getStringExtra()

In my main activity, I have the following code that calls my FileBrowser activity: 在我的主要活动中,我有以下代码调用了FileBrowser活动:

  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: 这次我再次打开DDMS来运行该应用程序以查找错误,它是这样的:

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): 这是第17行(位于onCreate之外):

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

What's wrong? 怎么了? Can I not use putExtra with startActivityForResult? 我不能将putExtra与startActivityForResult一起使用吗? Can putExtra only be used with startActivity? 只能将putExtra与startActivity一起使用吗?

Try moving the declaration inside the onCreate(), or any method, this will ensure you have acess to the intent data. 尝试将声明移到onCreate()或任何方法中,这将确保您可以访问意图数据。 Declaring the variable before onCreate() and thus any other method, you won't have acess to the intent extras. 在onCreate()之前声明变量,然后再声明任何其他方法,您将无需使用意图的附加内容。

Leave line 17 as private String action; 将第17行保留为private String action;

And inside onCreate() 在onCreate()里面

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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