This question is simple. There are for example 2 activities Main Activity and Main Activity 2. How can I send string(for example) from Main Activity to Main Activity 2. Let's say if Main Activity 2 gets string. It calls a function to change that string. And then how to send that changed string back to Main Activity?
2 Answers
From Main activity 1 send the string:
Intent intent = new Intent(this, MainActivity2); intent.putExtra("string", stringVal); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); Then in Main Activity 2, receive the string:
String str = getIntent().getExtras().getString("string"); Then just change the value and send it back to Main Activity 1, you could get the intent within the onResume if you want, but check for nulls.
4 Comments
The Standard Way:
If you want to send a primitive data from Activity1 to Activity2, you need to use Intent. For example if you just want to send a String:
public class Activity1 extends Activity { public static final String EXTRA_STRING = "extra_string"; private void sendString(String s) { Intent intent = new Intent(this, Activity2.class); intent.putExtra(EXTRA_STRING, s); startActivity(intent); } } Suppose you change that string in Activity2 and also want the result back to Activity1, you need to use startActivityForResult() in Activity1 and setResult() in Activty2.
For example:
public class Activity1 extends Activity { public static final String EXTRA_STRING = "extra_string"; private static final int REQUEST_CODE = 1; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { // Get the string back String changedString = data.getStringExtra(Activity2.EXTRA_STRING); } } private void sendString(String s) { Intent intent = new Intent(this, Activity2.class); intent.putExtra(EXTRA_STRING, s); startActivityForResult(intent, REQUEST_CODE); } } In Activity2:
public class Activity2 extends Activity { public static final String EXTRA_STRING = "string_extra"; private String myString; @Override public void onCreate(Bundle bundle) { // receive the string from activity1 if (getIntent() != null) { myString = getIntent().getStringExtra(Activity1.EXTRA_STRING); } } // Send the string back to activity1 private void sendBack() { Intent data = new Intent(); data.putExtra(EXTRA_STRING, myString); setResult(RESULT_OK, data); finish(); } } The downside of the method is you can only send primitive variable. If you want to send an object, it must implements Parcelable or Serializable.
The Quick and Easy Way:
You can send variable of any kind, any complicated object between activity, service or whatever you want using EventBus. Please take a look at the Documentation to know how to use it. It's really quick and easy.