通过许多活动传递变量

时间:2017-06-05 22:47:05

标签: java android

on MainActivity我有两个编辑文本,我得到姓名和年龄值

现在我在此活动中有例如name="Mohamed" age=26

我的问题是如何在其他活动中自由使用这些变量而不通过Intent

传递它们

1 个答案:

答案 0 :(得分:2)

使用共享偏好设置。

设置值:

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();

检索值

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredName = prefs.getString("name", null); //null is the default value.
int age = prefs.getInt("age", 0); //0 is the default value.

有关详细信息,请访问Android Doc Shared Preferences