Reputation: 185
I am working on an update details of an object in an android project using rest with retrofit2.0. After I call the edit method I get a positive response, that my changes are being saved but while saving it in the shared prefernces and trying to get it from it I get the old unchanged data and checking in the database its the old data (the rest service work just fine I tested it with postman).
this is my code :
public void editUser(){
user.setNom(nom);
user.setPrenom(prenom);
user.setAdresse(adresse);
user.setTel(telephone);
apiService = RestService.createService(SolarAPIService.class);
Call<String> call = apiService.editUser(nom,prenom,adresse,telephone,user.getIdUser());
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.body().isEmpty()){
Snackbar.make(layout, "OOps modification non autorisée !", Snackbar.LENGTH_LONG).show();
}else{
save(user);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Snackbar.make(layout, "OOps!!!!!", Snackbar.LENGTH_LONG).show();
}
});
}
This is where the edit is being called
valider.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editUser();
phoneView.setText(""+user.getTel());
adrView.setText(user.getAdresse());
nomV.setText(user.getNom()+" "+user.getPrenom());
mailV.setText(user.getLogin());
getUserShrdPref();
Snackbar.make(layout, "Changement effectué avec sucess !!"+user.getAdresse(), Snackbar.LENGTH_LONG).show();
}
});
And this is the save and getSharedPrefernces
public void save(User user) {
mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(user);
prefsEditor.putString("user", json);
prefsEditor.commit();
}
public void getUserShrdPref() {
Gson gson = new Gson();
String json = mPrefs.getString("user", "");
user = gson.fromJson(json, User.class);
}
The problem is there is no exceptions or crashes nothing at all, I can't figure out the error.
Upvotes: 0
Views: 154
Reputation: 1914
Json to string conversion is a time taking process. As per your code updation of shared preference is just below the json conversion code. There is a chance to execute shared pref updation before json conversion.
So the better solution is, use async task for this conversion and update shared preference in the onPostExcecute(). This may solve your issue. Please try.
Refer link: https://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 0
Reputation: 2069
Could be a race condition. Check where nom, prenom, and those fields are set. =)
Upvotes: 1