MainActivity
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
private List<String> myList;
File file;
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.i("MEDIA", "A");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("MEDIA", "B");
ListView listView = (ListView) findViewById(R.id.listView1);
myList = new ArrayList<String>();
Log.i("MEDIA", "C");
File directory = Environment.getExternalStorageDirectory();
file = new File(directory + "/Test");
File list[] = file.listFiles();
Log.i("MEDIA", "D");
//for (int i = 0; i < list.length; i++)
for (int i = 0; i < 5; i++)
{
Log.i("MEDIA", "D1"); //CRASHES HERE
//myList.add(list[i].getName());
myList.add(list[i].getName());
Log.i("MEDIA", "D2");
}
Log.i("MEDIA", "E");
final StableArrayAdapter adapter = new StableArrayAdapter(this,android.R.layout.simple_list_item_1, myList);
listView.setAdapter(adapter);
// Set all the file in the list.
}
private class StableArrayAdapter extends ArrayAdapter<String>
{
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,List<String> objects)
{
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i)
{
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position)
{
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds()
{
return true;
}
}
}
Log: http://pastebin.com/WWmqKKvQ
I've picked the answer form this question on SO:
How to show audio files in a listview in Android?
Andhave also tried this tutorial:
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
The probem was that "/Test" directory does not exist, so i replaced it with "/Bluetooth" (which is a dir that exists) , and now it displays a list of files in that folder.
Problem solved. :D
Log.i("MEDIA", "C");
File directory = Environment.getExternalStorageDirectory();
file = new File(directory+ "/Bluetooth");// + "/Test");
File list[] = file.listFiles();
Related
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 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
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
This question already has answers here:
Android expandable list need help to delete item
(2 answers)
Closed 8 years ago.
public class DeleteActivity extends ExpandableListActivity {
private RingtoneAdapter expListAdapter;
int myProgress = 0;
List<String> items = new ArrayList<String>();
final Context myApp = this;
// private static final String DIRECTORY = "/system/media/audio/ringtones/";
private static final String DIRECTORY = "/sdcard/download/";
private MediaPlayer mp = new MediaPlayer();
List<String> Ringtones = new ArrayList<String>();
ArrayAdapter<String> adapter;
TextView tv, empty;
ExpandableListView exlv1;
// ListView lv1;
Boolean hasErrors = false;
int currentPosition = 0;
private static final String LOG_TAG = "MobiIntheMorning";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
refreshList();
Toast.makeText(this, "hello this is delete called", Toast.LENGTH_LONG).show();
Ringtones.remove(DIRECTORY+Ringtones.get(1));//THIS DOSE NOT GIVING ANY AFFECT
refreshList();
Intent i = new Intent(DeleteActivity.this, FindFilesByType.class);
startActivity(i);
}
public void refreshList() {
File ringtones_directory = new File(DIRECTORY);
if (!ringtones_directory.exists()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Directory Not Found");
ad.setMessage("Sorry! The ringtones directory doesn't exist.");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
}
if ( !ringtones_directory.canRead()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! You don't have permission to list the files in that folder");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
} else {
Ringtones = FindFiles(false);
if (Ringtones.size() < 1) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! No ringtones exists in " + DIRECTORY
+ ".");
ad.setPositiveButton("OK", null);
ad.show();
Log.e(LOG_TAG, "No ringtones were found.");
hasErrors = true;
}
}
try {
if ( !hasErrors) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
DeleteActivity.this, android.R.layout.test_list_item,
Ringtones);
ArrayList<String> GrouppList = new ArrayList<String>();
GrouppList.addAll(Ringtones);
ArrayList<ArrayList<Color>> colors = new ArrayList<ArrayList<Color>>();
for (int i = 0; i <= Ringtones.size(); i++) {
ArrayList<Color> color = new ArrayList<Color>();
color = new ArrayList<Color>();
color.add(new Color("", "", true));
colors.add(color);
}
expListAdapter = new RingtoneAdapter(this, GrouppList, colors);
Toast.makeText(this, GlobalVariable.getstrEmail(),
Toast.LENGTH_LONG).show();
Ringtones.remove(0);
// setListAdapter(expListAdapter);
exlv1 = (ExpandableListView) findViewById(R.id.expandableListView1);
this.exlv1.setAdapter(this.expListAdapter);
}
this.exlv1.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
Toast.makeText(DeleteActivity.this, "hello" + arg0,
Toast.LENGTH_LONG).show();
GlobalVariable.SetcurrentPosition(arg0);
GlobalVariable.SetstrEmail(DIRECTORY + Ringtones.get(arg0));
}
});
} catch (Exception e) {
Toast.makeText(this, "Error " + e.toString(), Toast.LENGTH_LONG)
.show();
Log.i(LOG_TAG, e.toString());
}
}
private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
Resources resources = getResources();
// array of valid audio file extensions
String[] audioTypes = resources.getStringArray(R.array.audio);
FilenameFilter[] filter = new FilenameFilter[audioTypes.length];
int i = 0;
for (final String type : audioTypes) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File(DIRECTORY), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
} else {
tFileList.add(f.getName());
}
}
return tFileList;
} // find fil
#SuppressWarnings("unchecked")
public List<String> loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
List<String> read_field = (List<String>) in.readObject();
in.close();
return read_field;
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
public Collection<File> listFiles(File directory, FilenameFilter[] filter,
int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter.accept(directory, entry.getName())) {
files.add(entry);
Log.v(LOG_TAG, "Added: " + entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory()))
files.addAll(listFiles(entry, filter, recurse - 1));
}
}
return files;
}
public class FileUtils {
public void saveArray(String filename, List<String> output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
} catch (IOException e) {
e.getStackTrace();
}
}
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
}
}
I've done some code that code fetches .mp3 files from the sdcard and displays it to me
now i am trying to delete selected item from it using
Ringtones.remove(DIRECTORY+Ringtones.get(1));
that is it should delete my first item from the list but it doesn't works for me
what is wrong i ma doing into this?
I am not able to find any silly mistakes I made here; Ringtones.remove("test.mp3"); and Ringtones.remove(1.mp3); both I've also tried.
Why are you doing
DIRECTORY + Ringtones.get(1)
Ringtones is a List so you want to be doing something like
Ringtones.remove(1);
or
Ringtones.remove(aRintoneString)
what you effectively doing here is getting the first element and adding a other string which gives you a NEW third string that doesn't exist in Ringtones
Hi Call notifyDataSetChanged() on your Adapter after removing the item from the List.
It will refresh your List and you will get updated items in your list.