Android 中读取SD卡文件时抛出NullPointerException错误解决办法
程序员文章站
2023-12-04 11:24:46
android 中读取sd卡文件时抛出nullpointerexception错误解决办法
相关源码:
package com.example.musicpla...
android 中读取sd卡文件时抛出nullpointerexception错误解决办法
相关源码:
package com.example.musicplayer; import java.io.file; import java.util.arraylist; import java.util.list; import android.app.activity; import android.os.bundle; import android.os.environment; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.widget.listview; import android.widget.textview; import android.widget.toast; public class mainactivity extends activity { private listview listview; private final string path = "/storage/sdcard/mp3/"; private list<string> musiclist; private viewholder viewholder; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); listview = (listview) findviewbyid(r.id.lv_music); toast.maketext(getapplicationcontext(), path, toast.length_short).show(); initmusic(); } private void initmusic() { file file = new file(path); file[] files = file.listfiles(); musiclist = new arraylist<string>(); for (file f : files) { if (f.getname().endswith(".mp3")) { musiclist.add(f.getabsolutepath()); } } listview.setadapter(new musiclistadapter()); } private class musiclistadapter extends baseadapter{ @override public int getcount() { return musiclist.size(); } @override public view getview(int position, view convertview, viewgroup parent) { view view = null; if(convertview == null){ view = view.inflate(getapplicationcontext(), r.layout.activity_music_item, null); viewholder = new viewholder(); viewholder.musicname = (textview) view.findviewbyid(r.id.tv_music_name); } else { view = convertview; } string path = musiclist.get(position); viewholder.musicname.settext(path.substring(path.lastindexof("/") + 1)); return view; } @override public object getitem(int position) { // todo auto-generated method stub return null; } @override public long getitemid(int position) { // todo auto-generated method stub return 0; } } }
获取sd卡中mp3文件夹下的文件信息时在foreach时抛出nullpointerexception,最后发现是没有添加读取sd卡的权限
<uses-permission android:name="android.permission.read_external_storage"/>
获取sd卡路径:”/mnt/sdcard/” “/storage/sdcard/”
官方推荐:
environment.getexternalstoragedirectory.getpath();
该方法获取的路径最后没有'/'
"/mnt/sdcard" "/storage/sdcard"
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!