问题
I'm trying to send data between activities using:
on Activity 2
Bundle bloc = new Bundle();
bloc.putString("DataLoc", et1.getText().toString());
Intent intent = new Intent(this, Activity2.class);
intent.putExtras(bloc);
on Activity 1
Intent iinf = getIntent();
Bundle binf = iinf.getExtras();
if (binf != null) {
String data = binf.getString("DataInf");
tv_1.setText(data);
tv_1.setText(getIntent().getExtras().getString("DataInf"));
}// end if
My Problem
I'm on Activity2
(with Activity1 under Activity2
opened), when I press back button I need show bundle on one TextView, EditText or similar but only I get to show onCreate
method.
I try using onResume
and onRestart
but... impossible.
Any suggestions?
回答1:
How do I pass data between activities when I press back button in Android?
Start second Activity using StartActivityForResult and use onActivityResult
in parent Activity for updating TextView
using received from second Activity
In Second Activity override onBackPressed()
method and call setResult
for send data using Intent:
@Override
public void onBackPressed() {
Intent data = new Intent();
// add data to Intent
setResult(Activity.RESULT_OK, data);
super.onBackPressed();
}
回答2:
You can use onActivityResult();
For Sending
Intent in= new Intent();
setResult(Activity.RESULT_OK, in);
finish();
For Recieving
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (abc) : {
if (resultCode == Activity.RESULT_OK) {
// your stuff
}
break;
}
}
}
回答3:
I think you are looking for an startActivityForResult()
and onActivityResult()
methods. Here you can find an example how to use it.
回答4:
Use 'DataLoc' string to get back the required value in the activity. You must use startActivityForResult() and onActivityResult() methods and get the value back using setResult() method.
来源:https://stackoverflow.com/questions/29206186/how-do-i-pass-data-between-activities-when-i-press-back-button-in-android