打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SharedPreferences
 在此之前的学习内容是数据存储之一文件存储。在本地存储中常用的有,文件、配置文件、数据库。前面的学习主要是针对本地文件的。我认为可以把SharedPreferences看做是配置文件,虽然它也是采用XML格式存储的。
 
       比如我们使用的桌面软件中,通常会有一个“选项”菜单,选项是对软件的常规或核心设置。在Android中我们使用SharedPreferences来完成这种对配置文件的读写。在JavaSE和JavaEE中常用的是*.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创建配置的时候必须为它的文件访问模式设置为允许其他程序读取或写入等。
 
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/romanticlife/archive/2010/03/01/5335907.aspx
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
10.Android-SharedPreferences使用
SharedPreferences数据共享
android:SharedPreferences
android SharedPreferences简单使用
18. SharePreferences 保存数据
Android开发中SharedPreferences的应用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服