Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1398293
  • 博文数量: 188
  • 博客积分: 1784
  • 博客等级: 上尉
  • 技术积分: 2772
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-05 22:20
个人简介

发上等愿,结中等缘,享下等福;择高处立,就平处坐,向宽处行。

文章分类

全部博文(188)

文章存档

2020年(12)

2019年(11)

2018年(4)

2017年(3)

2016年(11)

2015年(22)

2014年(19)

2013年(25)

2012年(32)

2011年(49)

分类: Android平台

2013-10-17 12:54:30

很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data//shared_prefs目录下:
SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "黑马");
editor.putInt("age", 4);
editor.commit();//提交修改
生成的itcast.xml文件内容如下:
< ?xml version='1.0' encoding='utf-8' standalone='yes' ?>

黑马


因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。

10、访问SharedPreferences中的数据
访问SharedPreferences中的数据代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个为cn.itcast.action的应用使用下面语句创建了preference。
getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("cn.itcast.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 0);

如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如:
File xmlFile = new File(“/data/data//shared_prefs/itcast.xml”);//应替换成应用的包名

登录保存到sp
package com.itheima.login.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
* 登陆相关的服务
*
* @author Administrator
*
*/
public class LoginService {
    // 上下文 其实提供了应用程序 的一个详细的环境信息. 包括 包名是什么 /data/data/目录在哪里.
    // we do chicken right


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37


/**
 * 保存用户信息到文件
 * 
 * @param username
 *            用户名
 * @param password
 *            密码
 */
public static void saveUserInfoToFile(Context context, String username,
        String password) throws Exception {
    SharedPreferences sp = context.getSharedPreferences("config",
            Context.MODE_PRIVATE);

    Editor editor = sp.edit();
    editor.putString("username", username);
    editor.putString("password", password);
    editor.commit();

}

/**
 * 读取用户的用户名和密码
 * 
 * @return // zhangsan##123456
 */
public static String[] readUserInfoFromFile(Context context)
         {
    SharedPreferences sp = context.getSharedPreferences("config",
            Context.MODE_PRIVATE);
    String username = sp.getString("username", "");
    String password = sp.getString("password", "");
    String[] infos = new String[2];
    infos[0] = username;
    infos[1] = password;
    return infos;

}

}
package com.itheima.login;

import com.itheima.login.service.LoginService;

import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
* activity 实际上是上下文的一个子类
*
* @author Administrator
*
*/
public class MainActivity extends Activity {
    private EditText et_username;
    private EditText et_password;
    private CheckBox cb_remeber_pwd;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    cb_remeber_pwd = (CheckBox) findViewById(R.id.cb_remeber_pwd);
    et_username = (EditText) findViewById(R.id.et_username);
    et_password = (EditText) findViewById(R.id.et_password);

    String[] infos = LoginService.readUserInfoFromFile(this);
    et_username.setText(infos[0]);
    et_password.setText(infos[1]);


}

/**
 * 登陆按钮的点击事件
 * 
 * @param view
 */
public void login(View view) {
    String username = et_username.getText().toString().trim();
    String password = et_password.getText().toString().trim();
    if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
        Toast.makeText(getApplicationContext(), "用户名或者密码不能为空", 0).show();
        return;
    }
    // 检查是否勾选了cb
    if (cb_remeber_pwd.isChecked()) {// 记住密码
        try {
            LoginService.saveUserInfoToFile(this, username, password);
            Toast.makeText(this, "保存用户名密码成功", 0).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "保存用户名密码失败", 0).show();
        }
    }
}

}

设置界面
package com.itheima.setting;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
    private RelativeLayout rl_sound;
    private CheckBox cb_status;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


private SharedPreferences sp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rl_sound = (RelativeLayout) findViewById(R.id.rl_sound);
    cb_status = (CheckBox) findViewById(R.id.cb_status);

    //初始化sp
    sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);

    boolean checked = sp.getBoolean("checked", false);
    cb_status.setChecked(checked);

    rl_sound.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //创建sharedpreference的编辑器
            Editor editor = sp.edit();

            if(cb_status.isChecked()){
                editor.putBoolean("checked", false);
                cb_status.setChecked(false);
            }else{
                cb_status.setChecked(true);
                editor.putBoolean("checked", true);
            }
            //操作完参数后 一定要记得commit();
            editor.commit();
        }
    });
}

}

阅读(2062) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~