Answer the question
In order to leave comments, you need to log in
How to properly implement SharedPreferences?
Good afternoon, I'm a newbie, there was a problem when implementing SharedPreferences, it always returns a default value.
MainActivity.java
private PreferenceEditor userPref;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SharedPreferences preference = this.getSharedPreferences("user_pref", Context.MODE_PRIVATE);
userPref = new PreferenceEditor(preference);
userPref.addUser(userDevice);
}
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(),"ID юзера:" + userPref.getUser(), Toast.LENGTH_LONG).show();
}
package com.test.test.model;
import android.content.SharedPreferences;
public class PreferenceEditor {
private SharedPreferences preference;
public PreferenceEditor(SharedPreferences preference){
this.preference = preference;
}
public void addUser(User user){
SharedPreferences.Editor editor = preference.edit();
editor.putLong("id", user.getId());
editor.commit();
}
public long getUser(){
return preference.getLong("id", -1);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question