-3

I have been following this example on creating a multirow list-view on android. However, I get the error

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

in the line marked below. As far as I see I have followed the example as it is described, but maybe I have missed something obvious.

The relevant pieces of the code are as follows:

Excerpt of the code to show the view (when the user presses a button):

public void stat(View view) {

    // First, sort the pile of entries
    Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();
    for (int i = 0; i < quizIndex.size(); i++) {
        testMap.put(i, quizIndex.get(i).getPriority());
    }
    MyComparator comparator = new MyComparator(testMap);

    Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(comparator);
    sortedMap.putAll(testMap);

    // Then, fill out the lists of lists
    ArrayList<HashMap<String,String>> adapterList = new ArrayList<HashMap<String,String>>();
    int index;
    for (Map.Entry<Integer, Integer> mapentry : sortedMap.entrySet())
    {
        System.out.println(mapentry.getKey() + "/" + mapentry.getValue());
        index = mapentry.getKey();
        Entry entry = quizIndex.get(index);
        System.out.println(String.format("%30s   %d  %d  %s  %d  %d  %d",
                entry.name(), entry.number_ok, entry.number_nok, entry.history, entry.randomIndex, entry.histIndex, entry.getPriority()));

        HashMap<String,String> temp=new HashMap<String, String>();
        temp.put(COLUMN_NAME, entry.name());
        temp.put(COLUMN_OK, Integer.toString(entry.number_ok));
        temp.put(COLUMN_NOK, Integer.toString(entry.number_nok));
        temp.put(COLUMN_HIST, entry.history);
        temp.put(COLUMN_PRANDOM, Integer.toString(entry.randomIndex));
        temp.put(COLUMN_PHIST, Integer.toString(entry.histIndex));
        temp.put(COLUMN_PTOT, Integer.toString(entry.getPriority()));
        adapterList.add(temp);
    }

    // Finally, create the view
    ListView listView=(ListView)findViewById(R.id.listview1);
    StatViewAdapter adapter=new StatViewAdapter((Activity)this, adapterList);
    listView.setAdapter(adapter); // ERROR HERE
}

And here is the complete StatViewAdapter:

public class StatViewAdapter  extends BaseAdapter {
    public ArrayList<HashMap<String, String>> list;
    Activity activity;
    TextView txtName;
    TextView txtOK;
    TextView txtNOK;
    TextView txtHist;
    TextView txtPrandom;
    TextView txtPhist;
    TextView txtPtotal;

    public StatViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
        super();
        this.activity=activity;
        this.list=list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=activity.getLayoutInflater();

        if(convertView == null){

            convertView=inflater.inflate(R.layout.list_view, null);

            txtName=(TextView) convertView.findViewById(R.id.listname);
            txtOK=(TextView) convertView.findViewById(R.id.listok);
            txtNOK=(TextView) convertView.findViewById(R.id.listnok);
            txtHist=(TextView) convertView.findViewById(R.id.listhist);
            txtPrandom =(TextView) convertView.findViewById(R.id.listprandom);
            txtPhist=(TextView) convertView.findViewById(R.id.listphist);
            txtPtotal=(TextView) convertView.findViewById(R.id.listptot);
        }

        HashMap<String, String> map=list.get(position);
        txtName.setText(map.get(COLUMN_NAME));
        txtOK.setText(map.get(COLUMN_OK));
        txtNOK.setText(map.get(COLUMN_NOK));
        txtHist.setText(map.get(COLUMN_HIST));

        return convertView;
    }
}

How can it be a null-reference error? I define a valid object, as far as I see, which is not-null...?

Addendum: The 'listview1`:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>
Alex
  • 41,580
  • 88
  • 260
  • 469
  • That means it can't find the `ListView` with ID `listView1` in your current layout. `listView` is null. – Mike M. Jan 20 '17 at 19:13
  • The first thing to check is whether `findViewById(R.id.listview1)` is returning `null`. If it is, you need to check the id is correct and whether you are calling `setContentView()` in `onCreate()` of the Activity – David Rawson Jan 20 '17 at 19:15
  • 1
    Note that the tutorial has `listView1` not `listview1` – David Rawson Jan 20 '17 at 19:17
  • I guess you are all wrong. I have checked and using `listview1`, and I even posted the whole code of `stat_list.xml` containing `listview1`. – Alex Jan 20 '17 at 19:21
  • Well, you just changed `listView1`. Anyhoo, `public void stat(View view)` - Where's the `Button` that presumably calls that method as its `onClick`? You sure that layout you just posted with the `` is actually being loaded into the `View` hierarchy? – Mike M. Jan 20 '17 at 19:24
  • In a different view in the same activity. – Alex Jan 20 '17 at 19:26
  • OK, then how are you loading both of those layouts? Is one ``d in the other? – Mike M. Jan 20 '17 at 19:27
  • In the methods I say: ` setContentView(R.layout.quiz_edit);` or whatever I need. – Alex Jan 20 '17 at 19:28
  • 1
    Which one is `quiz_edit`? How are you loading the second one? The `setContentView()` method _sets_ the current layout; it doesn't add another each time you call it, so if you're calling it more than once, the last one is the layout that's current, and any one set before that is gone. – Mike M. Jan 20 '17 at 19:30
  • `findViewById()` called in an Activity means 'find the view in the Activities contentView`. I can't see any connection between the contentView and the code where you have the ListView – David Rawson Jan 20 '17 at 19:32
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – David Rawson Jan 20 '17 at 19:35
  • David: I guess you are close. I solved it with the help of your comments... But then I guess the example is outdated... (like always) – Alex Jan 20 '17 at 19:37
  • okay - i'm glad it helped. if you are learning Android, I would recommend the book by CommonsWare 'Busy Coder's Guide to Android Development' which is always up to date. Please help out the Android crew by accepting the duplicate (we get this question a lot) – David Rawson Jan 20 '17 at 19:38

3 Answers3

0

Most probably the line

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

is returning null on listview.

Try this, Replace line

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

with

    ListView listView=(ListView)view.findViewById(R.id.listView1);
P.Vamsi
  • 73
  • 1
  • 1
  • 10
  • Indeed, `listView` is null. Does not make any sense. Why is `listView` null? – Alex Jan 20 '17 at 19:24
  • please post your XML code where R.id.listview1 is located – P.Vamsi Jan 20 '17 at 19:25
  • No. This is not the solution. I found it, but thanks to your help. I must insert the following line: `setContentView(R.layout.stat_list);` to make it work. A change in the line you suggest is not required. Update your answer and I click on 'accept answer'... – Alex Jan 20 '17 at 19:34
0

Try to swap these lines below,

ListView listView=(ListView)findViewById(R.id.listview1);
StatViewAdapter adapter=new StatViewAdapter((Activity)this, adapterList);

So, you'll be referring to the same Content view when you set the adapter for the list.

-1

As the error states, listView is null. Make sure you are setting the correct content view. Here is some code to help you:

public class MainActivity extends AppCompatActivity {

    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.myListView);
        //use mListView as normal
    }
}

Better yet, use Butterknife:

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.myListView)
    ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Butterknife.bind(this);
        //use mListView as normal
    }
}

As an aside, you should probably be using a RecyclerView.

Orbit
  • 2,985
  • 9
  • 49
  • 106