Android偏好设置不保存

时间:2010-10-04 12:17:37

标签: android preferences

当用户更新(或者,我猜,安装)我的应用时,我正在尝试创建一个“新的”弹出式对话框。我有以下一点逻辑来检查最后安装的版本是否将它与当前版本进行比较,然后将当前版本保存为“最后”版本(这在我的“onCreate()的末尾调用” “Activity):

    int lastVersion = getPreferences(MODE_PRIVATE).getInt(LAST_VERSION, 34);
    try {
        int currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

        Log.d(getClass().getSimpleName(), "Old Version = " + lastVersion);
        Log.d(getClass().getSimpleName(), "New Version = " + currentVersion);

        if (currentVersion != lastVersion) {
            // write the current version to the preferences so they won't see the popup again
            getPreferences(MODE_PRIVATE)
                .edit()
                .putInt(LAST_VERSION, lastVersion)
                .commit();

            // tell the user the new thing
            AlertDialog dia = new AlertDialog.Builder(this)
                .setTitle(R.string.main_menu_new_title)
                .setMessage(R.string.main_menu_new_body)
                .create();
            dia.show();
        }
    } catch (NameNotFoundException ex) {}        

问题是,无论我运行应用程序多少次,我总是得到lastVersion的默认值,因此弹出窗口总是会发生。想法?

1 个答案:

答案 0 :(得分:2)

您正在将版本号写回首选项。

变化:

getPreferences(MODE_PRIVATE)
                .edit()
                .putInt(LAST_VERSION, lastVersion)
                .commit();

为:

getPreferences(MODE_PRIVATE)
                .edit()
                .putInt(LAST_VERSION, currentVersion)
                .commit();