Android: Passing context to helper class results in NPE

為{幸葍}努か 提交于 2020-02-07 17:15:20

问题


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 use the SharedPreferences API. However, my code keeps giving me a NullPointerException. Can anyone 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 up the 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 this line:

sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);

回答1:


it's not resulting in a NPE. What you are doing wrong is accessing context before assigning it. Change your 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;
}



回答2:


You can also get the context from the view object.

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


来源:https://stackoverflow.com/questions/27170428/android-passing-context-to-helper-class-results-in-npe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!