How to store data using SharedPreferences in android

Source: Internet
Author: User

Most of the time, the software we develop needs to provide users with the software parameter setting function, such as our commonly used QQ, users can set whether to allow strangers to add themselves as friends. For saving software configuration parameters, if the window software is used, we usually use the INI file for saving. If it is a j2se application, we will use the properties property file or xml for saving. For Android applications, how can we save software configuration parameters? The Android platform provides us with a SharedPreferences class, which is a lightweight storage class and is especially suitable for storing software configuration parameters. Use SharedPreferences to save data. xml files are used to store data in the/data/<package name>/shared_prefs directory:

SharedPreferences sharedPreferences = getSharedPreferences ("ljq", Context. MODE_PRIVATE );

Editor editor = sharedPreferences. edit (); // get the Editor

Editor. putString ("name", "Lin ji qin ");

Editor. putInt ("age", 24 );

Editor. commit (); // submit the modification

The content of the generated ljq. xml file is as follows:

<? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?>

<Map>

<String name = "name"> Lin jiqin </string>

<Int name = "age" value = "24"/>

</Map>

Because SharedPreferences uses an xml file to save data, the first parameter of the getSharedPreferences (name, mode) method is used to specify the name of the file. The name does not need a suffix, And the suffix will be automatically added by Android. The second parameter of the method specifies the file operation mode. There are four operation modes. the preceding four modes are described when you use the File mode to save data. If you want the xml file used by SharedPreferences to be read and written by other applications, you can specify the Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE permissions.

In addition, Activity provides another getPreferences (mode) method to operate SharedPreferences. By default, This method uses the Class Name of the current class without the package name as the file name.

Access Data in SharedPreferences

The data code used to access SharedPreferences is as follows:

SharedPreferences sharedPreferences = getSharedPreferences ("ljq", Context. MODE_PRIVATE );

// The second parameter of getString () is the default value. If the key does not exist in preference, the default value is returned.

String name = sharedPreferences. getString ("name ","");

Int age = sharedPreferences. getInt ("age", 1 );

To access Preference in other applications, the precondition is that the Context. MODE_WORLD_READABLE or Context. MODE_WORLD_WRITEABLE permission is specified when the preference is created.

For example, an application whose <package name> is com. ljq. action creates a preference using the following statement.

GetSharedPreferences ("ljq", Context. MODE_WORLD_READABLE );

To access the preference of the above application, other applications must first create the Context of the above application and then access the preference through the Context. when accessing the preference, the preference will be found in the shared_prefs directory under the package where the application is located:

Context othersponcontext = createPackageContext ("com. ljq. action", Context. CONTEXT_IGNORE_SECURITY );

SharedPreferences sharedPreferences = otherequcontext. getSharedPreferences ("ljq", Context. MODE_WORLD_READABLE );

String name = sharedPreferences. getString ("name ","");

Int age = sharedPreferences. getInt ("age", 0 );

If you do not create a Context to access the preference of other applications, you can also directly access the xml file corresponding to the preference of other applications by reading the xml file, for example:

File xmlFile = new File ("/data/<package name>/shared_prefs/itcast. xml"); // replace <package name> with the package name of the application

Case:

String. xml file

Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "hello"> Hello World, SpActivity! </String>
<String name = "app_name"> Software configuration parameters </string>
<String name = "name"> name </string>
<String name = "age"> age </string>
<String name = "button"> Save settings </string>
<String name = "showButton"> display </string>
</Resources>

Main. xml layout FileCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">
<RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content">
<TextView android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/name"
Android: textSize = "20px"
Android: id = "@ + id/nameLable"/>
<EditText android: layout_width = "80px"
Android: layout_height = "wrap_content"
Android: layout_toRightOf = "@ id/nameLable"
Android: layout_alignTop = "@ id/nameLable"
Android: layout_marginLeft = "10px"
Android: id = "@ + id/name"/>
</RelativeLayout>
<RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content">
<TextView android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: textSize = "20px"
Android: text = "@ string/age"
Android: id = "@ + id/ageLable"/>
<EditText android: layout_width = "80px"
Android: layout_height = "wrap_content"
Android: layout_toRightOf = "@ id/ageLable"
Android: layout_alignTop = "@ id/ageLable"
Android: layout_marginLeft = "10px"
Android: id = "@ + id/age"/>
</RelativeLayout>
<RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content">
<Button android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/button"
Android: id = "@ + id/button"/>
<Button android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/showButton"
Android: layout_toRightOf = "@ id/button"
Android: layout_alignTop = "@ id/button"
Android: id = "@ + id/showButton"/>
</RelativeLayout>
<TextView android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: textSize = "20px"
Android: id = "@ + id/showText"/>
</LinearLayout>

