Android SharedPreferences的使用

来源:互联网 发布:农业部 优化种植结构 编辑:程序博客网 时间:2024/04/25 22:36

SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,android123提示最 终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml 处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。

这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法基本上和 J2SE(java.util.prefs.Preferences)中的用法一样,以一种简单、 透明的方式来保存一些用户个性化设置的字体、颜色、位置等参数信息。一般的应用程序都会提供“设置”或者“首选项”的这样的界面,那么这些设置最后就可以 通过Preferences来保存,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只 是在性能上不知道会有什么问题。

在Android系统中,这些信息以XML文件的形式保存在 /data/data/PACKAGE_NAME /shared_prefs 目录下。


下面是程序代码:

package com.cloay;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.EditText;import android.widget.ImageButton;/** *  * MySharedPreferencesActivity.java * @author cloay * 2011-10-18 */public class MySharedPreferencesActivity extends Activity {private EditText user = null;private EditText password = null;private ImageButton loginBtn = null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        user = (EditText)findViewById(R.id.user);        password = (EditText)findViewById(R.id.pass);        loginBtn = (ImageButton)findViewById(R.id.loginButton);        initView();        loginBtn.setOnTouchListener(new OnTouchListener(){@Overridepublic boolean onTouch(View v, MotionEvent event) {if(event.getAction()==MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.dengluxitong1);SharedPreferences userInfo = getSharedPreferences("user_info", 0);userInfo.edit().putString("name", user.getText().toString()).commit();userInfo.edit().putString("pass", password.getText().toString()).commit();}else if(event.getAction()==MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.dengluxitong);}return false;}                });    }private void initView() {SharedPreferences userInfo = getSharedPreferences("user_info", 0);String username = userInfo.getString("name", "");String pass = userInfo.getString("pass", "");user.setText(username);password.setText(pass);}}

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
通过名称,得到一个SharedPreferences,顾名思义,这个Preferences是共享的,共享的范围据现在同一个Package中,这里 面说所的Package和Java里面的那个Package不同,貌似这里面的Package是指在AndroidManifest.xml文件中的

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.cloay"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".MySharedPreferencesActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_width="185dp" android:id="@+id/user"
android:layout_height="40dp" android:hint="请输入用户名"
android:singleLine="true" android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/pass" android:layout_marginTop="66dp">
<requestFocus></requestFocus>
</EditText>
<EditText android:inputType="textPassword"
android:layout_width="185dp" android:id="@+id/pass"
android:layout_height="40dp" android:hint="请输入密码" android:singleLine="true"
android:layout_below="@+id/user" android:layout_centerHorizontal="true"
android:layout_marginTop="44dp">
</EditText>
<ImageButton android:layout_height="40dp"
android:layout_width="80dp" android:id="@+id/loginButton"
android:background="@drawable/dengluxitong"
android:layout_centerVertical="true" android:layout_alignRight="@+id/pass"
android:layout_marginRight="17dp"></ImageButton>
</RelativeLayout>

运行结果如下,首次显示的时空白,第二次运行时如下:



原创粉丝点击