Simple data persistence (SharedPreferences)
To save some simple configurations, similar to the CCUserDefault of iOS NSUserDefault and cocos2dx, Android provides SharedPreferences.
1 Layout
First look:
Open main. xml and modify the content as follows:
Binary definition string
Open strings. xml and add the following content:
Name
Age
Save Parameters
Saved
Failed to save
Three Functions
The code for modifying MainActivity. java is as follows:
Private EditText nameText; private EditText ageText; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); nameText = (EditText) this. findViewById (R. id. input_name); ageText = (EditText) this. findViewById (R. id. input_age); // read the saved value // SharedPreferences preferences = this. getPreferences (Context. MODE_PRIVATE); // The default class name is used as the file name // SharedPreferences preferences = this. getSharedPreferences (preference, Context. MODE_PRIVATE); SharedPreferences preferences = getApplicationContext (). getSharedPreferences (preference, Context. MODE_PRIVATE); String name = preferences. getString (name, null); String age = String. valueOf (preferences. getInt (age, 0); nameText. setText (name); ageText. setText (age);} public void save (View v) {String name = nameText. getText (). toString (); Integer age = Integer. valueOf (ageText. getText (). toString (); try {// The first parameter is the file name, And the suffix cannot be specified. The second parameter is the file operation mode SharedPreferences preferences = getApplicationContext (). getSharedPreferences (preference, Context. MODE_PRIVATE); SharedPreferences. editor editor = preferences. edit (); editor. putString (name, name); editor. putInt (age, age); editor. commit (); Toast. makeText (getApplicationContext (), R. string. success, Toast. LENGTH_LONG ). show ();} catch (Exception e) {Toast. makeText (getApplicationContext (), R. string. fail, Toast. LENGTH_LONG ). show (); e. printStackTrace ();}}
Iv. Running results
First running result
Enter the content, click "Save parameter", exit the program, and open the program again,