如果我不删除arraylist,程序只是关闭,它应该显示我的歌曲,但是程序无法打开

时间:2018-10-16 10:44:12

标签: java android-studio arraylist

https://www.youtube.com/watch?v=D9--BF-W0AY

我确实使用了此视频(Android Studio)。但由于“私有ArrayList readSongs(文件根目录){}”而无法使用,我认为...所有程序都无法打开。...

MainActivity.java”

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity{
private ListView listView;
private String songNames[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = findViewById(R.id.listView);

    final ArrayList<File> songs = readSongs(Environment.getExternalStorageDirectory());

    songNames = new String[songs.size()];

    for(int i = 0; i < songs.size(); ++i){
        songNames[i] = songs.get(i).getName().toString().replace(".mp3","");
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.song_layout, R.id.textView,songNames);

    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            startActivity(new Intent(MainActivity.this, AudioPlayer.class).putExtra("position", i).putExtra("list", songs));
        }
    });
}

private ArrayList<File> readSongs(File root){
    ArrayList<File> arrayList = new ArrayList<File>();
    File files[] = root.listFiles();

    for(File file : files){
        if(file.isDirectory()){
            arrayList.addAll(readSongs(file));
        }else{
            if(file.getName().endsWith(".mp3")){
                arrayList.add(file);
            }
        }
    }
    return arrayList;
}

}

1 个答案:

答案 0 :(得分:-1)

在主线程中扫描sd卡的根路径会占用太多时间,可能会触发ANR,因此应异步调用方法。