I've been having a frustrating time extracting METADATA_KEY_TITLE
of .mp3 files to arraylist and arrayadaper for my ListView to display titles of songs only and in exceptinal cases where title is null, title element returns filename...
Here's my code:
final ArrayList<String> myTitu = findTitles(Environment.getExternalStorageDirectory());
metaTitu = new String[myTitu.size()];
for(int j = 0; j<myTitu.size(); j++){
metaTitu[j] = myTitu.get(j);
}
ArrayAdapter<String> adp = new ArrayAdapter<String>(getContext(),R.layout.songslist_content,R.id.name_of_song_tab, metaTitu);
lv.setAdapter(adp);
// -------------------------------------------------------------------------------
public ArrayList<String> findTitles(File root) {
ArrayList<String> all = new ArrayList<String>();
File[] files = root.listFiles();
String names;
for (File singlet : files) {
if (singlet.isDirectory() && !singlet.isHidden()) {
all.addAll(findTitles(singlet));
} else {
if (singlet.getName().endsWith(".mp3")){
try{
metameta = new MediaMetadataRetriever();
metameta.setDataSource(singlet.getPath());
names = metameta.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
all.add(names);
} catch (Exception e){
names = singlet.getName().toString();
all.add(names);
}
}
}
}
return all;
}
Please note that all these are in a Fragment and also debugger complains of a
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
without pointing to any specific line
First of all, check whether file object singlet
is not null
and add null
check before matching extension with .mp3
too. You are getting null pointer exception because your are not checking for null
value inside your catch method.
So your code will be as follows :
for (File singlet : files) {
if (null != singlet) {
if (singlet.isDirectory() && !singlet.isHidden()) {
all.addAll(findTitles(singlet));
} else {
if (null != singlet.getName() && singlet.getName().endsWith(".mp3")){
try{
metameta = new MediaMetadataRetriever();
metameta.setDataSource(singlet.getPath());
names = metameta.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
all.add(names);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}