SharedPreferes learning Summary

Source: Internet
Author: User

Today, I learned about SharedPreferences. After explaining it, I learned that SharedPreferences is a lightweight storage class on the Android platform. It mainly stores some common configurations, such as window status, generally, the onSaveInstanceState in the Activity is reloaded and generally stored using SharedPreferences. It provides regular Long integer, Int integer, and String storage on the Android platform. It can be divided into multiple permissions that can be shared globally. android123 prompts that the database will be saved in xml format. The overall efficiency is not particularly high. It is much better than SQLite in general lightweight scenarios, if the storage capacity is not large, you can define your own file format. During xml processing, Dalvik will parse the local XML Parser that comes with the underlying layer, such as the XMLpull method, so that the memory resource usage is better.

This method should be the simplest method for Android to read and write external data. Its usage is basically the same as J2SE (java. util. prefs. preferences) in the same usage, in a simple and transparent way to save some user personalized settings of the font, color, location and other parameter information. Generally, Preferences can be used for storage, and programmers do not need to know in what form it is saved and where it is saved.

In the Android system, the information is saved as an XML file

/Data/PACKAGE_NAME/shared_prefs directory.

SharedPreferences pre = getSharedPreferences ("soft ",

Context. MODE_WORLD_READABLE );

Here we can call the method provided by activity. This method has two parameters:

1). file name. Pay special attention here. In Android, it has been confirmed that SharedPreferences are saved in the xm l format. Therefore, when entering the file name parameter, do not specify the suffix ". xml". android will automatically add it. It stores parameters in the form of key-value pairs. When you need to obtain a parameter value, you can index it according to the key of the parameter.

2). The second one can be understood as the creation mode is the same as the previous file storage mode.

Context. MODE_PRIVATE

Context. MODE_APPEND

Context. MODE_WORLD_READABLE

Context. MODE_WORLD_WRITEABLE

1. Resource file content

<String name = "name_text"> name </string>

<String name = "age_text"> age </string>

<String name = "save_text"> submit </string>

2. layout File Content

<? Xml version = "1.0" encoding = "UTF-8"?>

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

Android: orientation = "vertical">

<LinearLayout

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: orientation = "horizontal">

<TextView

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: layout_marginRight = "30dp"

Android: text = "@ string/name_text"/>

<EditText

Android: id = "@ + id/nameEt"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"/>

</LinearLayout>

<LinearLayout

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: orientation = "horizontal">

<TextView

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: layout_marginRight = "30dp"

Android: text = "@ string/age_text"/>

<EditText

Android: id = "@ + id/ageEt"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"/>

</LinearLayout>

<Button

Android: id = "@ + id/saveBtn"

Android: layout_marginTop = "30dp"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: text = "@ string/save_text"/>

</LinearLayout>

3. Save

Private void findViews (){

NameEt = (EditText) this. findViewById (R. id. nameEt );

AgeEt = (EditText) this. findViewById (R. id. ageEt );

SaveBtn = (Button) this. findViewById (R. id. saveBtn );

SaveBtn. setOnClickListener (new View. OnClickListener (){

Public void onClick (View v ){

String name = nameEt. getText (). toString (). trim ();

Int age =

Integer. valueOf (ageEt. getText (). toString (). trim ());

SharedPreferences sharedPreferences =

SharedpreferencesTestActivity. this

. GetSharedPreferences ("myOption", MODE_PRIVATE );

Editor editor = sharedPreferences. edit ();

Editor. putString ("name", name );

Editor. putInt ("age", age );

Editor. commit ();

}

});

}

Effect

Now we add the READ function:

1. Resource file content:

<String name = "name_text"> name </string>

<String name = "age_text"> age </string>

<String name = "save_text"> Save </string>

<String name = "read_text"> Read </string>

2. layout File Content

<TableLayout

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: layout_margin = "15dp"

Android: stretchColumns = "*">

<TableRow>

<Button

Android: id = "@ + id/saveBtn"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: layout_marginTop = "30dp"

Android: text = "@ string/save_text"/>

<Button

Android: id = "@ + id/readBtn"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: layout_marginTop = "30dp"

Android: text = "@ string/read_text"/>

</TableRow>

</TableLayout>

3. modify the content in the onClick method:

Public void onClick (View v ){

SharedPreferences sp = getSharedPreferences ("myOption ",

MODE_PRIVATE );

String name = "anonymous ";

Int age =-1;

Switch (v. getId ()){

Case R. id. saveBtn:

Name = nameEt. getText (). toString (). trim ();

Age = Integer. valueOf (ageEt. getText (). toString (). trim ());

Editor editor = sp. edit ();

Editor. putString ("name", name );

Editor. putInt ("age", age );

Editor. commit ();

Break;

Case R. id. readBtn:

Name = sp. getString ("name", "anonymous ");

Age = sp. getInt ("age",-1 );

Toast. makeText (this,

"Name:" + name + "age:" + String. valueOf (age ),

Toast. LENGTH_SHORT). show ();

Break;

}

}

Effect

1. Read SharedPreferences of other applications

First, make sure that the SharedPreferences project is used:

Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE

2. Let's look at a simple example (read the SharedPreferences of the above project

):

Resource file content:

<String name = "app_name"> ReadOtherSharedPreferences </string>

<String name = "read_text"> Read the SharedPreferences file of other projects. </string>

Layout file content:

<Button

Android: id = "@ + id/readOther"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: text = "@ string/read_text"/>

The Code read in the current project is:

Public class ReadOtherSharedPreferencesActivity extends Activity implements OnClickListener {

Button readBtn;

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

FindViews ();

}

Private void findViews (){

ReadBtn = (Button) this. findViewById (R. id. readOther );

ReadBtn. setOnClickListener (this );

}

Public void onClick (View v ){

If (v. getId () = R. id. readOther ){

Try {

Context otherContext = this. createPackageContext (

"Cn. class3g. activity", Context. CONTEXT_IGNORE_SECURITY );

SharedPreferences shared = otherContext. getSharedPreferences ("info", MODE_PRIVATE );

String res = "name =" + shared. getString ("name", "wms") +

"Age =" + String. valueOf (shared. getInt ("age",-1 ));

Toast. makeText (this, res, Toast. LENGTH_LONG). show ();

} Catch (NameNotFoundException e ){

E. printStackTrace ();

}

}

}

}

Effect:

 

Click Button

 

Author chizhidan_luck
 

Related Article

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.