您好,登錄后才能下訂單哦!
本篇文章為大家展示了在Android應(yīng)用中讀取SD卡文件時(shí)程序NullPointerException報(bào)錯(cuò)如何解決,內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
Android 中讀取SD卡文件時(shí)拋出NullPointerException錯(cuò)誤解決辦法
相關(guān)源碼:
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文件夾下的文件信息時(shí)在foreach時(shí)拋出NullPointerException,最后發(fā)現(xiàn)是沒有添加讀取SD卡的權(quán)限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
獲取SD卡路徑:”/mnt/sdcard/” “/storage/sdcard/”
官方推薦:
Environment.getExternalStorageDirectory.getPath();
該方法獲取的路徑最后沒有'/'
"/mnt/sdcard" "/storage/sdcard"
上述內(nèi)容就是在Android應(yīng)用中讀取SD卡文件時(shí)程序NullPointerException報(bào)錯(cuò)如何解決,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。