i'm having little problems using the SharedPreferences. I want to save and later load strings to/from the Preferences.
I initialize my prefs in the onCreate-method:
prefs = this.getSharedPreferences("com.example.android_test", Activity.MODE_PRIVATE);
I do saving in another method:
public void saveUser()
{
prefs.edit().putString("username", username);
prefs.edit().putString("password", password);
prefs.edit().apply();
}
And loading in yet another method:
public void loadUser()
{
username = prefs.getString("username", "default");
password = prefs.getString("password", "test");
}
And those are my Test-Methods:
public void showUser(View v)
{
loadUser();
text.setText(username);
}
public void addUser(View v)
{
changeUser(eingabe.getText().toString(),"newpass");
}
public void changeUser(String user, String pass)
{
username = user;
password = pass;
saveUser();
}
username and password are global, private Strings, eingabe is an EditText and text is a TextView.
However, when executing showUser() i only get the defaultvalue displayed to the TextView, even if im using saveUser with different usernames... No crash or anything... its just only the defaultvalue being shown...
You forgot to commit your edits:
prefs.edit().putString("username", username).commit();
prefs.edit().putString("username", username);
prefs.edit().putString("password", password);
Change this each time edit will return diffrent instance so your changes wont get committed.
Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
Try this.
Unlike commit(), which writes its preferences out to persistent
storage synchronously, apply() commits its changes to the in-memory
SharedPreferences immediately but starts an asynchronous commit to
disk and you won't be notified of any failures. If another editor on
this SharedPreferences does a regular commit() while a apply() is
still outstanding, the commit() will block until all async commits are
completed as well as the commit itself.
Ok, apply is same as commit, it only writes the preferences atomically making it thread safe. (It requires API Level 9 though, so be careful)
See the documentation
The problem is what Rajesh CP is saying.
You need to create an editor pointer and then apply:
Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
Else, every time you create a new instance of the editor and when you apply the changes, the editor that is being instructed to apply the changes, doesn't have any changes
Related
My Android app stores 15-20 settings pairs with SharedPreferences, and I've been using a helper class so I don't have to create a new method in every class that needs to retrieve them.
Some retrievals are starting to take >100ms, and I'm not sure my current method is efficient for performance since it passes in the Context and creates a new SharedPreferences object each time. This happens numerous times throughout the app's AsyncTasks.
Here's what I've been doing:
public class SharedPrefHelper {
static void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
static void setDefaultsInt(String key, int value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();
}
//... continued with other variable types and getDefault variants
//.......
}
Would below be a more efficient way of handling this?
public class SharedPrefHelper {
private static SharedPreferences preferences;
static void init(#NonNull final App app) {
preferences = PreferenceManager.getDefaultSharedPreferences(app);
}
//App is the Application class, init is called in onCreate()
static void setDefaults(String key, String value) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
//... continued with other variable types and getDefault variants
//.......
}
Or are there other variable keywords that would do better (final, etc)?
+100ms is a long time for such a simple action and so little key-value pairs.
I think the problem is not here.
However, to answer your question, yes, the proposed alternative is certainly better than the original one. Indeed, there is no point in calling getDefaultSharedPreferences(context) multiple times, as that method points to a default file, which is set application-wide.
So just store it as instance/static field (but avoid static as much as possible).
preferences.edit()
returns a new, fresh, Editor (EditorImpl, it maintains a Map of the changed key-value pairs and then persist everything on apply) every call, so you're totally fine.
I'm making a toggle button which changes activity but it changes only for once but want to make it permanent so user does not need to change it again and again.
Use Shared Preference for that . When user Toggle Button ON (logged) into your application store login status into sharedPreference and clear sharedPreference when user click on OFF(logged Out).
Check every time when user enter into application if user status from shared Preference is true then no need to login otherwise move to login page.
To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now first check
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Call Next Activity
}
I'm wanting to save the value of strings (numeral Strings) to somewhere where i can when the user reloads the app, the values can be passed back into the app. Being saved to local storage is preferrable
I would suggest using shared preferences over a SQLLite DB if you are only saving a small amount of strings.
private void saveStringToPreferences(String key, String str){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, str);
editor.apply();
}
private void getStringFromPreferences(String key){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String previousText = preferences.getString(key, "");
return previousText;
}
You really should do some research before asking such a question. Here is a link to the options available for storing data in android:
http://developer.android.com/guide/topics/data/data-storage.html
I have a Settings activity in my android application which purpose is to save preferences upon an item selection. My problem is, my settings don't get saved. The following method is called every time a user selection is made:
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
settings = getSharedPreferences(SettingsTAG, 0);
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
I also use the following code in my MAIN activity where all the settings get restored upon start up:
public void restoreValues()
{
settings = getSharedPreferences(SettingsTAG, 0);
int SelectedVolume = settings.getInt("selectVolume", 0);
int SelectedPressure = settings.getInt("selectPressure", 0);
int SelectedTemperature = settings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
I use global variables throughout my whole application and those get saved but the settings do not. I'm positive that both savePreferences() and restoreValues() method gets called but whatever the user had selected doesn't get saved.
In other words, nothing gets saved/restored. I don't know what I'm doing wrong but this issue has been driving me nuts. This used to work for me before but I'm doing a Settings UI revamp and the same code suddenly isn't working...
Any help please?
Think you should be doing this in your activity:
private SharedPreferences prefSettings;
public void restoreValues()
{
prefSettings = PreferenceManager.getDefaultSharedPreferences(this);
int SelectedVolume = prefSettings.getInt("selectVolume", 0);
int SelectedPressure = prefSettings.getInt("selectPressure", 0);
int SelectedTemperature = prefSettings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
In your method that I've noticed, your parameters do not look right actually...why are you using SettingsTAG, with 0 as parameters to the getSharedPreference method? Is your activity extending PreferenceActivity? You should be using the context.
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
//settings = getSharedPreferences(SettingsTAG, 0);
settings = PreferenceManager.getDefaultSharedPreferences(context); // Notice CONTEXT!
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
Edit:
If you want to debug it, it might be better to do it this way:
public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private static final String TAG = "PreferencesActivity";
///.... code....
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){
Log.d(TAG, "onSharedPreferenceChanged() - key = " + key);
// Yup! The key within the shared preferences was changed... inspect 'em via Log!
}
The reason: you're "listening" on the changes whenever its made to confirm that you are indeed saving the preferences. When you're done with debugging, be sure to take out the Log calls so that it does not appear in the logcat.
I'm writing my first android app, and I have an EditText object that I want to be read across my entire program (multiple activities). I'd like to take in a user's name on one screen/activity/layout and read it in several others to manipulate or display it, so I've found that the string needs to be public and static, and that there should be a class with my global variables. What is the correct way to do this? I've tried using bundles and several other methods, but none seem to work.
You should definitely be passing this value through intents.
Intent intent = new Intent(getApplicationContext(),NEXTCLASS.class);
intent.putExtra("username",mEditText1.getText().toString());
startActivity(intent);
and then to receive it in the next class
Bundle extras = intent.getExtras();
mEditText1.setText(extras.getString("username"))
You could also use shared preferences however I think that is unnecessary for your situation as you do not need the username to persist when the app is closed.
Update:
To use shared prefs..
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", myusername);
To read from shared prefs...
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
An example of using a static property
public class utility {
public static String USERNAME = "username";
}
To invoke you do not need to instantiate the class just do this from each class that needs it
String username = sharedPreferences.getString(utility.USERNAME, "")
You can use SharedPreferences to store the value. Read more here.