尝试在空对象引用错误

时间:2015-09-30 00:06:28

标签: android

我试图创建一个歌曲对象以插入基于对象的数组列表(对于音乐播放器应用)。歌曲对象应包含属性专辑,艺术家,标题等。

然而,当我运行该程序时,他的应用程序崩溃,我在日志猫中收到此错误。

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

这是我的主要课程:

private ListView listView1;

// A list of song objects
private ArrayList<Song> songObectList;

// Song object will be passed to SongObjectList
private Song songObject = new Song();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Add song objects to songObjectList
    getMusic();

    // Initialize adapter
    SongAdapter adapter = new SongAdapter(this, R.layout.listview_item_row, songObectList);

    // Initialize listView
    listView1 = (ListView)findViewById(R.id.listView1);

    // Initialize header
    View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);

    // Add header to listView
    listView1.addHeaderView(header);

    // Add adapter to listView
    listView1.setAdapter(adapter);


private void getMusic() {

    // Set URI
    Uri contentURI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    // Set projection parameter for getContentResolver query
    String[] projection = {
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DURATION
    };

    // Run getContentResolver query
    final Cursor mCursor = getContentResolver().query(
            contentURI, projection, null, null, null
    );

    // Set song object properties 
    if (mCursor.moveToFirst()) {
        do {

            songObject.album = mCursor.getString(0);
            songObject.artist = mCursor.getString(1);
            songObject.title = mCursor.getString(2);
            songObject.data = mCursor.getString(3);
            songObject.duration = mCursor.getString(4);

            songObectList.add(songObject);

        } while (mCursor.moveToNext());
    }

    mCursor.close();

    return;
}

2 个答案:

答案 0 :(得分:2)

我不知道你在哪里初始化songObectList。

尝试替换

// A list of song objects
private ArrayList<Song> songObectList;

// A list of song objects
private ArrayList<Song> songObectList = new ArrayList<Song>();

答案 1 :(得分:2)

您从未初始化过songObjectList。做:

private ArrayList<Song> songObectList = new ArrayList<>();