即使使用commit(),SharedPreference值也会在每次登录时更改

时间:2016-01-22 10:45:57

标签: android sharedpreferences

我试图在用户第5次登录应用时显示“评价我们”对话框。在注册时,共享首选项LOG_COUNT设置为0,另一个共享首选项LOG_BOOLEAN的值设置为true。

当用户第一次登录时,我会检查LOG_BOOLEAN的值是否为真。如果是,则LOG_BOOLEAN设置为false。每次用户登录时,共享首选项LOG_COUNT的值都会增加。如果它是5,那么我显示要求评级的对话框,如果用户没有给应用评分,则将其设置回0。

但每次用户登录时,LOG_BOOLEANtrueLOG_COUNT为0,但我将其设置为false并在首次登录时递增。

我使用类SessionManager来存储和更改共享偏好。

这是SessionManager.java:

package com.prematixsofs.taxiapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.HashMap;

/**
 * Created by admin on 05-01-2016.
 */
public class SessionManager {


    SharedPreferences pref;
    String userName;
    Editor editor;
    Context _context;
    int PRIVATE_MODE = 0;
    int loginCount;

    private static final String PREF_NAME = "TaxiPref";
    private static String LOGIN_BOOLEAN = "loginBoolean";
    private static String IS_LOGIN = "IsLoggedIn";
    private static String LOG_COUNT = "loginCount";

    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "email";
    public static final String KEY_NAME = "name";

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

    public void createLoginSession(String name, String email) {
        // Storing login value as TRUE
        // Storing email in pref
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        editor.putBoolean(IS_LOGIN, true);
        // commit changes
        editor.commit();
    }

    public void setLoginCount(int count) {
        if (count == 0) {
            editor.putInt(LOG_COUNT, count);
            editor.commit();
        } else {
            loginCount = pref.getInt(LOG_COUNT, 10);
            editor.putInt(LOG_COUNT, loginCount + 1);
            editor.commit();
        }
    }

    public int getLoginCount() {

        return pref.getInt(LOG_COUNT, 11);//random default value
    }

    public void setLoginSessionToTrue() {
        editor.putInt(LOG_COUNT, 0);
        editor.commit();
        editor.putBoolean(LOGIN_BOOLEAN, true);
        editor.commit();
    }

    public boolean getLoginBoolean() {
        boolean bool;
        bool = pref.getBoolean(LOGIN_BOOLEAN, true);
        return bool;
    }

    public void setLoginBooleanToFalse() {

        editor.putBoolean(LOGIN_BOOLEAN, false);
        editor.putInt(LOG_COUNT, 0);
        editor.commit();
        boolean set = pref.getBoolean(LOGIN_BOOLEAN, false);
        int cou = pref.getInt(LOG_COUNT, 100);


    }

    /**
     * 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, LoginActivity.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);
        }

    }

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

        return pref.getString(KEY_NAME, null);

    }

    public String getUserEmail() {
        return pref.getString(KEY_EMAIL, null);
    }

    /**
     * Clear session details
     */
    public void logoutUser() {
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

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

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

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

    /**
     * Quick check for login
     * *
     */
    // Get Login State
    public boolean isLoggedIn() {
        return pref.getBoolean(IS_LOGIN, false);
    }
}

这是登录:

 login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //databaseHelper.delete();
            item = databaseHelper.getLogin(uname.getText().toString(), pass.getText().toString());

            if (item) {

                sessionManager.createLoginSession(databaseHelper.getUserName(uname.getText().toString()), uname.getText().toString());

                int c = sessionManager.getLoginCount(); // the value here is 11,the random default value.not the incremented value
                countCheck = sessionManager.getLoginBoolean();
                if (countCheck) { //check if first time log in

                    sessionManager.setLoginBooleanToFalse();
                    uname.setText("");
                    pass.setText("");
                    sessionManager.setLoginCount(0);
                    Intent intent2 = new Intent(getApplicationContext(), DateVehiclePicker.class);
                    startActivity(intent2);
                } else if (sessionManager.getLoginCount() == 5) {
                    Intent intent1 = new Intent(getApplicationContext(), DateVehiclePicker.class);
                    sessionManager.setLoginCount(0);
                    intent1.putExtra("login", true);
                    startActivity(intent1);

                }
            } else
                uname.setError("Enter a valid Email & Password");

        }
    });

这是Register.java,我将sharedpreference设置为true并将LOG_COUNT指定为零:

signup.setOnClickListener(new View.OnClickListener() {
sessionManager.setLoginSessionToTrue();
});

1 个答案:

答案 0 :(得分:1)

试试这个

private SharedPreferences.Editor getEditor() {
    SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
    return settings.edit();
}

然后

public void setUserId(String userId) {
    this.userId = userId;
    getEditor().putString(userIdKey, userId).commit();
}

你应该创建默认初始化

 private void initSharedPreference() {
    SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
    userId = settings.getString(userIdKey, ""); // to avoid nullpointerexception
}

在您的SharedPref构造函数中调用此方法

修改

像这样创建SharedPref:

public class SharedPref {

private Context mContext;
private String userId;

private final static String GENERAL_PREFERENCE = "general_pref";
private String userIdKey = "userIdKey";

 public SharedPref(Context context) {
    this.mContext = context;
    initSharedPreference();
 }

 private void initSharedPreference() {
    SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);

    userId = settings.getString(userIdKey, "");
 }

private SharedPreferences.Editor getEditor() {
    SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
    return settings.edit();
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
    getEditor().putString(userIdKey, userId).commit();
}
}

创建处理程序类时:

public class DataSourceController {
public SharedPref sharedPref;
private static DataSourceController sInstance;

private DataSourceController(Context context) {
    sharedPref = new SharedPref(context);
}

public static synchronized DataSourceController getInstance() {
    return sInstance;
}


public static DataSourceController initSingleton(Context context) {
    if (sInstance == null) {
        sInstance = new DataSourceController(context);
    }
    return sInstance;
}

public static SharedPref getSharedPreference() {
    return getInstance().sharedPref;
}
}

在Application类中初始化此处理程序类,如下所示:

public class App extends Application {

@Override
public void onCreate() {
    super.onCreate();
    DataSourceController.initSingleton(this);
}
}

现在您可以从应用的任何位置拨打DataSourceController.getSharedPreference().getUserId();DataSourceController.getSharedPreference().setUserId("id");