Android:将上下文传递给辅助类会导致NPE

时间:2014-11-27 12:07:53

标签: java android nullpointerexception android-context

我正在创建一个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);

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您还可以从视图对象中获取上下文。

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