0

I'm trying to setup a ListView using ArrayList but when I run the app I face with the error Unfortunately, app has stopped. Here is the error in android monitor:

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)

and this is my code:

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);}}

Also the ListView id is list

How should I fix it?

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
ali ghasemzad
  • 66
  • 1
  • 10

1 Answers1

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

(android.R.id.list) is wrong. You have to refer your list which you have used in your xml like - ListView listView = (ListView) findViewById(R.id.listView);

where listView is id of your Listview in layout

Passiondroid
  • 1,573
  • 1
  • 16
  • 28