音乐播放器应用崩溃尝试抓取寻找音频文件的子文件夹

时间:2016-02-18 01:04:22

标签: android

我有一个有效的音乐播放器应用程序,但到目前为止,该应用程序仅设置为在用户指定的顶级文件夹中查找音频文件。我想查看至少1级深度音频文件的子文件夹。

我的代码尝试在子文件夹中查找音频文件:

//search subfolders of root media directory for audio files
            File[] someFiles = home.listFiles();
            for (int i = 0; i < someFiles.length; i++) {
                File selectedFile = someFiles[i];
                if (selectedFile.isDirectory()) {
                    searchForAudioFiles(selectedFile, uniqueSongIDInt);
                }
            }

不幸的是我得到一个空指针异常。我运行调试器试图找出哪个变量为null,但还没有想出来。

logcat的:    java.lang.RuntimeException:无法启动活动ComponentInfo {com.joshbgold.simplemusicplayer / com.joshbgold.simplemusicplayer.MainActivity}:java.lang.NullPointerException                                                                                      在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)                                                                                      在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)                                                                                      在android.app.ActivityThread.access $ 700(ActivityThread.java:158)                                                                                      在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1296)                                                                                      在android.os.Handler.dispatchMessage(Handler.java:99)                                                                                      在android.os.Looper.loop(Looper.java:176)                                                                                      在android.app.ActivityThread.main(ActivityThread.java:5365)                                                                                      at java.lang.reflect.Method.invokeNative(Native Method)                                                                                      在java.lang.reflect.Method.invoke(Method.java:511)                                                                                      在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1102)                                                                                      在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)                                                                                      at dalvik.system.NativeStart.main(Native Method)                                                                                   引起:java.lang.NullPointerException                                                                                      at com.joshbgold.simplemusicplayer.SongsManager.searchForAudioFiles(SongsManager.java:66)                                                                                      在com.joshbgold.simplemusicplayer.SongsManager.getPlayList(SongsManager.java:56)                                                                                      在com.joshbgold.simplemusicplayer.MainActivity.onCreate(MainActivity.java:126)

这是第66行,Logcat似乎表明可能导致异常:

   if ((home.listFiles(new FileExtensionFilter()).length > 0)) {

这是完整的SongsManager类:

import android.content.Context;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

public class SongsManager {

    public HashMap<String, String> song;
    public String songTitle;
    private String uniqueSongIDString = "0";
    public Context mContext;
    protected String lowerCaseName = "";

    // SDCard Path
    public String MEDIA_PATH = "/storage";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<>();
    private ArrayList<HashMap<String, String>> filteredSongsList = new ArrayList<>();


    public SongsManager(Context context, String folderPath) {
        mContext = context;
        if (folderPath != null && !"".equals(folderPath)) {
            MEDIA_PATH = folderPath;
        }
    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     */
    public ArrayList<HashMap<String, String>> getPlayList() {

        File home = new File(MEDIA_PATH);

        uniqueSongIDString = "0";
        int uniqueSongIDInt = 0;

        if (songsList != null) {
            songsList.clear();
        }

        if (home.listFiles() != null) {
            //search audio files in root media directory user has selected
            //searchForAudioFiles(home, uniqueSongIDInt);

            //search subfolders of root media directory for audio files
            File[] someFiles = home.listFiles();
            for (int i = 0; i < someFiles.length; i++) {
                File selectedFile = someFiles[i];
                if (selectedFile.isDirectory()) {
                    searchForAudioFiles(selectedFile, uniqueSongIDInt);
                }
            }

        }
        // return songs playlist_item array
        return songsList;
    }

    private void searchForAudioFiles(File home, int uniqueSongIDInt) {
        if ((home.listFiles(new FileExtensionFilter()).length > 0)) {
            for (File file : home.listFiles(new FileExtensionFilter())) {  //for each file that is an audio file in home directory
                song = new HashMap<>();  //make a hashmap data structure to store song info

                songTitle = file.getName();

                //remove track numbers from song titles
                songTitle = songTitle.replaceFirst("^\\d*\\s", "");  //replaces leading digits & following space
                songTitle = songTitle.replaceFirst("^\\d*\\-\\d*", "");  //replaces leading digits, following hyphen, and following digits

                song.put("songTitle", songTitle);
                song.put("songPath", file.getPath());
                song.put("songUniqueID", uniqueSongIDString);
                uniqueSongIDInt++;
                uniqueSongIDString = String.valueOf(uniqueSongIDInt);

                // Adding each song to SongList
                songsList.add(song);
            }
        }
    }

    /**
     * Class to filter files which are having .mp3 extension
     */
    class FileExtensionFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            lowerCaseName = name.toLowerCase();
            return (name.endsWith(".mp3") || name.endsWith(".wma") || name.endsWith(".wav") || name.endsWith(".m4a") || name.endsWith(".flac"));
        }
    }

    // Filter Class
    public ArrayList<HashMap<String, String>> filter(String searchString) {
        searchString = searchString.toLowerCase(Locale.getDefault());

        songsList.clear();
        songsList = getPlayList();

        //searchString is empty, so show all songs in results
        if (searchString.length() == 0) {

            if (filteredSongsList != null) {
                filteredSongsList.clear();
            }
            filteredSongsList = songsList;
        }

        //only return songs that match the search string
        else {

            if (filteredSongsList != null) {
                filteredSongsList.clear();
            }

            for (HashMap<String, String> song : songsList) {
                if (song != null) {
                    String songTitle = song.get("songTitle");
                    if (songTitle.toLowerCase().contains(searchString)) {
                        filteredSongsList.add(song);
                    }
                }
            }
        }

        return filteredSongsList;
    }
}

您可以从Github here

克隆整个项目

1 个答案:

答案 0 :(得分:2)

listFiles()的javadoc清楚地表明,当目录为空时它可以返回null。所以你应该检查并处理这个案例。