Android data sharing between activities
July 27, 2011 13:49:26 Last update: July 27, 2011 13:52:03
Some ways to pass data from one activity to another:
- Add data to the Intent:
- The sending side:
// create Intent Intent intent = new Intent(); intent.setAction("the-action"); intent.setData(Uri.parse("a-valid-uri-for-the-second-activity")); // add data intent.putExtra("key", "value"); // start the second activity startActivity(intent);
- The receiving side:
Bundle bundle = getIntent().getExtras(); String value = bundle.getString("key");
- The sending side:
- Use SharedPreferences (data is persisted in this case):
- The sending side:
SharedPreferences prefs = getSharedPreferences("prefID", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.purString("key", "value"); editor.commit();
- The receiving side:
SharedPreferences prefs = getSharedPreferences("prefID", Context.MODE_PRIVATE); String value = prefs.getString("key");
- The sending side: