使用SharedPreferences进行数据存储

来源:互联网 发布:并行程序设计 书 知乎 编辑:程序博客网 时间:2024/06/05 18:20

保存数据

Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/包名/shared_prefs目录下

如果不知道如何查看请点击 Android Studio查看模拟机中文件

SharedPreferences sharedPreferences = getSharedPreferences("wlh", Context.MODE_PRIVATE);Editor editor = sharedPreferences.edit();//获取编辑器editor.putString("name", "王力宏");editor.putInt("age", 41);editor.commit();//提交修改

生成的wlh.xml文件内容如下

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map>   <string name="name">王力宏</string>   <int name="age" value="41" /></map>

getSharedPreferences(name,mode)方法
第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上

第二个参数指定文件的操作模式,共有四种操作模式,如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限

另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称

访问数据

SharedPreferences sharedPreferences = getSharedPreferences("wlh", 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权限

例如有个包名为com.wlh.action的应用使用下面语句创建了preference
getSharedPreferences(“wlh”, Context.MODE_WORLD_READABLE);

其他应用要访问上面应用的preference
1、首先需要创建上面应用的Context
2、然后通过Context 访问preference,应用所在包下的shared_prefs目录找到preference

Context otherAppsContext = createPackageContext("com.wlh.action", Context.CONTEXT_IGNORE_SECURITY);SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("wlh", Context.MODE_WORLD_READABLE);String name = sharedPreferences.getString("name", "");int age = sharedPreferences.getInt("age", 0);

读取xml文件方式直接访问

如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件

File xmlFile = new File("/data/data/包名/shared_prefs/itcast.xml");

练习

strings.xml

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

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:orientation="vertical">    <LinearLayout        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"            />        <EditText            android:id="@+id/name"            android:layout_width="80dp"            android:layout_height="wrap_content"/>    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/age"            />        <EditText            android:id="@+id/age"            android:layout_width="80dp"            android:layout_height="wrap_content"/>    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content">        <Button            android:id="@+id/button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/button"/>        <Button            android:id="@+id/showButton"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/showButton"/>    </LinearLayout>    <TextView        android:id="@+id/showText"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>

MainActivity

import android.support.v7.app.AppCompatActivity;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 MainActivity extends AppCompatActivity {    private EditText nameText;    private EditText ageText;    private TextView resultText;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_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("wlh",                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;            SharedPreferences sharedPreferences=getSharedPreferences("wlh",                    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(MainActivity.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;            }        }    };}

运行结果

运行结果

原创粉丝点击