I'm trying to set a ListView and I was able to do it using a simple String[] Array as you can see in the code.
Later on, I commented out the Array and used a List
My problem starts when I want to use the List (since I need to manipulate the contents) and a simple Array can't be dynamically changed. When I use the List I get a NullPointerException when I create the ArrayAdapter and I don't know why.
I read in the documentation of the ArrayAdapter that it is overloaded with 6 different constructors and one of them is
ArrayAdapter(Context context, int resource, List objects)
Why am I getting the NullPointerException?
What should I do to make it work with a List instead of an Array?
Thanks in advance!
public class MainActivity extends Activity implements OnItemClickListener {
ListView l;
// String[] days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
List<String> days;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
days.add(0, "Sunday");
days.add(1, "Monday");
days.add(2, "Tuesday");
days.add(3, "Wednesday");
days.add(4, "Thursday");
days.add(5, "Friday");
days.add(6, "Saturday");
l = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, days);
l.setAdapter(adapter);
l.setOnItemClickListener(this);
}
@Override
public void onItemClick(
AdapterView<?> adapterView, // ListView that was clicked
View view, // Reference to the row that was clicked (each row is a TextView)
int i, // position
long l) { // id of the TextView that was clicked
Toast.makeText(this, days.get(i) + " " + i, Toast.LENGTH_LONG).show();
}
}