在intent中设置字符串

时间:2016-10-11 11:00:58

标签: android android-intent

案例1:应用启动

应用启动 - > SplashActivity(启动画面,没有设置字符串意图) - > LoginAactivity。

案例2:重置密码后

PasswordResetActivity(设置字符串意图,在LoginActivity中预先填充的电子邮件) - > LoginActivity。

LoginActivity,onCreate

  

String email = getIntent()。getExtras()。get(" email");

     

if(email == null){       //应该在case1中执行}   其他{       //应该在case2}中执行

但这是在启动应用程序时抛出空指针异常?有什么工作?

3 个答案:

答案 0 :(得分:1)

尝试以这种方式实施

private void someMethod() {

    String email = null;

    Intent intent = getIntent();
    if (intent != null && intent.hasExtra("email"))
        email = intent.getStringExtra("email");

    if (email == null) {
        //should execute in case1
    } else {
        //should execute in case2
    }
}

答案 1 :(得分:1)

这是因为当您在LoginActivity之后执行SplashScreen时,LoginActivity没有额外内容,因此getIntent().getExtras()null且{{1}抛出getIntent().getExtras().get("email")

您可以通过多种方式避免它,但解决方案可以是:

NullPointerException

希望它有所帮助!

答案 2 :(得分:0)

您可以在登录活动中使用以下代码。首先,我们将在bundle中获取intent值。之后检查捆绑包是否具有意图值,然后我们将获取电子邮件值。通过这种方式可以停止空指针崩溃。即使密钥也被更改,它也不会崩溃,在下面的情况下,它会将电子邮件字符串值保持为null。通常,在继续之前始终检查null。

//Fetching the intent extra values using the bundle...
Bundle bundle = getIntent().getExtras();

// Checking whether there is value in bundle or not...
if (bundle != null) {
String email = bundle.getString("email");
}