简体   繁体   中英

SD card not getting accessed in android

I am facing continuous problem with accessing SD Card even after using Environment.getExternalStorageDirectory() or even directly using /sdcard/ application is fetching data from phone's internal memory .I am using moto e for testing

Please help

public class SongsManager {

final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager(){

}




public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);
    walkdir(home);





    return songsList;



}

public void walkdir(File dir) {
    String Pattern = ".mp3";
    File listFile[] = dir.listFiles();
    if (listFile != null) {
    for (int i = 0; i < listFile.length; i++) {
    if (listFile[i].isDirectory()) {
    walkdir(listFile[i]);
    } else {
    if (listFile[i].getName().endsWith(Pattern)){
        for (File file : dir.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);
        }

    }
    }
    }  
    }  
    }

}


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

Instead of doing this:

final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
...
File home = new File(MEDIA_PATH);

You could just do this:

File home = Environment.getExternalStorageDirectory();

and then to call you method walkdir

walkdir(home);

I think that the problem is in the getPath() method. Maybe it should be the getAbsolutePath() method

That is normal for Android. It's not easy to get the path to removable media on android. You can read a lot about this on this site. Add a directory picker to your app so the user canindicate it. Try getExternalFileDirs(). If it gives you two directories the latter will be the micro SD card.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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