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<String> data = new ArrayList<>();
// add some data to your ArrayList.
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
You can also use a String[]
array instead of an ArrayList<String>
or any other List<String>
for that matter.
On your code it should look like:
private ArrayAdapter<String> itemsAdapter;
private ArrayList<String> 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<String>(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.
I think you should try this..!
ArrayList<MyClass> myList = new ArrayList<MyClass>();
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this, R.layout.row,
to, myList.);
listView.setAdapter(adapter);
Initialize your adapter itemsAdapter=new ArrayAdapter<>(...);
Initialize your adapter in OnCreateView() and before adding any value,
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, taskNames);
here taskNames can an array or arrayList of task names which you would have defined as,
ArrayList<String> taskNames; // or String[] taskNames;
Let me know if it works for you...
And do mark it as answer so that it would be useful to others...
You haven't created an instance of an ArrayAdapter
for your itemsAdapter
variable when you try to call the add()
method on it.
Try to initialise it using:
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
Note: values
is either a String[]
or List<String>
so you'll need to pass that in correctly