我对开发Android应用程序非常陌生,我不明白为什么我的应用程序崩溃了。这是代码:
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("");
}
});
}
我不明白为什么产品会被添加到数据库中,但我仍然收到错误,告诉我我正在尝试调用null对象上的方法。
错误:
Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference
我已经在SO上看到了类似的主题,但它对我没有帮助 - 正如你所看到的,我在这个类中将我的适配器声明为全局变量。发生了什么事?
答案 0 :(得分:2)
您需要使用ListActivity
中的setListAdapter方法,而不是使用ListView
中的方法。
在onCreate中,你可以这样做:
setListAdapter(adapter);
而不是
lv.setAdapter(adapter);
答案 1 :(得分:0)
尝试:
adapter = (ArrayAdapter<Product>) getListAdapter();
而不是:
ArrayAdapter<Product> adapter = (ArrayAdapter<Product>) getListAdapter();
并改变:
private ArrayAdapter<Product> adapter;
为:
public ArrayAdapter<Product> adapter;