使用Sharedpreferences检索和更新值

时间:2016-01-03 19:23:39

标签: android sharedpreferences

我需要知道如何使用共享首选项来保持我的数据持久性并更新值。我已经编写了一些代码。

MainActivity.java

SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
        if(sPrefs.contains("userData"))
        {
            retreivepreviousdata=gson.fromJson(sPrefs.getString("userData",""),DataStore.class);
            userDataStore.getDataStore().addAll(retreivepreviousdata.getDataRetrieve());
        }
            userDataStore.getDataStore().add(usrData);
            SharedPreferences.Editor prefEditor = getSharedPreferences(mypreference, Context.MODE_PRIVATE).edit();
            String saveData = gson.toJson(userDataStore);
            prefEditor.putString("userData", saveData);
            prefEditor.apply();
            Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();`

SecondActivity.java

String mypreference="user_data";
    SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
    DataStore dataPull=new DataStore();
    Gson gson=new Gson();
    String pull=sPrefs.getString("userData","");
    dataPull=gson.fromJson(pull,DataStore.class);
    System.out.println(dataPull.getDataStore().get(0).toString());
    RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    MyRecyclerAdapter mAdapter=new MyRecyclerAdapter(dataPull);
    recyclerView.setAdapter(mAdapter);

此代码的问题是输入的值已保存且持久。但是当我关闭时,重新打开应用程序并输入先前数据被覆盖的值。

2 个答案:

答案 0 :(得分:0)

将值存储到SharedPreferences

SharedPreferences shared = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = shared.edit();
            editor.putString("key", value);
            editor.commit();

要从SharedPreferences中检索值,只需使用此

SharedPreferences sharedPref = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
        String value = sharedPref.getString("key", "defaultValue");

答案 1 :(得分:0)

如果要在SharedPreferences中存储ArrayList,只需将其转换为字符串即可。然后,你可以“去转换”它。 E.G。

String toSave;
// Object is for your object type. Just get your objects converted to string, that's the point.
for(Object obj : arrayList){
    toSave += obj.toString() + "\n";
}
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", toSave);
editor.apply();

和...

SharedPreferences prefs = getSharedPreferences("PREFS_NAME",Context.MODE_PRIVATE);
String toGet = prefs.getString("key", "");
String[] parts = toGet.split("\n");
for(String s : parts){
    arrayList.add(s); // or do whatever conversion you want to get your Object type
}