2014-12-24 115 views
2

我需要在我的SharedPreferences中存儲一個類型爲「Comment」的ArrayList。這是我的模型類:Android:在SharedPreferences中存儲ArrayList <T>?

public class Comment { 

    public String getPID() { 
     return PID; 
    } 
    public void setPID(String pID) { 
     PID = pID; 
    } 
    public String PID; 
    public String Comment; 
    public String Commenter; 
    public String Date; 

    public String getComment() { 
     return Comment; 
    } 
    public void setComment(String comment) { 
     Comment = comment; 
    } 
    public String getCommenter() { 
     return Commenter; 
    } 
    public void setCommenter(String commenter) { 
     Commenter = commenter; 
    } 
    public String getDate() { 
     return Date; 
    } 
    public void setDate(String date) { 
     Date = date; 
    } 
} 

所以我的ArrayList包含2個需要存儲在SharedPreferences中的註釋。我試過HashSet,但它需要字符串值:

ArrayList<Comment_FB> fb = getFeedback(); //my Comments List 

SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0); 
Editor editor = pref.edit(); 
Set<String> set = new HashSet<String>(); 
set.addAll(fb); 
editor.putStringSet("key", set); 
editor.commit(); 

我該如何解決這個問題? :)

+0

序列化你的'評論'類 – Elango

+0

好了嗎? @Elango – Pjayness

+0

使用GSON將其保存爲SP – WISHY

回答

1

我認爲你需要將它作爲一個文件存儲。

public static boolean save(String key, Serializable obj) { 
    try { 
     FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key); 
     ObjectOutputStream objOutStream; 
     objOutStream = new ObjectOutputStream(outStream); 
     objOutStream.writeObject(obj); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 

    return true; 
} 


public static Object getObject(String key) { 
    Object obj = null; 
    if (!new File(instance.getCacheDir() + "/" + key).exists()) 
     return obj; 
    FileInputStream inputStream; 
    try { 
     inputStream = new FileInputStream(instance.getCacheDir() + "/" + key); 
     ObjectInputStream objInputStream = new ObjectInputStream(inputStream); 
     obj = objInputStream.readObject(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return obj; 
} 

您的「評論」類應執行Serializable

相關問題