`
Ancool
  • 浏览: 30789 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Android数据存储之二SharedPreferences

阅读更多

       在此之前的学习内容是数据存储之一文件存储。在本地存储中常用的有,文件、配置文件、数据库。前面的学习主要是针对本地文件的。我认为可以把SharedPreferences 看做是配置文件,虽然它也是采用XML 格式存储的。

 

       比如我们使用的桌面软件中,通常会有一个 选项 菜单,选项是对软件的常规或核心设置。在Android 中我们使用SharedPreferences 来完成这种对配置文件的读写。在JavaSEJavaEE 中常用的是*.properties ,在Windows 平台下常使用*.ini 文件。

 

       下面,我们编写一个使用SharedPreferences 读写配置文件的小例子。

 

       1. 创建Android 工程

       Project name:AndroidSharedPreferences

       BuildTarget:Android2.1

       Application name:Android 应用程序配置

       Package name:com.changcheng.sharedpreferences

       Create Activity:AndroidSharedPreferences

       Min SDK Version:7

 

       2. 编辑strings.xml

<? xml version = "1.0" encoding = "utf-8" ?>

< resources >

    < string name = "hello" > Hello World, AndroidSharedPreferences! </ string >

    < string name = "app_name" > Android 应用程序配置 </ string >

    < string name = "tv_name" > 姓名 </ string >

    < string name = "tv_age" > 年龄 </ string >

    < string name = "bt_write" > 设置 </ string >

    < string name = "bt_read" > 读取 </ string >

    < string name = "save_success" > 保存成功 </ string >

    < string name = "save_failed" > 保存失败 </ string >

</ resources >

 

       3. 编辑main.xml

<? 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 android:layout_width = "fill_parent"

                   android:layout_height = "wrap_content" >

                   < TextView android:layout_width = "70dip" android:layout_height = "wrap_content"

                            android:textSize = "25dip" android:id = "@+id/tv_name" android:text = "@string/tv_name" />

                   < EditText android:layout_width = "300dip"

                            android:layout_height = "wrap_content" android:layout_toRightOf = "@id/tv_name"

                            android:id = "@+id/et_name" />

         </ RelativeLayout >

         <!-- 年龄 -->

         < RelativeLayout android:layout_width = "fill_parent"

                   android:layout_height = "wrap_content" >

                   < TextView android:layout_width = "70dip" android:layout_height = "wrap_content"

                            android:textSize = "25dip" android:id = "@+id/tv_age" android:text = "@string/tv_age" />

                   < EditText android:layout_width = "300dip"

                            android:layout_height = "wrap_content" android:layout_toRightOf = "@id/tv_age"

                            android:id = "@+id/et_age" />

         </ RelativeLayout >

         <!-- 按钮 -->

         < RelativeLayout android:layout_width = "fill_parent"

                   android:layout_height = "wrap_content" android:gravity = "right" >

                   < Button android:layout_width = "wrap_content"

                            android:layout_height = "wrap_content" android:text = "@string/bt_write"

                            android:id = "@+id/bt_set" />

                   < Button android:layout_width = "wrap_content"

                            android:layout_height = "wrap_content" android:layout_toRightOf = "@id/bt_set"

                            android:text = "@string/bt_read" android:id = "@+id/et_read" />

         </ RelativeLayout >

</ LinearLayout >

 

       4. 为按钮添加事件代码

package com.changcheng.sharedpreferences;

 

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.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

public class AndroidSharedPreferences extends Activity {

 

         private static final String TAG = "AndroidSharedPreferences" ;

         private EditText etName ;

         private EditText etAge ;

 

         /** Called when the activity is first created. */

         @Override

         public void onCreate(Bundle savedInstanceState) {

                   super .onCreate(savedInstanceState);

                   setContentView(R.layout. main );

                   // 获取按钮

                   Button btSet = (Button) this .findViewById(R.id. bt_set );

                   Button btRead = (Button) this .findViewById(R.id. bt_read );

                   // 获取编辑框

                   etName = (EditText) this .findViewById(R.id. et_name );

                   etAge = (EditText) this .findViewById(R.id. et_age );

                   // 添加事件

                   btSet.setOnClickListener( new OnClickListener() {

                            @Override

                            public void onClick(View v) {

                                     // 获取名称和年龄

                                     String name = etName .getText().toString();

                                     String age = etAge .getText().toString();

                                     // 创建SharedPreferences

                                     SharedPreferences sp = getSharedPreferences( "preferences" ,

                                                        Context. MODE_PRIVATE );

                                     // 添加数据

                                     Editor editor = sp.edit();

                                     editor.putString( "name" , name);

                                     editor.putInt( "age" , Integer.parseInt (age));

                                     // 保存数据

                                     if (editor.commit())

                                               Toast.makeText (AndroidSharedPreferences. this ,

                                                                 R.string. save_success , 1).show();

                                     else

                                               Toast.makeText (AndroidSharedPreferences. this ,

                                                                 R.string. save_failed , 1).show();

                            }

                   });

                   btRead.setOnClickListener( new OnClickListener() {

                            @Override

                            public void onClick(View v) {

                                     // 创建SharedPreferences

                                     SharedPreferences sp = getSharedPreferences( "preferences" ,

                                                        Context. MODE_PRIVATE );

                                     // 获取数据

                                     String name = sp.getString( "name" , "defName" );

                                     String age = sp.getInt( "age" , 0) + "" ;

                                     // 显示数据

                                     etName .setText(name);

                                     etAge .setText(age);

                            }

                   });

         }

}

 

       5. 运行程序

       启动模拟器,运行程序。输入名称和年龄,点击保存。我们使用的代码是getSharedPreferences("preferences",Context.MODE_PRIVATE); ,当然commit 时。它会为我们为”/data/data/com.changcheng.sharedpreferences/shared_prefs/preferences.xml” 。将 preferences.xml 导出,查看它的内容为:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

<map>

<string name="name"> 长城</string>

<int name="age" value="25" />

</map>


      
将名称和年龄编辑框的内容清空,然后点击读取按钮,刚才写出的内容被读取进来。 SharedPreferences 的使用就是这么简单。

 

       6. 其他程序访问本程序的配置

       通过SharedPreferences 创建的配置文件,不需要指定路径和文件后缀名,读取的时候也是。通常情况下,配置只是提供给本应用程序使用的。在这里我们介绍一个小知识点,即其他程序想使用本应用程序的配置,那应该如何使用SharedPreferences 呢?如下:

Context otherAppContext = createPackageContext("com.changcheng.sharedpreferences", Context.CONTEXT_IGNORE_SECURITY);

SharedPreferences sharedPreferences = otherAppContext.getSharedPreferences("preferences", Context.MODE_WORLD_READABLE);

 

       注意,为了使其他程序可以访问本应用程序的配置。那么在我们使用 getSharedPreferences 创建配置的时候必须为它的文件访问模式设置为允许其他程序读取或写入等。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics