Setting sharedpreferences default value - android

I am using the following methods to save and read user settings:
private void saveUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userSettings.edit();
editor.putInt("timeOne",timeOne);
editor.apply();
}
private int getUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
timeOne = userSettings.getInt("timeOne",timeOne);
}
Then in onCreate the following:
SharedPreferences prefs = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
This is fine and the data is saved when the app relaunches. However I want to have default data when the app is installed initially it seems to be that the values should be stored in an xml file.
I have created the following file under res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="timeOne"
android:defaultValue="2"/>
</PreferenceScreen>
Then in onCreate:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
I changed the "userSettings" to preferences to match up but this dosen't work and returns a value of zero. Is this method of reading the xml file ok or/and am I overlooking something?

I think you are overcomplicating yourself.
In this instruction the second parameter is the default to use if there is no shared preference with that name.
You just need to set that value to the default you need.
timeOne = userSettings.getInt("timeOne",<Put here the default value>);
EDIT I
Lets say the default value if it is the first time the app runs and there is no setting saved yet, is 2.
The method that reads the value should be like this.
private int getUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
timeOne = userSettings.getInt("timeOne",2);
}

Related

How can I use sharedPreferences Date Diaplay sent next Activity

I need to send data Date Display to next Activity and keep that data
private void updateDisplay()
{
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(ShowdatanameActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
mDateDisplay.setText(new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
editor.putString("key1", mDateDisplay);
editor.commit();
Intent myIntent = new Intent(ShowdatanameActivity.this,Showdata_result_resume.class);
startActivity(myIntent);
}
Well that's true you can acces to Data/Calendar object from every place of your application. But if you insist:
You've put your string to SharedPreferences under "key1" so in other activity you have to call:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences("KEY_FOR_YOUR_DATA",ShowdatanameActivity.this);
String data = app_preferences.getString("key1","");
So when you call SharedPreferences you also need key for them. It's some kind of "database version", you can write anything there (i use for example PREFS-KEYv1, and when I need new one I'm incrementing to v2). And don't use same key everywhere it's bad practice.
The other method you could use to send your String to other activity is via intent.
intent.putExtra("key1",yourStringVariable);
and Showdata_result_resume in onCreate after setContent you can get it by:
String data = intent.getExtras().getString("key1");
Using code like this to make preferences code portable between various apps and classes.
from a fragment I get the sharedpref like this. Notice how I have the preferences named in a resource and I use getActivity to get to the preferences.
sharedPref = getActivity().getSharedPreferences(
getString(R.string.preferences), Context.MODE_PRIVATE);
From the main activity I get the sharedpref like this. Notice how I have the preferences named in a resource.
sharedPref = getSharedPreferences(getString(R.string.preferences),
Context.MODE_PRIVATE);
the resource which is shared by all classes in the app.
<string name="preferences">com.gosylvester.hilbilyfashliegt.prefrences</string>
<string name="about_firstrun">com.gosylvester.hilbilyfashliegt.firstrunabout</string>
now to get the data from any class I referer to it with an R string resource.
_Checked = sharedPref.getBoolean(getString(R.string.about_firstrun),
false);
Good Luck

Android set preferences from XML with PreferenceManager

I am trying to get preferences from XML but without using a PreferenceActivity.
I just want to load from the file when my Main activity is created and toast a value from preferences. But the problem is that the toast is empty (null?). I have a class that load the preferences.
Here is the onCreate method of the Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Preferences prefs = new Preferences();
}
Preferences class (only the constructor...)
public Preferences(Context context) {
PreferenceManager.setDefaultValues(context, "MyPrefs", 0, R.xml.preferences, false);
SharedPreferences sharedPreferences = context.getSharedPreferences("MyPrefs", 0);
Editor editor = sharedPreferences.edit();
String myValue = sharedPreferences.getString("myKey", null); // I don't know if null is OK
Toast.makeText(context.getApplicationContext(), myValue, Toast.LENGTH_SHORT).show();
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference android:key="myKey" android:defaultValue="hello" />
</PreferenceScreen>
The first time I launch the app, I would like the default value to be set. So here I want the app to toast "hello" while I haven't set the value with editor.putString(key, value).
Do you know what could be wrong?
Thanks
You are programming in java. By suns convention I think you are obliged to use config.propeties file.
I will give a quick and full tutorial to get you going in this matter. I really recommend you using this method cause most of programmers do like that.
I will give you a quick tutorial how to make this file. Where to put it. And how to get data from it.
Begin.
Put a file config.properties into assets folder:
SAMPLE of config.properties
domain=#domain.com.pl
errorTextColor=\#FF0000
serverPort=1234
Method how to access and retrieve data from config.properties
public static String getConfigurationPropertiesValue(String value,
Context context) {
try {
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("config.properties");
Properties properties = new Properties();
properties.load(inputStream);
return properties.getProperty(value);
} catch (IOException e) {
Log.e("getConfigurationPropertiesValue",
"Failed to open config property file");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Literature:
http://en.wikipedia.org/wiki/.properties
http://www.mkyong.com/java/java-properties-file-examples/
EDIT:
You can also use sharedPreferences to have more control over data like adding data/deleting data/update data. SharedPreferences are more like a SQLite database of android with a nice api to use so you don't really need to know the location of database or SQL.
In order to use it you need to create your data. You only need to do this once. Or more if user decides that he has an urge to clean you app data from settings -> applications.
Creating data:
public static void create(Context cw) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isRegistered", false);
editor.putString("phoneNumber", null);
editor.putString("callingCode", null);
String uuid = UUID.randomUUID().toString();
editor.putString("token", uuid);
editor.putBoolean("internetOnly", false);
editor.putBoolean("logToDev", true);
editor.putBoolean("dataTransfer", true);
Log.i("create", "Generating Token: " + uuid);
editor.commit();
}
Accesing existing data:
public static String getToken(Context cw) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
return sharedPreferences.getString("token", null);
}
Updating data:
public static void setPhoneNumber(Context cw, String phoneNumber) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("phoneNumber", phoneNumber);
editor.commit();
}
For an mechanism that will check if data exist or if user deleted it you can use something simple like an additional variable that should be true if all your data is configured. Or there should be an checked method from appshared preferences for that.
Cheers!
I tried for a long time and found a solution for this :-)
Just a "Preference" is not being recognized by android. Though i don't know why.
If you change it as a Any of the tag like "EditTextPreference" or "CheckboxPreference" its working fine.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference android:key="CLIENT_HOMESCREEN_TITLE"
android:defaultValue="Home Screen"/>
<EditTextPreference android:key="CLIENT_ADMIN_BUTTON"
android:defaultValue="Admin"/>
<EditTextPreference android:key="CLIENT_PLAYER_BUTTON"
android:defaultValue="Player"/>
<EditTextPreference android:key="CLIENT_SAVE_BUTTON"
android:defaultValue="Save"/>
<EditTextPreference android:key="CLIENT_CANCEL_BUTTON"
android:defaultValue="Cancel"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_IP"
android:defaultValue="IP:"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_PORT"
android:defaultValue="Port:"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_TITLE"
android:defaultValue="Server Setup"/>
</PreferenceScreen>

