Standard use of SharedPreferences and sharedpreferences in android Projects
1. What is SharedPreferences?
SharedPreferences is one of the four data storage technologies of Android (SharedPreferences, SQLite, Content Provider, and File). SharedPreferences process a key-value pair ), it is often used to store lightweight data.
(The official website is the best place to learn about android)
Official Website: http://developer.android.com/reference/android/content/SharedPreferences.html
Ii. Simple use
1. Create a contents class to save the key-value
public class ShareContents {public static String ShareName="shareName";public static String myName = "myName";public static String isGood = "isGood";}
2. Create a ShareManager class for unified management of the get and set methods of SharedPreferences, which is equivalent to setting or the value of key-value.
Import android. content. context; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; public class ShareManager {private SharedPreferences share; private Editor editor; private String TAG = "ShareManager"; private ShareManager () {super ();} public void clear () {editor. clear (). commit () ;}; public ShareManager (Context context) {super (); share = context. getSharedPreferences (inclucontents. shareName, Context. MODE_PRIVATE); editor = share. edit ();}/*** get myName ** @ return */public String getMyName () {String result = share. getString (Response contents. myName, ""); return result;}/*** set myName ** @ param myName */public void setMyName (String myName) {editor. putString (contents. myName, myName ). commit ();}/*** get isGood * @ return */public boolean isGood () {boolean result = share. getBoolean (Response contents. isGood, false); return result;}/*** set isGood * @ param isGood */public void setIsGood (boolean isGood) {editor. putBoolean (extends contents. isGood, isGood ). commit ();}}
3. demo of SharedPreferences
Public class SharePreferencesActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); final Button button = new Button (this); setContentView (button); button. setText ("click the screen to set SharedPreferences and obtain the value displayed on the screen"); // generate the object shareManagerfinal ShareManager shareManager = new ShareManager (this ); // set the name shareManager. setMyName ("li xiao long"); // set isGood to trueshareManager. setIsGood (true); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {button. setText ("myName:" + shareManager. getMyName () + ";" + "isGood:" + shareManager. isGood ());};});}}
You can click here to find the demo in this section
Link: http://www.cnblogs.com/liqw/p/4148411.html