当前位置: 移动技术网 > IT编程>移动开发>Android > android使用SharedPreferences进行数据存储

android使用SharedPreferences进行数据存储

2019年07月24日  | 移动技术网IT编程  | 我要评论

决意同人,高清裸体美女桌面壁纸,王景曦

很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的qq,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是android应用,我们最适合采用什么方式保存软件配置参数呢?android平台给我们提供了一个sharedpreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用sharedpreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:

sharedpreferences sharedpreferences = getsharedpreferences("ljq", context.mode_private);

editor editor = sharedpreferences.edit();//获取编辑器

editor.putstring("name", "林计钦");

editor.putint("age", 24);

editor.commit();//提交修改 

生成的ljq.xml文件内容如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

<map>

 <string name="name">林计钦</string>

 <int name="age" value="24" />

</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("ljq", 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>为com.ljq.action的应用使用下面语句创建了preference。

getsharedpreferences("ljq", context.mode_world_readable);

其他应用要访问上面应用的preference,首先需要创建上面应用的context,然后通过context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :

context otherappscontext = createpackagecontext("com.ljq.action", context.context_ignore_security);

sharedpreferences sharedpreferences = otherappscontext.getsharedpreferences("ljq", 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>应替换成应用的包名

案例:

string.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="hello">hello world, spactivity!</string>
 <string name="app_name">软件配置参数</string>
 <string name="name">姓名</string>
 <string name="age">年龄</string>
 <string name="button">保存设置</string>
 <string name="showbutton">显示</string>
</resources>

main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" 
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <relativelayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <textview android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:text="@string/name"
   android:textsize="20px"
   android:id="@+id/namelable" />
  <edittext android:layout_width="80px"
   android:layout_height="wrap_content" 
   android:layout_torightof="@id/namelable"
   android:layout_aligntop="@id/namelable"
   android:layout_marginleft="10px"
   android:id="@+id/name" />
 </relativelayout>
 <relativelayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <textview android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:textsize="20px"
   android:text="@string/age"
   android:id="@+id/agelable" />
  <edittext android:layout_width="80px"
   android:layout_height="wrap_content" 
   android:layout_torightof="@id/agelable"
   android:layout_aligntop="@id/agelable"
   android:layout_marginleft="10px"
   android:id="@+id/age" />
 </relativelayout>
 <relativelayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <button android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:text="@string/button"
   android:id="@+id/button" />
  <button android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:text="@string/showbutton"
   android:layout_torightof="@id/button"
   android:layout_aligntop="@id/button"
   android:id="@+id/showbutton" />
 </relativelayout>
 <textview android:layout_width="fill_parent"
   android:layout_height="wrap_content" 
   android:textsize="20px"
   android:id="@+id/showtext" />
</linearlayout>

package com.ljq.activity;

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.widget.button;
import android.widget.edittext;
import android.widget.textview;
import android.widget.toast;

public class spactivity extends activity {
 private edittext nametext;
 private edittext agetext;
 private textview resulttext;
 @override
 public void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
  
  nametext = (edittext)this.findviewbyid(r.id.name);
  agetext = (edittext)this.findviewbyid(r.id.age);
  resulttext = (textview)this.findviewbyid(r.id.showtext);
  
  button button = (button)this.findviewbyid(r.id.button);
  button showbutton = (button)this.findviewbyid(r.id.showbutton);
  button.setonclicklistener(listener);
  showbutton.setonclicklistener(listener);
  
  // 回显
  sharedpreferences sharedpreferences=getsharedpreferences("ljq123", 
    context.mode_world_readable+context.mode_world_writeable);
  string namevalue = sharedpreferences.getstring("name", "");
  int agevalue = sharedpreferences.getint("age", 1);
  nametext.settext(namevalue);
  agetext.settext(string.valueof(agevalue));
 }
 
 private view.onclicklistener listener = new view.onclicklistener(){
  public void onclick(view v) {
   button button = (button)v;
   //ljq123文件存放在/data/data/<package name>/shared_prefs目录下
   sharedpreferences sharedpreferences=getsharedpreferences("ljq123", 
     context.mode_world_readable+context.mode_world_writeable);
   switch (button.getid()) {
   case r.id.button:
    string name = nametext.gettext().tostring();
    int age = integer.parseint(agetext.gettext().tostring());
    editor editor = sharedpreferences.edit(); //获取编辑器
    editor.putstring("name", name);
    editor.putint("age", age);
    editor.commit();//提交修改
    toast.maketext(spactivity.this, "保存成功", toast.length_long).show();
    break;
   case r.id.showbutton:
    string namevalue = sharedpreferences.getstring("name", "");
    int agevalue = sharedpreferences.getint("age", 1);
    resulttext.settext("姓名:" + namevalue + ",年龄:" + agevalue);
    break;
   }
  }
 };
}

运行结果

如何访问其他应用中的preference

package com.ljq.sp;

import java.io.file;
import java.io.fileinputstream;

import android.content.context;
import android.content.sharedpreferences;
import android.test.androidtestcase;
import android.util.log;

public class accesssharepreferencetest extends androidtestcase{
 private static final string tag = "accesssharepreferencetest";
 
 /**
  * 访问sharepreference的方式一,注:权限要足够
  * @throws exception
  */
 public void testaccesspreference() throws exception{
  string path = "/data/data/com.ljq.activity/shared_prefs/ljq123.xml";
  file file = new file(path);
  fileinputstream inputstream = new fileinputstream(file);
  //获取的是一个xml字符串
  string data = new fileservice().read(inputstream);
  log.i(tag, data);
 }
 
 /**
  * 访问sharepreference的方式二,注:权限要足够
  * @throws exception
  */
 public void testaccesspreference2() throws exception{
  context context = this.getcontext().createpackagecontext("com.ljq.activity", 
    context.context_ignore_security);
  sharedpreferences sharedpreferences = context.getsharedpreferences("ljq123", 
    context.mode_world_readable+context.mode_world_writeable);
  string name = sharedpreferences.getstring("name", "");
  int age = sharedpreferences.getint("age", 1);
  log.i(tag, name + " : " +age);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网