gpt4 book ai didi

java - SharedPreferences 在应用程序退出时不保存

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:40 26 4
gpt4 key购买 nike

我的应用程序不保存共享首选项。我尝试使用 commit()apply() 来保存这些首选项,但应用程序关闭后它们不会保存。如果我更改应用程序中的屏幕,则会进行更改,但在应用程序重新启动时会丢失。

应用程序启动时调用的静态方法:

static {
prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.getContext());//MainActivity.getContext().getSharedPreferences("LocationTimer", Context.MODE_PRIVATE);
editor = prefs.edit();
if(!prefs.contains("totalLocations")) {
prefs.edit().putInt("totalLocations", 0).commit();
}
if(prefs.getInt("totalLocations", 0) == 0) {
for (int i = 1; i <= COUNT; i++) {
addItem(createLocationItem(i));
}
Log.i("PREFERENCES", "CREATED 1 LOCATION");
} else {
for (int i = 1; i <= prefs.getInt("totalLocations", 1); i++) {
addItem(new LocationItem(String.valueOf(i), "Location " + String.valueOf(i), prefs.getString(String.valueOf(i), "")));
}
Log.i("PREFERENCES", "LOADED LOCATION(S)");
}
Log.i("PREFERENCES", "LOADED " + String.valueOf(prefs.getInt("totalLocations", 1)) +" LOCATION(S)");
}

记录的消息是“PREFERENCES: LOADED LOCATION(S)”而不是“PREFERENCES: CREATED 1 LOCATION”,所以我知道该项目正在加载而不是简单地创建。

创建/加载任何项目时调用的方法:

public static void addItem(LocationItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);

saveStringToPreferences(item.id, item.details);

editor.putInt("totalLocations", ITEMS.size());
editor.apply();

Log.i("PREFERENCES", "CONTAINS " + String.valueOf(prefs.getInt("totalLocations", 1)) +" LOCATION(S)");
Log.i("ITEMS", "CONTAINS " + String.valueOf(ITEMS.size()) +" LOCATION(S)");
}

我如何知道这是在应用程序已加载时保存首选项,上面的消息显示除一个之外的其他数字。一是应用加载时显示的金额。

感谢您的帮助和建议。如果您有任何疑问,请留言,我会尽快回复。

最佳答案

对于遇到此类问题的每个人,我的解决方法是将 SharedPreferences 放入专用的类文件中。我创建了一个名为 AssetLoader.java 的文件,并将所有 SharedPreferences 编辑和初始化都放在其中。

这是我的 AssetLoader 文件:

import android.content.Context;
import android.content.SharedPreferences;

import com.xenicdev.locationtimer.MainActivity;

public class AssetLoader {
private static SharedPreferences prefs;

public static void load() {

// Prefs
prefs = MainActivity.getContext().getSharedPreferences("LocationTimer", Context.MODE_PRIVATE);
if(!prefs.contains("totalLocations")) {
prefs.edit().putInt("totalLocations", 0).apply();
}
}

public static void setTotalLocations(int totalLocations) {
prefs.edit().putInt("totalLocations", totalLocations).apply();
}

public static Integer getTotalLocations() {
return prefs.getInt("totalLocations", 0);
}

public static void setItemDetails(String id, String details) {
prefs.edit().putString(id, details).apply();
}

public static String getItemDetails(String id) {
return prefs.getString(id, "");
}
}

在创建主文件时添加:

AssetLoader.load();

要在其他文件中调用这些方法,请添加:

AssetLoader.getTotalLocations();

使用此方法的另一个好处是,如果您删除所有 SharedPreferences 并仅使用对 AssetLoader 的调用,则可以清理相当多的其他类。

关于java - SharedPreferences 在应用程序退出时不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369438/

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