SharedPreferences未被清除android

时间:2014-05-07 04:07:36

标签: java android sharedpreferences logout

我有一个用户登录的应用程序并保存了他的详细信息,以便下次启动应用程序时他不需要再次登录。我已经使用SharedPreferences用于此目的。现在,当我实现注销功能时,我清除了首选项,并获得了一个包含0个元素的Map。我也删除了首选项文件。但是当另一个用户登录时,他仍然可以看到以前的用户详细信息而不是他的。我该如何解决这个问题?

这是我的代码: -

SessionManagement.java

public class SessionManagement extends Application
{
    static 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 = "MyUserDetails";

    // 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_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 usersname)
    {
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);

        editor.putBoolean(KEY_DEVICEREGISTERED, true);
        editor.putString(KEY_EMAILID, emailId);

        editor.putString(KEY_USERSNAME, usersname);

        editor.commit();

        // commit changes

    }


    /**
     * 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_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(this, 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.remove(KEY_EMAILID);
        editor.remove(KEY_USERSNAME);
        editor.remove(IS_LOGIN);

        editor.clear();
        editor.commit();

    }

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

Login.java

sessionManager = new SessionManagement(getApplicationContext());

if(sessionManager.isLoggedIn())
{
    //Go directly to main activity
    HashMap<String, String> userDetails = sessionManager.getUserDetails();

    startMyActivity();
    finish();
}
else
{
    sessionManager.createLoginSession(email, username);
}
public void startMyActivity()
{
    // TODO Auto-generated method stub
    Intent in = new Intent(getApplicationContext(), Details1.class);

    in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    startActivity(in);
    finish();
}

Logout.java

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

ClearData cl = new ClearData();
cl.clearApplicationData(getApplicationContext());

Intent i = new Intent(Home.this, 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
startActivity(i);

ClearData.java

public class ClearData
{
    public static void clearApplicationData(Context context)
    {
        File cache = context.getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                File f = new File(appDir, s);
                if(deleteDir(f))
                    Log.i("TAG", String.format("**************** DELETED -> (%s) *******************", 
                            f.getAbsolutePath()));
            }
        }
    }
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}

5 个答案:

答案 0 :(得分:1)

您可以使用null值编辑sharedpreference的值,而不是从共享首选项中删除值。

       public void logoutUser()
       { 
           editor.putBoolean(IS_LOGIN, false);
           editor.putBoolean(KEY_DEVICEREGISTERED, false);
           editor.putString(KEY_EMAILID, null);
           editor.putString(KEY_USERSNAME, null);
           editor.commit();
        }

我认为这会有效..

答案 1 :(得分:1)

您可以更改共享偏好设置的值。

public void logoutUser()
   { 
       editor.putBoolean(IS_LOGIN, false);
       editor.putBoolean(KEY_DEVICEREGISTERED, false);
       editor.putString(KEY_EMAILID, "");
       editor.putString(KEY_USERSNAME, "");
       editor.clear();
       editor.commit();
    }

或您尝试此代码。清除您的共享偏好设置值。

pref.edit().clear().commit();

答案 2 :(得分:1)

如果你当时正在使用Marshmallow 在xml文件夹中添加文件 mybackupscheme.xml

    <full-backup-content>
         <exclude domain="sharedpref" path="yourshared pref name.xml"/>
    </full-backup-content>

然后添加AndroidManifest.xml

<application
...
android:fullBackupOnly="false"
android:fullBackupContent="@xml/mybackupscheme"
/>

希望使用此功能,您的问题将得到解决。

答案 3 :(得分:0)

每次调用commit()之前尝试获取编辑器。 如果这不起作用,请检查返回首选项的上下文,它们必须位于一个应用程序和进程中。

我认为问题在于你使用编辑器。

答案 4 :(得分:0)

我认为您对编辑器和偏好全球化的看法存在问题,您必须在本地创建首选项和编辑器.... 因为你得到了偏好

public SessionManagement(Context context)
{
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

现在你没有得到任何更新的偏好.... 每当你必须使用你的喜好时...... 每次都初始化首选项和编辑器。

登录或退出。