我想从内部存储中获取.mp3文件,这里是for循环
public ArrayList<File> findsong(File file){
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
for (File singleFiles: files){
if (singleFiles.isDirectory() && !singleFiles.isHidden()){
arrayList.addAll(findsong(singleFiles));
}else {
if (singleFiles.getName().endsWith(".mp3")){
arrayList.add(singleFiles);
}
}
}
return arrayList;
}
但是我遇到了空指针错误
java.lang.NullPointerException: Attempt to get length of null array
这是我的完整代码
正在尝试执行的操作的上下文:我想显示内部/外部存储中的音频文件列表,并且由于是Android开发的新手,所以我会在此处停留,对您有所帮助
提前致谢
ListView myListViewForSongs;
String[] items;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runtimePermission();
myListViewForSongs= (ListView) findViewById(R.id.listView);
}
public void runtimePermission(){
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE).withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
display();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findsong(File file){
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
assert files != null;
for (File singleFiles: files){
if (singleFiles.isDirectory() && !singleFiles.isHidden()){
arrayList.addAll(findsong(singleFiles));
}else {
if (singleFiles.getName().endsWith(".mp3")){
arrayList.add(singleFiles);
}
}
}
return arrayList;
}
void display(){
final ArrayList<File> mySongs=findsong(new File(Environment.getExternalStorageState()));
items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++){
items[i]= mySongs.get(i).getName().replace(".mp3","");
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
myListViewForSongs.setAdapter(adapter);
}
}
最佳答案
您应该使用内容提供商从内部存储中提取歌曲。