SharedPreferences always get default value in my existing app but when created new app its ok

后端 未结 11 955
眼角桃花
眼角桃花 2020-12-16 13:18

SharedPreferences doesn\'t work correct in one existing apps. I tried many different ways but still not working. Always get default values app start again.

  • It\
11条回答
  •  长情又很酷
    2020-12-16 14:08

    Just use below method and check.

    Create one Java class AppTypeDetails.java

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    
    public class AppTypeDetails {
    
        private SharedPreferences sh;
    
        private AppTypeDetails() {
        }
        private AppTypeDetails(Context mContext) {
            sh = PreferenceManager.getDefaultSharedPreferences(mContext);
        }
        private static AppTypeDetails instance = null;
        public synchronized static AppTypeDetails getInstance(Context mContext) {
            if (instance == null) {
                instance = new AppTypeDetails(mContext);
            }
            return instance;
        }
    
        // get user status
        public String getUser() {
            return sh.getString("user", "");
        }
        public void setUser(String user) {
            sh.edit().putString("user", user).commit();
        }
    
        // Clear All Data
        public void clear() {
            sh.edit().clear().commit();
        }
    }
    

    Now Set value to SharedPreferences.

    AppTypeDetails.getInstance(MainActivity.this).setUser();
    

    Get Value form SharedPreferences.

    String userName = AppTypeDetails.getInstance(MainActivity.this).getUser();
    

    Now do any thing with the userName.

    Always check

    if(userName.trim().isEmpty())
    {
        // Do anything here.
    }
    

    because In SharedPreferences we set user name blank ("")

    or

    you can set user name null in SharedPreferences then you need check

    if(userName != null){
        //do anything here
    }
    

    For clear data from SharedPreferences.

    AppTypeDetails.getInstance(MainActivity.this).setUser("");
    

    or

    AppTypeDetails.getInstance(MainActivity.this).clear();
    

提交回复
热议问题