I have an application which has a Prefernces Class and I want to know how could i make so that when the application is started the settings to be applied even before entering the preferences ( settings ) class. I have a getPrefs() void method which is called when i press "Save" Button in preference activity.
So, could you help me and tell what should I do the "default" preferences to be applied when entering the application ? (I need getprefs method from another class )
I would be grate if you could give me some advices or tips.Thank you !
To get an instance of the SharedPreferences from anywhere in your application use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPrefences(context);
To set a value in the preferences, you need to call the editor for those preferences, then set the value for a key and finally commit the result. It can all be done in a single line:
prefs.edit().putString("myKey","myValue").commit();
This would store the string value myValue on a key named myKey and it will be accessible (after you commit) to any class if it has the application's context when it calls getDefaultSharedPreferences.
To retrieve the stored value you specify the key and a fallback value in case there is no preference set with that key:
prefs.getString("myKey","oops no value found");
Related
I have 2 fragments.
Fragment 1
Loads sharedpreference to display string
Fragment 2
Saves sharedprefence for string
Is it possible to retrieve that string in my first Fragment without running the second Fragment?
Yes, this is possible. You just need to make sure you are reading with the same key you used to write with:
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading from SharedPreferences
String value = prefs.getString("myKey", "defaultValue");
Log.d(LOG_TAG, value);
Note that we've assigned a defaultValue as the return value here. If there is no value with the key "myKey" in your shared prefs, it will instead return "defaultValue". This is a nice safeguard, think of it like a null pointer check - you will always get a value from getString(), even if it's just the default.
You don't need to be in the same activity for this to work, you just need to make sure that 1) your preferences name is the same and 2) the key used to store the value is the same in both spots.
First, don't get confuse between Activity and Fragment.
And yes, you can.
I have a problem in the LiveWallpaper app (my first) I am developing.
Consider 2 classes: LiveWallpaperService and LiveWallpaperSettings.
LiveWallpaperSettings extends PreferencyActivity. Example data representing
the preferences selected by the user, for example a boolean displaySprite (true=> display the sprite on the screen, false do not display) are saved/persisted via SharedPreferences in LiveWallpaperSettings.
Upon starting the application (Settings -> Display -> LiveWallpaper -> MyLiveWallpaper), the saved preferences need to be known so that the sprite can be displayed or not.
However, LiveWallpaperSettings is not instantiated until the Settings button is clicked, so SharedPreferences is not available, and thus saved settings are unavailable until then.
I tried this in LiveWallpaperService.onCreateScene(), but it has no data in it:
SharedPreferences startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
What can I do?
There is a default value if the entry/sharedpref file does not exist:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean display = settings.getBoolean("display", true);
"public abstract boolean getBoolean (String key, boolean defValue)"
Added in API level 1
Retrieve a boolean value from the preferences.
Parameters
key The name of the preference to retrieve.
defValue Value to return if this preference does not exist.
Hope I didnt misunderstood your question :)
In your preferences xml set the default value and in your MainActivity onCreate() add the following code setDefaultValues(this, R.xml.yourxmlname, false);
I have a settings.xml file that contains Preferences for my app. All the values by default are set to "true" and its used by PreferenceActivity in my app.
In my main activity I read the values through
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(appContext);
Boolean key = sp.getBoolean("M", false);
it gets me whatever I need at any run except the first time. Only when I open my app for the first time and doesn't open my settings menu I get "false". I mean I have to open menu and only after that the app run correctly.
Any suggestions?
Because yor are getting the default value for first time.
that is false -->
Boolean key = sp.getBoolean("M", false);
use this
Boolean key = sp.getBoolean("M", true);
Use sp.getBoolean("M", true); instead. Default values in preferences file is what it will be when preferences activity is first started. SharedPreferences know nothing about your settings.xml.
Alternatively you can have a separate defaults.xml file (or any other name) containing all the default values for all preferences. Then you use these values in both settings.xml (#bool/default_M_value) and your application (sp.getBoolean("M", getResources().getBoolean(R.bool.default_M_value))).
I personally would stick to first approach though.
I'm developing an app that has to share strings between activities. I'm trying to get the seperate activities to call a public class with set and get methods. The calling the methods part works and I manage to get a response although the set value has to be rememberd by the set and get class. Here's a link to my set and get class, it's pretty basic: http://pastebin.com/0WabNKz3
Now my question is this: How do I make the set and get class to remember my values between sessions? Feel free ask questions if there's anything you didn't understand.
Thanks!
You need to use SharedPreferences. That's the way to save data even after the app is closed and you can access it from anywhere:
public void savePrefrences(String key, String value)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
prefs.edit().putString(key, value).commit();
}
public String getPrefrences(String key)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
return prefs.getString(key, "");
}
Save the prefrence when and whereever you want and get it whenever and from wherver you want.
The value will not delete when you close the app.
I ended up creating invisible EditTextPreference that now hold the data that I want to keep because they can be shared easily.
When you say saving between sessions, do you mean between the app being paused, or closed completely?
A good resource for lifecycle and storing data across sessions is:
//developer.android.com/training/basics/activity-lifecycle/index.html
I have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.