Android本地数据存储之Sharedpreference
转载请标明出处:http://blog.csdn.net/wu_wxc/article/details/49358459
本文出自【吴孝城的CSDN博客】
Sharedpreference用来保存Android软件的配置参数,Android的设置,音效开关等等信息
它最终以.xml文件保存在/data/data/<page name>/shared_prefs里
Android Studio中查看方法
Tool >> Android >> Android Device >> Monitor
第一次打开会有一个发送什么到谷歌的,直接回车就行,
打开后在DDMS >> File Explore >> data >> data >> (包名) >> shared_prefs
默认没有shared_prefs文件夹的,只有在运行了Sharedpreference方法之后都有
如果没有开模拟器的话,打开后看到的内容是空白的
可以点击右边指出的推送将选中的xml文件推到电脑上打开查看,也可点击拉入一个文件,可删除选中的文件,旁边的“+”只有在选中文件夹时才有效
下面一个小例子
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <!--android:ems="10"textview或editview宽度为10个字符长度 只显示10个字符多出的不显示--> <EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="18dp" android:ems="10" android:hint="输入名字" /> <Button android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/name" android:layout_alignLeft="@+id/name" android:layout_marginTop="18dp" android:layout_marginLeft="48dp" android:text="保存"/> <!--android:layout_alignBaseline="@+id/save" 与cancel控件对齐 --> <Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/save" android:layout_alignLeft="@+id/save" android:layout_marginTop="10dp" android:text="查看"/> <Button android:id="@+id/clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/read" android:layout_alignLeft="@+id/read" android:layout_marginTop="10dp" android:text="清除"/> <Button android:id="@+id/del" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/clear" android:layout_alignLeft="@+id/clear" android:layout_marginTop="10dp" android:text="删除"/></RelativeLayout>
MainActivity.java
package cn.wuxiaocheng.sharedpreferences;import android.content.Context;import android.content.SharedPreferences;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.content.SharedPreferences.Editor;import android.widget.Toast;import java.io.File;public class MainActivity extends AppCompatActivity{ private TextView tvname; //用数组定义按钮 private int[] buttons = {R.id.save, R.id.read, R.id.clear, R.id.del}; private Button[] button = new Button[buttons.length]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvname = (TextView) findViewById(R.id.name); //找到按钮和设置监听 Choosebtn btn = new Choosebtn(); for (int i=0; i<buttons.length; i++){ button[i] = (Button) findViewById(buttons[i]); button[i].setOnClickListener(btn); } } //内部类实现按钮点击 class Choosebtn implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()){ case R.id.save: String name = tvname.getText().toString(); SaveData(name); break; case R.id.read: load(MainActivity.this); break; case R.id.clear: clearSP(); break; case R.id.del: del(); break; } } } //保存输入的内容到SharedPreferences private void SaveData(String name) { /*getSharedPreferences(name, mode) 第一参数是xml文件的文件名,不用加后缀,后缀Android会自动加上 第二个参数是文件的操作类型 Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件 Context.MODE_PRIVATE:可写为0,私有方法,只有创建这个文件的程序才能访问,写入的数据会覆盖原文件的内容 Context.MODE_WORLD_READABLE:可写为2当前文件可被其他文件读取 Context.MODE_WORLD_WRITEABLE:可写为1,当前文件可被其他文件读取和写稿*/ SharedPreferences sp = getSharedPreferences("username", Context.MODE_WORLD_READABLE); //通过Editor对象以键值对<String Key,String Value>存储数据 Editor editor = sp.edit(); editor.putString("savename", name); //通过.commit()方法保存数据 editor.commit(); /*清除数据 editor.clear().commit();*/ } //读取SharedPreferences内容 private void load(Context context) { //用xml文件名拿里面的内容,后面权限可不一样。 SharedPreferences sp = context.getSharedPreferences("username", Context.MODE_WORLD_READABLE); //.getString("savename","没有保存数据")第一个参数为文件内的name,方法的第二个参数为缺省值,如果SharedPreferences没有该参数,将返回缺省值 Toast.makeText(MainActivity.this, sp.getString("savename","没有保存数据").toString(),Toast.LENGTH_SHORT).show(); } //清除SharedPreferences内容 private void clearSP(){ SharedPreferences sp = getSharedPreferences("username", 0); Editor editor = sp.edit(); //用clear()方法清除数据,commit()保存清除结果 editor.clear().commit(); Toast.makeText(MainActivity.this, "清除成功", Toast.LENGTH_SHORT).show(); } //想删除Sharepreference文件 private void del(){ //自动获取包名,定位到username.xml文件 File file= new File("/data/data/"+getPackageName().toString()+"/shared_prefs","username.xml"); if(file.exists()){ //删除username.xml文件 file.delete(); //当文件删除成功时弹出吐司 Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_LONG).show(); } }}
界面如下
输入内容,点击保存,会保存到xml文件中,导出xml文件,打开看
username.xml
点击查看,会看到一个显示查询结果的吐司
想要访问另外一个程序的Sharedpreference
可用Context otherAppsContext = createPackageContext("cn.wuxiaocheng.sharedpreferences", Activity.CONTEXT_IGNORE_SECURITY);方法
activity_name.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/con" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="用Context查询"/></RelativeLayout>
MainActivity.java
package cn.wuxiaocheng.preference;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.con); btn.setOnClickListener(this); } @Override public void onClick(View v) { context(); } private void context() { //定义一个Context,初始化为null; Context otherAppContext = null; try { /*创建其他包的上下文 第一个参数为被读取的程序的包名 第二个参数有两个方法 CONTEXT_INCLUDE_CODE的意思是包括代码,也就是说可以执行这个包里面的代码 CONTEXT_IGNORE_SECURITY的意思是忽略安全警告 前面的Activity可以换成Context 如果不加这个标志的话,有些功能是用不了的,会有安全警告*/ otherAppContext = createPackageContext("cn.wuxiaocheng.sharedpreferences", Activity.CONTEXT_IGNORE_SECURITY); } catch (Exception e) { e.printStackTrace(); } //定义一个SharedPreferences,用来存放拿到的xml文件 SharedPreferences sharedPreferences = otherAppContext.getSharedPreferences("username", Activity.MODE_WORLD_READABLE); //拿到文件里name为savename的内容,如果没有内容返回缺省值,输出"没有啦" String name = sharedPreferences.getString("savename", "没有啦"); //吐司输出内容 Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show(); }}
不想用Context还可以直接访问其他程序的xml文件,
File xmlFile = new File(“/data/data/<package name>/shared_prefs/zkliu.xml”);
<package name>替换成被访问的应用的包名
获取SharedPreferences的两种方式:
1 调用Context对象的getSharedPreferences()方法,获得的SharedPreferences对象可以被同一应用程序下的其他组件共享
2 调用Activity对象的getPreferences()方法,获得的SharedPreferences对象只能在该Activity中使用
源码下载
更多相关文章
- Android中视频播放以及解码
- 如何查看无法导出的android数据库文件?
- Android(安卓)Studio 如何引用aar包
- ADT在线安装(http://dl-ssl.google.com/android/eclipse 打不开)
- Android学习笔记(二三): 多页显示-Flipper的使用
- Arcgis android 10.2安装方法
- Android(安卓)studio 打不开官方虚拟机 100%成功解决方法
- React Native 官方文档中文版(含最新Android内容)
- 输入法软键盘搜索执行两次的解决方法