Can't call function from within onOptionsItemSelected

560 Views Asked by At
public boolean onOptionsItemSelected(MenuItem item)
{
    //check selected menu item
    switch (item.getItemId()) { 
    case R.id.exit:
        this.finish();
        return true;
    case R.id.basic: 
        Difficulty = DIFFICULTY_BASIC;
        Toast.makeText(YogaPosesActivity.this, "Difficulty is Basic", Toast.LENGTH_SHORT).show();
        SetImageView(myDbHelper);
        return true;
    case R.id.advanced: 
        Toast.makeText(YogaPosesActivity.this, "Difficulty is Advanced", Toast.LENGTH_SHORT).show();
        Difficulty = DIFFICULTY_ADVANCED;
        SetImageView(myDbHelper);
        return true;
    case R.id.allPoses:
        Toast.makeText(YogaPosesActivity.this, "All Poses Will Be Displayed", Toast.LENGTH_SHORT).show();
        Difficulty = DIFFICULTY_ADVANCED_AND_BASIC;
        SetImageView(myDbHelper);
        return true;
    default: 
       return super.onOptionsItemSelected(item);
    }
}

I get an error when I call the SetImageView function, which was defined out of the OnCreate Activity. Can you not call a function unless it was defined inside the OnCreate?

I get a nullPointer Exception when calling the function.

1

There are 1 best solutions below

0
On

If you define your SetImageView (myDbHelper) inside your Activity (and outside of onCreate()), it should be OK to call it like you did.

If you are getting a nullPointer Exception, the reason might be that myDbHelper is still null. Check whether this is true.

By the way Java suggests we lower case for the first letter of a method or variable, and use upper case for Class.

Sorry I can not comment because I don't have enough point, so I have to answer directly even though I don't have all the info. If you post more code and logcat info. I will revise my answer.