代码之家  ›  专栏  ›  技术社区  ›  Jeremy Logan

Android首选项未保存

  •  1
  • Jeremy Logan  · 技术社区  · 15 年前

    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 回复  |  直到 15 年前
        1
  •  2
  •   David Webb    15 年前

    你在写 古老的

    更改:

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

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