2016-01-03 41 views
-1

我需要知道如何使用共享首選項來保持我的數據持久性並更新值。我寫了一些代碼。使用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); 

這段代碼的問題是進入保存的價值和persistent.But當我關閉,重新打開應用程序,並輸入值以前的數據會被覆蓋。

回答

0

對於其存儲到SharedPreferences

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

對於從SharedPreferences檢索值如果你想店內SharedPreferences一個ArrayList只是用這個

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

我們怎麼做,在數組列表的情況下, –

0

,只需將其轉換爲字符串。然後,你可以「解除」它。例如。

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 
}