从媒体库返回的空指针

时间:2019-03-06 11:57:46

标签: android nullpointerexception fragment android-mediaplayer mediastore

显示方法程序

void display() {
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    ContentResolver contentResolver = getActivity().getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor cursor = contentResolver.query(uri, null, selection, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        int songTitle = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int songArtist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        do {
            int i = 0;
            String title = cursor.getString(songTitle);
            String artist = cursor.getString(songArtist);
            songsList.add(title + "\n" + artist);
            i++;
        } while (cursor.moveToNext());
    }
    cursor.close();
    songsList = new ArrayList<>();
    songsAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, songsList);
    l1.setAdapter(songsAdapter);

    l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    });
}

显示方法错误

2019-03-05 23:16:59.323 504-504/? E/ANDR-IOP: IOP HAL: Received pkg_name = com.noob.audioplayer pid = 0 2019-03-05 23:16:59.723 18049-18049/com.noob.audioplayer E/AndroidRuntime: FATAL EXCEPTION: main Process: com.noob.audioplayer, PID: 18049 java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.ArrayList.add(int, java.lang.Object)' on a null object reference at com.noob.audioplayer.SongsFragment.display(SongsFragment.java:137) 

1 个答案:

答案 0 :(得分:0)

您正试图添加到未创建的歌曲列表。在添加歌曲之前先创建歌曲列表:

const month = moment.utc();  // here I would use something to define the selected month
const startMonth = moment(month).startOf("month");
const endMonth = moment(month).endOf("month");
const monthTransaction = getUserTransactions.filter(
  transaction =>
    transaction.createdAt > startMonth.toISOString() &&
    transaction.createdAt < endMonth.toISOString()
);