0

I have a problem: I need to delete data from a database, but whenever I run the code, it always throws a NullPointerException.

Here is the code:

public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.del:
                try {
                    String selectedSpinner2 = spinner_2.getSelectedItem().toString();
                    System.out.println(selectedSpinner2);
                    catlist.deleteCategory(selectedSpinner2);
                    Toast.makeText(this, "Task Deleted", Toast.LENGTH_SHORT).show();
                    return true;
                }
                catch (NullPointerException e){
                    e.printStackTrace();
                }

            case R.id.set_cat:
                spinner_2.setOnItemSelectedListener(this);
        }
        return true;
}

And for the database

  public boolean deleteCategory(String category){
    return DB.delete(TABLE_NAME, CAT_NAME + "=" + category, null) > 0;
}

And the stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean za.co.brdsa.kyle.planitto_doapp.CategoryList.deleteCategory(java.lang.String)' on a null object reference at za.co.brdsa.kyle.planitto_doapp.Activity3.onMenuItemClick(Activity3.java:314)

Kyle Barry
  • 44
  • 1
  • 6
  • Without stacktrace how can we know where you get exception? – Areca Apr 26 '16 at 13:35
  • please format the code and post only the relevent sections and also add the stacktrace – e4c5 Apr 26 '16 at 13:35
  • 1
    The canonical answer for this question: http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – nasch Apr 26 '16 at 13:37
  • try to change the database version like instead of static final int DB_VERSION = '1' use static final int DB_VERSION = '2' or '3' etc also you can delete the app from device or emulator then run it some time exception arise because of old data base version....! – Nowshad Apr 26 '16 at 13:40
  • you never have initialized `catList` so logically, you never initialized DB and this, I guess, throws the null pointer – Opiatefuchs Apr 26 '16 at 13:44

0 Answers0