Accessing SharedPreferences - android

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);

Related

I want to know how to check whether a checkbox is checked or not in android from broadcast receiver

I want to know how to check whether a checkbox is checked or not when an application is not running. Please help me. I'm making a call blocker, and I'm stuck.
When the application is not running, how can it check whether the checkbox is checked or not.
Android provides SharedPreferences class which is an utility that helps you to save user settings within your app internal memory and can be accessed by providing your application context.
Let's say that the user has checked the checkbox control, you could save that choice using SharedPreferences instance saving it onto disk.
For example:
myCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences prefs = yourActivityContext.getSharedPrefences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor = prefs.edit(); //Create this instance in order to save data
editor.putBoolean("checked", isChecked); //Store the checkbox value
editor.commit(); //Call this to save the preferences to disk
}
}
);
Then in your BroadcastReceiver:
#Override
public void onReceive(Context context, Intent data) {
SharedPreferences prefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
boolean checkboxValue = prefs.getBoolean("checked", false);
//The second argument provide a default value if you haven't saved that setting before.
}
you can store checkbox value in database or web api and check through Android Services class.
Every time you start an application, a completely new instance of the program is created. And once the application terminates, the instance that was running no longer exists for you to check its state.
What you will have to do is...
Store the settings in a file or database when the program closes (or when the user hits "save" depending on how you design it)
When the application opens, have it read the settings and populate the screen (e.g., checkboxes) with its contents
If you didn't write the program that owns the checkbox (which wasn't clear in your original post), then the program must already do this; otherwise, it would have no way to re-populate the screen when it starts up. In this case, all you have to do is find out what the file or database table stores the info you need and figure out how to extract the data you need from that location.
Use SharedPreferences. In the onCheckChangedListener, just store a shared preferences with the boolean value associated with the checkbox. The broadcast receiver should have the same context, so you should be able to access the shared preference from there.

How to store strings in Shared Preferences

I would like the user to be able to create a nickname for a string that shows up in their textview. The app will feed a string into the activity through a service and display it in a textview. I would then like the user to be able to nickname that string, so that every time the string is displayed again the nickname will show up instead of the original string.
My question is, can I use shared preferences to do this? What would be the logic behind the user being able to assign nicknames? If you could point out any literature or sample code that would be greatly appreciated as well. Thank you for any help.
Algorhithm:
At a certain point in your app lifecycle, write a preference using a "name" and a value.
Retrieve the value when the app starts and compare it to something.
Act consequently.
From the reference site: http://developer.android.com/guide/topics/data/data-storage.html#pref
Using Shared Preferences
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Here is an example that saves a preference for silent keypress mode in a calculator:
public class Calc extends Activity
{
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
//...
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop()
{
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}

SharedPreferences default values

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.

How to keep the project always be open using login page on android/eclipse

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.

Acces Preferences From another class

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");

Categories

Resources