GuyTsir GuyTsir - 1 year ago 86
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();

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

Answer Source

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.


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

etName = findViewById(;

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