android中保存一个ArrayList到SharedPreferences的方法
16lz
2021-01-22
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=0;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", 0);
for(int i=0;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(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
+ "]";
}
}
第一种方案就很方便的解决了我的问题,仅此记录一下,同时也给遇到同样问题的朋友们一个思路.
更多相关文章
- android:使用网络通信技术从客户端直接获取服务端的对象数据
- 如何设计数据库模型来记录客户的历史活动?
- 为什么使用KML数据检索Android版Google方向论不再适用? [重复]
- Android 字符串资源
- 如何使用adb命令查看android中的数据库
- Android网络编程-----从服务器端获取xml数据并解析
- Android使用SQLite数据库(3)
- viewpager 分页请求数据库并展示
- 通过数据库接口获取到的中文数据是问号怎么办?