我正在尝试创建一个媒体播放MP3播放器,但它正在犯错误导致应用程序停止 这是代码MainActivity
public class MainActivity extends Activity {
ListView lv;
String[] items;
Button btnA1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnA1 = (Button) findViewById(R.id.btnA);
btnA1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent a1 = new Intent(getApplicationContext(), Player.class);
startActivity(a1);
finish();
}
});
lv = (ListView) findViewById(R.id.lvPlaylist);
final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
items[i] = mySongs.get(i).getName().toString().replace(".mp3", "").replace(".wav", "");
}
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), R.layout.song_layout,
R.id.textView, items);
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
startActivity(new Intent(getApplicationContext(), Player.class).putExtra("pos", position)
.putExtra("songlist", mySongs));
}
});
}
public ArrayList<File> findSongs(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
al.add(singleFile);
}
}
}
return al;
}
@Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
ab.setTitle("Exit");
ab.setMessage("Are You Sure Exit?");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
MainActivity.this.finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ab.show();
}
}
错误在于
public ArrayList<File> findSongs(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
al.add(singleFile);
}
}
}
return al;
}
如果我替换if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
到if (singleFile.isDirectory() && singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
那么应用程序只会加载sdcard上的mp3文件,因为sdcard / music不会
如果我很恐怖在singleFile中,应用程序将被停止