关于sharepreference的使用
为了保证文件数据的可读性和轻便性,我们能使用sharepreference!
SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。SharedPreferences保存数据用xml文件,,如果不做修改,文件一般存放在/data/data/ /shared_prefs目录下。
在上一次的登录界面中,所讲的数据存储和读取过于麻烦,所以这次我用shareperference完善了它。
下面是java代码:
ackage com.bmcq.laucher;
import java.util.Map;
import com.bmcq.laucher.service.LoginService;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private EditText et_user_name;
private EditText et_user_pwd;
private CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_user_name = (EditText)findViewById(R.id.et_user_name);
et_user_pwd = (EditText)findViewById(R.id.et_user_pwd);
cb = (CheckBox)findViewById(R.id.cb_remember_pwd);
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
String name = sp.getString("username", "");
et_user_name.setText(name);
String password = sp.getString("password", "");
et_user_pwd.setText(password);
}
public void login(View v)
{
String name = et_user_name.getText().toString().trim() ;
String password = et_user_pwd.getText().toString().trim();
if (TextUtils.isEmpty(name)||TextUtils.isEmpty(password))
{
Toast.makeText(this, "登录名或用户密码不能为空", 1).show();
}
else
{
if (cb.isChecked())//判断是否保存密码
{
Log.i(TAG,"需要保存密码。");
LoginService.SaveUserInfo(this, name, password) ;
Toast.makeText(this, "保存用户信息成功", 0).show();
}
if("bmcq".equals(name)&&"123".equals(password))
{
Toast.makeText(this, "登陆成功", 0).show();
}
else {
Toast.makeText(this, "登录名或用户密码错误", 1).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
业务代码如下:
package com.bmcq.laucher.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.ContentHandler;
import java.nio.MappedByteBuffer;
import java.util.HashMap;
import java.util.Map;
import android.R.string;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class LoginService {
/*
* 保存用户名和密码的业务方法
* @param user_name 用户名
* @param password 用户密码
*@ return true保存成功 false 保存失败
*@ getFileDire() /data/data/com.bmcq.login/File
*@ getCacheDir() /data/data/com.bmcq.login/Cache
*/
public static void SaveUserInfo(Context context,String username,String password)
{
SharedPreferences sp = context.getSharedPreferences("config",context.MODE_PRIVATE );//得到接口类对象
Editor editor = sp.edit();//获得sp编辑器
editor.putString("username", username);
editor.putString("password",password);
editor.commit();//类似于数据库的事务,保证数据同时提交
}
}
一个简单的用sharepreference存储代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("bmcq", Context.MODE_PRIVATE); //私有数据
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "bmcq");
editor.putInt("age", 5);
editor.commit();//提交修改
生成的bmcq,xml文件如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">bmcq</string>
<int name="age" value="5" />
</map>
分析以下几个方法:
一、getSharedPreferences(name,mode)
方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上;
方法的第二个参数指定文件的操作模式,共有四种操作模式。
四种操作模式分别为:
MODE_APPEND: 追加方式存储
MODE_PRIVATE: 私有方式存储,其他应用无法访问
MODE_WORLD_READABLE: 表示当前文件可以被其他应用读取
MODE_WORLD_WRITEABLE: 表示当前文件可以被其他应用写入
MODE_MULTI_PROCESS: 适用于多进程访问(目前已被废弃,google官方推荐使用ContentProvider来实现进程间共享访问)
二、edit()方法获取editor对象
Editor editor = sharedPreferences.edit();
editor存储对象采用key-value键值对进行存放,editor.putString(“name”, “wujaycode”);
通过commit()方法提交数据
与之对应的获取数据的方法:
SharedPreferences share=getSharedPreferences(“Acitivity”,Activity.MODE_WORLD_READABLE);
int i=share.getInt(“i”,0);
String str=share.getString(“str”,”“);
boolean flag=share.getBoolean(“flag”,false);
getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
如果你想要删除通过SharedPreferences产生的文件,可以通过以下方法:
File file= new File(“/data/data/”+getPackageName().toString()+”/shared_prefs”,”Activity.xml”);
if(file.exists()){
file.delete();
Toast.makeText(TestActivity.this, “删除成功”, Toast.LENGTH_LONG).show(); }
三、访问其他应用中的Preference
如果要访问其他应用中的Preference,必须满足的条件是,要访问的应用的Preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。
举例,假如有个为com.wujay.action下面的应用使用了下面语句创建了Preference,getSharedPreferences(“wujay”, Context.MODE_WORLD_READABLE),
现在要访问该Preferences:
首先,需要创建上面的Context,然后通过Context访问Preferences,访问preference时会在应用所在包下的shared_prefs目录找到preference:
Context otherAppsContext = createPackageContext(“com.wujay.action”, Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences(“wujay”, 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”);//应替换成应用的包名。
xml文件的存储我用代码给大家展示:
package com.bmcq.write_xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.xmlpull.v1.XmlSerializer;
import com.bmcq.write_xml.domain.info;
import android.support.v7.app.ActionBarActivity;
import android.R.xml;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private List<info> smsinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsinfo = new ArrayList<info>();
Random random = new Random();
Long number = (long) 178565653;
for (int i=0;i<10;i++)
{
smsinfo.add(new info(System.currentTimeMillis(),"短信内容"+i,number+i+"",i));
}
}
/* public void backSMS1(View view) //将信息备份到SD卡中
{//假设获得所有的信息
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<smss>");
for ( info info: smsinfo)
{
sb.append("<sms>");
sb.append("<address>");
sb.append(info.getAddress());
sb.append("</address>");
sb.append("<body>");
sb.append(info.getBody());
sb.append("</body>");
sb.append("<data>");
sb.append(info.getDate());
sb.append("</date>");
sb.append("<type>");
sb.append(info.getType());
sb.append("</type>");
sb.append("</sms>");
}
sb.append("</smss>");
File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
Toast.makeText(this, "备份成功", 0).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "备份失败", 1).show();
}
}*/
public void backSMS2(View view) {
XmlSerializer xmlserializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),"backup2.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
xmlserializer.setOutput(fos, "utf-8");
xmlserializer.startDocument("utf-8", true);
xmlserializer.startTag(null, "smss");
for (info info: smsinfo)
{
xmlserializer.startTag(null, "sms");
xmlserializer.attribute(null, "id", info.getId()+"");
xmlserializer.startTag(null, "data");
xmlserializer.text(info.getDate()+"");
xmlserializer.endTag(null, "data");
xmlserializer.startTag(null, "address");
xmlserializer.text(info.getAddress()+"");
xmlserializer.endTag(null, "address");
xmlserializer.startTag(null, "body");
xmlserializer.text(info.getBody()+"");
xmlserializer.endTag(null, "body");
xmlserializer.endTag(null, "sms");
}
xmlserializer.endTag(null, "smss");
xmlserializer.endDocument();
fos.close();
Toast.makeText(this, "保存成功", 0).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this,"保存失败", 1).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
业务方法:
package com.bmcq.write_xml.domain;
import android.R.integer;
public class info {
private long date;
private String body;
private String address;
private int id;
public info(long date, String body, String address, int id) {
super();
this.date = date;
this.body = body;
this.address = address;
this.id = id;
}
public info() {
super();
// TODO Auto-generated constructor stub
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
布局文件的代码如下:
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bmcq.write_xml"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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>