我正在创建一个Android应用,并且试图使用SettingsManager类读取和写入首选项。要使用此功能,我必须将上下文传递给此SettingsManager才能使用SharedPreferences API。但是,我的代码一直给我NullPointerException。谁能告诉我为什么?

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;
}


NPE发生在这条线上:

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

最佳答案

它不会导致NPE。您做错了什么是在分配context之前访问它。像这样更改您的代码

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;
}

关于java - Android:在NPE中将上下文传递给助手类结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27170428/

10-10 23:14