After I "saved" a String it will return (in my case) "error": html_value1 is not ""
MainActivity:
tools.getEditor(tools.getPreferences(getApplicationContext())).putString("wochea9a", html_value1);
tools.getEditor(tools.getPreferences(getApplicationContext())).putString("wocheb9a", html_value2);
tools.getEditor(tools.getPreferences(getApplicationContext())).commit();
Alarmserviceactivity:
savedwochea9a = tools.getPreferences(getApplicationContext()).getString("wochea9a", "error");
savedwocheb9a = tools.getPreferences(getApplicationContext()).getString("wocheb9a", "error");
tools:
public class tools {
static SharedPreferences preferences;
static SharedPreferences.Editor editor;
public static SharedPreferences getPreferences(Context context){
preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences;
}
public static SharedPreferences.Editor getEditor(SharedPreferences preferences){
editor = preferences.edit();
return editor;
}
...
How can I fix this?
Each time you create an editor (using edit()
) you have to call either commit()
or apply()
in order for the results to be saved.
So, your code should look like this:
MainActivity:
tools.getEditor(tools.getPreferences(getApplicationContext()))
.putString("wochea9a", html_value1)
.putString("wocheb9a", html_value2)
.commit(); // or .apply();
Even better if you use apply()
. This method returns straight away, saving the data in the background without blocking the thread.