2012-07-30 133 views
0

可能重複之後如何留住一個變量的值:
variables retaining values after app close退出應用程序

我是比較新的Android和Java,所以我很抱歉,如果這是一個愚蠢的問題。我有一個android應用程序,允許用戶拍照並保存。我將圖片保存爲附件0,附件1等。

我正在使用整數來決定附件編號,並且每次創建附件時都會增加此int值。我的照片會以正確的名稱正確保存,但是當我關閉應用程序時,整數值將重置爲0,並且已保存的附件會被覆蓋。如何防止整數在關閉和打開應用程序時重置?謝謝 !

+0

使用http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putInt(java.lang.String,int) – 2012-07-30 03:46:47

+0

看看這個:http://stackoverflow.com/questions/6913819 /變量保留值 - 應用程序關閉後 – 0gravity 2012-07-30 03:47:08

回答

7

使用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的基本概念,從這個角度來說,我認爲將上述教程適用於您的目的不會有任何問題。

+0

謝謝,它修復了它! – 2012-07-30 03:51:20