I am trying to load all the mp3 files to an array, but android keeps showing this error : java.lang.NullPointerException: Attempt to get length of null array
, the error is in this line : if(path.isDirectory() && path.listFiles().length > 0)
I added these two permission lines to my manifest files, but there was no effect :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
my function is initially called by : locateSongs(Environment.getExternalStorageDirectory());
and this is my function to iterate the full device :
private void locateSongs(File path) {
if(path.isDirectory() && path.listFiles().length > 0){
File files[] = path.listFiles();
for(File f : files){
locateSongs(f.getAbsoluteFile());
}
}else if(path.isFile() && path.getName().contains(".mp3")){ // // TODO: 2/5/2016 add more types other than mp3
MediaMetadataRetriever metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path.getAbsolutePath());
Song newSong = new Song();
newSong.setAlbum(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
newSong.setArtist(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
newSong.setAuthor(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR));
newSong.setName(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
newSong.setBitRate(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
newSong.setGenre(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));
newSong.setDataSourse(path.getAbsolutePath());
newSong.setDuration(metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
byte[] art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
newSong.setImage(songImage);
}
}
metaRetriver.getEmbeddedPicture()
allowed to return null. When it happens you'll get similar error.path
is null orpath.listFiles()
returns null. Check both for null before use and do not use if it is null but display a toast to the user saying so.