如果用户已经从存储目录中删除了recyclerview项,该如何删除?

时间:2018-09-25 05:52:48

标签: java android android-recyclerview

下面是我尝试的代码,

import android.os.FileObserver;
import android.support.annotation.Nullable;
import android.util.Log;

public class ObserveFiles extends FileObserver {
public RecyclerViewAdapter recyclerViewAdapter;

public String absolutePath;

public ObserveFiles(String path) {
    super(path, FileObserver.ALL_EVENTS);

    absolutePath = path;
}

@Override
public void onEvent(int event, @Nullable String path) {

    if (path == null) {
        return;
    }
    //a new file or subdirectory was created under the monitored directory
    if ((FileObserver.DELETE & event)!=0) {
        Log.d("Deleted---------->", "File Deleted [" + absolutePath +  "/" + path + "]");
        String filepath = absolutePath + "/" + path;
        recyclerViewAdapter.removeOutOfApp(filepath);
    }

    //data was written to a file
    if ((FileObserver.MODIFY & event)!=0) {
        Log.d("Deleted---------->", "File Modified [" + absolutePath  +  "/" + path + "]");
    }

    //the monitored file or directory was deleted, monitoring effectively stops
    if ((FileObserver.DELETE_SELF & event)!=0) {
        Log.d("Deleted---------->", "File Self Deleted [" + absolutePath + "/URecorder" +  "/" + path + "]");
    }

    //a file or directory was opened
    if ((FileObserver.MOVED_TO & event)!=0) {
        Log.d("Deleted---------->", "File Moved To [" +  absolutePath  +  "/" + path  + "]");
    }

    //a file or subdirectory was moved from the monitored directory
    if ((FileObserver.MOVED_FROM & event)!=0) {
        Log.d("Deleted---------->", "File Moved From [" + absolutePath  +  "/" + path + "]");
    }

    //the monitored file or directory was moved; monitoring continues
    if ((FileObserver.MOVE_SELF & event)!=0) {
        Log.d("Deleted---------->", "File Moved Self[" + absolutePath  + "/" +  path + "]");
    }

}
}

............................................... .................................

@Override
    protected void onResume() {
    super.onResume();

    String filePath = android.os.Environment.getExternalStorageDirectory().toString() + "/URecorder";
    observeFiles = new ObserveFiles(filePath);
    observeFiles.startWatching();
}

@Override
protected void onDestroy() {
    super.onDestroy();

    observeFiles.stopWatching();
}

3 个答案:

答案 0 :(得分:1)

欢迎您! :)

这是伪代码:

1)删除:从RecyclerView删除项目有4个步骤

list.remove(position);
recycler.removeViewAt(position);
mAdapter.notifyItemRemoved(position);                 
mAdapter.notifyItemRangeChanged(position, list.size());

这些代码行对我有用。

2)更新数据:我唯一要做的就是

mAdapter.notifyDataSetChanged();

您必须使用“活动/片段”代码而不是RecyclerView适配器代码来完成所有这些操作。

希望有帮助。

答案 1 :(得分:0)

我不知道您的数据/文件数量或您正在执行的任务。 但是,另一种可选方式是将数据加载到OnResume();中。 如果用户 最小化应用程序>删除文件。.>当应用程序进入前台时,将再次调用onResume。

因此,每次它将加载新数据,除非其他背景事物将删除该文件。

答案 2 :(得分:0)

字符串路径=“ file://” + newfile [i] .getAbsolutePath();

文件文件=新文件(路径);

file.delete();

这是直接从存储中删除文件的过程