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.
Most Android phones come preinstalled with at least one file manager app. A file manager app lets you view and work with the files sitting on both internal and SD card storage on your device. This app may be called File Manager, Files, or something similar and should be available in the app drawer of your device.
Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With