Why does preferences.getString("key", "DEFAULT") always return "DEFAULT"?

I have user_preferences.xml in my XML directory. A PreferencesActivity uses this file to create the user preferences activity.. and that works. Whatever the user selects here persists. But I am unable to retrieve the value the user selected.
When I use...
SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);
String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
... mapTypeString is always "DEFAULT".
It seems like my user_preferences.xml is not found when I instantiate my SharedPreferences object. But, the PreferencesActivity finds it, of course. So, what am I missing?
Many thanks!
change your code to:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
You have to commit the preferences after edit it.
SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("map_type_pref_key", "blah_blah");
editor.commit();

Trouble using sharedPreferences between two activities

I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.

Android: How to check does shared preferences exist, and how to delete them

To check does preferences exist I tried this way, but it shows null every time(maybe because I saved preferences in different view):
String def = null;
String test = getPreferences(MODE_PRIVATE).getString(PREF_GAME,def);
if(test == null) Log.v("main", "no saved data");
To delete preferences I tried editor.clear(), but it does't delete (however commit() every time return true):
SharedPreferences preferences = getSharedPreferences(PREF_GAME,MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
boolean tt = editor.commit();Log.v("DELETE PREF", String.valueOf(tt));
UPDATE: I found that if I check preferences exist in the same view, where i saved it, this checking works fine, but how can i do this in different view?
Update: I guessed with myself, thanks everyone!
Use getSharedPreferences() to get your preference.
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.
This is my code:
public String prefGet(String id) {
SharedPreferences opener = getPreferences(MODE_PRIVATE);
String value = opener.getString(id, "Default");
return value;

Categories

Resources