SharedPreferences未被清除android

时间:2014-05-06 05:13:37

标签: java android sharedpreferences logout

我的应用中有登录功能。此时,当用户首次登录时,用户详细信息将保存在共享首选项文件中。当用户下次登录时,我将用户直接指向第二个屏幕。这很好用。现在我已经实现了注销功能。在这里我清除了偏好。然后,如果我从另一个帐户登录,我仍然会获得第一个帐户的用户详细信息。

这是我的代码: -

   public class SessionManagement
{
     SharedPreferences pref;

        // Editor for Shared preferences
        SharedPreferences.Editor editor;

        // ContextS
        Context _context;

        // Shared pref mode
        int PRIVATE_MODE = 0;

        // Sharedpref file name
        private static final String PREF_NAME = "UserDetails";

        // All Shared Preferences Keys
        private static final String IS_LOGIN = "IsLoggedIn";

        // User name (make variable public to access from outside)
        public static final String KEY_EMAILID = "email";

        // Email address (make variable public to access from outside)
        public static final String KEY_DEVICEURL = "deviceurl";

        public static final String KEY_ENDPOINTHOST = "endpointhost";
        public static final String KEY_DEVICENAME = "devicename";
        public static final String KEY_USERSNAME = "usersname";
        public static final String KEY_ENCODEDACCOUNTNAME = "encodedaccountname";
        public static final String KEY_HOSTURL = "hosturl";
        public static final String KEY_DEVICEiD = "deviceid";

        public static final String  KEY_DEVICEREGISTERED = "deviceregistered";
        // Constructor
         static SessionManagement session = null;

    public static SessionManagement  getInstance(Context context)
    {
    _context = context;
    if(session == null)
        session = new SessionManagement ();
    return session;
    }
    public SessionManagement()
    {

        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

        public void createLoginSession(String emailId, String deviceauthurl, String deviceid, String endpointhost, String devicename, String usersname, String encodedaccountname, String hosturl)
        {
            // Storing login value as TRUE
            editor.putBoolean(IS_LOGIN, true);

            editor.putBoolean(KEY_DEVICEREGISTERED, true);
            editor.putString(KEY_EMAILID, emailId);
            editor.putString(KEY_DEVICEURL, deviceurl);
            editor.putString(KEY_DEVICEiD, deviceid);
            editor.putString(KEY_ENDPOINTHOST, endpointhost);
            editor.putString(KEY_DEVICENAME,devicename);
            editor.putString(KEY_USERSNAME, usersname);
            editor.putString(KEY_ENCODEDACCOUNTNAME, encodedaccountname);
            editor.putString(KEY_HOSTURL, hosturl);

            // commit changes
            editor.commit();
        }

        /**
         * Get stored session data
         * */
        public HashMap<String, String> getUserDetails()
        {
            HashMap<String, String> user = new HashMap<String, String>();

            user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
             user.put(KEY_DEVICEAUTHURL, pref.getString(KEY_DEVICEAUTHURL, null));
            user.put(KEY_DEVICEiD, pref.getString(KEY_DEVICEiD, null));
            user.put(KEY_ENDPOINTHOST, pref.getString(KEY_ENDPOINTHOST, null));
            user.put(KEY_DEVICENAME, pref.getString(KEY_DEVICENAME, null));
            user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, null));
            user.put(KEY_ENCODEDACCOUNTNAME, pref.getString(KEY_ENCODEDACCOUNTNAME, null));
            user.put(KEY_HOSTURL, pref.getString(KEY_HOSTURL, null));

            // return user
            return user;

        }
        /**
         * Check login method wil check user login status
         * If false it will redirect user to login page
         * Else won't do anything
         * */
        public void checkLogin()
        {
            // Check login status
            if(!this.isLoggedIn())
            {
                // user is not logged in redirect him to Login Activity
                Intent i = new Intent(_context, Login.class);
                // Closing all the Activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // Add new Flag to start new Activity
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                // Staring Login Activity
                  _context.startActivity(i);
            }

        }

       // This function clears all session data and redirect the user to LoginActivity
        /**
             * Clear session details
             * */
            public void logoutUser()
            {
                // Clearing all data from Shared Preferences
                //editor.clear();
                editor.remove(KEY_DEVICEURL);
                editor.remove(KEY_DEVICENAME);
                editor.remove(KEY_DEVICEREGISTERED);
                editor.remove(KEY_DEVICEiD);
                editor.remove(KEY_EMAILID);
                editor.remove(KEY_ENCODEDACCOUNTNAME);
                editor.remove(KEY_ENDPOINTHOST);
                editor.remove(KEY_HOSTURL);
                editor.remove(KEY_USERSNAME);
                editor.remove(IS_LOGIN);
                editor.remove(PREF_NAME);
                editor.clear();
                editor.commit();


                File file = new File("/data/data/com.zcv.acb/shared_prefs/UserDetails.xml");
                file.delete();


                // After logout redirect user to Loing Activity
                Intent i = new Intent(_context, Login.class);
                // Closing all the Activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // Add new Flag to start new Activity
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                // Staring Login Activity
                _context.startActivity(i);

            }

            public boolean isLoggedIn()
            {
                return pref.getBoolean(IS_LOGIN, false);
            }
}

Login.java

    SessionManagement sessionManager =SessionManagement.getInstance(this);
        session.logoutUser();
sessionManager.createLoginSession(username, deviceUrl, deviceId, endPointHost, deviceName, name, encodedAccountNameToken, hostUrlToken);
   if(sessionManager.isLoggedIn())
      {
          //Go directly to main activity
         HashMap<String, String> userDetails = sessionManager.getUserDetails();

        startMyActivity();
        finish();   
      }

Logout.java

SessionManagement session =SessionManagement.getInstance(this);
        session.logoutUser();
            this.finish();

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

用于保存共享首选项

保存共享偏好设置时,请以savePreference("Username","some name");

方式调用

删除共享偏好设置时,请{my}}

savePreference("Username","");

获取共享偏好

现在,只要在空字符串将用户重定向到登录活动时检查首选项。否则到用户屏幕

private void savePreferences(String key, String value) 
{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}

这很简单。

更新:2

private boolean loadSavedPreferences() 
{
    boolean check=false;
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String name = sharedPreferences.getString("Username", "");
    if(!name.equals(""))
    {
        check = true;
    }
    return check;
}

记住一件事。 savePreference只是accept(String,String),你需要为(String,boolean)

创建一个

答案 1 :(得分:0)

    brother use this method to remove the string shared preference:

        public static void removeSharedPrefStringData(Context context, String key)
        {

            SharedPreferences appInstallInfoSharedPref = context.getSharedPreferences(Constant.SHARED_PREF_NAME, context.MODE_MULTI_PROCESS);

            Editor appInstallInfoEditor = appInstallInfoSharedPref.edit();
            appInstallInfoEditor.remove(key);
            appInstallInfoEditor.commit();

        }

set and get preference methods are here:

    public static void setSharedPrefStringData(Context context, String key, String value)
    {
        SharedPreferences appInstallInfoSharedPref = context.getSharedPreferences(Constant.SHARED_PREF_NAME, context.MODE_MULTI_PROCESS);
        Editor appInstallInfoEditor = appInstallInfoSharedPref.edit();
        appInstallInfoEditor.putString(key, value);
        appInstallInfoEditor.commit();
    }

    public static String getSharedPrefStringData(Context context, String key)
    {

        SharedPreferences userAcountPreference = context.getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_MULTI_PROCESS);

        return userAcountPreference.getString(key, "");

    }

答案 2 :(得分:0)

问题是,您使用的是2个不同的会话管理对象,即Login具有不同的对象,并且注销具有不同的会话管理对象。这就是为什么它不起作用。它们都属于不同的共享偏好对象。当你初始化logout对象时,会创建另一个共享首选项对象。解决方法是使用单例对象或使用静态方法和成员来解决你的问题。但我认为单例对此有好处。像这样编写你的代码:

public class SessionManagement {
static SessionManagement man = null;

public static SessionManagement  getInstance(){
if(man == null)
   man = new SessionManagement ();
return man;
}

...

}

并将您的类构造函数设为私有(只需删除public并在构造函数中替换为private)

此后所有代码保持不变。

现在在登录活动和登出活动中,通过调用此

获取您的对象
SessionManagement sess = SessionManagement.getInstance();