Search code examples
javaandroidlistviewandroid-arrayadapter

ArrayAdapter and ListView - my app crashing


I've spent reading and tweaking my code for a while now but it keeps crashing and I can't figure out why it's crashing. Can someone please point out where I am making the error. I am a noob to programming and Android development trying to understand the basics of ArrayAdapters and ListViews.

Here's my code: MainActivity.java

package com.example.android.samplelistviewapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> listItems = new ArrayList<String>();

    ArrayAdapter<String> adapter;

    ListView listView = (ListView) findViewById(R.id.list);

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

        listItems.add("hello");
        listItems.add("how do you do");
        listItems.add("Ca va");
        listItems.add("Bonjour");
        listItems.add("Toronto");
        listItems.add("hello");
        listItems.add("mississauga");
        listItems.add("computer");
        listItems.add("ipad");
        listItems.add("sky");
        listItems.add("hello");
        listItems.add("road");
        listItems.add("mountain");

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);

        listView.setAdapter(adapter);
    }
}

Here's my xml: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Solution

  • ListView listView = (ListView) findViewById(R.id.list); gets executed in the constructor, before the call to setContentView. Since the view has not yet been loaded the requested view does not exist, returning null.

    Move the findViewById to after the call to setContentView