Passing data between activities in Android

2018-12-31 19:12发布

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

标签: android
3条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 19:41

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()
查看更多
还给你的自由
3楼-- · 2018-12-31 19:44

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);
}
查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 19:53

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

}  
查看更多
登录 后发表回答