使用ArrayList设置ListView - null对象引用错误

时间:2016-03-18 08:11:18

标签: android listview android-studio arraylist

我正在尝试使用ArrayList设置ListView,但是当我运行应用程序时,我面临错误,不幸的是,应用已停止。 这是android监视器中的错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.example.nfp.weather_g.MainActivity.onCreate(MainActivity.java:35)

这是我的代码:

package com.example.nfp.weather_g;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends AppCompatActivity {

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


        List<String> forecast = new ArrayList<>();
            forecast.add("Today - Sunny - 88/63");
            forecast.add("Tomorrow - Foggy - 70/40");
            forecast.add("Weds - Cloudy  - 72/63");
            forecast.add("Thurs - Asteroids - 75/65");
            forecast.add("Fri - Heavy Rain - 65/56");
            forecast.add("Sat - HELP TRAPPED IN WEATHERSTATION - 60/51");
            forecast.add("Sun - Sunny - 80/68");


        ArrayAdapter<String> arrayAdapter = new ArrayAdapter(
                getApplication(),
                android.R.layout.simple_list_item_1,
                forecast
        );
        ListView listView = (ListView) findViewById(android.R.id.list);
        listView.setAdapter(arrayAdapter);}}

ListView id也是列表

我该如何解决?

1 个答案:

答案 0 :(得分:3)

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

(android.R.id.list)错了。您必须参考您在xml中使用的列表,例如 -      ListView listView =(ListView)findViewById(R.id.listView);

其中listView是布局中Listview的ID