-1

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);
    }
}
kennyYice23
  • 73
  • 1
  • 10
  • 2
    Possible duplicate of [What's the difference between commit() and apply() in Shared Preference](http://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference) – R. Zagórski Nov 13 '16 at 15:19
  • How are you using this class? Where and when are you reading and writing data from it? – clownba0t Nov 13 '16 at 15:30
  • @clownba0t Question was edited for more information. – kennyYice23 Nov 13 '16 at 15:36
  • Thanks! So just to confirm, the issue is that you're logging in with the "remember me" button checked, but the data isn't being saved to `SharedPreferences`? – clownba0t Nov 13 '16 at 15:43
  • @clownba0t Yes that is correct – kennyYice23 Nov 13 '16 at 15:46
  • As an aside, you should call `editor.apply();` after `editor.remove();` in your `removeData` method. – clownba0t Nov 13 '16 at 15:47
  • Have you tried adding logging to each of the methods in your `SharedPreferenceManager` class and doing another user creation action with the "remember me" checkbox checked? That way you could see which, if any, of the methods are being called. – clownba0t Nov 13 '16 at 15:51
  • Also, is there any particular reason you're using `getBaseContext()` in your calls where you read the data? Your `Activity` is already a context, so you can just pass `this` instead. – clownba0t Nov 13 '16 at 15:54
  • Okay! I found the culprit! The problem is that my token variable is set to null for some reason. And since i have an if statement that says if it's not null to set the Edit Texts, it will never be able to set them. – kennyYice23 Nov 13 '16 at 16:20
  • Now, I have another problem. It only saves the username :( – kennyYice23 Nov 13 '16 at 17:00

1 Answers1

1
  • 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();
}
Joey Dalu
  • 1,113
  • 9
  • 13
  • 1
    I'm not sure that this is necessarily correct. The documentation for `SharedPreferences` states that "For any particular set of preferences, there is a single instance of this class that all clients share." (provided those clients are within the same process). Also, although `apply` is considered asynchronous, it's only the writing of the changes to disk that is asynchronous. As per the documentation, "..., apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk ...". – clownba0t Nov 13 '16 at 15:36
  • 1
    `SharedPreferences` is is implemented with **Singleton**, so you can't create new instances of it.. all of the references in this code point to the same instance. – Gal Yedidovich Nov 13 '16 at 15:56
  • Oh I didn't know that, then it's probably some other issue then. – Joey Dalu Nov 13 '16 at 16:02