经过前面两篇博客,大家都会基本使用RecycleView了,但是发现重新进入APP后,状态仍是之前拖拽、删除前状态,那么怎么实现保存改变后的状态呢?sharedpreferences实现不了,因为它保存的是一个 List,即是一个Object,那么我想使用File文件进行数据存储,是可以实现的:
1、首先对数据源data进行重新改造下,如果为null,就重新生成,不然就从sd卡中读取之前保存的数据:
try {
data = (List<String>) SaveObjectTool.readObject("dataset");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
Log.i(TAG, "error: "+e.toString());
e.printStackTrace();
}
if(data==null){
data = new ArrayList<String>();
for (int i = 0; i < 100; ++i) {
data.add(new String("item") + i);
}
}
2、在onMove方法中 adapter.notifyItemMoved(fromPosition, toPosition);之前加入下面保存文件代码:
try {
SaveObjectTool.writeObject(data,"dataset");
} catch (IOException e) {
Log.i(TAG, "error: "+e);
e.printStackTrace();
}
3、在onSwiped方法中 adapter.notifyItemRemoved(position);之前加入下面保存文件代码:
try {
SaveObjectTool.writeObject(data,"dataset");
} catch (IOException e) {
Log.i(TAG, "error: "+e);
e.printStackTrace();
}
4、最后SaveObjectTool 工具类方法是:
public class SaveObjectTool {
@SuppressLint("SdCardPath")
private static String defaultPath = "/sdcard/damily_cache/";
public static void writeObject(Object object, String name)
throws FileNotFoundException, IOException {
File file = getFile(name);
ObjectOutputStream outputStream = new ObjectOutputStream(
new FileOutputStream(file));
outputStream.writeObject(object);
outputStream.flush();
outputStream.close();
Log.i("SaveObjectTool", file.getAbsolutePath());
}
public static Object readObject(String name) throws FileNotFoundException,
IOException, ClassNotFoundException {
File file = getFile(name);
ObjectInputStream inputStream = new ObjectInputStream(
new FileInputStream(file));
Object object = inputStream.readObject();
inputStream.close();
Log.i("SaveObjectTool", file.getAbsolutePath());
return object;
}
private static File getFile(String name) {
File path = new File(defaultPath);
if (!path.exists()) {
path.mkdirs();
}
String objPath = path.getAbsolutePath() + name + ".txt";
File file = new File(objPath);
return file;
}
}