我正在尝试从移动设备获取所有Mp3文件并将其显示在列表视图中。我能够从模拟器的SD卡中获取特定文件中的歌曲,但是当我尝试获取所有文件时它没有显示任何歌曲。我试过两种方法
1.`
public class MainActivity extends ListActivity {
final String MEDIA_PATH = Environment.getExternalStorageDirectory()
.getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updatelist();
}
public ArrayList<HashMap<String, String>> getPlayList() {
System.out.println(MEDIA_PATH);
if (MEDIA_PATH != null) {
File home = new File(MEDIA_PATH);
File[] listFiles = home.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
// return songs list array
return songsList;
}
private void scanDirectory(File directory) {
if (directory != null) {
File[] listFiles = directory.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
}
private void addSongToList(File song) {
if (song.getName().endsWith(mp3Pattern)) {
HashMap<String, String> songMap = new HashMap<String, String>();
songMap.put("songTitle",
song.getName().substring(0, (song.getName().length() - 4)));
songMap.put("songPath", song.getPath());
// Adding each song to SongList
songsList.add(songMap);
}
}
private void updatelist(){
ArrayAdapter<String> songMp =new ArrayAdapter<String>(this,R.layout.content_main,songsList);
setListAdapter(songMp);
}
}
` 2
public class MainActivity extends ListActivity {
private ListView listView;
final String MEDIA_PATH = Environment.getExternalStorageDirectory()
.getPath() + "/";
private List<String> songsList = new ArrayList< String>();
private String mp3Pattern = ".mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(android.R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
updatePlaylist();
}
class Mp3Filter implements FilenameFilter{
@Override
public boolean accept(File dir, String filename) {
return (filename.endsWith(mp3Pattern));
}
}
private void updatePlaylist(){
File home = Environment.getExternalStorageDirectory();
if (home.listFiles(new Mp3Filter()).length>0){
for (File file:home.listFiles(new Mp3Filter())){
songsList.add(file.getName());
}
ArrayAdapter<String> song =new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,songsList);
setListAdapter(song);
}
}
}
有人可以告诉我我在其中任何一个方面做错了。我在第一个中出错了,在第二个中我得到了一个空白的活动 提前任何示例或提示都足够了。