您好,登錄后才能下訂單哦!
本篇文章為大家展示了在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。