我是 Android 新手,连续六个小时都卡在这里了。
问题是我不知道偏好设置文件的名称,并且需要从偏好设置文件中获取值。我正在使用 Android Studio 并创建了一个“设置活动”。一路上除了 SettingsActivity.java
,我没有给任何文件命名。
所以我的问题是共享偏好设置文件的名称是什么(因为应用程序保留了值)。或者如果有办法找到它的话。
或者也许我在代码中缺少明显的东西。以下是我的相关代码。
String key = "example_text";
final String PREF_FILE_NAME = "SettingsActivity";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
String value = preferences.getString(key, " null");
编辑1:我有一个名为RemoteDevice.java
的活动,在这个活动中,我有一个用于互联网使用的异步任务子类。现在我已经通过上述PreferencesActivity
存储了IP地址,现在想要检索它。但是我找不到它。
编辑2:在下面的代码中,我正在尝试从编辑文本中获取值。
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:key="example_text"
android:title="@string/pref_host_ip_address"
android:defaultValue="@string/pref_default_host_address"
android:selectAllOnFocus="true"
android:inputType="numberDecimal"
android:digits="123456789."
android:capitalize="words"
android:singleLine="true"
android:maxLines="1" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:key="example_list"
android:title="@string/pref_title_add_friends_to_messages"
android:defaultValue="-1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:negativeButtonText="@null"
android:positiveButtonText="@null" />
我猜这里 android:key
是要在
String value = preferences.getString(key, " null");
中作为参数传递的关键字。
PreferenceFragment
和PreferenceActivity
使用的SharedPreferences
实例的方式。你可以调用PreferenceManager.getDefaultSharedPreferences()
,并提供你应用程序中的任何Context
作为参数(例如,一个Activity
实例)。 - CommonsWarenull
。 - Abbas