整个SharedPreference未被清除

时间:2014-06-03 05:36:08

标签: java android session sharedpreferences

我正在创建两个SharedPreferences文件,以便在我的应用中维护我的会话。

当我在应用程序中创建Logout功能时,SharedPreferences不会被清除,当下一个用户尝试登录时,他仍然会看到以前的用户详细信息或根本没有detials。

以下是我的两个SharedPreferences文件: -

StorageHelper.java

public class StorageHelper 
{
    private static Context myContext = Login.getMyContext();
     public static Login myLogin = new Login();
     public String deviceId;
     public static String UserDataFile = "UserData";
     SharedPreferences localSettings;
     SharedPreferences.Editor editor;

    public StorageHelper(String deviceID) 
    {
        // TODO Auto-generated constructor stub
        deviceId = deviceID;
    }


    public StorageHelper() 
    {
        // TODO Auto-generated constructor stub
    }


    public  void SetDeviceId(String deviceId)
    {
        // TODO Auto-generated method stub
          localSettings = myContext.getSharedPreferences(UserDataFile,0);
         editor = localSettings.edit();
        editor.putString("DeviceId",  deviceId);
        editor.commit();

    }
       public  String GetDeviceId()
      {
          String deviceId = "";
          localSettings = myContext.getSharedPreferences(UserDataFile,0);
          if (localSettings.contains("DeviceId"))
          {
              deviceId = localSettings.getString("DeviceId", "Nothing found");
          }
          return deviceId;
      }

    public static Boolean GetRegistrationInformation() 
    {
        // TODO Auto-generated method stub
        return true;
    }

    public  void SetRegistrationInformation(Boolean value) 
    {
        // TODO Auto-generated method stub
         localSettings = myContext.getSharedPreferences(UserDataFile,0);
         editor = localSettings.edit();
       editor.putBoolean("Registration", value);
       editor.commit();


    }

    public void ClearData() 
    {
         localSettings = myContext.getSharedPreferences(UserDataFile,0);
         editor = localSettings.edit();
        editor.clear();
        editor.commit();
    }

}

SessionManagement.java

 SharedPreferences pref;

        // Editor for Shared preferences
        Editor editor;

        // Context
        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_DEVICENAME = "devicename";
        public static final String KEY_USERSNAME = "usersname";


        public static final String  KEY_DEVICEREGISTERED = "deviceregistered";
        // Constructor
        public SessionManagement(Context context)
        {
            this._context = context;
            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.putString(KEY_DEVICENAME,devicename);
            editor.putString(KEY_USERSNAME, usersname);


            // commit changes
            editor.commit();
        }

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

            user.put(KEY_DEVICENAME, pref.getString(KEY_DEVICENAME, null));
            user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, 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);

                // 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_DEVICENAME);

                editor.remove(KEY_USERSNAME);
                e
                editor.remove(PREF_NAME);
                editor.commit();

                // 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);

                // 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);
            }

我清除了以下数据: -

  case R.id.action_settings:

        StorageHelper helper  = new StorageHelper();
        helper.ClearData();

        SessionManagement session = new SessionManagement(getApplicationContext());
        session.logoutUser();

        finish();

        return true;

2 个答案:

答案 0 :(得分:0)

来自 docs

  

“与commit()不同,后者将其首选项写入持久性   同步存储,apply()将其更改提交到内存中   SharedPreferences立即“

同样来自 docs

  

“对于任何特定的首选项,都有一个实例   所有客户共享的这个类(SharedPreferences)“

这意味着您尝试从两个不同的位置修改SharedPreferences的相同(且唯一)副本,并且由于commit()写入磁盘(这是昂贵的),因此存在不一致(最后提交需要优先级)。

解决问题的第一步是要意识到你只有一个SharedPreferences实例并且你正在从不同的地方访问同一个实例 - 这可能会造成竞争条件。考虑到这一点,正确的做法是重新设计您的软件以考虑它!

你可以在使用应该更安全的提交之前尝试使用apply()(因为它改变了“内存中”对象,这比写入磁盘要快得多),甚至可以添加同步机制 - 但即使它解决问题,这也不正确地使用SharedPreferences

答案 1 :(得分:-1)

使用这种方式清除数据

SharedPreferences sharedPref= getSharedPreferences("mypref",0);
 SharedPreferences.Editor editor = sharedPref.edit();
 editor.clear();      //its clear all data.
 editor.commit();  //Don't forgot to commit  SharedPreferences