I am totally new to developing Android applications and I do not understand why my app crashes. Here's the code:
public class ProductListActivity extends ListActivity {
private ProductDataSource datasource;
private ListView lv;
private ArrayAdapter<Product> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
this.addListenerOnAddNewProductButton();
datasource = new ProductDataSource(this);
datasource.open();
datasource.deleteAllProducts();
List<Product> values = datasource.getAllProducts();
lv = (ListView) findViewById(android.R.id.list);
adapter = new ArrayAdapter<Product>(
this,
android.R.layout.simple_list_item_1,
values );
lv.setAdapter(adapter);
}
private void addListenerOnAddNewProductButton() {
Button btn = (Button) findViewById(R.id.add_new);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText addProductInput = (EditText) findViewById(R.id.add_product_text);
String newProductName = addProductInput.getText().toString();
Product addedProduct = datasource.createProduct(newProductName);
ArrayAdapter<Product> adapter = (ArrayAdapter<Product>) getListAdapter();
adapter.add(addedProduct);
Toast.makeText(getApplicationContext(), "Product added", Toast.LENGTH_LONG).show();
addProductInput.setText("");
}
});
}
I do not understand why products are added to database and still I am receiving the error telling me I am trying to invoke a method on a null object.
Error:
Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference
I've already seen similar topic here on SO, but it didn't help me - as you can see, I declared my adapter as a global variable in this class. What's going on?