Sunitha
Sunitha

Reputation: 261

How to control the execution of getIntent() in android?

I have this login activity which is also the launching activity. I wanted to send some error messages from other activities to this login activity through intents. I used this piece of code for accepting the message,

Intent i = getIntent();
String Message = i.getExtras().getString("msg");

Since during the initial launch no value is passed to getIntent(), adding this piece of code will crash my app.

How to I implement this logic ?

Upvotes: 0

Views: 180

Answers (4)

MRX
MRX

Reputation: 1442

You can check like this

String msg = "";
if (getIntent().getExtras() != null) {
    msg= getIntent().getStringExtra("msg");
}

Upvotes: 0

akshay_shahane
akshay_shahane

Reputation: 4643

Intent i = getIntent();
if (i != null && i.hasExtra("msg")) {
String Message = i.getStringExtra("msg");
}

Upvotes: 1

Aman Grover
Aman Grover

Reputation: 1641

check for null values in getIntent() like this:

Intent i = getIntent();
if(i.getExtras() != null) {
    String Message = i.getExtras().getString("msg");
}

Upvotes: 2

Shreeya Chhatrala
Shreeya Chhatrala

Reputation: 1449

Use like this

Intent i = getIntent();
if (i != null){
    String Message = i.getStringExtra("msg");
}

Upvotes: 0

Related Questions