我有音乐下载和播放器应用程序,问题是我每天都会收到大量的空指针异常,因为不同设备上的目录路径不同。 如何解决?
这是我的路径:
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().toString() + "/Music");
以及我如何创建歌曲列表(getPlaylist):
public ArrayList<HashMap<String, String>> getPlayList(){
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());
songsList.add(song);
}
}
return songsList;
}
来自崩溃分析服务的堆栈跟踪:
Full Stack Trace:
java.lang.NullPointerException
music.download.justin.utils.SongReader.getPlayList(SongReader.java:22)
music.download.justin.Player.player(Player.java:164)
music.download.justin.Player.onViewCreated(Player.java:103)
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
android.support.v4.view.ViewPager.populate(ViewPager.java:951)
android.support.v4.view.ViewPager$3.run(ViewPager.java:250)
android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
android.view.Choreographer.doCallbacks(Choreographer.java:579)
android.view.Choreographer.doFrame(Choreographer.java:547)
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
android.os.Handler.handleCallback(Handler.java:800)
android.os.Handler.dispatchMessage(Handler.java:100)
android.os.Looper.loop(Looper.java:194)
android.app.ActivityThread.main(ActivityThread.java:5371)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:525)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
dalvik.system.NativeStart.main(Native Method)
受影响较大的设备: 三星(所有型号) 京瓷 HTC
答案 0 :(得分:0)
我想这是因为设备无法从SD卡/外部存储加载媒体路径。您可以使用异常处理/在else条件中抛出一些有效的错误消息,以避免崩溃或异常。
检查这些设备的Android版本,如果它超过了marshmallow,那么你必须在代码级别指定权限。