Possible Duplicate:
variables retaining values after app close




我对android和java相对较新,所以如果这是一个愚蠢的问题,我感到抱歉。我有一个android应用程序,允许用户拍照并保存。我将图片另存为附件0,附件1等。

我使用整数来确定附件号,并且每次创建附件时,此int都会增加。我的照片使用正确的名称正确保存,但是当我关闭应用程序时,整数值重置为0,而已保存的附件被覆盖。如何防止在关闭和打开应用程序时重置整数?谢谢 !

最佳答案

使用SharedPreferences保存int值,然后将其重新加载到onCreate中。

有很多优秀的代码here供您学习,我将为您提供一些伪代码以帮助您入门:

onCreate:
    prefs = <load shared preferences>;
    yourInt = prefs.getInt("name of your int", 0);
    // do whatever with yourInt

onPause: // maybe not onPause, maybe you want to save each time it changes?
    prefs = <load shared preferences>;
    editor = prefs.edit();
    editor.putInt("name of your int", yourInt);
    editor.commit();


那应该做到的!这是SharedPreferences的基本概念,从那以后,我认为您可以毫无疑问地将上述教程用于您的目的。

07-24 09:49
查看更多