May Be this works on before Lolipop/Kitkat but I didn't test it. I am testing this on marshmallow on my xperia m2 aqua and It's not displaying music from my removable sdcard, so, I copied two music from sdCard to Internal Storage and it's displaying those two music. Other music player are working well on phone. Below is my code:
public class ListviewActivity extends AppCompatActivity {
ListView listView;
String[] items;
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs);
listView= (ListView) findViewById(R.id.listView);
ArrayList<File> mySongs = findSong(Environment.getExternalStorageDirectory());
Log.d("myLog"," "+Environment.getExternalStorageState());
Log.d("myLog"," "+Environment.getExternalStorageDirectory());
Log.d("myLog"," "+Environment.getExternalStorageDirectory().getAbsolutePath());
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
Toast.makeText(this, " "+mySongs.get(i).getName().toString(), Toast.LENGTH_SHORT).show();
// items[i] = mySongs.get(i).getName().toString();
items[i] = mySongs.get(i).getName().toString();
}
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
Log.d("myLog"," "+items);
listView.setAdapter(arrayAdapter);
}
public ArrayList<File> findSong(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles(); // All file and folder automatic collect
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSong(singleFile)); //Recursively call
} else {
if (singleFile.getName().endsWith(".mp3")) {
al.add(singleFile);
}
}
}
return al;
}
}
Log.d from above code results
mounted
/storage/emulated/0
/storage/emulated/0
Manifest Permisson
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And Permisson Programmically for Marshmallow and higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 738);
}
}
Result Its only displaying songs from internal storage. I have added two songs to internal storage for checking, and it displyed. Why not reading from sdCard although I have set the permission and all working code??
UPDATE
@Manoj has flag this question as possible duplicate but it's not true. I have give a proper permission and if user also hits on deny then it will ask again next time. In my code I have use if/else for permission, I think @Manoj didn't see it clearly..