Reputation: 960
I'm trying to set the shared preferences in my asynctask but it seems to not be working. Could anyone help me out. I tried a billion things already
Button/ASYNC Code:
button.setOnClickListener(new OnClickListener(){
private ProgressDialog cancelDialog = null;
int valid;
@Override
public void onClick(View arg0) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
valid = api.validateLogin(username.getText().toString(), password.getText().toString());
return null;
}
@Override
protected void onPreExecute() {
cancelDialog = new ProgressDialog(LoginActivity.this);
cancelDialog.setMessage("Validating Username & Password");
cancelDialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result){
cancelDialog.cancel();
if(valid == 2){
SharedPreferences savedSession = getApplicationContext().getSharedPreferences("xdaeaf", Activity.MODE_PRIVATE);
savedSession.edit().putString("username", username.getText().toString());
try {
String passtext = MCrypt.bytesToHex(mcrypt.encrypt(password.getText().toString()));
savedSession.edit().putString("password", ""+passtext);
savedSession.edit().commit();
} catch (Exception e) {
e.printStackTrace();
//TODO:
}
//TODO:
}else{
//TODO:
}
super.onPostExecute(result);
}
}.execute();
}
});
My accessing code:
SharedPreferences savedSession = context.getSharedPreferences("xdaeaf", Activity.MODE_PRIVATE);
String username = savedSession.getString("username", "");
String password = savedSession.getString("password", "");
System.out.println("username:"+username+" password:"+password);
I checked if I was passing on empty variables to the putSTring but it is passing values to it. Its just not saving. When I rerun the accessing code it just prints out "Username: password:". The values are blank when trying to re access it.
Upvotes: 1
Views: 3858
Reputation: 11357
savedSession.edit().putString("username", username.getText().toString());
Every call to edit() returns you a new Editor instance. So you get an instance, make a change and leave it alone. Then you get a second one and commit that without changes, which results in no value changes in the preferences.
Editor editor = savedSession.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", ""+passtext);
editor.commit();
Upvotes: 4
Reputation: 48602
If you call the everytime the savedSession.edit()
then it will return you different object then you have to call the commit
method on each to save the values.
So get one instance of the Editor
like this
Editor editor = savedSession.edit();
then use this reference to save the values.
Your code should be
Editor editor = savedSession.edit();
editor.putString("username", username.getText().toString());
String passtext = MCrypt.bytesToHex(mcrypt.encrypt(password.getText().toString()));
editor.putString("password", ""+passtext);
editor.commit();
Upvotes: 1