在活动之间共享数据

时间:2015-06-08 13:17:43

标签: android android-intent android-fragments android-activity

我想从2个活动(Activity和fragmentActivity)获取数据,我想在另一个类中使用这些数据。有没有办法在不使用意图的情况下在活动之间共享数据?

2 个答案:

答案 0 :(得分:1)

有多种方法可以实现这一目标:

方法1:

使用静态类setter和getter方法:

创建静态类并从第一个活动设置值并从第二个活动中获取值

方法2:

通过意图发布你的价值

方法3:

使用数据库存储来自一个活动的数据并从其他活动中获取数据

方法4:

使用共享偏好

答案 1 :(得分:0)

像这样使用SharedPreferences

//in the first activity where you want to save some values
SharedPreferences prefs = this.getSharedPreferences("com.myPackage.myApp", Context.MODE_PRIVATE);
prefs.edit().putString("name", "value").apply(); //the first parameter is the name with which you will fetch the value later, the cond one is the actual value

....
//fetch your data from another activity:
SharedPreferences prefs = this.getSharedPreferences("com.myPackage.myApp", Context.MODE_PRIVATE);
String myVariable = prefs.getString("name", ""); //second parameter is a default value; you could use all primitive variable types like getString, getBoolean, getLong etc

P.S。如果您在片段中使用Sharedpreferences,请使用this更改getActivity(),其他所有内容都相同,只是因为this并不代表相同的意思像活动中的片段