I want to list all the files on the SD card. I use a this code for it:
myList = new ArrayList();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( "storage/" + root_sd ) ;
Log.e(myLog, file.getName());
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
Log.e(myLog, list[i].getName() + " : " + list[i].getTotalSpace());
}
And I get a nullPointerException for it after I log the name. I tried an other file also:
file = new File( root_sd ) ;
Ended with the same result.
So, how can I list the files properly? Thx for help!
...//initing the variables
String fileName = Environment.getExternalStorageDirectory().toString();
title.setText(fileName);
ArrayList<String> FilesInFolder = GetFiles(fileName);
mList.setAdapter(new ArrayAdapter<String>(getActivity() , android.R.layout.simple_list_item_1 , FilesInFolder));
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
and 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;
}
If you want a different layout make an own ArrayAdapter
Related
In my app, first a create a NewFolder, and then i record audios and save them inside this new folder. I also have a ArrayList to show my RecordsHere I create the NewFolder
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String sep = File.separator; // Use this instead of hardcoding the "/"
String newFolder = "FolderName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
//myNewFolder.mkdir();
myNewFolder.mkdirs();
while (fs.getfetchstatus() != true) {
mySongs = fs.findSongs(Environment.getExternalStorageDirectory());
//>>>>>>>>>>HERE IS HAVING ANY ERROR<<<<<<<<<
}
if (mySongs != null) {
dialog.dismiss();
}
mySongs = fs.getsonglist();
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
items[i] = mySongs.get(i).getName().toString().replace(".3gp", "");
}
final ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items);
adp.notifyDataSetChanged();
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Player.class);
intent.putExtra("pos", i);
adp.notifyDataSetChanged();
startActivity(intent);
finish();
}
});
here is my ArrayList
boolean fetchstatus=false;
ArrayList<File> songs=new ArrayList<File>();
String sep = File.separator; // Use this instead of hardcoding the "/"
String newFolder = "FolderName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
//File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
FetchSongs(){
}
public ArrayList<File> findSongs(File root){
ArrayList<File> al=new ArrayList<File>();
// File[] files=root.listFiles();
//File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(Environment.getExternalStorageDirectory(), newFolder);
File[] files = file.listFiles();
for (File singleFile : files){
if(singleFile.isDirectory() && !singleFile.isHidden()){
al.addAll(findSongs(singleFile));
//>>>>>>>ERROR HERE<<<<<<<<<<<<<<<<<<<
}
else {
if(singleFile.getName().endsWith(".mp3")){
al.add(singleFile);
}
}
}
fetchstatus=true;
songs=al;
return al;
}
I'm having these errors
java.lang.RuntimeException: Unable to start activity ComponentInfo
at org.usr.usr.musicplayer.FetchSongs.findSongs(FetchSongs.java:35)
at org.usr.usr.musicplayer.MainActivity.onCreate(MainActivity.java:124)
Maybe it's just this line the error
File file = new File(Environment.getExternalStorageDirectory(), newFolder);
Nexus not always has got an external storage, but to be more accurate you should check the trace error, most likely you'll be able to see the exactly lines that cause the runt time error
Sort list view with Folders and Files alphabetically
I am trying the following code
public class MainActivity extends ActionBarActivity {
private File file;
private List<String> myList;
private ListView listView;
private TextView pathTextView;
private String mediapath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
private final static String[] acceptedExtensions= {"mp3", "mp2", "wav", "flac", "ogg", "au" , "snd", "mid", "midi", "kar"
, "mga", "aif", "aiff", "aifc", "m3u", "oga", "spx"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.pathlist);
pathTextView=(TextView) findViewById(R.id.path);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
Log.e("Root",root_sd);
String state = Environment.getExternalStorageState();
File list[] = null ;
/* if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
list=getAllFilesOfDir(Environment.getExternalStorageDirectory());
}*/
pathTextView.setText(root_sd);
file = new File( root_sd ) ;
list = file.listFiles(new AudioFilter());
Log.e("Size of list ","" +list.length);
//LoadDirectory(root_sd);
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0)
myList.add(name);
/*int count=getAllFilesOfDir(list[i]);
Log.e("Songs count ",""+count);
*/
}
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList ));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
File temp_file = new File( file, myList.get( position ) );
if( !temp_file.isFile())
{
//LoadDirectory(myList.get( position ));
file = new File( file, myList.get( position ));
File list[] = file.listFiles(new AudioFilter());
myList.clear();
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0)
myList.add(name);
/*int count=getAllFilesOfDir(list[i]);
Log.e("Songs count ",""+count);
if(count!=0)
myList.add(name);*/
}
pathTextView.setText( file.toString());
//Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, myList ));
}
}
});
}
It gives me the files and folders for all songs
Howevever ,If a folder contains both sub folders and songs ,I want to sort the listview to show all sub folders first and then all the songs in that folder
How can this be done
use this function
Collections.sort(myList);
add this line before setAdapter.
it will sort your String Arraylist in Alphabet order.
Try the following code to sort:
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
I am developing a simple audio streaming android app. While playing audios from the URLs, the app also has an option to download the file. The audio files are being downloaded in Internal Storage/voices folder. How can I show all the downloaded audios of this folder in my app? I want to access all the audios in voices folder and show in my app so the users don't need to search the files manually. Please guide. Thank you!
String path = Environment.getExternalStorageDirectory().toString()+"/voices";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
This way you will get all the files stored in voices directory into files array.
I did it using the following code:
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
private MediaPlayer mp = new MediaPlayer();
private List<String> ListOfFiles = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString()+"/voices";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
for (int i = 0; i < files.length; i++) {
ListOfFiles.add(files[i].getName());
}
listAdapter = new ArrayAdapter<String>(this, R.layout.row_layout, ListOfFiles);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(path +"/"+ ListOfFiles.get(position));
Log.d("Path",path + ListOfFiles.get(position));
}
});
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
I know how to list the files, but
getFilesDir()
and
Environment.getExternalStorageDirectory()
both gives internal storage list
Please help me
Full Code
Internal
File dir = new File(getFilesDir().getAbsolutePath());
File[] list = dir.listFiles();
String[] name = new String[list.length];
for (int i = 0; i < name.length; i++) {
name[i] = list[i].getName();
}
ListAdapter adapter = new FilesAdapter(this, android.R.layout.simple_list_item1, name);
ListView listView = (ListView) findViewById(R.id.internal_list);
listView.setAdapter(adapter);
External
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath());
File[] list = dir.listFiles();
String[] name = new String[list.length];
for (int i = 0; i < name.length; i++) {
name[i] = list[i].getName();
}
ListAdapter adapter = new FilesAdapter(this, android.R.layout.simple_list_item1, name);
ListView listView = (ListView) findViewById(R.id.internal_list);
listView.setAdapter(adapter);
Thanks
I have set up code to display all folders that are on the SD card but now I am trying to figure out how to only display folders which contain MP3 files.
How can I filter out the folders that don't contain .MP3 files? thanks.
class:
public class FragmentFolders extends ListFragment {
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
File temp_file = new File(file, myList.get(position));
if (!temp_file.isFile()) {
file = new File(file, myList.get(position));
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
Toast.makeText(getActivity(), file.toString(), Toast.LENGTH_LONG)
.show();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
return;
}
}
You can check if the files within a directory are mp3 files before adding to your list view's dataset
Modify your code as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
//list content of root sd
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
//check the contents of each folder before adding to list
File mFile = new File(file, list[i].getName());
File dirList[] = mFile.listFiles();
if(dirList == null) continue;
for (int j = 0; j < dirList.length; j++) {
if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp3")){
myList.add(list[i].getName());
break;
}
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
}
I tested this and it works. Only caveat is, it doesn't check for sub-directories.
So in:
sdcard/Music/mistletoe.mp3
sdcard/Media/Tracks/mistletoe.mp3
only the Music folder will be listed.
Also, you may want to use an asyncTask to eschew hogging the UI thread
You can user a fileNameFilter and filter out the folders/files you don't want.
File baseDirectory = new File("/mnt/sdcard/"); //Your base dir here
File[] files = baseDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String fileName) {
File possibleMp3Folder = new File(dir, fileName);
if (possibleMp3Folder.isDirectory()) {
File[] files1 = possibleMp3Folder.listFiles();
for (File file : files1) {
if (file.getName().toLowerCase().endsWith(".mp3")) {
return true;
}
}
}
return false;
}
});
If you are looking for all folders contains mp3 files (both on Internal storage and SD Card) and available storages contains media:
Initialize two Sets for media storage paths and mp3 folders paths:
private HashSet<String> storageSet = new HashSet<>();
private HashSet<String> folderSet = new HashSet<>();
Get both in one method (you can return value if you need only one):
private void getMediaFolders() {
ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = resolver.query(uri, projection, selection, null, null);
if(cursor != null && cursor.getCount() > 0) {
int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
while(cursor.moveToNext()) {
String data = cursor.getString(dataIndex);
int i = 0;
for (int slashCount = 0; i < data.length(); i++) {
if (data.charAt(i) == '/' && ++slashCount == 3) {
storageSet.add(data.substring(0, i));
break;
}
}
if (data.toLowerCase().endsWith("mp3")) {
int lastSlashIndex = data.lastIndexOf('/');
while (i < lastSlashIndex) {
data = data.substring(0, lastSlashIndex);
folderSet.add(data);
lastSlashIndex = data.lastIndexOf('/');
}
}
}
}
if (cursor != null) { cursor.close(); }
}
Filter folders (with Annimonstream):
private ArrayList<File> getFilteredFolders(#NonNull String path, HashSet<String> folderSet) {
File[] filesList = new File(path).listFiles();
if (filesList == null) { return new ArrayList<>(); } // Or handle error as you wish
return Stream.of(filesList)
.filter(File::isDirectory)
.filter(f -> folderSet.contains(f.getAbsolutePath()))
.collect(Collectors.toCollection(ArrayList::new));
}
Show storages (if needed).
Uri,Projection,
MediaStore.Video.Media.DATA
+ " like " + "'%.mp4%'"
+ " AND "
+ MediaStore.Video.Media.DATA
+ " like " + "'%" + getResources().
getString(R.string.string_store_video_folder)
+"%'", null,
MediaStore.Video.Media.DATE_MODIFIED
this will give mp4 files in a specific folder