我有一个正在运行的活动,而没有操作共享首选项。添加后,单击按钮后出现空指针错误。
我认为我使用共享首选项的方式不正确。任何人都可以帮助指出问题所在吗?我应该在使用前new()吗?
public class BanknameActivity extends Activity {
String [] bank_name;
String selected_bank_config;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bankname);
// Show the Up button in the action bar.
// setupActionBar();
bank_name = getResources().getStringArray(R.array.bankname);
ListView lv1 = (ListView) findViewById(R.id.bankname_listview);
lv1.setChoiceMode(1); // CHOICE_MODE_SINGLE
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, bank_name);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
//selected_bank_config = "Citi";
prefs.edit().putString(selected_bank_config, "citi").commit();
return_to_config(view);
}
});
}
以下是我的代码的一部分:
public void return_to_config(View view){
Intent intent = new Intent(this, ConfigActivity.class);
startActivity(intent);
this.finish();
}
最佳答案
**you need to initialize your shared Preferences. Without initialization it will always be null.**
yo need to do following stuff:
// mPrefs=getSharedPreferences("Preferences Name",mode);
mPrefs=getSharedPreferences("FBPref",0);
Editor edit=mPrefs.edit();
edit.putString("UserName", "");
edit.putString("UserId","");
edit.putString("EmailId","");
edit.commit();
这段代码工作正常。
希望您会感激。
关于android - 使用共享首选项时遇到空点异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18044790/