Android 提供了2种可选的数据存储方式,分别是:内部存储(Shared Preferences,File,Database),外部存储(SDCard,网络存储)。 至于选用里面的哪种主要取决于下面2个原因:
1.数据是否公开给其他APP使用?
2.需要多大的存储空间?
Android利用Content Provider 可以把当前APP的私有数据暴露给其他APP。其他APP可以读写操作你的APP数据。
一、Shared Preferences
生命周期:存储在shared preferences的数据,可以被你整个APP程序使用,即时你的APP被KILL掉了,数据还是会保存在那里,实际上就是以XML的形式保存在data/data/你的包名/shared_prefs/目录下面, 文件名:你的perferences名称.xml
适用场景:数据量比较少; 是key-value的基本数据类型,例如:boolean, float,int,long,和string。
测试例子:
写入数据:
//get the preferences, then editor, set a data item
SharedPreferences appPrefs = getSharedPreferences("config", 0);
SharedPreferences.Editor prefsEd = appPrefs.edit();
prefsEd.putString("site", "www.ahuoo.com");
prefsEd.commit();
你可以在其他activity读取site的值:
//get the preferences then retrieve saved data, specifying a default value
SharedPreferences appPrefs = getSharedPreferences("config", 0);
String savedData = appPrefs.getString("site", "www.ahuoo.com");
通过eclipse的 File Explorer窗口,可以查看shared preferences在模拟器里面的存储情况, 打开对应的preferences文件config.xml文件,内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="site">www.ahuoo.com</string> </map>
更多内容参看PPT>>>>>>>>>>>>>>>>>>>>>>>下载 Android存储.pptx
Activity A 中的write data测试代码:
//sharedPreferences storage
SharedPreferences sp = getSharedPreferences("config",Context.MODE_PRIVATE);
String state = sp.getString("state", "");
ToastUtil.shortTips(mContext, state);
if(state.equals("")){
SharedPreferences.Editor edit = sp.edit();
edit.putString("state", "category list activity");
edit.putBoolean("bKey", true);
edit.putFloat("fKey", 0.57f);
edit.putLong("lKey", 23423L);
edit.putInt("iKey", 33);
edit.commit();
ToastUtil.shortTips(mContext, sp.getString("state", "null-2"));
}
//file storage
try {
FileOutputStream fos = this.openFileOutput("test.txt",Context.MODE_PRIVATE);
fos.write("file storage: hello.".getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
//sd card
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdDir = Environment.getExternalStorageDirectory();
Log.v(TAG,"sdDir=" + sdDir);
File file = new File(sdDir,"sd.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("sd storage: world.".getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//database
SQLiteDatabase db = this.openOrCreateDatabase("test2.db", Context.MODE_PRIVATE, null);
String sql = "create table if not exists tb_test(id integer default '1' not null primary key autoincrement," +
"name text not null," +
"content text not null)";
db.execSQL(sql);
for(int i=0; i<5; i++){
String sqlInsert = "insert into tb_test(name,content) values('ahu"+i+"','我是阿虎,批量插入')";
db.execSQL(sqlInsert);
}
ContentValues cv = new ContentValues();
cv.put("name", "caih");
cv.put("content", "我是阿虎,ContentValues插入的");
db.insert("tb_test",null,cv);
db.close();
在另外一个activity B里面使用这些存储方式的测试代码:
//sharedPreferences
SharedPreferences sp = getSharedPreferences("config",0);
String state = sp.getString("state", "null-3");
ToastUtil.shortTips(mContext, state);
SharedPreferences.Editor edit = sp.edit();
edit.putString("state", "goods list activity");
edit.commit();
ToastUtil.shortTips(mContext, sp.getString("state", "null-4"));
//file storage
try {
FileInputStream fis = this.openFileInput("test.txt");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=fis.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
ToastUtil.shortTips(mContext, bos.toString());
bos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//sd card storage
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(),"sd.txt"));
byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer();
while(fis.read(buffer)!=-1){
sb.append(new String(buffer));
}
ToastUtil.shortTips(mContext, sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
//raw folder
try {
Resources res = this.getResources();
InputStream is = res.openRawResource(R.raw.appconfig);
byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer();
while(is.read(buffer) != -1){
ToastUtil.shortTips(mContext, "raw file content: " + new String(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
//database
SQLiteDatabase db = this.openOrCreateDatabase("test2.db", Context.MODE_PRIVATE, null);
Cursor cur = db.rawQuery("select * from tb_test order by id desc limit 5 ", null);
while(cur.moveToNext()){
int id = cur.getInt(cur.getColumnIndex("id"));
String name = cur.getString(cur.getColumnIndex("name"));
String content = cur.getString(2);
Log.i(TAG, id + "," + name + "," + content);
}
cur.close();
db.close();