I need to set some values to their associated persistently stored data, if they exist, on initialization. If not I need to initialize them. Is there any disadvantage to using the SharedPreference to initialize the variable on the first run. That is, something like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("MyDataName", Context.MODE_PRIVATE);
String name = sp.getString("name", "");
boolean isFirstRunning = sp.getBoolean("firstTime", true);
if (isFirstRunning) {
Toast.makeText(this, "YEA", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
If there is no disadvantage from a processing level, is there a standard practice as far as this situation is concerned? Also, is there any alternative way to handle the persistent data, or do we have to use SharedPreferences for this?
Yes that's perfectly acceptable. For neatness it may be better to define the keys, and default values as constants but the approach you have will work fine.
That is based on your requirement. if u need sharedpreference values quickly its good which you wrote. other wise no use.
Related
In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?
I'm creating a shared preference in my MainActivity and then I want to get a value saved in the shared preference in my IntentService; however; I keep getting the default value rather than the value that I had saved.
This is my code to create the SharedPreference in my MainActivity:
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.edit().putString("inter", inter).apply();
And in my IntentService class:
protected void onHandleIntent(Intent intent) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
final String inter = preferences.getString("inter", "default_no");
}
The problem here is a subtle one:
SharedPreferences.Editor#commit stores the modifications to storage in a blocking fashion, so you are guaranteed that any other instance that queries the value on the same thread will actually get the new one.
SharedPreferences.Editor#apply does so asynchronously so if you fetch the value on another instance of SharedPreferences too fast, it might not get the updated value.
Commit may actually work better on your situation as you are not doing any big change to the preferences. If you need to use apply, you might want to induce a slight delay using Handler#post.
Cheers.
Try using and editor to save your value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
SharedPreferences.Editoreditor = pref.edit();
editor.putString("inter", inter);
editor.commit();//This will make your value store in SharedPreferences
I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.
I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.
I'm a complete beginner to Java and Android development and had a question about preferences.
A tutorial asked me to use preferences to read and save the time in which the onCreate method is called.
I've sat on this problem for at least two days but have come up with nothing. Can anyone give me an example on how to code such an action?
public static final String PREFS_NAME = "Time_Pref";
public class QuizSplashActivity extends QuizActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
SharedPreferences = getSharedPreferences ("Time_Pref", "MODE_PRIVATE);
}
But that's where I seem to get lost. I'm not even sure if I'm heading in the right direction.
Although I tend to agree with Falmarri's comment on your question, I'll provide some pointers...
The first thing you should do in onCreate() is to create an instance of GregorianCalendar using new GregorianCalendar() to initialize it to current date/time.
Next use getSharedPreferences to create your SharedPreferences then get an editor using its edit() method.
The simplest way to store the time would be in milliseconds so use the GregorianCalendar getTimeInMillis method (inherited from Calendar) to get a Long result.
Finally, use the SharedPreferences editor's putLong() method to store the result of getTimeInMillis and use the editor's commit() method to make the change permanent.
Searching these pages will give you all the information you need...
Android Developers
I'd recommend you to read the dev guide's chapter about SharedPreferences. You can find it here.
I suggest you to use System.currentTimeMillis() to get the time value to save.
Basic code to save something to preferences should look like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// view setup stuff here...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("onCreateCallTime", System.currentTimeMillis());
editor.commit();
}
Then use android.text.format.Time class to format that time after reading it from preferences:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
long timeMillis = settings.getLong("onCreateCallTime", 0);
Time t = new Time();
t.set(timeMillis);
Read the Time class documentation to learn how to format/convert time with its methods :)