android采用sharepreference方式保存数据
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
页:
[1]