почему так странно работает shared preference

Я безуспешно пытаюсь заставить работать shared preference,причём странно когда я пытаюсь запустить код, оно не "вылетает", оно просто заново запускает приложение, но я отрыл 2 ошибки:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference

Caused by: java.lang.reflect.InvocationTargetException

мой код:

    public class Authorisation extends AppCompatActivity {
private Call call;
private Response response;
public SharedPreferences authpref;
public SharedPreferences.Editor authpref_ed;
private EditText login,pass;
private String s;//response body
private TextView res;//shows response body
private OkHttpClient client = new OkHttpClient();//the client
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_authorisation);
    SharedPreferences authpref
            = PreferenceManager.getDefaultSharedPreferences(Authorisation.this);//to save login and password
    SharedPreferences.Editor authpref_ed = authpref.edit();//to edit it

    login=findViewById(R.id.login_et);
    pass=findViewById(R.id.password_et);
    res=findViewById(R.id.res_of_auth);
}
public void authentication(View view){
    Log.d("MyTag",login.getText().toString());
    authpref_ed.putString("login",login.getText().toString());//ошибка
    authpref_ed.putString("pass",pass.getText().toString());
    Log.d("MyTag","1");
    authpref_ed.commit();//далее следует то, что должно было выполняться после

причём, когда я ставлю строку в onCreate(), она начинает работать.


Ответы (1 шт):

Автор решения: woesss
SharedPreferences.Editor authpref_ed = authpref.edit();//to edit it

Здесь вы объявили локальную переменную authpref_ed и присвоили значение ей, а не полю с тем же именем - поле так и осталось не инициализированным.
Уберите тип или присвойте это значение полю:

// вариант 1
authpref_ed = authpref.edit();//to edit it
//----------------------------------------------
// вариант 2
SharedPreferences.Editor authpref_ed = authpref.edit();//to edit it
// ссылкой 'this' указываем что обращаемся именно к полю класса, а не к локальной переменной 
this.authpref_ed = authpref_ed; 

→ Ссылка