Search code examples
javaandroidandroid-fragmentsfragmentsharedpreferences

get SharedPrefrences values in fragment?


how can i get SharedPrefrences value for example below get login status in fragment for save?

SharedPreferences prefs;
prefs= PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("isSignIn", "Yes");
editor.commit();

Solution

  • anyone who is confused i can give you a simple code :

    // You can create separate class for sharedPreferences and use it in every activity

    public class UserLoginPref {
    
    private Context context;
    private SharedPreferences sharedPreferences;
    private String Phone;
    private boolean isSignIn;
    
    public void setIsSignIn(boolean isSignIn){
    sharedPreferences.edit().putBoolean("isSignIn",isSignIn).commit();
    }
    
    public boolean getIsSignIn(){
    isSignIn = sharedPreferences.getBoolean("isSignIn",false);
    }
    
    
    public String getPhone() {
        String mobile = sharedPreferences.getString("Phone","");
        return mobile;
    }
    
    public void setPhone(String phone) {
        sharedPreferences.edit().putString("Phone",phone).commit();
    }
    
    public UserLoginPref(Context context){
        this.context = context;
        sharedPreferences = context.getSharedPreferences("UserLoginPref",Context.MODE_PRIVATE);
    }
    
    public void logOutUser(){
        sharedPreferences.edit().clear();
        setPhone("");
    }
    }
    
    
    
    
    // And use it in your activity like this
    UserLoginPref userPref = new UserLoginPref(this);
    userPref.setIsSignIn(true);