Java 如何在Android中获得首选项?
我不明白偏好是怎么起作用的 我有一个首选项活动和一个字段:Java 如何在Android中获得首选项?,java,android,sharedpreferences,Java,Android,Sharedpreferences,我不明白偏好是怎么起作用的 我有一个首选项活动和一个字段: <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <EditTextPreference android:key = "@string/pr_rest_service_url" android:title = "@string/rest_service_url" android:summar
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key = "@string/pr_rest_service_url"
android:title = "@string/rest_service_url"
android:summary = "%s"
android:shouldDisableView="false"
android:selectable="true"
android:enabled="true"
android:defaultValue="543543543"
/>
</PreferenceScreen>
以及它的作品。很好用。
现在我想从应用程序的另一个部分获得首选项。我将此代码放在MainActivity中:
String key = this.getString(R.string.pr_rest_service_url);
SharedPreferences mSharedPreferences = getSharedPreferences(key, Context.MODE_PRIVATE);
String g = mSharedPreferences.getString(key, null);
结果是空的。
那么如何处理偏好呢?
或者我在开始时出错,不应该使用PreferenceActivity作为设置屏幕?还是更喜欢与活动相关的东西?
那我怎么才能得到呢
更新
我试过了
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sp.getString("myKey", "");
但得到了空字符串。更新:使用此选项,然后:
SharedPreferences yourOutputdata =
context.getSharedPreferences("YourKEY", MODE_PRIVATE); // Save as YourKEY in the Activity which you're passing data to this one ...
因此:
String key = this.getString(R.string.pr_rest_service_url);
您实际上是从资源文件中获取字符串并将其保存到首选项,我相信这会导致空值
试试这个:
要保存:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key","your text-data here");
editor.apply();
并获得:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");
这没用。名称为空字符串。我已经气疯了。因为在我的手机上GetDefaultSharedReferences有效,在我朋友的手机上这不起作用。在Android Emilator上,这不起作用。我已经解释了它返回null的原因。另外,您没有保存任何要通过SharedReference获取的内容,而是尝试获取返回null的资源字符串。不过,我更新了答案。
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");