本篇文章为大家展示了在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<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"
上述内容就是在Android应用中读取SD卡文件时程序NullPointerException报错如何解决,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。