有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java应用程序关闭后如何保存整数的值?

我在屏幕上设置了一个整数为100。当我点击一个按钮时,该值下降一(99)。但是,当我重新启动应用程序时,如何才能获得与之前相同的值99,而不将其重置为100


共 (4) 个答案

  1. # 1 楼答案

    您可以这样做:

    onPause()中,使用此代码将计数器的值保存到SharedReference文件

    SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
    Editor editor = sharedPrefs.edit();
    editor.putInt(KEY_NAME, THE_INTEGER_VALUE);
    // Replace `putInt` with `putString` if your value is a String and not an Integer.
    editor.commit();
    
    1. 替换上面使用的PREFERENCE_FILE_NAME,以选择将创建用于存储值的XML文件
    2. ^上面使用的{}是用于访问(用于保存和读取第1点中命名的SharedReference文件)的密钥它是SharedReference中使用的键值对的一部分
    3. THE_INTEGER_VALUE是实际值

    onResume()中,您可以检索并显示该值:

    SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
    int counter = sharedPrefs.getInt(KEY_NAME, 0);
    // Replace the `int counter` with `String counter` if your value is a String and not an Integer.
    // Also, replace the `getInt` with `getString`
    

    您可以稍后使用int counterTextView中显示

  2. # 2 楼答案

    使用共享优先权作为doc example读/写int值的更改:

    public class Calc extends Activity {
        public static final String PREFS_NAME = "MyPrefsFile";
    
        @Override
        protected void onCreate(Bundle state){
           super.onCreate(state);
           . . .
    
           // Restore preferences
           SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
           int lastIndex = settings.getInt("yournumbername", 100);
           setLastIndex(lastIndex);
        }
    
        @Override
        protected void onStop(){
           super.onStop();
    
          // We need an Editor object to make preference changes.
          // All objects are from android.context.Context
          SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
          SharedPreferences.Editor editor = settings.edit();
          editor.putInt("yournumbername", mlastIndex);
    
          // Commit the edits!
          editor.commit();
        }
    }
    
  3. # 3 楼答案

    您需要以这种方式使用SharedPreferences保存值,然后再次获取它

    private final String NUMBER = "Number";
    private final String PROFILE = "Profile";
    
    SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
    SharedPreferences.Editor prefsEditorProfiles = a.edit();
    prefsEditorProfiles.putInt(Profile, 1);
    prefsEditorProfiles.putInt(Number, 1);
    prefsEditorProfiles.commit();
    

    然后在其他Activity中还原SharedPreferences

    SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
    int ab = a.getInt(Number, 0);
    
  4. # 4 楼答案

    您可以使用SharedPreferences来实现您想要的。设置count,退出应用程序时,重新打开应用程序时,从那里获取应用程序

    例如,关于如何使用它,请选中此out