GuyTsir GuyTsir - 3 months ago 19
Android Question

Sharedpreferences in android studio

I've been starting to develop a pretty basic app but I cant use sharedpreference for some reason. The app crashes when it should be saved.

this is my code:

SharedPreferences sp=getSharedPreferences("details1",0);
SharedPreferences.Editor editor=sp.edit();
editor.putString("etName",etName.getText().toString());
editor.putString("etLName",etLName.getText().toString());
editor.putString("etCity",etCity.getText().toString());
editor.putString("btnDateOfBirth",btnDateOfBirth.getText().toString());
editor.putString("btnGender",btnGender.getText().toString());
editor.commit();


I've declared on the variables needed. What might cause it to crash ?

Answer

I generally use this way to get the sharedPreferences of my application:

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

Also, you should provide the stack trace because the error could as well come from the getText methods you use for example? You say the variables are declared, but it's not enough. They have to point to an existing TextView or you get a null pointer exception.

Additional trick: you can chain the putX methods as they return the editor.

editor.putString("etName",etName.getText().toString())
    .putString("etLName",etLName.getText().toString())
    .putString("etCity",etCity.getText().toString())
    .putString("btnDateOfBirth",btnDateOfBirth.getText().toString())
    .putString("btnGender",btnGender.getText().toString())
    .commit();

EDIT : from the stacktrace it seems that etName is null. So you should ensure it points to an existing TextView. Typically:

etName = findViewById(R.id.et_text);

if your TextView (or EditText) has the id et_text in your XML layout.