我想在listview中显示来自sdcard的歌曲,但它会给出Force Close。 任何人都可以帮助我。 代码:
package com.ex.imageGallery;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.FilenameFilter;
public class audioList extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
Uri[] mUrls;
String[] mFiles=null;
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_list);
ListView lv;
lv = (ListView)findViewById(R.id.LV);
/*File home = Environment.getDataDirectory();
File[] audioList = home.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return(name.endsWith(".mp3"));
}
});
mFiles = new String[audioList.length];
for(int i=0;i<audioList.length;i++)
{
mFiles[i] = audioList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0;i<mFiles.length;i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
lv.setAdapter(new ArrayAdapter<String>(audioList.this,R.layout.new_list,mFiles));
lv.setDividerHeight(2);
lv.setTextFilterEnabled(true); */
}
}
答案 0 :(得分:3)
系统会自动注册媒体文件,因此您需要使用查询来检索媒体。
final Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME }, null, null, null);
加载光标。要在ListView中显示它,您需要使用SimpleCursorAdapter在ListView中显示数据。
答案 1 :(得分:1)
public class Database extends Activity {
/** Called when the activity is first created. */
private List<String> list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//creating a folder in sdcard
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ "mymusic" //folder name
);
if(!file.exists()) {
file.mkdirs();
}
ListView lv=(ListView) findViewById(R.id.listView1);
list=getSD();
lv.setAdapter((ListAdapter) new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
}
//read from sdcard
private List<String> getSD() {
List<String> item = new ArrayList<String>();
File f = new File("/mnt/sdcard/mymusic");
File[] files = f.listFiles();
for(int i=0; i < files.length; i++) {
File file = files[i];
//take the file name only
String myfile = file.getPath().substring(file.getPath().lastIndexOf("/")+1,file.getPath().length()).toLowerCase();
item.add(myfile);
}
return item;
}