java - Android: Passing context to helper class results in NPE -


i creating android app , trying use settingsmanager class read , write preferences. use this, have pass context settingsmanager in order use sharedpreferences api. however, code keeps giving me nullpointerexception. can tell me why?

main.java

@override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_status);          mnavigationdrawerfragment = (navigationdrawerfragment)                 getfragmentmanager().findfragmentbyid(r.id.navigation_drawer);         mtitle = gettitle();          // set drawer.         mnavigationdrawerfragment.setup(                 r.id.navigation_drawer,                 (drawerlayout) findviewbyid(r.id.drawer_layout));         setbutton();     } 

...

public void setbutton(){     button btn = (button) findviewbyid(r.id.button1);     btn.setonclicklistener(new onclicklistener() {         @override         public void onclick(view v) {             settingsmanager settings = settingsmanager.getinstance(getbasecontext());             settings.getusername();         }     }); } 

settingsmanager.java

static context context;  private settingsmanager(){     sharedpreferences = context.getsharedpreferences(settingsfile, context.mode_private); }  public static settingsmanager getinstance(context cntxt){     if(instance == null){         instance = new settingsmanager();     }     context = cntxt;     return instance; } 

the npe happens on line:

sharedpreferences = context.getsharedpreferences(settingsfile, context.mode_private); 

it's not resulting in npe. doing wrong accessing context before assigning it. change code like

private settingsmanager(context context){    context = cntxt;    sharedpreferences = context.getsharedpreferences(settingsfile, context.mode_private); }   public static settingsmanager getinstance(context cntxt){     if(instance == null){                 instance = new settingsmanager(cntxt);     }     return instance; } 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -