Search code examples
javaandroidandroid-sharedpreferences

SharedPreferences doesn't seem to save the variables


I have a class that implements the SharedPreferences but whenever I try to save the data or get the data it does not seem to do it.

public class SharedPreferenceManager {

public SharedPreferenceManager() {
    super();
}

public static final String FILENAME = "PREFERENCES_FILE";

public static void saveData(Context context, String key, String data)
{
    SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, data);
    editor.apply();
}

public static String getData(Context context, String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
    String data = sharedPreferences.getString(key, null);
    return data;
}

public static void removeData(Context context, String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.remove(key);

}
}

This is where I save the Data:

public class CreateUserActivity extends Activity {
EditText txtName, txtEmail, txtPassword;
AlertDialogManager alert = new AlertDialogManager();
private String token;
private SharedPreferenceManager sharedPreferenceManager;

public void setToken(String token) {
    this.token = token;
}

public String getToken() {
    return token;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.create_user_activity);
    txtName = (EditText) findViewById(R.id.loginName);
    txtEmail = (EditText) findViewById(R.id.loginEmail);
    txtPassword = (EditText) findViewById(R.id.loginPassword);
    sharedPreferenceManager = new SharedPreferenceManager();
}

public void checkCreateUser(View view) throws JSONException {
    String name = txtName.getText().toString();
    String email = txtEmail.getText().toString();
    String password = txtPassword.getText().toString();
    String token = getToken();

    CheckBox checkBox = (CheckBox) findViewById(R.id.login_remember_checkbox);
    if (name.trim().length() > 0 && password.trim().length() > 0 && email.trim().length() > 0) {
        JSONObject userObj = new JSONObject();
        userObj.put("name", name);
        userObj.put("email", email);
        userObj.put("password", password);
        String jsonDocument = userObj.toString();
        PostUserTask put = new PostUserTask();
        put.execute("http://api.evang.dk/v2/users", jsonDocument);
        if (checkBox.isChecked()) {
            sharedPreferenceManager.saveData(CreateUserActivity.this, "USERNAME", name);
            sharedPreferenceManager.saveData(CreateUserActivity.this, "EMAIL", email);
            sharedPreferenceManager.saveData(CreateUserActivity.this, "PASSWORD", password);
            sharedPreferenceManager.saveData(CreateUserActivity.this, "TOKEN", token);
        } else {
            sharedPreferenceManager.removeData(CreateUserActivity.this, "USERNAME");
            sharedPreferenceManager.removeData(CreateUserActivity.this, "EMAIL");
            sharedPreferenceManager.removeData(CreateUserActivity.this, "PASSWORD");
            sharedPreferenceManager.removeData(CreateUserActivity.this, "TOKEN");
        }
    }
    else
    {
        alert.showAlertDialog(CreateUserActivity.this, "Login failed!", "Please enter name, username and password", false);
    }
    Intent i = new Intent(getBaseContext(), UserActivity.class);
    i.putExtra("SESSIONID", token);
    i.putExtra("NAMEID", name);
    startActivity(i);
}

And where I read the data of the SharedPreferences:

EditText userNameTxt, passwordTxt, emailTxt;
SharedPreferenceManager sharedPreferenceManager;
String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Intent intent = getIntent();
    userNameTxt = (EditText) findViewById(R.id.userNameLogin);
    passwordTxt = (EditText) findViewById(R.id.passwordLogin);
    emailTxt = (EditText) findViewById(R.id.emailLogin);
    sharedPreferenceManager = new SharedPreferenceManager();
    String userName = sharedPreferenceManager.getData(getBaseContext(), "USERNAME");
    String email = sharedPreferenceManager.getData(getBaseContext(), "EMAIL");
    String password = sharedPreferenceManager.getData(getBaseContext(), "PASSWORD");
    token = sharedPreferenceManager.getData(getBaseContext(), "TOKEN");
    if(userName != null && email != null && password != null && token != null)
    {
        userNameTxt.setText(userName);
        emailTxt.setText(email);
        passwordTxt.setText(password);
    }
}

Solution

    • since in saveData(...), you use editor.apply() and not editor.commit(), it's possible your data hasn't been written to file before you're reading it. (editor.apply() is asynchronous and doesn't write changes to disk immediately unlike editor.commit())

    Try using editor.commit() instead, like this:

    public static void saveData(Context context, String key, String data)
    {
    SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, data);
    editor.commit();
    }