gpt4 book ai didi

java - SharedPreferences 在不重新启动应用程序的情况下不保存

转载 作者:行者123 更新时间:2023-11-30 03:31:09 28 4
gpt4 key购买 nike

什么代码用于检测应用程序运行时在 SharedPreferences 中所做的任何更改?在我的 SharedPreferences 中所做的更改仅在应用程序关闭并再次启动时才会反射(reflect)出来。它在同一 session 期间不会更改。

要获取首选项,我使用以下代码在 SettingsActivity.java 中

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference("unit_type"));
}

在activity.java中

final SharedPreferences unitpreference = PreferenceManager.getDefaultSharedPreferences(this);
final String unitstring = unitpreference.getString("unit_type", "");

但是我应该在什么地方编写一些代码以便立即进行更改?

完整更新代码:设置 Activity .java

package com.basic.mileagecalculatorwithsettings;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import java.util.List;

public class SettingsActivity extends PreferenceActivity
{

private static final boolean ALWAYS_SIMPLE_PREFS = false;
protected static final String TAG = null;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setupActionBar();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
} else {
// use normal preferences
setupSimplePreferencesScreen();

PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mPrefsListener);
}
}

SharedPreferences.OnSharedPreferenceChangeListener mPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
if ("unit_type".equals(key)) {
Log.v(TAG, "Setting has been changed!");
}
}

};
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);

//setupSimplePreferencesScreen();
}
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
addPreferencesFromResource(R.xml.pref_general);}
@Override
public boolean onIsMultiPane()
{
return isXLargeTablet(this) && !isSimplePreferences(this);
}
private static boolean isXLargeTablet(Context context)
{
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static boolean isSimplePreferences(Context context)
{
return ALWAYS_SIMPLE_PREFS
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| !isXLargeTablet(context);
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target)
{
if (!isSimplePreferences(this))
{
//loadHeadersFromResource(R.xml.pref_headers, target);
}
};
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value)
{
String stringValue = value.toString();

if (preference instanceof ListPreference)
{
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(index >= 0 ? listPreference.getEntries()[index]:null);
}
else if (preference instanceof RingtonePreference)
{
if (TextUtils.isEmpty(stringValue))
{
//preference.setSummary(R.string.pref_ringtone_silent);
}
else
{
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null)
{preference.setSummary(null);}
else
{
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
}
else
{
preference.setSummary(stringValue);
}
return true;
}
};
private static void bindPreferenceSummaryToValue(Preference preference)
{
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference("example_list"));
bindPreferenceSummaryToValue(findPreference("fuel_type"));
bindPreferenceSummaryToValue(findPreference("unit_type"));

}
@Override
public void onResume() {
super.onResume();


}
public void onPause(Bundle savedInstanceState)
{
super.onPause();
addPreferencesFromResource(R.xml.pref_general);

}
}
}

pref_general.xml

<ListPreference
android:defaultValue="1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:key="city_list"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_add_friends_to_messages" android:enabled="true"/>

<ListPreference
android:defaultValue="1"
android:entries="@array/pref_fuel_type_titles"
android:entryValues="@array/pref_fuel_type_values"
android:key="fuel_type"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_select_fuel" android:enabled="true"/>

<ListPreference
android:defaultValue="1"
android:entries="@array/pref_units_titles"
android:entryValues="@array/pref_units_values"
android:key="unit_type"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_unit" android:enabled="true"/>

</PreferenceScreen>

最佳答案

我检查了您的代码,看起来您根本没有创建 GeneralPreferenceFragment。所以,如果我添加以下内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();

// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
}

并删除 setupSimplePreferencesScreen() 调用,然后它在最新的 Android 版本上工作正常。

如果您需要支持旧版本,我会按照以下方式进行:

public class SettingsActivity extends PreferenceActivity {

private static final boolean ALWAYS_SIMPLE_PREFS = false;
protected static final String TAG = null;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
} else {
// use normal preferences
setupSimplePreferencesScreen();

PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mPrefsListener);
}
}

SharedPreferences.OnSharedPreferenceChangeListener mPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
Log.v(TAG, "Setting has been changed!");
}
};

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
//NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);

//setupSimplePreferencesScreen();
}
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
addPreferencesFromResource(R.xml.pref_general);
}

@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this) && !isSimplePreferences(this);
}

private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static boolean isSimplePreferences(Context context) {
return ALWAYS_SIMPLE_PREFS
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| !isXLargeTablet(context);
}

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
if (!isSimplePreferences(this)) {
//loadHeadersFromResource(R.xml.pref_headers, target);
}
}

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
Log.v(TAG, "Setting has been changed!");

String stringValue = value.toString();

if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(index >= 0 ? listPreference.getEntries()[index]:null);
}
else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
//preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}

return true;
}
};
private static void bindPreferenceSummaryToValue(Preference preference){
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference("example_list"));
bindPreferenceSummaryToValue(findPreference("fuel_type"));
bindPreferenceSummaryToValue(findPreference("unit_type"));
}

@Override
public void onResume() {
super.onResume();
}

public void onPause(Bundle savedInstanceState) {
super.onPause();
addPreferencesFromResource(R.xml.pref_general);
}
}
}

我已经使用以下 pref_general.xml 检查了该代码:

<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
android:title="Title category">

<ListPreference
android:key="example_list"
android:title="example_list"
android:summary="example_list"
android:entries="@array/entries_list_preference"
android:entryValues="@array/entryvalues_list_preference"
android:dialogTitle="example_list" />
<ListPreference
android:key="fuel_type"
android:title="fuel_type"
android:summary="fuel_type"
android:entries="@array/entries_list_preference"
android:entryValues="@array/entryvalues_list_preference"
android:dialogTitle="fuel_type" />
<ListPreference
android:key="unit_type"
android:title="unit_type"
android:summary="unit_type"
android:entries="@array/entries_list_preference"
android:entryValues="@array/entryvalues_list_preference"
android:dialogTitle="unit_type" />
</PreferenceCategory>

</PreferenceScreen>

并且能够观察到 Setting has been changed! 日志。

基本上,您的代码存在的问题是您既没有创建 GeneralPreferenceFragment,它的监听器也没有使用 SharedPreferences.OnSharedPreferenceChangeListener。我建议使代码更具可读性,这样您可能更容易发现问题。

关于java - SharedPreferences 在不重新启动应用程序的情况下不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462688/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com