服务中的SharedPreference访问不返回值

时间:2014-02-27 18:19:20

标签: android android-fragments android-service

我正在使用偏好片段。在我对设备的测试中,可以编辑和更改编辑文本字段的值,并在重新打开设置后,正确更改该值。但是当我在我的服务中访问首选项时,该值没有改变。

知道我做错了吗?

这是我的PreferenceFragment

    public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{

    private static final String TAG = SettingsFragment.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

有显示片段的活动

public class PreferencesActivity extends Activity {

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();


}       
}

我的偏好xml:

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
       <PreferenceCategory 
           android:title="@string/pref_sendall_address_title"
       >
                   <EditTextPreference
                    android:key="@string/pref_sendall"
                    android:title="@string/titleSendallAddress"
                    android:summary="@string/summarySendall"
                    android:dialogTitle="@string/editSendallAddress" 
                    android:defaultValue="http://192.168.101.202/test"                      
                    />
       </PreferenceCategory>
    </PreferenceScreen>

在我的服务中,我像这样访问共享偏好

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    final String sendallUrl = prefs.getString(getString(R.string.pref_sendall),"n/a");
    Log.d(TAG, "using sendall address " + sendallUrl);

1 个答案:

答案 0 :(得分:0)

更改第二行的资源名称

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String sendallUrl = prefs.getString(getString(R.string.pref_test),"n/a");
Log.d(TAG, "using sendall address " + sendallUrl);