android读取sd卡为空,Android 中读取SD卡文件时抛出NullPointerException错误解决办法

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

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卡的权限

获取sd卡路径:”/mnt/sdcard/” “/storage/sdcard/”

官方推荐:

environment.getexternalstoragedirectory.getpath();

该方法获取的路径最后没有'/'

"/mnt/sdcard"

"/storage/sdcard"

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值