单击菜单项android时出错

时间:2014-06-02 08:11:21

标签: android database click menuitem

我想点击菜单项来替换所有按钮功能,但当我点击菜单项时,我收到错误,下面是我的源代码:

@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,它将是错误的。你有任何解决方案吗?

2 个答案:

答案 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);