In my android application I have a listview with a bunch of items with checkboxes. If the checkboxes are checked, a value is calculated. However, after the application is terminated, the listview开发者_运维问答 resets itself, with all checkboxes being unticked again. How would I have it so when the application is completely terminated, the checkboxes checked/unchecked states are saved? I've looked up various methods but all seem rather complicated for a beginner :(
You would probably want to try SharedPreferences
Also, there is a APIDemo of using SharedPreferences
here: APIDemo
Here is a link to do just that, along with a simple example to follow: http://developer.android.com/guide/topics/data/data-storage.html#pref
As others have suggested, you should save your checkbox settings to SharedPreferences
. The basic idea is that within your onPause()
method you read the state of your UI and write these values into the preferences. Then in onResume()
your read these values back and re-populate the UI.
The example in the Data Storage link puts the saving of preferences in onStop()
, however the android Application fundamentals state that:
Note the Killable column in the table above. It indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code. Three methods (
onPause()
,onStop()
, andonDestroy()
) are marked "Yes." BecauseonPause()
is the first of the three, it's the only one that's guaranteed to be called before the process is killed —onStop()
andonDestroy()
may not be. Therefore, you should useonPause()
to write any persistent data (such as user edits) to storage.
As such I would suggest writing to preferences in onPause()
rather than onStop()
.
精彩评论