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.
Related
I am new in Android Development. I am trying my hands on developing an alarm app. When I set the alarm, I use a TextView to show the time for which the alarm in set up(initially empty). But when I close or minimize the app and start it again the TextView is again empty. How to get rid of this?
I looked for its solution in android app development manual, but still couldn't find my way out.
Particularly visiting developer.android.com will help you to get started with android development. Anyways you can either use any of the following to save your data:
SharedPreferences
Sqlite Database
File (Pertaining to your app's location)
And when you are reopening your application you can retrieve the information from this methods.
Saving data can be done easily with the SharedPreferences.
private final String SAVED_ALARM_TIME_KEY = "SavedAlarmTime"
private final String ALARM_PREFERENCES = "AlarmPreferences"
private void saveAlarmTime(Context context, long alarmTimestamp) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong(SAVED_ALARM_TIME, alarmTimestamp);
editor.commit();
}
private long getAlarmTime(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
return sharedPref.getLong(SAVED_ALARM_TIME, 0);
}
This is great for something like user settings in the application. But I imagine you will later want to add multiple alarms to your application. In this case it would be better if you used a database. It will provide you with more options to scale the implementation. For instance you wish to add a functionality for repeating alarms at certain days the database will come in very handy.
You can refer to the documentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
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.
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
}
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.