Skip to content Skip to sidebar Skip to footer

Android: Passing Context To Helper Class Results In Npe

I am creating an Android app and I am trying to use a SettingsManager class to read and write preferences. To use this, I have to pass context to this SettingsManager in order to u

Solution 1:

it's not resulting in a NPE. What you are doing wrong is accessing context before assigning it. Change your code like

privateSettingsManager(Context context){
   context = cntxt;
   sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);
}


publicstatic SettingsManager getInstance(Context cntxt){
    if(instance == null){        
        instance = new SettingsManager(cntxt);
    }
    return instance;
}

Solution 2:

You can also get the context from the view object.

SettingsManagersettings= SettingsManager.getInstance(v.getContext());

Post a Comment for "Android: Passing Context To Helper Class Results In Npe"