简体   繁体   中英

Passing String Values between Activities using intents

I understand how to pass string values from the MainActivity to the SecondaryActivity using intents, but how would you do that Vise Versa. Here is the code that I am using, I just don't know where to put the Recieving classes code.

In my SecondActivity

Intent intent = new Intent(SecondActivity.this, MainActivity.class);
String TimeValue = ("00:00:00");
intent.putExtra("TimeValue", TimeValue);
startActivity(intent)

and This is the code that I am not sure where to put so it doesn't crash when the app starts

String intent = getIntent().getExtras().getString("TimeValue");
TextView timeText = (TextView)findViewById(R.id.timeText);
timeText.setText(intent);

The problem is that MainActivity won't always be created with an intent coming from SecondActivity . It will also be created just when the app is launched.

You need to make sure that extras actually exists before trying to get extras from it! It could be null!

So this should be in your onCreate method, after you inflate the view.

Bundle extras = getIntent().getExtras();

String intentString;
if(extras != null) {
    intentString = extras.getString("TimeValue");
} else {
    intentString = "Default String";
}
TextView timeText = (TextView)findViewById(R.id.timeText);
timeText.setText(intentString);

I also highly recommend that you change the name of your String to "intentString" instead of "intent." The name "intent" is typically used for actual Intent objects, not the String that you get out of the Intent . So naming it "intentString" makes things more readable for other developers.

If you're trying to pass data back from SecondActivity to the MainActivity, then use startActivityForResult instead.

Once you have launched your SecondActivity and ready to pass the data back to the MainActivity, create a new Intent and use SecondActivity.setResult(resultCode, Intent); . Then call finish, to finish the SecondActivity.

Now, in your MainActivity, you will get a call to onActivityResult() which will give you the Intent you passed in the SecondActivity as a data parameter.

You can look at this link for more info: http://developer.android.com/training/basics/intents/result.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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