灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2346回复:0

Android SharedPreferences的使用

楼主#
更多 发布于:2012-09-06 13:48


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 目录下。

下面是程序代码:

[java] view plaincopyprint?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(){

            @Override
            public 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);
    }
}
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(){
   @Override
   public 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文件中的

[html]  <?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"?>
<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="请输入用户名"
AndroidingleLine="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="请输入密码" AndroidingleLine="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>

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




喜欢0 评分0
游客

返回顶部