goman 发表于 2013-8-28 16:29

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&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;    xmlns:tools=&quot;http://schemas.android.com/tools&quot;    android:layout_width=&quot;match_parent&quot;    android:layout_height=&quot;match_parent&quot; &gt;     &lt;EditText      android:id=&quot;@+id/et_name&quot;      android:layout_width=&quot;fill_parent&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignParentTop=&quot;true&quot;      android:layout_centerHorizontal=&quot;true&quot;      android:layout_marginTop=&quot;16dp&quot;      android:ems=&quot;10&quot;      android:hint=&quot;姓名&quot; /&gt;     &lt;EditText      android:id=&quot;@+id/et_height&quot;      android:layout_width=&quot;fill_parent&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignParentLeft=&quot;true&quot;      android:layout_marginTop=&quot;168dp&quot;      android:ems=&quot;10&quot;      android:hint=&quot;身高&quot; /&gt;     &lt;EditText      android:id=&quot;@+id/et_age&quot;      android:layout_width=&quot;fill_parent&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignParentLeft=&quot;true&quot;      android:layout_below=&quot;@+id/et_name&quot;      android:layout_marginTop=&quot;32dp&quot;      android:ems=&quot;10&quot;      android:hint=&quot;年龄&quot; /&gt;     &lt;Button      android:id=&quot;@+id/button1&quot;      android:layout_width=&quot;wrap_content&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignParentLeft=&quot;true&quot;      android:layout_below=&quot;@+id/et_height&quot;      android:layout_marginLeft=&quot;32dp&quot;      android:layout_marginTop=&quot;40dp&quot;      android:gravity=&quot;center_horizontal&quot;      android:text=&quot;Preferences的简单的测试&quot; /&gt; &lt;/RelativeLayout&gt;</div
页: [1]
查看完整版本: android采用sharepreference方式保存数据