yokks
yokks

Reputation: 5773

Passing data between activities in Android

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

Upvotes: 35

Views: 30535

Answers (3)

AlphaStack
AlphaStack

Reputation: 125

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();

}  

Upvotes: 0

Patricia
Patricia

Reputation: 2865

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()

Upvotes: 1

Pentium10
Pentium10

Reputation: 207912

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);
}

Upvotes: 56

Related Questions