I have a small ap with preferences. In this class I've set the onPreferenceClick to get coordinates from the GPS. When the listener returns, my hope was to set the lat / long textedits automatically. I've tried every source sample out there, no luck:
public void onLocationChanged(Location l) {
Log.d("H","Location Received: "+l.toString());
prefLocation.setSummary(l.toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor1 = settings.edit();
editor1.putString("posLat","xxx");
editor1.commit();
}
When this code executes when I click on my PreferenceScreen and the location listener returns, the EditTextPreference with the key "posLat" still shows the old value.
I'm going crazy trying to figure out what's wrong!
My prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="My_Shared_Preferences">
<PreferenceCategory
android:title="Your Location">
<PreferenceScreen
android:title="Find Location..."
android:key="location"
android:summary="Click here to read your location automatically"/>
<EditTextPreference
android:title="Latitude"
android:key="posLat" />
<EditTextPreference
android:title="Longtitude"
android:key="posLong" />
<EditTextPreference
android:title="Altitude"
android:key="posAlt" />
</PreferenceCategory>
</PreferenceScreen>
Alternatively, maybe there is a better way to store the location value for an application? I don't really want the user to manually enter the coordinates, but I dont want to resort to saving and loading a text file with the settings, it seems so crude.
I've been having kind of the same problem. My solution was to use the default shared preferences instead of manually created preferences with a given name.
Change the reference to SharedPreferences from this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
to this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
and see if that makes any difference.
Seems that this has actually changed (see 1 and 2)
The new way to do this is
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(PREF_NAME, YOUR_VALUE);
editor.commit();
What is "the old value". With the code that you've posted it looks like the only thing that is going to get stored in your preferences is the String "xxx" you need to replace that with a string that represents the location inside your putString() method.
Related
I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is.
Here's the code.
NotificationUtils.java
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
if (preferences.getBoolean("notification_key", true)) {
notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
}
preferences.xml
<SwitchPreference
android:contentDescription="Turn notifications on/off"
android:defaultValue="true"
android:key="notification_key"
android:summaryOff="Off"
android:summaryOn="On"
android:title="Notifications" />
I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.
Try replacing
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
with
PreferenceManager.getDefaultSharedPreferences(context);
I believe you're attempting to retrieve "notification_key" from the wrong SharedPreferences, which is why it's always using the default value of true and showing your notification.
Edit: You can check to see whether the SharedPreferences you're using contains the "notification_key" key with the contains() method.
I solved it, actually the value wasn't toggling, in settings screen the Switch was turning off and on but the value remained the default. Solved it by setting the new value in OnPreferenceChangeListener and that worked.
I've implemented a OnPreferenceChangeListener on two preference object in my preference page ( extends PreferenceActivity)
But ever since the preference value isn't updated upon change,
I even tried using :
SharedPreferences sharedPreferences = getSharedPreferences("myCustomSharedPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(preference.getKey(), Integer.parseInt(newValue.toString()));
editor.commit();
Where preference is the changed preference and newValue is the new value...
What am I missing ?
Thanks
You need to return true to get the value updated, see the Android documentation.
Can you see if preference.getKey() is giving the correct name? Can you print in your console and see. Code looks clean to me. May be the name is different than what is expected.
Also make sure that the value is also having the correct value.
I am currently doing an Android security application and I'm trying to uncheck a CheckboxPreference after certain conditions have been made. So I'm trying to uncheck the checkbox by doing this, by default the CheckBoxPreference is actually false so it is unchecked.
Preferences:
<CheckBoxPreference
android:id="#+id/isPhysicalTheftEnabled"
android:key="isPhysicalTheftEnabled"
android:title="Enable Physical Theft Protection"
android:summary="Select to enable the Physical Theft Protection"
android:defaultValue="false"/>
<Preference android:key="physicaltheft" android:title="Set Physical Theft Protection Password" android:dependency="isPhysicalTheftEnabled"></Preference>
SharedPreferences inside Activity:
SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("isPhysicalTheftEnabled", false);
ed.commit();
The CheckBoxPreference wouldn't be untick even if I have done so. Any idea what could be the problem?
I dont really understand what you try to accomplish, but my guess is you get the wrong SharedPrefence file.
Try calling
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(myContext);
Or check what the filename is called, look under data/data/yourpackage/shared_prefs
You write to a preference file called "isPhysicalTheftEnabled" which i guess is not the same.
Uhh, you're putting a "false" in your shared preferences without touching the checkboxpreference view... if you stored a reference somewhere, great it not
CheckBoxPreference cbp = (CheckBoxPreference) findViewById(R.id.isPhysicalTheftEnabled);
SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("isPhysicalTheftEnabled", cbp.getChecked()); //puts the real value in here
ed.commit();
cbp.setChecked(false); //turn it off as you intended
cbp.postInvalidate(); //refresh the view
setChecked() might have to be called from a Handler, or via runOnUIThread()
How to make in app changes persist so that when app relaunches all settings remain same(like if from app i have selected vibration then when app is not running if my phone is ringer mode when app relaunches it sets itself to vibration)?
There's actually multiple ways to persist changes. The Android documentation covers all of them in more detail, but essentially these are the five ways. Easiest is SharedPreferences, probably.
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
Use SharedPreferences. You can put key value pairs and retrieve when needed .
You need to store these settings within the Database. On how to use this see Using Databases
Use SharedPreferences
Save your settings:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", "my_email#email.com");
editor.putString("name", "Albert");
editor.commit();
Retrieve them:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
String email = prefs.getString("email", "default#email.com");
Thing that you could do is to create a PreferenceActivity like :
public class Prefs extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
In res/xml folder add preference.xml with this content :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="General" >
<CheckBoxPreference
android:key="notification"
android:summaryOff="You will not receive any notification"
android:summaryOn="Notifications are sent to your device"
android:title="Get notification" />
</PreferenceCategory>
</PreferenceScreen>
In your code you can do now :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean sendNotification = prefs.getBoolean("notification", false);
If I have a onSharedPreferenceChanged event in my PreferenceActivity, that is checking if a CheckBoxPreference is checked or not and setting setEnabled on some other Preference, does the actual value of the other Preference get changed in the SharedPreferences, or do I have to manually set them?
What I have is:
public void onSharedPreferenceChanged(Settings sharedPreferences, String key)
{
CheckBoxPreference cbUpdatesEnabled = (CheckBoxPreference)getPreferenceScreen().findPreference("updatesenabled");
CheckBoxPreference cbVibrate = (CheckBoxPreference)getPreferenceScreen().findPreference("vibrate");
cbVibrate.setEnabled(cbUpdatesEnabled.isChecked());
}
Which toggles whether the "vibrate" checkbox is enabled or disabled in the UI, but then do I also have to use:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("vibrate", cbUpdatesEnabled.isChecked());
editor.commit();
Or is there some other way of updating the SharedPreferences? It doesn't look like the value is automatically saved just based on if it's enabled or not.
You don't have to manually update the preference value if you are using PreferenceActivity.
For more information check following tutorials.
Click here
Click here