如何在ListView中显示SD卡上的文件?

发布于 2024-11-03 17:18:19 字数 170 浏览 3 评论 0原文

我想创建一个按钮,单击该按钮将转到一个类,该类使用 ListView 显示 SD 卡中的所有媒体文件。

从列表中选择后,它将把所选的文件名返回到主类。如果返回的文件是图像文件,它将显示在 ImageView 中,如果返回的文件是音频文件,它将只显示一个图标。

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 from the list it will then return the filename selected to the main class. IF the returned file is an image file, it will be displayed in an ImageView and if the returned file is an audio file, it'll just display an icon.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

空名 2024-11-10 17:18:20

将方法 GetFiles() 添加到您的程序中。调用它来获取所有文件的ArrayList。然后您可以使用它来填充您的listview。您需要提供字符串参数DirectoryPath

功能:

public ArrayList<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

    f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++) 
            MyFiles.add(files[i].getName());
    }

    return MyFiles;
}

使用示例:

@Override
public void onCreate() {
// Other Code

    ListView lv;
    ArrayList<String> FilesInFolder = GetFiles("/sdcard/somefolder");
    lv = (ListView)findViewById(R.id.filelist);

    lv.setAdapter(new ArrayAdapter<String>(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
         }
    });
}

确保外部存储可读: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

<强>过滤基于名称/扩展名的文件: 如何访问SD卡并返回特定格式文件的数组?

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<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

    f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++) 
            MyFiles.add(files[i].getName());
    }

    return MyFiles;
}

Usage Example:

@Override
public void onCreate() {
// Other Code

    ListView lv;
    ArrayList<String> FilesInFolder = GetFiles("/sdcard/somefolder");
    lv = (ListView)findViewById(R.id.filelist);

    lv.setAdapter(new ArrayAdapter<String>(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?

携余温的黄昏 2024-11-10 17:18:20

首先,我强烈建议您先阅读一些有关 android 的教程,以便了解基础知识。您必须执行以下操作才能

  1. 列出所有媒体文件 - 如何列出所有Android 中的媒体?
  2. 开始new Activity
  3. Android:捕获 Activity 的返回

First i strongly suggest you read some tutorials about android first so you get the basics. You have to implement the following to do this

  1. List all media files - How to list all media in Android?
  2. Start new Activity
  3. Android: Capturing the return of an activity
゛清羽墨安 2024-11-10 17:18:20
File mfile=new File("/sdcard");
File[] list=mfile.listFiles();

System.out.println("list"+mfile.listFiles().length);
for(int i=0;i<mfile.listFiles().length;i++)
{
    if(list[i].isHidden())
    }
        System.out.println("hidden path files.."+list[i].getAbsolutePath());
    }
}

可能这会有所帮助!

File mfile=new File("/sdcard");
File[] list=mfile.listFiles();

System.out.println("list"+mfile.listFiles().length);
for(int i=0;i<mfile.listFiles().length;i++)
{
    if(list[i].isHidden())
    }
        System.out.println("hidden path files.."+list[i].getAbsolutePath());
    }
}

may this would help!!!

爱要勇敢去追 2024-11-10 17:18:20
public class FileActivity extends ListActivity {
String str;
ArrayList<String> al;
ArrayAdapter<String> adapter;
ListView lv;

@SuppressLint("SdCardPath")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.file_view);
    Intent int1=getIntent();
    ArrayList<String> arr1=GetFiles(Environment.getExternalStorageDirectory().getPath());
    adapter= new ArrayAdapter<String>(getApplicationContext(),
                            android.R.layout.simple_expandable_list_item_1,arr1);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);
}  
private ArrayList<String> GetFiles(String path) {
    ArrayList<String> arr2=new ArrayList<String>();
    File file=new File(path);
    File[] allfiles=file.listFiles();
    if(allfiles.length==0) {
        return null;
    }
    else {
        for(int i=0;i<allfiles.length;i++) {
            arr2.add(allfiles[i].getName());
        }
    }
 return arr2; 
  }


@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    }
public class FileActivity extends ListActivity {
String str;
ArrayList<String> al;
ArrayAdapter<String> adapter;
ListView lv;

@SuppressLint("SdCardPath")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.file_view);
    Intent int1=getIntent();
    ArrayList<String> arr1=GetFiles(Environment.getExternalStorageDirectory().getPath());
    adapter= new ArrayAdapter<String>(getApplicationContext(),
                            android.R.layout.simple_expandable_list_item_1,arr1);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);
}  
private ArrayList<String> GetFiles(String path) {
    ArrayList<String> arr2=new ArrayList<String>();
    File file=new File(path);
    File[] allfiles=file.listFiles();
    if(allfiles.length==0) {
        return null;
    }
    else {
        for(int i=0;i<allfiles.length;i++) {
            arr2.add(allfiles[i].getName());
        }
    }
 return arr2; 
  }


@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    }
微凉徒眸意 2024-11-10 17:18:20

更新的函数:: 将其用于新的 api

调用函数,如下所示:

 searchForFileInExternalStorage("filename.ext");  

@implementation

 public File searchForFileInExternalStorage(String filename) {
            File storage = Environment.getExternalStorageDirectory();

            return searchForFileInFolder(filename, storage);
        }

        public File searchForFileInFolder(String filename, File folder) {
            File[] children = folder.listFiles();
            File result;

            for (File child : children) {
                if (child.isDirectory()) {
                    result = searchForFileInFolder(filename, child);
                    if (result != null) {
                        return result;
                    }
                } else {
                    // replace equals by equalsIgnoreCase if you want to ignore the
                    // case of the file name
                    if (child.getName().equals(filename)) {
                        return child;
                    }
                }
            }

            return null;
        }

Updated function:: use this for new apis

call function like this:

 searchForFileInExternalStorage("filename.ext");  

@implementation

 public File searchForFileInExternalStorage(String filename) {
            File storage = Environment.getExternalStorageDirectory();

            return searchForFileInFolder(filename, storage);
        }

        public File searchForFileInFolder(String filename, File folder) {
            File[] children = folder.listFiles();
            File result;

            for (File child : children) {
                if (child.isDirectory()) {
                    result = searchForFileInFolder(filename, child);
                    if (result != null) {
                        return result;
                    }
                } else {
                    // replace equals by equalsIgnoreCase if you want to ignore the
                    // case of the file name
                    if (child.getName().equals(filename)) {
                        return child;
                    }
                }
            }

            return null;
        }
还不是爱你 2024-11-10 17:18:20

这对您来说是正确的解决方案!或者我给你一个链接这个东西!

public class SongsManager {
// SDCard Path
//choose your path for me i choose sdcard
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<hashmap<string, string="">> songsList = new ArrayList<hashmap<string, string="">>();

// Constructor
public SongsManager(){

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 * */
public ArrayList<hashmap<string, string="">> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<string, string=""> song = new HashMap<string, string="">();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

/**
 * Class to filter files which are having .mp3 extension
 * */
//you can choose the filter for me i put .mp3
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}
 }

this is a correct solution for you! or i give you a link for this stuff!

public class SongsManager {
// SDCard Path
//choose your path for me i choose sdcard
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<hashmap<string, string="">> songsList = new ArrayList<hashmap<string, string="">>();

// Constructor
public SongsManager(){

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 * */
public ArrayList<hashmap<string, string="">> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<string, string=""> song = new HashMap<string, string="">();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

/**
 * Class to filter files which are having .mp3 extension
 * */
//you can choose the filter for me i put .mp3
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文