2016-02-13 75 views
0

您好我一直以來都在尋找一種方式來保存和檢索與自定義對象的ArrayList到機器人Sharedpreferences。很幸運我有一個辦法做到這一點使用這個Answer從ArrayList中<object>刪除一個對象保存在sharedPreferences

public void saveArray(ArrayList<CartItem> sKey) 
{ 
    SharedPreferences sp = PreferenceManager 
      .getDefaultSharedPreferences(this.getApplicationContext()); 
    SharedPreferences.Editor mEdit1 = sp.edit(); 

     Gson gson = new Gson(); 
     String json = gson.toJson(sKey); 
     mEdit1.putString("itemx", json); 
     mEdit1.commit(); 
} 

public ArrayList<CartItem> readArray(){ 
    SharedPreferences appSharedPrefs = PreferenceManager 
      .getDefaultSharedPreferences(this.getApplicationContext()); 
    String json = appSharedPrefs.getString("itemx", ""); 
    Gson gson = new Gson(); 
    Type type = new TypeToken<ArrayList<CartItem>>(){}.getType(); 
    ArrayList<CartItem> List = gson.fromJson(json, type); 

    return List; 
} 

現在,這裏是我想要的只是刪除ArrayList中的對象的一個​​部分,我該怎麼辦呢?

+1

從SharedPreferences獲取它到字符串並使用Gson解析它到Array,移除該項並將其保存到SharedPreferences中。 – ddog

+0

@ddog你能告訴我一些示例代碼 – Tuna

+0

你如何確定從ArrayList中刪除哪個對象?你想在此之後做任何事嗎? –

回答

1

您可以閱讀陣列,刪除元素,並將其保存回:

public void removeElement(CartItem item) { 
    ArrayList<CartItem> items = readArray(); 
    items.remove(item); 
    saveArray(items); 
} 

附:如果你不是一個嚴重的動機同步做到這一點的方法,我建議你在你的保存方法與apply()替換commit()(保存將是異步的話)。

+0

iam以異步的方式使用這些方法,但閱讀UI線程上的sharedpreferences似乎很慢,我想我應該使用數據庫或文件來代替。 – Tuna

+0

@ C.B如果您不需要,我絕不建議將對象保存在SP中。數據庫是管理自定義模型的最佳方式 –

-1

充分利用SharePreferences的JSON和轉化爲對象的部分在你的代碼已經提到的,如果你知道哪些需要被然後被刪除步驟的對象CartItem。

  1. 覆蓋equalsCartItem,這將有助於在列表裏面比較對象。
  2. Arraylist.conatins(Object)如果爲true,則繼續並刪除它。 ArrayList.remove(Obejct)