调用为SharedPreference创建的类没有发生

时间:2017-04-05 09:56:09

标签: android sharedpreferences

创建单独的类以执行sharedPreference,而API调用发生在我尝试调用活动中的SharedPreference类但调用未发生的活动中?

public  void saveInt(Context context, String key, String value) {

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(key, value);
        editor.commit();
}

1 个答案:

答案 0 :(得分:0)

请检查这个,

这是我自己创建的类<​​/ p>

public class ShardPref {

    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;

    private static final String PREFERENCES = "bgvs_app";

    private static final String IS_USER_LOGIN = "is_user_login";
    private static final String BRANCH_ID = "branch_id";
    private static final String EMP_ID = "emp_id";
    private static final String USERNAME = "user_name";
    private static final String PASSWORD = "user_password";
    private static final String USER_TYPE = "user_type";


 public ShardPref(Context mContext) {

        mPreferences = mContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);

    }



public void setUserData(String strBranchId, String strEmpId, String strUsername, String strPassword, String usertype) {
        mEditor = mPreferences.edit();
        mEditor.putString(BRANCH_ID, strBranchId);
        mEditor.putString(EMP_ID, strEmpId);
        mEditor.putString(USERNAME, strUsername);
        mEditor.putString(PASSWORD, strPassword);
        mEditor.putString(USER_TYPE, usertype);
        mEditor.apply();
    }

    public String getBranchId() {
        return mPreferences.getString(BRANCH_ID, "");
    }

    public String getEmpId() {
        return mPreferences.getString(EMP_ID, "");
    }

    public String getUsername() {
        return mPreferences.getString(USERNAME, "");
    }

    public String getPassword() {
        return mPreferences.getString(PASSWORD, "");
    }

    public String getUserType() {
        return mPreferences.getString(USER_TYPE, "");
    }


}

此后只需致电

 private ShardPref mPref;

 mPref = new ShardPref(LoginActivity.this);
// Set Data
 mPref.setUserData(set data here);
// Get Data
mPref.getEmpId();