I\'ve been trying to fix this null pointer exception but I cant. I know its pointing to a null object but I don\'t how to fix it. I am beginner in Java programming so please don
Your itemsAdapter
is never initialized. And it has no values at all. That's why you're getting a NullPointerException when you call your add()
.
Try to do this:
ArrayList data = new ArrayList<>();
// add some data to your ArrayList.
itemsAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);
You can also use a String[]
array instead of an ArrayList
or any other List
for that matter.
On your code it should look like:
private ArrayAdapter itemsAdapter;
private ArrayList data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EditText
final EditText etTask = (EditText) findViewById(R.id.editText);
final String task = etTask.getText().toString();
data = new ArrayList<>();
itemsAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, data);
//Button
Button btn = (Button) findViewById(R.id.button);
//OnClickListeners
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data.add(task);
itemsAdapter.notifyDataSetChanged();
etTask.setText("");
}
});
Edit: If you're creating that ArrayAdapter
to use in something like a ListView
. Where is it on your code? I guess you also forgot to get it.
Something like:
ListView lv = (ListView) findViewById(R.id.yourListView);
// initialize the adapter and stuff.
lv.setAdapter(itemsAdapter);
For further reading on ListView
and adapters, take a look at this link, and this tutorial. Also, check the docs.