android中儲存一個ArrayList到SharedPreferences的方法
今天在項目中需要本地儲存一個ArrayList,因為不想儲存在資料庫中,首先便想到了便利的sp,但是根據自己已有知識發現sp隻能存寫基本資料,對于一些複雜資料并沒有提供合适的方法,于是就搜尋了解決方案.如下所示:
儲存
public boolean saveArray(List<String> list) {
SharedPreferences sp = mContext.getSharedPreferences("ingoreList", mContext.MODE_PRIVATE);
SharedPreferences.Editor mEdit1= sp.edit();
mEdit1.putInt("Status_size",list.size());
for(int i=;i<list.size();i++) {
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, list.get(i));
}
return mEdit1.commit();
}
取值
public void loadArray(List<String> list) {
SharedPreferences mSharedPreference1 = mContext.getSharedPreferences("ingoreList", mContext.MODE_PRIVATE);
list.clear();
int size = mSharedPreference1.getInt("Status_size", );
for(int i=;i<size;i++) {
list.add(mSharedPreference1.getString("Status_" + i, null));
}
}
———————————————-
如果想用SharedPreferences存取更複雜的資料類型(類、圖像等),就需要對這些資料進行編碼。我們通常會将複雜類型的資料轉換成Base64編碼,然後将轉換後的資料以字元串的形式儲存在 XML檔案中
需要用到:commons-codec-1.4.jar
如下所示
AddNewWord addWord=new AddNewWord();
addWord.setWords(word.getWords());
addWord.setWordClass(i);
SharedPreferences mySharedPreferences=getSharedPreferences("new_word", Activity.MODE_WORLD_READABLE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos=null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(addWord);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 将Product對象放到OutputStream中
// 将Product對象轉換成byte數組,并将其進行base64編碼
String newWord = new String(Base64.encodeBase64(baos.toByteArray()));
SharedPreferences.Editor editor = mySharedPreferences.edit();
// 将編碼後的字元串寫到base64.xml檔案中
editor.putString("newWord", newWord);
editor.commit();
讀取對象:
String wordBase64 = mySharedPreferences.getString("new_word", "");
// 對Base64格式的字元串進行解碼
byte[] base64Bytes = Base64.decodeBase64(wordBase64 .getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
// 從ObjectInputStream中讀取Product對象
AddNewWord addWord= (AddNewWord ) ois.readObject();
對象實體:
public class AddNewWord implements Serializable{
private static final long serialVersionUID = -L;
private String words;
private int wordClass;
public String getWords() {
return words;
}
public void setWords(String words) {
this.words = words;
}
public int getWordClass() {
return wordClass;
}
public void setWordClass(int wordClass) {
this.wordClass = wordClass;
}
@Override
public String toString() {
return "AddNewWord [words=" + words
+ ", wordClass=" + wordClass
+ "]";
}
}
第一種方案就很友善的解決了我的問題,僅此記錄一下,同時也給遇到同樣問題的朋友們一個思路.