简体   繁体   English

在Android中引发空指针异常

[英]Throwing null pointer exception in Android

I'm trying to fetch an audio file from the audio directory, for that I'm using below code. 我正在尝试从音频目录中获取音频文件,为此,我正在使用以下代码。 I'm not able to figure out why this condition if (home.listFiles(new FileExtensionFilter()).length > 0) is throwing an error. 我无法弄清楚为什么if (home.listFiles(new FileExtensionFilter()).length > 0)情况引​​发错误。 Code is given below. 代码如下。

Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String MEDIA_PATH = allsongsuri.toString();
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

public ArrayList<HashMap<String, String>> getPlayList(){
    System.out.println(" -- "+MEDIA_PATH);
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
        song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

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

class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
    return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}

I need to store audio file in ArrayList using hashMap. 我需要使用hashMap将音频文件存储在ArrayList中。 I tried this example to store file in List http://android-er.blogspot.in/2012/02/list-audio-media-in-mediastoreaudiomedi.html . 我尝试了此示例以将文件存储在列表http://android-er.blogspot.in/2012/02/list-audio-media-in-mediastoreaudiomedi.html中 Using this example I tried a lot to store the list in ArrayList as my reqirement need that. 使用此示例,我做了很多尝试,以将列表存储在ArrayList中,因为我需要此列表。 But didn't succeed. 但是没有成功。 I need help. 我需要帮助。 I have to store Audio file in Arraylist. 我必须将音频文件存储在Arraylist中。

This must be home.listFiles returning null . 这必须是home.listFiles返回null

From Android developer reference on public File[] listFiles (FileFilter filter) 来自Android开发人员的有关public File[] listFiles (FileFilter filter)

Gets a list of the files in the directory represented by this file. 获取此文件表示的目录中文件的列表。 This list is then filtered through a FileFilter and matching files are returned as an array of files. 然后,此列表通过FileFilter进行过滤,匹配的文件作为文件数组返回。 Returns null if this file is not a directory. 如果此文件不是目录,则返回null。 If filter is null then all files match. 如果filter为null,则所有文件匹配。

So you need to make sure that MEDIA_PATH is a proper directory. 因此,您需要确保MEDIA_PATH是正确的目录。

The "listFiles()" method can return null if the file is not found. 如果找不到该文件,则“ listFiles()”方法可以返回null。 I would suggest putting in a check to see if it's null first, and only proceed if it is something other than null. 我建议先检查一下是否为空,并且仅在它不是null时再进行检查。 Example: 例:

public ArrayList<HashMap<String, String>> getPlayList(){
    System.out.println(" -- "+MEDIA_PATH);
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()) != null){
        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

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

    return songsList;
}

You will probably want to put in an else statement as well, in order to make sure that songsList is not null when it is returned. 您可能还需要放入else语句,以确保当返回SongsList时不为null。

public class SongsManager {
    final String MEDIA_PATH = Environment.getExternalStorageDirectory()
            .getPath() + "/";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private String mp3Pattern = ".mp3";

    // Constructor
    public SongsManager() {

    }

    /**
     * Function to read all mp3 files and store the details in
     * ArrayList
     * */
    public ArrayList<HashMap<String, String>> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }

    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }

                }
            }
        }
    }

    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap<String, String> songMap = new HashMap<String, String>();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());

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


}

with ref to Anup's and Destrom's answer I just want put the code with with Filename Filter 引用Anup和Destrom的答案,我只想将代码与Filename Filter一起使用

    public class SongsManager {
    // SDCard Path
//  final String MEDIA_PATH = new String("/sdcard/sound_recorder"); 

    final String MEDIA_PATH =Environment.getExternalStorageDirectory()+"/sound_recorder";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    // Constructor
    public SongsManager(){

    }

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

        Log.d("testsd",MEDIA_PATH);
        File home = new File(MEDIA_PATH);

    //  if (home.listFiles(new FileExtensionFilter()).length > 0) //don't use this to avoid null pointer exception !
        if (home.listFiles(new FileExtensionFilter())!=null) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();


                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList


                songsList.add(song);

            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * Class to filter files which are having .mp3 extension
     * */
    class FileExtensionFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith(".3gpp") || name.endsWith(".wav")); //add more extensions here
        }
    }
}

Thanks a lote.....was getting mat with the moto g without a sdcard.....it emulate the physical sdcard....still not work. 非常感谢.....在没有sdcard的情况下与moto g融为一体.....它模仿了物理sdcard ....仍然无法正常工作。

But your code work perfect with another motorola that has the physical sdcard 但是您的代码可以与另一个具有物理sdcard的摩托罗拉完美配合

i mean when the sdcard is emulated dontwork ..i try all the MEDIA_PATHS possibles 我的意思是当模拟sdcard时不起作用。我尝试所有MEDIA_PATHS可能

i need your advice...thanks. 我需要您的建议...谢谢。 //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //最终字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getPath()+“ /”; //private final String MEDIA_PATH = new String("/sdcard/res/raw/"); //私有最终字符串MEDIA_PATH = new String(“ / sdcard / res / raw /”); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; //最终字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getAbsolutePath()+“ /”; //final String MEDIA_PATH = new String("/sdcard/"); //最终的字符串MEDIA_PATH = new String(“ / sdcard /”); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //最终字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getPath()+“ /”; // final String MEDIA_PATH =""; // final String MEDIA_PATH =“”; //final String MEDIA_PATH = new String("/sdcard/Musica/"); //最终的字符串MEDIA_PATH = new String(“ / sdcard / Musica /”); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //最终字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getPath()+“ /”; //final String MEDIAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musica/"; //最终字符串MEDIAPATH = Environment.getExternalStorageDirectory()。getAbsolutePath()+“ / Musica /”; //final String MEDIAPATH = new String("/sdcard/"); //最终的字符串MEDIAPATH = new String(“ / sdcard /”); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //最终字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getPath()+“ /”; final String MEDIA_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; 最后的字符串MEDIA_PATH = Environment.getExternalStorageDirectory()。getAbsolutePath()+“ /”;

确保您不要忘记manifest.xml中的使用权限READ EXTERNAL STORAGE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM