共享偏好的不当行为

时间:2014-05-21 12:03:28

标签: java android list set sharedpreferences

在你判断我之前,我想说我读过这个:左

但是我仍然无法理解,无法让事情奏效。我完全不喜欢我的偏好。我的代码:

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+]

只要app正在运行就可以了......但是如果我杀了我的应用程序并重新启动我会得到完全不同的列表,如

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

有人可以解释一下我的错误吗?

1 个答案:

答案 0 :(得分:3)

您的清单之前和之后的唯一区别是订购......

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

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>());

HashSets还有其他选择here