我想点击菜单项来替换所有按钮功能,但当我点击菜单项时,我收到错误,下面是我的源代码:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menuclearcontainer:
// Single menu item is selected do something
ListView listitem = (ListView)findViewById(R.id.listitem);
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getWritableDatabase(); // LINE 526
String SQL = "DELETE FROM itemchecked";
db.execSQL(SQL);
try
{
final ArrayList<ItemDetail_class> itemlist = dbHelper.getAllItem(tseparate, tgroup);
listitem.setAdapter(new ItemAdapter(getBaseContext(), itemlist));
Toast.makeText(getBaseContext(), "Selection has been cleared !", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
System.out.println(e);
}
return true;
case R.id.menuaddcontainer:
return true;
}
}
表示错误:
06-02 15:02:08.763: E/AndroidRuntime(15040): java.lang.NullPointerException
06-02 15:02:08.763: E/AndroidRuntime(15040): at com.example.app.ViewDetail.onOptionsItemSelected(ViewDetail.java:526)
06-02 15:02:08.763: E/AndroidRuntime(15040): at android.app.Activity.onMenuItemSelected(Activity.java:2606)
我有上面功能的按钮(在menuclearcontainer上),它正常工作,但如果我切换到放入MenuItem,它将是错误的。你有任何解决方案吗?
答案 0 :(得分:2)
首先纠正你应该改变这个
menuInflater.inflate(R.layout.menu, menu);
到
menuInflater.inflate(R.menu.menu, menu);
并在listitem
onCreate(....)
你还需要创建Object
dbHelper
dbHelper = new DataProcessor(this);
答案 1 :(得分:0)
可能实例变量从未初始化
更改此
final DataProcessor dbHelper = new DataProcessor(this);
// dbHelper is local to onCreate
// re-declared and initialized. While the instance variable is null
要
dbHelper = new DataProcessor(this);
同时更改
menuInflater.inflate(R.layout.menu, menu);
到
menuInflater.inflate(R.menu.menu, menu);