开发者

Android: Setting preferences programmatically

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