35

How do you pass data between activities in an Android application?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
yokks
  • 5,683
  • 9
  • 41
  • 48

3 Answers3

56

in your current activity, create an intent

Intent i = new Intent(getApplicationContext(), ActivityB.class);
i.putExtra(key, value);
startActivity(i);

then in the other activity, retrieve those values.

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    String value = extras.getString(key);
}
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • 1
    Is this how everyone does it? – dotty Jul 28 '11 at 09:19
  • I currently have insufficient rep to vote this down, but it's worth noting that, while this will work in some cases, it is not the only way to do it, and is not always the best, simplest, quickest or most efficient. Emre's answer (which has luckily been selected as the right answer despite a huge difference in votes) links to a variety of methods, from which you can choose the best solution for your app. – M_M Aug 11 '12 at 14:47
  • This is not working all the time, because when you have lots of data, you can't attach them to the intent as extras. https://groups.google.com/forum/?fromgroups#!topic/android-developers/sosGdqTGF8I – Aurelian Cotuna Jun 20 '13 at 06:17
1

Use a global class:

public class GlobalClass extends Application
{
    private float vitamin_a;


    public float getVitaminA() {
        return vitamin_a;
    }

    public void setVitaminA(float vitamin_a) {
        this.vitamin_a = vitamin_a;
    }
}

You can call the setters and the getters of this class from all other classes. Do do that, you need to make a GlobalClass-Object in every Actitity:

GlobalClass gc = (GlobalClass) getApplication();

Then you can call for example:

gc.getVitaminA()
Patricia
  • 2,885
  • 2
  • 26
  • 32
0

Put this in your secondary activity

SharedPreferences preferences =getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE);

android.content.SharedPreferences.Editor editor = preferences.edit();

editor.putString("name", "Wally");
            editor.commit();

Put this in your MainActivity

SharedPreferences preferences = getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE);

if(preferences.contains("name")){

Toast.makeText(getApplicationContext(), preferences.getString("name", "null"), Toast.LENGTH_LONG).show();

}  
AlphaStack
  • 125
  • 1
  • 6