开发者

Passing values with condition in intent?

I want to send some data from activity A to activity B ONLY in case I have entered some values in activity A. So, in A I have

Inten开发者_运维问答t i = new Intent(A.this, B.class);
i.putExtra("email", email);
i.putExtra("password", password);
startActivity(i);

In B:

EditText login = (EditText) findViewById(R.id.login);
EditText password = (EditText) findViewById(R.id.password);
if(!(getIntent().getExtras().getString("email").isEmpty())){
    emailText = getIntent().getExtras().getString("email");
    login.setText(emailText);
    if(!(getIntent().getExtras().getString("password").isEmpty())){
        passwordText = getIntent().getExtras().getString("password");
        password.setText(passwordText);
    } 
}

But when I run my project, I get "Sorry, the application has stopped unexpectedly..." In LogCat I get a NullPointerException.

What is my mistake?


getIntent().getExtras().getString("email") will return null if "email" extra is not defined.

So:

if(getIntent().getStringExtra("email") != null){
    emailText = getIntent().getStringExtra("email");
    login.setText(emailText);
    if(getIntent().getStringExtra("password") != null){
        passwordText = getIntent().getStringExtra("password");
        password.setText(passwordText);
    } 
}

Updated: there are no extras at all so getIntent().getExtras() will already return null. Updated above code to handle that.


isEmpty() only returns true if the string is length 0. If the string does not exist, a null value will be provided and you cannot call isEmpty() on a null string. That will throw a null exception.

you can change it to

if (!(getIntent().getExtras().getString("email") == null )


getIntent() or getIntent().getExtras() or getIntent().getExtras().getString("email") or getIntent().getExtras().getString("password") or findViewById(R.id.login) or findViewById(R.id.password) returns null

edit: added 2 more options

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