I have a problem with playing songs, which are in listview.
Songs are correctly save, but I can not to play them. I have a path of songs, so everything should work... Here is a code in oncreate and outside: listView = (ListView) findViewById(R.id.filesList);
ArrayList<String> FilesInFolder = GetFiles("/sdcard/Kandydaci");
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
File audioFile = getApplicationContext().getCacheDir();
String name = (String) parent.getItemAtPosition(position);
String OUTPUT_FILE ="sdcard/Kandydaci/"+name;
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
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;
}
And here is bug, which I get after click on item in listview:
E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
E/FileSource: Failed to open file 'sdcard/Kandydaci/Thu Nov 30 17:36:34 GMT+01:00 2017.mp3'. (Permission denied)
E/GenericSource: Failed to create data source!
E/MediaPlayer: error (1, -2147483648)
your code is absolutely correct but problem is you missed defining permission to access EXTERNAL STORAGE.
So go like that.
Declare in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Now add this code before list setting:
If(ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission))
{
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
}
else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
By this code you will get the storage access permissions, here permission is:
String ="Manifest.permission.WRITE_EXTERNAL_STORAGE";
Happy coding!!