Throwing null pointer exception in Android

眉间皱痕 提交于 2019-12-23 01:55:34

问题


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. 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. I tried this example to store file in List 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. But didn't succeed. I need help. I have to store Audio file in Arraylist.


回答1:


This must be home.listFiles returning null.

From Android developer reference on 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. Returns null if this file is not a directory. If filter is null then all files match.

So you need to make sure that MEDIA_PATH is a proper directory.




回答2:


The "listFiles()" method can return null if the file is not found. I would suggest putting in a check to see if it's null first, and only proceed if it is something other than 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.




回答3:


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);
        }
    }


}



回答4:


with ref to Anup's and Destrom's answer I just want put the code with with 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
        }
    }
}



回答5:


Thanks a lote.....was getting mat with the moto g without a sdcard.....it emulate the physical sdcard....still not work.

But your code work perfect with another motorola that has the physical sdcard

i mean when the sdcard is emulated dontwork ..i try all the MEDIA_PATHS possibles

i need your advice...thanks. //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //private final String MEDIA_PATH = new String("/sdcard/res/raw/"); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; //final String MEDIA_PATH = new String("/sdcard/"); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; // final String MEDIA_PATH =""; //final String MEDIA_PATH = new String("/sdcard/Musica/"); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; //final String MEDIAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musica/"; //final String MEDIAPATH = new String("/sdcard/"); //final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/"; final String MEDIA_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";




回答6:


Make sure you don't forget the uses permission READ EXTERNAL STORAGE in manifest.xml



来源:https://stackoverflow.com/questions/20022439/throwing-null-pointer-exception-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!