RecyclerView-重新进入APP仍保存拖拽、删除后状态(数据改变状态)-3

经过前面两篇博客,大家都会基本使用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;
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值