我打算使用LoadPreferences和SavePreferences方法。我希望它尽可能灵活,这样我就可以要求任何可爱的" savable"数据在我需要时被调用,并在我完成任何类/方法的更改时保存。当我像任何可返回变量一样设置它时,它会给我一个nullpointerexception。这就是我所拥有的:
public class MainActivity extends Activity {
// Add SharedPreference loader
int mPlayerCharisma = SharedPrefLoader("playerCharisma", 0); //I want variable
// playerCharisma if it exists, and to default to int 0 if it does not
int mPlayerBusiness = SharedPrefLoader("playerBusiness", 0);
int mPlayerCombat = SharedPrefLoader("playerCombat", 0);
int mPlayerLevel = SharedPrefLoader("playerLevel", 0);
int mPlayerLocation = SharedPrefLoader("playerLocation", 0);
int mPlayerMoney = SharedPrefLoader("playerMoney", 500);
int mPlayerEnergy = SharedPrefLoader("playerEnergy", 10);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ...
}
public int SharedPrefLoader(String key, int defValue) {
SharedPreferences sharedPref = this.getSharedPreferences("drudlordmt",
MODE_PRIVATE); //This is where my nullpointerexception points to//
int returnedValue = sharedPref.getInt(key, defValue);
return returnedValue;
}
public void SharedPrefSaver(String key, int value) {
SharedPreferences settings = getSharedPreferences("druglordmt", 0);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putInt(key, value).commit();
}
}
从我的阅读中我知道我需要以某种方式传递我的背景,但我想确保我仍然可以做我想要的事情。任何建议都将不胜感激。
谢谢!
答案 0 :(得分:0)
移动:
int mPlayerCharisma = SharedPrefLoader("playerCharisma", 0); //I want variable
// playerCharisma if it exists, and to default to int 0 if it does not
int mPlayerBusiness = SharedPrefLoader("playerBusiness", 0);
int mPlayerCombat = SharedPrefLoader("playerCombat", 0);
int mPlayerLevel = SharedPrefLoader("playerLevel", 0);
int mPlayerLocation = SharedPrefLoader("playerLocation", 0);
int mPlayerMoney = SharedPrefLoader("playerMoney", 500);
int mPlayerEnergy = SharedPrefLoader("playerEnergy", 10);
在SharedPrefLoader()
内(以及对onCreate()
的所有其他调用)。请参阅:Why getApplicationContext() in constructor of Activity throws null pointer exception?