简体   繁体   English

Android未清除SharedPreferences

[英]SharedPreferences not being cleared android

I have an app where a user logs in and his details are saved so that the next time he starts the app he doesn't need to log in again.I have used SharedPreferences for this purpose. 我有一个应用程序,用户可以在其中登录并保存其详细信息,以便下次启动该应用程序时无需再次登录。为此,我使用了SharedPreferences。 Now when I implement a logout function, I clear the preferences and I get a Map with 0 elements. 现在,当我实现注销功能时,我清除了首选项,并得到了一个包含0个元素的Map。 Also I delete the Preference file. 我也删除了首选项文件。 But when another user logs in he can still see the previous users details instead of his. 但是,当另一个用户登录时,他仍然可以看到以前的用户详细信息,而不是他的信息。 How can I solve this? 我该如何解决?

Here is my code:- 这是我的代码:

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 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 注销.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 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();
    }
}

Instead of removing value from sharedpreference you can just edit value of sharedpreference with null value. 除了从sharedpreference中删除值外,您还可以使用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();
        }

i think this will work.. 我认为这会工作..

You can change the values of Shared preferences. 您可以更改共享首选项的值。

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

or You try this code. 或者您尝试此代码。 Clear your Shared preferences values. 清除您的共享首选项值。

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

if your are using Marshmallow then Add file in xml folder mybackupscheme.xml 如果您使用的是棉花糖,则在xml文件夹mybackupscheme.xml中添加文件

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

then add in AndroidManifest.xml 然后添加AndroidManifest.xml

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

Hope this using this your issue will be resolved. 希望以此解决您的问题。

Try to get editor every time before calling commit(). 尝试在每次调用commit()之前获取编辑器。 If this not works, check contexts, that are returning preferences, they must be in one application and process. 如果这不起作用,请检查返回首选项的上下文,它们必须位于一个应用程序和进程中。

I think problem is in your way of working with editor. 我认为问题在于您使用编辑器的方式。

I think there is problem in your view of your editor and preference globalization you have to create preference and editor locally.... Because you are getting preferences 我认为您对编辑器和首选项全球化的看法存在问题,您必须在本地创建首选项和编辑器。...因为您正在获取首选项

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

And now you are not getting any updated Preferences.... Each and every time when you have to work with your preferences... Initialize preference and editor every time. 现在,您没有任何更新的首选项...。​​每次必须使用首选项时...每次初始化首选项和编辑器。

Either logging In or log out. 登录或注销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM