Android data sharing between activities 

Joined:
07/27/2010
Posts:
128

July 27, 2011 13:49:26    Last update: July 27, 2011 13:52:03
Some ways to pass data from one activity to another:
  1. 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");
      


  2. 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");
      


Share |
| Comment  | Tags