在Android中,实现数据持久化有五种方式:Preferences,文件File,I/O操作、SQLite数据库,ContentProvider组件。
下面逐个做一简单的介绍:
一、Preferences的介绍:
Preferences是一种轻量级的数据存储机制,他将一些简单的数据类型的数据,包括boolean类型,int类型,float类型,long类型以及String类型的数据,以键值对的形式存储在应用程序的私有Preferences目录(/data/data/<包名>/shared_prefs/)中,这种Preferences机制广泛应用于存储应用程序中的配置信息。
如下是Preferences的一个简单代码:
这个代码是创建不同权限的数据对象:
package com.example.data_sharedpreferences;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 写入数据
writeData();
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 读取数据
readData();
}
});
}
/**
* 写入数据
*/
public void writeData() {
// 设置权限为私有MODE_PRIVATE
SharedPreferences sp_p = this.getSharedPreferences("ct_sp_private",
Context.MODE_PRIVATE);
// 通过SharedPreferences对象的编辑器对象Editor来实现存入数据
SharedPreferences.Editor editor = sp_p.edit();
// 通过该编辑器函数设置键值
editor.putString("username", "marry_private");
// 提交数据,并将数据写入xml文件中
editor.commit();
// 设置为只读
SharedPreferences sp_or = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_READABLE);
sp_or.edit().putString("username", "marry_only_read").commit();
// 设置为只写
SharedPreferences sp_ow = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_WRITEABLE);
sp_ow.edit().putString("username", "marry_only_write").commit();
// 设置为可读可写
SharedPreferences sp_x = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
sp_x.edit().putString("username", "marry_write_read").commit();
}
/**
* 读取数据
* 通过SharedPreferences对象的键key可以获取到对应key的键值value。对于不同类型的键值有不同的函数:getBoolean
* ,getInt,getFloat,getLong.
*/
public void readData() {
// TODO Auto-generated method stub
text.setText("private_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_private")
+ "\r\n"
+ "read_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_only_read")
+ "\r\n"
+ "write_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_only_write")
+ "\r\n"
+ "write_read_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_write_read") + "\r\n");
}
@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;
}
}
下面这个代码则是实现在另外一个应用中访问上一个应用,并读取上面应用的数据:
package com.example.data_sharedpreferences2;
import com.example.data_sharedpreferences2.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* 该程序的功能是访问data_sharedpreferences应用 Sharedpreferences访问另一个应用的条件:
* 1、被访问的应用权限为可读或者可写 2、必须要知道被访问应用的包名
*
* @author marry
*
*/
public class MainActivity extends Activity {
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 访问应用1,并读取应用1的数据
try {
// 获得要访问应用的context
Context ortherContext = createPackageContext(
"com.example.data_sharedpreferences", 0);
// 通过ortherContext.getSharedPreferences打开应用1的文件
text.setText("private_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_private")
+ "\r\n"
+ "read_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_only_read")
+ "\r\n"
+ "write_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_only_write")
+ "\r\n"
+ "write_read_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_write_read") + "\r\n");
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@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;
}
}
使用Preferences时有以下需要注意的地方:
1、 通过Context.getSharedPreferences(String fileName,int mode)方法,可以打开一个xml文件,文件的位置在/data/data/package_name/shared_prefs/fileName.xml,如果不存在,则会自动创建。可以对该文件进行读写操作,在应用内的各组件之间共享数据。如果将mode设置为Context.MODE_WORLD_READ或者Context.MODE_WORLD_WRITE,则还可以被其他应用访问到。不过这不是android推荐的方式,要实现跨应用共享数据,推荐的方式是用ContentProvider实现
2、 如果要访问另一个应用创建的shared_prefs文件,需要满足2个条件,首先另一个应用要设置MODE_WORLD_READ或MODE_WORLD_WIRTE权限,并且要知道另一个应用的package_name,然后就可以通过Context.createPackageContext()方法,就可以得到另一个应用的context,然后context.getSharedPreferences()方法,就可以打开shared_prefs文件了。不过这种方法并不推荐
3、 在罕见的情况下,如果既把shared_prefs的权限设置为MODE_PRIVATE,又希望某些其他的应用可以访问到,那么可以在manifest文件中配置android:user_id(好像是这个属性),让多个应用共享USER_ID。因为本质上shared_prefs文件是采用linux的权限控制的,MODE_PRIVATE类似于-rw-------,所以如果多个应用使用了同一个USER_ID,自然都对这个文件有访问权限了
分享到:
相关推荐
本文实例讲述了Android数据持久化之Preferences机制。分享给大家供大家参考,具体如下: 在Android中,实现数据持久化有五种方式:Preferences,文件File,I/O操作、SQLite数据库,ContentProvider组件。 下面逐个做...
小编今天研究了在Unity3D中的数据持久化问题。数据持久化在任何一个开发领域都是一个值得关注的问题,小到一个应用中配置文件的读写,大到数据库的管理维护,都可以看到数据持久化的身影。小编在《C#基于Linq和反射...
Android数据存取之Preferences 这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法基本上和J2SE(java.util.prefs.Preferences)中的用法一样,以一种简单、 透明的方式来保存一些用户个性化设置的...
NULL 博文链接:https://byandby.iteye.com/blog/833292
Compatible with kotlin android and kotlin native for iphone class MyPresenter { val preferences = Preferences() fun start(){ preferences.getString("userName")?.let { view.displayUser(it) } val...
android-secure-preferences About This project uses the Encryption class from: http://www.java2s.com/Code/Android/Security/AESEncryption.htm Gives an implementation of SharedPreferences, which encrypts...
Android 使用Shared Preferences进行数据存储-样例,演示如何使用 Shared Preferences 获得数据和保存数据、如何使用getPreferences方法创建文件的模式,以及如何使用getPreferences模拟用户参数设置、查看 ...
Reactive SharedPreferences for Android. Usage Create an RxSharedPreferences instance which wraps a SharedPreferences: SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences...
安卓 数据存储 Preferences
Android Shared Preferences Helper Android Library to handle SharedPreferences boilerplate code and other tools Download dependencies { compile 'com.github.seanzor:shared-preferences-helper:1.1.0' }...
实验报告评语与评分: 评阅老师签名: 一、实验名称:Android数据存储与IO 二、实验日期:2014/11/13 三、实验目的: 1、掌握SharedPreferences的存储数据的格式及位置,能够读写其他应用程序的Shared Preferences。...
This is Android Shared preference wrapper that encrypts the values of Shared Preferences using AES 128, CBC, and PKCS5 padding with integrity checking in the form of a SHA 256 hash. Each key is stored...
NULL 博文链接:https://liyf155.iteye.com/blog/1455717
Tutorial Android Preferences
关于android的数据存储-SQLite-ContentProvider-preferences
移动开发技术(Android)——实验1Android开发环境搭建及简单程序实现 移动开发技术(Android)——实验1 Android开发环境搭建及简单程序实现 ⼀、实验⽬的 1.熟练掌握Android开发环境搭建步骤; 2.掌握Android应...
FastSave is An Android library for fast and easy access to Android Shared preferences. It allows you to save any type or list in the sharedpreferences and retrieve it in convenient way. Installation ...
介绍Android是如何对数据进行处理的,包括数据库Sqlite、ContentProvider、Preferences、文件I/O的处理
Android高手进阶教程之----Android 中Preferences的使用! .doc Android高手进阶教程之----Android 中自定义View的应用.doc Android高手进阶教程之----Android 中自定义属性(attr.xml,TypedArray)的使用! .doc ...