i have created a live wallpaper and in that there is a "setting" button which loads PreferenceActivity but without clicking on "settings" but i want to access the SharedPreferences within subclass of Engine or WallpaperService. As i just want to access the small single string so i don;t want user to go into settings and access that string.
So i want to execute this code inside Subclass of Engine or WallpaperSerivce
SharedPreferences mPrefs = getPreferenceManager().getSharedPreferences();
String option = mPrefs.getString(
this.getResources().getString(R.string.name),
this.getResources().getString(R.string.option));
It is not the best way to do it I'm sure but I use getters and setters to achieve this effect.
private int mySetting = defaultvalue
public int getMySetting() {
return mySetting;
}
public void setMySetting(int mySetting) {
this.mySetting = mySetting;
}
I obviously used some plain text in that code but hopefully it is pretty self explanitory
You set this variable while in Settings Class with...
Settings.this.setMySetting(value);
Remove "this" to call from other classes
You can retieve this information in any of your classes using the following
Settings.getMySetting();
You can use pretty much any variable type just make sure you define the mySetting variable as that type before trying to pass a value other than int as in this example. Hopefully this helps.
Related
May be I'm just a little confused but I'm having troubles to figure out how to set default values of a particular SharedPreferences.
As far as I understand, the approach
PreferenceManager.setDefaultValues(ctx, R.xml.myprefs, true);
only works for the DefaultSharedPreferences. In my case I use different SharedPreferences and I have to set the default values of one of them which is NOT the DefaultSharedPreferences. So I miss something like
PreferenceManager.setDefaultValues(mySharedPrefs, R.xml.myprefs, true).
Am I overlooking something??
Thanks in advance!
Thomas
The PreferenceManager class overloads this method to make it possible to specify the preference file and mode:
public static void setDefaultValues(Context context, String sharedPreferencesName,
int sharedPreferencesMode, int resId, boolean readAgain)
Excerpt from the reference:
Similar to setDefaultValues(Context, int, boolean) but allows the
client to provide the filename and mode of the shared preferences
file.
Although you cannot pass the SharedPreference object itself as a parameter, passing the correct sharedPreferencesName and sharedPreferencesMode of your preferences file will point to the same exact instance.
I am coding using Xamarin and have a question about application settings.
Is it possible to have application wide settings? I will give you an example:
I have a map application. I have a ListView where the user can select if the map is using the Street View, Satellite View or default view.
Depending on the item that is selected in the ListView depends of the map view that is shown.
Where and how can I save this selection such that this value is visible throughout the application and when the user exits the application, this setting can be remembered for when the user starts the application up again?
Thanks in advance
Yes, it's possible and also very easy. Usually you save simple application settings using SharedPreferences. They can be read from anywhere in the app.
For writing.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putBoolean("someBoolean", true);
editor.putString("someString", "string");
editor.commit();
For reading
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean someBoolean = sp.getBoolean("someBoolean", false);
boolean someString = sp.getString("someString", null);
I suppose you are familiar to Java I/O and android basic concepts. So here I go:
For data persistance in Android, you have two main solutions:
SQLite database
File system
I recommend you to use file system, as you don't really need to organize your data with relational constraints and you will probably not have to make a lot of data persist.
Android documentation is very clear on how to save files:
http://developer.android.com/training/basics/data-storage/files.html
I recommend you to create a Setting class that contains a HashMap attribute:
public class Settings implements Parcelable{
public static HashMap<String,String> settings;
public static void readSettings(){
//Here you read your settings file and you fill your hashmap
}
public static void writeSettings(){
//Here you iterate through your hashmap and you write your setting files
}
}
Every activities will have access to the settings, as the attribute/methods are static. Settings will also be synchronized through every activities (if you change a setting in one activity, every other activities will notice).
If you need some clarifications, leave a comment below.
I have question for receive value in smartwatch. Currently I follow this steps from this question
Actually,the person who ask it has the answer how to do that, but since my reputation for comment is not enough, so I can't ask question by comment in his/her question.
Right now, based on Mr. Eir,the person who answered the question. I have problem in what he answered:
You also want to pass some arguments to your Extension, i.e. the
String you mention. This can be a bit tricky; normally, you would pass
that String in the Intent itself, as an extra, but here, that is not
available. You need to save that information (the String) on a
location that your Extension can access as well. So, if your Activity
and your Extension are part of the same app, that location can be the
app preferences: the Activity saves the value in the preferences, and
the Extension reads it from the same preference and displays it on the
SmartWatch or whatever.
He said that I can save the value in preference and the Extension reads it from the same preference and displays it on the SmartWatch. Unfortunately, I don't know how the extension reads it. I have try to put the value in samplepreferenceactivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("SHARED_PREFS_FILE",0);
String message = settings.getString("send", "message");
}
I don't know how to put the value in controlextension class, If it possible to put, I want to you use for changing "Hello watch". Below you can find controlextension class:
public class HelloWatchExtension extends ControlExtension{
...
public HelloWatchExtension(Context context, String hostAppPackageName) {
super(context, hostAppPackageName);
width = getSupportedControlWidth(context);
height = getSupportedControlHeight(context);
layout = new RelativeLayout(context);
textView = new TextView(context);
textView.setText("Hello watch!");
textView.setTextSize(9);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.layout(0, 0, width, height);
layout.addView(textView);
}
Since it is not activity, so it is n't possible to take by using getpreference. Anybody knows how?
"Since it is not activity, so it is n't possible to take by using getpreference. Anybody knows how?"
You can access the preferences through context:
context.getApplicationContext().getSharedPreferences(...);
A few pointers about using shared preferences:
SharedPreferences preferences = _context. getApplicationContext().getSharedPreferences("com.example.AppName", Context. MODE_MULTI_PROCESS);
Putting string in shared preferences:
_preferences.edit().putString(“OBJECT”, “object_name”).commit();
Retreaving string from shared preferences:
_preferences.getString(“OBJECT”, "default_name");
If you are just trying to pass a string between an Activity in your project and your ControlExtension you don't need to use SharedPreferences. The easiest way is to just register a dynamic BroadcastReceiver in your extension and broadcast an Intent from the Activity passing your string inside the Intent.
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’m a new developer, so my question maybe too much basic.
I look for example of defining preferences of sound. User can choose what kind of sound will start an application, for example. There can be such a RingtonPreference widjet, so user can choose a sound.
As I know, preferences support the primitive types: Boolean, string, float, long and integer. What way is the best to design preferences: store in entryValues the names if sounds (strings), the address of files from Resourse class (integer), or other way.
Please provide a short example of code.
Thanks in advance!
First of all thank you for the quick and detailed answer!
I want to arrange list of sounds: there must be one “None”, list of sounds that contains folder “raw”, option to add a new sound from different locations and two buttons: “set” and “cancel”. When user touches one item from the list – sound starts to play.
There is a little problem with standard widget that provide android library. “ListPreference” isn’t appropriate because on touch on one of the items – item is chosen and list closes, “there are not buttons set and cancel”.
“RingtonPreference” isn’t appropriate as well – I didn’t succeed to add something to list.
How is possible to build a custom preference layout and that is options that were chosen will be saved as well as on standard widgets. Please provide a short code example. Thanks in advance!
I think the best way to store the Resource are by integers. or you could do names.
I think integer is more reliable.
So to use SharedPreference with this you will need to get access to the apps SharedPreference
public class PreferencesDemo extends Activity {
SharedPreferences app_preferences;
private int resourceNumber;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
resourceNumber = app_preferences.getInt("resourceNumber", 0);
if(resourceNumber == 0){
//This means the user hasnt selected a song and you must act accordingly. Or put a resource number where the 0 is do set it to a default song
}
You will probably want to create a method to put the songs in the SharedPreference such as;
private void createSongResouces(){
SharedPreferences.Editor editor = app_preferences.edit();
//Here you can put as many songs as you want just make sure you call editor.commit(); as i do.
editor.putInt("resourceNumber", resourceNumber);
editor.commit(); // Very important
}