Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

android - Save values before close the app?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...