2013-01-31 44 views
1

我有我自己的对象,我需要存储以供将来使用。用户保存这个对象,它被转换成JSON字符串,然后当用户连接到网络时,JSON字符串被重新转换为对象操作。如何使用SharedPreferences保存变量

我的问题是,在运行时,我该如何知道如何存储对象?

Gson gson= new Gson(); 
String pointOfInterest = gson.toJson(point); 
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit(); 
sharedprefEditor.putString(?KEY?,pointOfInterest); 

我可以用什么键的值?如果我使用索引,每次打开或关闭应用程序时都会重置,这将取代我的对象。

编辑 对不起,我没有搞清楚的是,上面的代码是在方法可以运行任意次数,有可能是几个pointsOfInterest存储。

+0

您可能错过了有关SharedPreferences的内容。 'key'唯一标识了您保存的值,并且可以使用相同的密钥将其返回。除非明确这样做,否则没有什么会“重置”。不要忘记'commit()'你的改变,尽管 – 323go

+0

不要使用SharedPreferences。它不是为了存储这样的数据而设计的。顾名思义,它就是存储用户设置(尽管它也有其他用途)。简单的布尔,字符串就是这样的事情。只需将您的JSON写入私有存储中的文件即可。 – Simon

回答

1

首先,如果你使用一个索引,优先级将永留:

例如:

sharedprefEditor.putString("JSON569",pointOfInterest); 

您也可以保存在其他偏好指数;例如通过用柱分离:

sharedprefEditor.putString("indexes","569;789;852"); 

您可以轻松地检查一个实例是否存在:

myPreference.getString("JSON789","").contentEquals(""); 

还是让所有的实例:

for (int anIndex:indexes) 
    Log.i("TAG","Current value: "+myPreference.getString("JSON"+anIndex,"")); 

请xplain多一点点你的问题,我看到没有困难/

+0

对不起,我忘了注意,代码可能会运行多次,我可能需要存储一些PointOfInterest对象 – TomSelleck

+0

请参阅编辑的答案 –

+0

问题是,如果我使用索引,然后应用程序被最小化,索引是重置,所以当它再次启动时,它将开始覆盖旧的 – TomSelleck

0

你可以任意命名的关键,只是让它c onsistent。做到这一点的方法之一是让一个恒定在你的类吧:

public class MyClass { 
    private static final String OBJECT_KEY = "myObjectKey"; 

    ... 

然后,当你保存你的对象:

Gson gson= new Gson(); 
String pointOfInterest = gson.toJson(point); 
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit(); 
sharedprefEditor.putString(OBJECT_KEY,pointOfInterest); 

当你加载它,只需使用OBJECT_KEY得到一个字符串出来的共享首选项:

String objectString = sharedPrefs.getString(OBJECT_KEY, ""); 
+0

感谢您的答复,对不起,我忘了提到,上面的代码可以运行很多次,并且可能有多个对象 – TomSelleck

+0

您最好制作自己的[SQLite](http://developer.android.com/guide/topics/data/data-storage.html#db)数据库然后。 – Ralgha