gpt4 book ai didi

java - 共享偏好的不当行为

转载 作者:搜寻专家 更新时间:2023-11-01 08:50:39 25 4
gpt4 key购买 nike

在你评判我之前,我想说我读了这些:

但我仍然无法理解,无法正常工作。我的偏好完全不当。我的代码:

public static SharedPreferences sharedAppPreferences;
public static final String AppsListKey = "AppListKey";
public static final String AppsPreferences = "AppsPreferences";
public static ArrayList<String> packageNames;

public void chooseApps(View view) {
sharedAppPreferences = getSharedPreferences(AppsPreferences, Context.MODE_PRIVATE);
if (sharedAppPreferences.contains(AppsListKey)) {
Set<String> buffer = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));
packageNames = new ArrayList<String>(buffer);
} else {
packageNames = new ArrayList<String>();
}
PackageManager packageManager = getPackageManager();

int flags = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES | PackageManager.GET_UNINSTALLED_PACKAGES;
List<ApplicationInfo> packageList = packageManager.getInstalledApplications(flags);

for (ApplicationInfo pack : packageList) {

if (((pack.flags & ApplicationInfo.FLAG_SYSTEM) == 1) || packageNames.contains(pack.loadLabel(packageManager).toString())) {
// System application or already in array
} else {
// Installed by user and isnt in array
packageNames.add(pack.loadLabel(packageManager).toString());
}
}
Editor editor = sharedAppPreferences.edit();
Set<String> buffer1 = new LinkedHashSet<String> (packageNames);
editor.putStringSet(AppsListKey, buffer1);
editor.commit();
//packageNames.clear();
//buffer1.clear();
buffer1 = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));
packageNames = new ArrayList<String>(buffer1);
AppList appList = new AppList();
appList.show(getSupportFragmentManager(), "AppList");
}

为什么我第一次运行我的应用程序时会得到这样的列表

[Skype, Facebook, Whatsapp, Twitter, Google+]

只要应用程序正在运行就没问题......但是如果我终止我的应用程序并重新启动,我现在会得到完全不同的列表,如

[Whatsapp, Google+, Skype, Twitter, Facebook]

谁能解释一下这里有什么问题吗?

最佳答案

列表前后的唯一区别是顺序...

为了扩展我一直在谈论的内容,我刚刚意识到你的错误..

LinkedHashSet被订购。但是,您存储在

Set<String> buffer 

Set<String>没有订购...

所以它又把它弄混了。

您需要将其存储在LinkedHashSet 的参数中如下图

LinkedHashSet<String> buffer = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));

(有两次我认为这需要更改。)

编辑:

您可以做的最后一件事是,与其创建新列表,不如从共享首选项中转换现有列表 ...

 LinkedHashSet<String> buffer = (LinkedHashSet<String>)sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>());

HashSet 有替代品 here

关于java - 共享偏好的不当行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23782636/

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