文件浏览中找不到文件夹

时间:2016-09-19 09:13:46

标签: android

我尝试过以下代码。

public class MainActivity extends GlobalActivity implements CompetitionListAdapter.OnOperationSelectedListener {

    private String path = "";
    private RecyclerView recyclerView;
    private boolean isOnBackPressed = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initLogger("MainActivity");
        recyclerView = (RecyclerView) findViewById(R.id.listRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);        
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        //path = "/storage/emulated/0/Download/pictures"; //When I pass this, then I can get the list of files in this folder.
        loadFolders(path);
    }

    private void loadFolders(String path) {
        if (this.path.isEmpty()) {
            this.path = path;
        } else if (!isOnBackPressed) {
            this.path += "/" + path; //But when I make same the path dynamically from here file2 is always null. 
        }
        writeLog(this.path);
        File f = new File(path);
        File file2[] = f.listFiles();
        ArrayList<String> folders = new ArrayList<>();
        if (file2 != null) {
            for (File file1 : file2) {
                folders.add(file1.getName());
            }
        } else {
            writeLog("fList is empty");
        }
        recyclerView.setAdapter(new CompetitionListAdapter(folders, this));
    }

    @Override
    public void onOperationSelected(CompetitionListAdapter.Operation operation, String name) {
        isOnBackPressed = false;
        loadFolders(name);
    }

    @Override
    public void onBackPressed() {
        String paths[] = this.path.split("/");
        if (path.length() > 1) {
            path = "";
            for (int i = 1; i < paths.length - 1; i++) {
                path += "/" + paths[i];
            }
            isOnBackPressed = true;
            loadFolders(path);
            return;
        }
        super.onBackPressed();
    }
}

所以上面的代码在启动应用程序时起作用...如果我从列表中选择任何文件夹,那么我会动态地在loadFolders创建路径,但这总是返回null。

3 个答案:

答案 0 :(得分:1)

您是适配器中的传递文件夹名称列表,这是

文件夹名称 folder_path 实例的原因
   @Override
    public void onOperationSelected(CompetitionListAdapter.Operation operation, String name) {
        isOnBackPressed = false;
        loadFolders(name);
    }

替换

folders.add(file1.getName());

folders.add(file1.getAbsolutePath());

答案 1 :(得分:0)

每次需要更新内部数据时,不要创建新的CompetitionListAdapter。 我不知道您的适配器是如何工作的,但您应该创建一个方法来更新/添加项目中的列表,然后您调用notifyDataSetChanged来更新视图。

答案 2 :(得分:0)

确保您必须使用以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如果您已经使用过,请确保路径是否正确。