SharedPreferences for Android Data Storage
SharedPreferences is a lightweight data storage method. It stores key-value pairs based on XML files and is usually used to store some simple configuration information. The SharedPreferences object can only obtain data, but does not support storage and modification. The storage modification is implemented through the Editor object. Each SharedPreferences file is managed by the framework and can be private or shared. Create an Android project for data storage. In the onCreate method of MainActivity, call the getSharedPreferences method. Note that if a file already exists, it will not be created, if the key-Value Pair does not exist, it will be added to it. If the name is the same and the value is different, the original value will be overwritten. Context context = MainActivity. this; SharedPreferences shared = context. getSharedPreferences ("Test", MODE_PRIVATE); Editor editor = shared. edit (); editor. putString ("Name", "FlyElephant"); editor. putInt ("Age", 24); editor. putBoolean ("IsMarried", false); editor. commit (); after the storage is complete, a Test is added to the folder. xml. The full path should be data/com. example. preference/shared_prefs/Test. after the xml is exported, the xml content is: <? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Map> <string name = "Name"> FlyElephant </string> <int name = "Age" value = "24"/> <boolean name = "IsMarried" value =" false "/> </map>: displays data. Set a button and click the event loadData public void loadData (View view) {SharedPreferences shared = MainActivity. this. getSharedPreferences ("Test", MODE_PRIVATE); EditText editText = (EditText) findViewById (R. id. edit_sharedName); editText. setText (shared. getString ("Name", ""); EditText editAge = (Edit Text) findViewById (R. id. edit_sharedAge); String ageString = String. valueOf (shared. getInt ("Age", 0); editAge. setText (ageString);} data display result: Click the second button to delete the node. The executed event is public void deleteNode (View view) {SharedPreferences shared = MainActivity. this. getSharedPreferences ("Test", MODE_PRIVATE); Editor editor = shared. edit (); editor. remove ("Age"); editor. commit (); Toast. makeText (MainActivity. this, "deleted successfully", Toast. LENGT H_SHORT ). show ();}: delete the File according to the path. After you call File, the File is deleted: public void deleteFile (View view) {String pathString = "/data/" + getPackageName () + "/shared_prefs"; File file = new File (pathString, "Test. xml "); Log. I ("com. example. preference ", pathString); if (file. exists () {file. delete ();} Toast. makeText (MainActivity. this, "the file is successfully deleted", Toast. LENGTH_SHORT ). show ();} Android beginners, during the day. NET. I came back to engage in Android in the evening and felt like I was back in college ~ Author: FlyElephant Source: Tracing.