復雜的數據類型(類、圖像等),就需要對這些數據進行編碼。我們通常會將復雜類型的數據轉換成Base64編碼,然後將轉換後的數據以字符串的形式保存
在 XML文件中,示例代碼如下:
AddNewWord addWord=new AddNewWord();
addWord.setWords(word.getWords());
addWord.setWordClass(i);
SharedPreferences mySharedPreferences=getSharedPreferences("new_word", Activity.MODE_WORLD_READABLE);
ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
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 = -37782648386953312L;
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
+ "]";
}
}