Save values before close the app?

南楼画角 提交于 2019-11-30 07:39:34

问题


I want to save some values before i closed the app. But i don't know if i must create a new file(.txt) and save it in; or i just can change strings.xml file and when i open app next time the saved values will be the right saved values or will be walues which i define them before first using. I know that exist really easy way to read from strings.xml file and so i think that there must be a way to set values in this file before closing (but i can't find on the net). Thanks for any examples or yours advice and explanation.


回答1:


Android provides the SharedPreferences class to help you save simple application data. You can use SharedPreferences class to save the config information or anything you want. When you put the application in background or close it, onStop() will be called. You can override it to implement what you want.

Usage of SharedPreferences class is very simple:

step 1: Writing with SharedPreferences object

//Create a object SharedPreferences from getSharedPreferences("name_file",MODE_PRIVATE) of Context
private SharedPreferences pref;
pref = getSharedPreferences("info", MODE_PRIVATE);
//Using putXXX - with XXX is type data you want to write like: putString, putInt...   from      Editor object
Editor editor = pref.edit();
editor.putString("key5","value5");
//finally, when you are done saving the values, call the commit() method.   
editor.commit()

step2: Reading with SharedPreferences object

//get SharedPreferences from getSharedPreferences("name_file", MODE_PRIVATE)
SharedPreferences shared = getSharedPreferences("info",MODE_PRIVATE)
//Using getXXX- with XX is type date you wrote to file "name_file"
 String string_temp = shared.getString("key5");

The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the application that created it.

The shared preferences file is save as an XML file in /data/data/<package_name>/shared_prefs folder




回答2:


Do your save operation in your activity's overridden onStop() method. As for where/how to save: follow the example here :

http://developer.android.com/guide/topics/data/data-storage.html#pref




回答3:


You can do it using preferences. Check this tutorial and example

http://www.vogella.com/articles/Android/article.html#preferences

If data has to be shared between multiple activities then use Shared Preferences




回答4:


Better go with shared preference for saving data but if you think you have save more amount of data then better go with database or save it as file.

Refer this LINK



来源:https://stackoverflow.com/questions/10127396/save-values-before-close-the-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!