How to display files on the SD card in a ListView?

前端 未结 6 2110
遥遥无期
遥遥无期 2020-12-03 06:24

I would like to create a button that when clicked will go to a class that displays all media files from an SD card using a ListView.

After selecting fro

6条回答
  •  误落风尘
    2020-12-03 06:43

    Add a Method GetFiles() to your program. Call it to get an ArrayList<> of all the files. You can then use it to populate your listview. You need to provide String argument DirectoryPath.

    The Function:

    public ArrayList GetFiles(String DirectoryPath) {
        ArrayList MyFiles = new ArrayList();
        File f = new File(DirectoryPath);
    
        f.mkdirs();
        File[] files = f.listFiles();
        if (files.length == 0)
            return null;
        else {
            for (int i=0; i

    Usage Example:

    @Override
    public void onCreate() {
    // Other Code
    
        ListView lv;
        ArrayList FilesInFolder = GetFiles("/sdcard/somefolder");
        lv = (ListView)findViewById(R.id.filelist);
    
        lv.setAdapter(new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, FilesInFolder));
    
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
                // Clicking on items
             }
        });
    }
    

    Make sure that the External Storage is Readable: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

    To Filter files based on Name/Extension: How to acces sdcard and return and array with files off a specific format?

提交回复
热议问题