1

I am trying to use the following code to populate a ListView using a predefined array of strings:

String[] schedule_names = getResources().getStringArray(R.array.test_schedules);

// Populate the ListView using the array of schedule names
ArrayList<String> als = new ArrayList<String>(Arrays.asList(schedule_names));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.listView, als);

adapter.add("Test");

ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);

But it force closes unless I comment out listView.setAdapter(adapter); (which obviously means the ListView isn't populated at all). It seems the reason is a NullPointerException.

Why is this?

Superbest
  • 25,318
  • 14
  • 62
  • 134

1 Answers1

1

This line is wrong...

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.listView, als);

...the second parameter of the constructor should not be your ListView, it should be a layout with a TextView.

Try replacing R.id.listView with android.R.layout.simple_list_item_1

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • This solved the problem, thanks! What is `simple_list_item_1`? – Superbest Oct 30 '12 at 23:02
  • Nevermind, it turns out this was explained in http://stackoverflow.com/questions/3663745/what-is-android-r-layout-simple-list-item-1 so I'll link from here for future reference. – Superbest Oct 30 '12 at 23:03
  • Glad to help. Yes, that's a good link explaining the pre-defined `android.R.layout` resources. – Squonk Oct 30 '12 at 23:05