1
我想在一個方法中編輯我的sharedpreferences並保存一個值。如果我這樣做,它說:SharedPreferences中的方法
java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
我在那裏工作的其他活動(但代碼是在OnCreate方法)。在這裏,代碼似乎不起作用。 這裏是我的代碼:
public class LoginActivity extends ActionBarActivity {
SharedPreferences myPrefs;
//some irrelevant code here and there
public void login(View view){
//some more irrelevant code
bt_SignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String theusername = String.valueOf(username.getText());
String thepass = String.valueOf(pass.getText());
if (theusername.equals("schueler") && thepass.equals("123456")) {
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("LehrerPref", false);
editor.apply();
Toast toast = Toast.makeText(getApplicationContext(), "Login erfolgreich! :D", Toast.LENGTH_SHORT);
toast.show();
Intent i = new Intent(getApplicationContext(), Frontpage.class);
startActivity(i);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Login fehlgeschlagen :(", Toast.LENGTH_SHORT);
toast.show();
}
if (theusername.equals("lehrer") && thepass.equals("14869")) {
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("LehrerPref", true);
editor.apply();
Toast toast = Toast.makeText(getApplicationContext(), "Login erfolgreich! :D", Toast.LENGTH_SHORT);
toast.show();
Intent i = new Intent(getApplicationContext(), Frontpage.class);
startActivity(i);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Login fehlgeschlagen :(", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
}
內,如果語句是那些投擲錯誤的部分。 我的錯誤在哪裏?
你永遠initalize'myPrefs' – Blackbelt
嗎?怎樣呢? onCreate中的 –
:'myPrefs = getSharedPreferences(「SHARED_PREF_NAME」,MODE_PRIVATE);' – Blackbelt