Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

android - Get data from another activity

Still working on my skills in android.

My problem here is that i have a label from my database that contain a name that is in a spinner, when i click on the label, a dialog comes and give you three choices: 1. update. 2. delete. 3. cancel. I got through the second and the third choices, but in the update am facing this problem; i go to another activity that has an editText and the 2 Buttons, save and cancel, i want the save button to get the data from the editText in putExtra and send it back to the same previous activity and change the old label with the data from the editText.

I appreciate any help. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your second activity, you can get the data from the first activity with the method getIntent() and then getStringExtra(), getIntExtra()...

Then to return to your first activity you have to use the setResult() method with the intent data to return back as parameter.

To get the returning data from your second activity in your first activity, just override the onActivityResult() method and use the intent to get the data.

First Activity:

//In the method that is called when click on "update"
Intent intent = ... //Create the intent to go in the second activity
intent.putExtra("oldValue", "valueYouWantToChange");
startActivityForResult(intent, someIntValue); //I always put 0 for someIntValue

//In your class
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //Retrieve data in the intent
    String editTextValue = intent.getStringExtra("valueId");
}

Second Activity:

//When activity is created
String value = intent.getStringExtra("oldValue");
//Then change the editText value

//After clicking on "save"
Intent intent = new Intent();
intent.putExtra("valueId", value); //value should be your string from the edittext
setResult(somePositiveInt, intent); //The data you want to send back
finish(); //That's when you onActivityResult() in the first activity will be called

Don't forget to start your second activity with the startActivityForResult() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...