android - Issue reading data from sharedpreferences. I have to run the app twice before it gets the data stored -


i have issues reading sharedpreferences in android. data stored in preference file, , ma sure of because used logcat log data when read stored used toast message display data after read preferences. when try read data again new activity returns default of empty sting. when exist app , run again read data stored. here code when save data, contains comments used verify data stored read back:

public void downloadmatchesasync() {      brawtaapiadapter.rungetmatches(new callback<jsonkeys>() {          @override         public void success(jsonkeys jsonkeys, response response) {             log.d(applicationconstants.tag, "blarg");             success = jsonkeys.issuccess();             message = jsonkeys.geterrormessage().tostring();              if(!message.isempty()){                 toast.maketext(myapplication.getappcontext(), message,    toast.length_short).show();             }              gson gson = new gson();             string jsonobject = gson.tojson(jsonkeys); //converts java object json string'               preferences.savetopreferences(activity, applicationconstants.match_data, jsonobject);             //data =preferences.readfrompreferences(activity, applicationconstants.match_data, "no data");             //toast.maketext(myapplication.getappcontext(), "in networkoperation" + data, toast.length_long).show();         }          @override         public void failure(retrofiterror error) {          }     }); // call async api      //return data; } 

in different activity try read data written so:

  jsonstring = preferences.readfrompreferences(matchselect.this, applicationconstants.match_data, ""); 

but code returns data stored if exist app , run again.

this preference class:

   public class preferences {  private static final string prefname = "net.brawtasports.brawtasportsgps";  public static void savetopreferences(context context, string key, string value) {      sharedpreferences sharedpreferences = context.getsharedpreferences(prefname, context.mode_private);     sharedpreferences.editor editor = sharedpreferences.edit();     editor.putstring(key, value);     editor.apply(); }  public static string readfrompreferences(context context, string key, string defaultvalue) {      sharedpreferences sharedpreferences = context.getsharedpreferences(prefname, context.mode_private);     return sharedpreferences.getstring(key, defaultvalue);  } 

}

what issue?

apply() asynchronous call, data doesn't have stored immediately. try calling .commit() instead.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -