繁体   English   中英

Android未清除SharedPreferences

[英]SharedPreferences not being cleared android

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

这是我的代码:

会话管理

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

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

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

我认为这会工作..

您可以更改共享首选项的值。

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

如果您使用的是棉花糖,则在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"
/>

希望以此解决您的问题。

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

我认为问题在于您使用编辑器的方式。

我认为您对编辑器和首选项全球化的看法存在问题,您必须在本地创建首选项和编辑器。...因为您正在获取首选项

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

现在,您没有任何更新的首选项...。​​每次必须使用首选项时...每次初始化首选项和编辑器。

登录或注销。

暂无
暂无

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

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