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"

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

02-06 14:19