Android-use SharedPreference as the guiding Interface

Source: Internet
Author: User

I have been familiar with the storage medium of sharedPreference android for a long time. However, I have never actually used it. Today, when I look at the previous app called "", I suddenly thought that I could use the sharedPreference class to improve a defect in this app.
Previously, I first introduced the use of sharedPreference.
Android data can be stored in four ways.
I. SharePreference
Ii. SQLite
Iii. File
Iv. ContentProvider

The SharedPreference class is a lightweight storage class, which is especially suitable for storing configuration parameters of software. SharedPreference actually generates an xml file to store data. The generated xml file is stored in the "/data/<package name>/shared_prefs" directory.
The usage process of the SharedPreference class is as follows:
1. Get the instantiated object of the SharedPreference class
2. Get the Editor object for editing SharedPreference class instances
3. Use Editor to add (modify) data
4. Use commit () to submit a transaction

1. Get the instantiated object of the SharedPreference class
You can use either of the following methods to obtain an object instantiated by the SharedPreference class:
  (1)Context. getSharedPreferences (String name, int mode)
Parameter Parsing:
A) name is the name of the xml file generated by SharedPreference. If the parameter name is set to "firstTest", after the code is executed, SharedPreference will generate a firstTest. xml file. This xml uses a key-value pair to save parameters.
B) mode is the creation mode and the storage mode for setting SharedPreference. There are four parameters in total:
Context. MODE_PRIVATE: the default operation mode, which indicates that the file is private data and can only be accessed by local applications.
Context. MODE_APPEND: Check whether the file exists. If yes, append the content to the file. Otherwise, create a new file.
Context. MODE_WORLD_READABLE: The current file can be read by other applications ·
Context. MODE_WORLD_WRITEABLEs: The current file can be written by other applications.
  (2)Activity. getPreferences (int mode)
In this way, the name is obtained through getLocalClassName () and cannot be set by ourselves. It will be transferred to getSharedPreferences () of ContextWrapper ()
We recommend that you use the first method to obtain the instantiated objects of the SharedPreference class.

2. Get the Editor object
The SharedPreferences object can only obtain data, but does not support storage and modification. The storage modification is implemented through the Editor object. The specific implementation is as follows:
SharedPreferences sp = ctx.getSharedPreferences("Test", MODE_PRIVATE);  
Editor editor = sp.edit();
3 + 4. Use Editor to add (modify) Data + use commit () to submit transactions
Editor has built-in writing functions for some common variables (using key-value pairs) to facilitate data storage. After storing data, you must use the commit () function to submit transactions, to complete data storage, the specific implementation is as follows:
editor.putString("STRING_KEY", "string");        editor.putInt("INT_KEY", 0);        editor.putBoolean("BOOLEAN_KEY", true);        editor.commit();

Through the SharedPreference class, we can implement the [user guide function] to be executed only when the app is accessed for the first time. The specific implementation is as follows:
/*** This class is the first interface to enter the app. The animation * @ author LiXuetao */public class startAnimationActivity extends Activity {public static final int SKIP_GUIDE = 0x001 is displayed; public static final int SKIP_MAIN = 0x002; SharedPreferences sharedPreferences; // This Thread is used to delay the jump to the activity thread Thread; // determines whether to open the application Boolean B for the first time; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_startanimation);/*** context. getgetSharedPreferences (String name, int mode) Get the sharedPreference object * name is the name of the xml file generated by sharedPreference */sharedPreferences = getSharedPreferences ("test", Context. MODE_PRIVATE); thread = new Thread (runnable); thread. start () ;}// this handler is used to process the interface Transformation (jump activity) Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case SKIP_GUIDE: Intent guideIntent = new Intent (startAnimationActivity. this, guideActivity. class); startActivity (guideIntent); break; case SKIP_MAIN: Intent mainIntent = new Intent (startAnimationActivity. this, MainActivity. class); startActivity (mainIntent); break ;};}; Runnable runnable = new Runnable () {@ Override public void run () {// TODO Auto-generated method stub try {// getBoolean (String key, boolean defValue) Get the isFirst value of the key, if this key is not available, the default value is obtained (the isFirst key is not used when the program is started for the first time) B = sharedPreferences. getBoolean ("isFirst", true); Message msg = handler. obtainMessage (); if (B) {// The Editor object is used to modify the sharedpreference object. After modification, a transaction must be submitted to complete the modification (see Database Transaction Processing). Editor editor = sharedPreferences. edit (); editor. putBoolean ("isFirst", false); editor. commit (); msg. what = SKIP_GUIDE;} else {msg. what = SKIP_MAIN;} // after sleep for 3 seconds, send the information to handler and the handler will jump to the activity Thread. sleep (3000); handler. sendMessage (msg);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}};}/*** this class is the main interface of the app * @ author LiXuetao **/public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;}/*** this class is the app boot interface, run * @ author LiXuetao */public class guideActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_guide );}}

The above is the specific implementation code of the guide interface when the app is started for the first time.
The problem with the model Daquan app I mentioned at the beginning is that the database of the APP is imported externally, so every time you modify the database, you have to re-import the database, otherwise, the data will be displayed according to the database of the previous version. At that time, I was unable to find a solution, so I had to delete the database every time I started the app, and then re-import the app.
Now with sharedPreference, you can delete the original database and import the new database only when the app is started for the first time. Now, I have to modify the code ~~~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.