Copy codeThe Code is as follows: package com. ljq. activity;

Import android. app. Activity;
Import android. content. Context;
Import android. content. SharedPreferences;
Import android. content. SharedPreferences. Editor;
Import android. OS. Bundle;
Import android. view. View;
Import android. widget. Button;
Import android. widget. EditText;
Import android. widget. TextView;
Import android. widget. Toast;

Public class SpActivity extends Activity {
Private EditText nameText;
Private EditText ageText;
Private TextView resultText;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

NameText = (EditText) this. findViewById (R. id. name );
AgeText = (EditText) this. findViewById (R. id. age );
ResultText = (TextView) this. findViewById (R. id. showText );

Button button = (Button) this. findViewById (R. id. button );
Button showButton = (Button) this. findViewById (R. id. showButton );
Button. setOnClickListener (listener );
ShowButton. setOnClickListener (listener );

// Echo
SharedPreferences sharedPreferences = getSharedPreferences ("ljq123 ",
Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE );
String nameValue = sharedPreferences. getString ("name ","");
Int ageValue = sharedPreferences. getInt ("age", 1 );
NameText. setText (nameValue );
AgeText. setText (String. valueOf (ageValue ));
}

Private View. OnClickListener listener = new View. OnClickListener (){
Public void onClick (View v ){
Button button = (Button) v;
// The ljq123 file is stored in the/data/<package name>/shared_prefs directory.
SharedPreferences sharedPreferences = getSharedPreferences ("ljq123 ",
Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE );
Switch (button. getId ()){
Case R. id. button:
String name = nameText. getText (). toString ();
Int age = Integer. parseInt (ageText. getText (). toString ());
Editor editor = sharedPreferences. edit (); // get the Editor
Editor. putString ("name", name );
Editor. putInt ("age", age );
Editor. commit (); // submit the modification
Toast. makeText (SpActivity. this, "saved successfully", Toast. LENGTH_LONG). show ();
Break;
Case R. id. showButton:
String nameValue = sharedPreferences. getString ("name ","");
Int ageValue = sharedPreferences. getInt ("age", 1 );
ResultText. setText ("name:" + nameValue + ", age:" + ageValue );
Break;
}
}
};
}

Running result

How to access Preference in other applications?

Copy codeThe Code is as follows: package com. ljq. sp;

Import java. io. File;
Import java. io. FileInputStream;

Import android. content. Context;
Import android. content. SharedPreferences;
Import android. test. AndroidTestCase;
Import android. util. Log;

Public class AccessSharePreferenceTest extends AndroidTestCase {
Private static final String TAG = "AccessSharePreferenceTest ";

/**
* Method 1 for accessing SharePreference. Note: You must have sufficient permissions.
* @ Throws Exception
*/
Public void testAccessPreference () throws Exception {
String path = "/data/com. ljq. activity/shared_prefs/ljq123.xml ";
File file = new File (path );
FileInputStream inputStream = new FileInputStream (file );
// Obtain an xml string.
String data = new FileService (). read (inputStream );
Log. I (TAG, data );
}

/**
* Method 2 for accessing SharePreference. Note: You must have sufficient permissions.
* @ Throws Exception
*/
Public void testAccessPreference2 () throws Exception {
Context context = this. getContext (). createPackageContext ("com. ljq. activity ",
Context. CONTEXT_IGNORE_SECURITY );
SharedPreferences sharedPreferences = context. getSharedPreferences ("ljq123 ",
Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE );
String name = sharedPreferences. getString ("name ","");
Int age = sharedPreferences. getInt ("age", 1 );
Log. I (TAG, name + ":" + age );
}
}

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.