lomza
lomza

Reputation: 9716

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

Intent 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?

Upvotes: 1

Views: 1770

Answers (3)

Peter Knego
Peter Knego

Reputation: 80340

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.

Upvotes: 2

Spidy
Spidy

Reputation: 40002

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 )

Upvotes: 1

Selvin
Selvin

Reputation: 6797

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

Upvotes: 0

Related Questions