使用SharedPreferences进行数据存储
很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。
对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?
Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。
使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/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' ?>
<map>
<string name="name">赵雅智博客</string>
<int name="age" value="4" />
</map>
因为SharedPreferences背后是使用xml文件保存数据,
getSharedPreferences(name,mode)
- 方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。
- 方法的第二个参数指定文件的操作模式
共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。
访问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权限。如:有个<package name>为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/<package name>/shared_prefs/itcast.xml”);//<package name>应替换成应用的包名
实例:login
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lession03_login"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lession03_login.LoginActivity"
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>
布局文件
<LinearLayout 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"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_name" />
<EditText
android:id="@+id/edit_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_pass" />
<EditText
android:id="@+id/edit_pass"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<RadioButton
android:id="@+id/radio_rom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/login_rom" />
<RadioButton
android:id="@+id/radio_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_sp" />
<RadioButton
android:id="@+id/radio_sd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_sd" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_login" />
<CheckBox
android:id="@+id/check_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="@string/login_remember" />
</LinearLayout>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">lession03_login</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="login_name">用户名</string>
<string name="login_pass">密码</string>
<string name="login_login">登陆</string>
<string name="login_remember">记住密码</string>
<string name="login_rom">rom存储</string>
<string name="login_sp">sp存储</string>
<string name="login_sd">sd存储</string>
</resources>
LoginService.java
package com.example.lession03_login.service;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class LoginService {
// 上下文对象
public Context context;
// 通过上下文对象传过来
public LoginService(Context context) {
super();
this.context = context;
}
/**
* 采用sharedPreferences方法
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveBysp(String name, String pass, String fileName) {
// 通过上下文api获取 sharedPreferences对象
SharedPreferences sharedPreferences = context.getSharedPreferences(
fileName, Context.MODE_PRIVATE);
// 根据 sharedPreferences对象的edit方法返回Editor对象
Editor editor = sharedPreferences.edit();
// 存放数据
editor.putString("name", name);
editor.putString("pass", pass);
// 提交
return editor.commit();
}
}
LoginActivity.java
package com.example.lession03_login;
import com.example.lession03_login.R;
import com.example.lession03_login.service.LoginService;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class LoginActivity extends Activity {
// 声明获取的用户名和密码
private EditText edit_name, edit_pass;
// 声明登陆按对象
private Button btn_login;
// 声明复选框组件对象
private Checkable box_remember;
// 声明业务对象
private LoginService loginService;
// 声明保存方式按钮
private RadioButton radio_rom, radio_sp, radio_sd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置显示视图
setContentView(R.layout.activity_login);
// 实例化业务对像
loginService = new LoginService(this);
// 根据id名获取相应组件对象
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pass = (EditText) findViewById(R.id.edit_pass);
btn_login = (Button) findViewById(R.id.button_login);
box_remember = (Checkable) findViewById(R.id.check_remember);
radio_rom = (RadioButton) findViewById(R.id.radio_rom);
radio_sp = (RadioButton) findViewById(R.id.radio_sp);
radio_sd = (RadioButton) findViewById(R.id.radio_sd);
// 给按钮注册事件
btn_login.setOnClickListener(new MyOnclickListener());
// 回显数据
SharedPreferences preferences = this.getSharedPreferences("csdn",
Context.MODE_PRIVATE);
edit_name.setText(preferences.getString("name", "csdn"));
edit_pass.setText(preferences.getString("pass", "csdn"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
// 内部类 有关点击的处理对象
class MyOnclickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.button_login:
// 获取用户名密码
String name = edit_name.getText().toString();
String pass = edit_pass.getText().toString();
// 判断用户名密码是否为空
if (TextUtils.isEmpty(name)) {
Toast.makeText(LoginActivity.this, "用户名不可 为空",
Toast.LENGTH_LONG).show();
return;
} else if (TextUtils.isEmpty(pass)) {
Toast.makeText(LoginActivity.this, " 密码不可 为空",
Toast.LENGTH_LONG).show();
return;
} else {
// 判断记住密码是否被选中
if (box_remember.isChecked()) {
// 进行保存
// 调用业务对象的业务方法
// 如果rom保存方式被选中
if (radio_rom.isChecked()) {
// 如果sp保存方式被选中
} else if (radio_sp.isChecked()) {
boolean flag = loginService.saveBysp(name, pass,
"csdn");
if (flag) {
Toast.makeText(LoginActivity.this, "保存成功",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "保存失败",
Toast.LENGTH_LONG).show();
}
// 如果sd保存方式被选中
} else if (radio_sd.isChecked()) {
}
} else {
Toast.makeText(LoginActivity.this, "不保存密码",
Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
}
}
}