Im new to programming with Android and i was trying to make a ListView by allowing a user to input a text through EditText. i finally got it working however i am not quite sure why my first approach did not work:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,values);
lv.setAdapter(adapter);
This caused a force close when the app was launched, and i found out it was due to lv.setAdapter(adapter)
After going through many stackoverflow questions, i saw one answer that stated there was no need to use ArrayList and ArrayAdapter. so i tried the following and it worked:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
This time it worked perfectly when i didnt create the Array List.
So, my question is why does this work when i didnt define/create a String Array in my ArrayAdapter, and why my first method didnt work.
thanks for the help in advance, and im sorry if i didnt post enough code.
EDIT: HERE IS MY FIRST METHOD BELOW i tried to recreate my first method and it is below: it still force closes like the first time. And just to take note, in my second method(which works) all i did was not use ArrayList and take the 3rd argument in the arrayAdapter construction. Also now that your answer have told me that i probably had values as "null", i think you are correct. How could i correct this for use in the future? Thanks!
public class TaskPage extends SherlockActivity {
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
ArrayList<String> values;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText1);
lv = (ListView) findViewById(R.id.listView1);
addButton = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
lv.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
values.add(task);
adapter.notifyDataSetChanged();
}
});
add(),insert(), etc later to populate your ListView.