SharedPreferences - Android(不同的数据类型)

时间:2014-01-14 22:41:01

标签: android primitive-types

我在两个不同活动之间共享数据时遇到问题。我有类似的数据:

 int number
 String name 
 int number_2
 int time
 int total

我试图使用这组数据制作订单列表。因此,它将采用一组数据,然后返回到先前的活动,向前移动并再次向其添加数据。

我知道在对象数组中创建它 - 但是在更改活动后,内部数据被清除。

我该怎么做?

我不知道是否以及如何将对象Array添加到SharedPreferences,并从那里获取一个元素的值。

3 个答案:

答案 0 :(得分:1)

如果您想要将密钥与要传递给第二个活动的值相关联,那么您应该查看Intent(s)的文档。

无论如何,你可以认为任何(sharedpref,database,...)方式传递你的参数,但对于那些事情来说,这是一个惯例,也是一个好的做法。

答案 1 :(得分:0)

为什么不使用Intents

Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);

在第二项活动中

Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");

编辑如果您想了解有关向共享首选项添加数组的详情,请查看

Is it possible to add an array or object to SharedPreferences on Android

也是这个

http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html

答案 2 :(得分:0)

不要为此使用共享首选项...使用单例模式,扩展Application,或者只使用静态变量创建一个类并更新它们......

您可以使用.putExtra,但由于您正在与多个活动进行通信,因此上述建议可能是最好的。

public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}

public static ShareData getInstance(){ return shareData} 
//create getters and setters;
}