共享首选项值在每次登录时都会更改,即使使用 commit()



我正在尝试在用户第 5 次登录应用程序时显示"评分"对话框。注册时,共享首选项LOG_COUNT设置为 0,另一个共享首选项LOG_BOOLEAN的值设置为 true。

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

但是每次用户登录时,LOG_BOOLEAN trueLOG_COUNT为 0,尽管我将其设置为 false 并在第一次登录时递增。

我使用类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");
        }
    });

这是寄存器.java我将共享首选项设置为 true 并将LOG_COUNT赋值为零:

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

尝试这样做

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
}

在共享Pref构造函数中调用此方法

编辑

像这样创建共享首选项:

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

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

public class App extends Application {
@Override
public void onCreate() {
    super.onCreate();
    DataSourceController.initSingleton(this);
}
}

因此,现在你可以从应用的任何位置调用DataSourceController.getSharedPreference().getUserId();DataSourceController.getSharedPreference().setUserId("id");

最新更新