推荐当贝市场

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 20584|回复: 0

[案例] android采用sharepreference方式保存数据

[复制链接]
发表于 2013-8-28 16:29 | 显示全部楼层 |阅读模式
1
使用Perference来实现数据的存储,用到了SharedPreferences接口和SharedPreferences内部的一个接口SharedPreferences.Editor。
调用Context.getSharedPreferences(String name,int mode)得到SharedPreferences接口。该方法的第一个参数是文件名称,第二个参数是操作模式,android给我们提供了三种模式:
.私有(MODE_PRIVATE):仅有创建程序有权限对其进行读取或写入
全局读(MODE_WORLD_READABLE):不仅创建程序可以对其进行读取或写入,其他应用程序也读取操作的权限,但没有写入操作的权限
全局写(MODE_WORLD_WRITEABLE):创建程序和其他程序都可以对其进行写入操作,但没有读取的权限
接下来,我们使用一个简单的例子实现上面的功能:
将数据保存到手机的sd中,需要如下的几步:
1.       通过getSharedPreferences(String name,int mode)得到SharedPreferences接口。该方法的第一个参数是文件名称,第二个参数是操作模式
2.       调用SharedPreferences.Editor方法对SharedPreferences进行修改
3.       往editor对象塞值并且提交
实现的代码如下:
MAIn.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <EditText
        android:id="@+id/et_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="姓名" />
    <EditText
        android:id="@+id/et_height"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="168dp"
        android:ems="10"
        android:hint="身高" />
    <EditText
        android:id="@+id/et_age"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/et_name"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="年龄" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/et_height"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:text="Preferences的简单的测试" />
</RelativeLayout>
</div
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /2 下一条

Archiver|小黑屋|新帖|标签|软件|Sitemap|ZNDS智能电视网 ( 苏ICP备2023012627号 )

GMT+8, 2026-11-6 07:17 , Processed in 0.019977 second(s), 7 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表