四種Android數(shù)據(jù)存儲方式
Android提供以下四種存儲方式:
- SharePreference
- SQLite
- File
- ContentProvider
Android系統(tǒng)中數(shù)據(jù)基本都是私有的,一般存放在“data/data/程序包名”目錄下。如果要實(shí)現(xiàn)數(shù)據(jù)共享,正確的方式是使用ContentProvider。
SharedPreference
SharedPreference是一種輕型的數(shù)據(jù)存儲方式,實(shí)際上是基于XML文件存儲的“key-value”鍵值對數(shù)據(jù)。通常用來存儲程序的一些配置信息。其存儲在“data/data/程序包名/shared_prefs目錄下。
SharedPreference本身只能獲取數(shù)據(jù),不支持存儲和修改。存儲和修改要通過Editor對象來實(shí)現(xiàn)。
1)、修改和存儲數(shù)據(jù)
- 根據(jù)Context的getSharedPrerences(key, [模式])方法獲取SharedPreference對象;
- 利用SharedPreference的editor()方法獲取Editor對象;
- 通過Editor的putXXX()方法,將鍵值對存儲數(shù)據(jù);
- 通過Editor的commit()方法將數(shù)據(jù)提交到SharedPreference內(nèi)。
綜合例子:
//設(shè)置單例里面的數(shù)值,然后再將數(shù)值寫入到SharedPreference里
private String setCityName(String _cityName){
City.getCity().setCityName(_cityName);
Context ctx =MainActivity.this;
SharedPreferences sp =ctx.getSharedPreferences("CITY", MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("CityName", City.getCity().getCityName());
editor.commit();
return City.getCity().getCityName();
}
2)、獲取數(shù)據(jù)
- 同樣根據(jù)Context對象獲取SharedPreference對象;
- 直接使用SharedPreference的getXXX(key)方法獲取數(shù)據(jù)。
綜合例子:
//從單例里面找,如果不存在則在SharedPreferences里面讀取
private String getCityName(){
String cityName = City.getCity().getCityName();
if(cityName==null ||cityName==""){
Context ctx =MainActivity.this;
SharedPreferences sp =ctx.getSharedPreferences("CITY", MODE_PRIVATE);
City.getCity().setCityName(sp.getString("CityName", "廣州"));
}
return City.getCity().getCityName();
}
注意
getSharedPrerences(key, [模式])方法中,第一個(gè)參數(shù)其實(shí)對應(yīng)到XML的文件名,相同key的數(shù)據(jù)會(huì)保存到同一個(gè)文件下。
使用SharedPreference的getXXX(key)方法獲取數(shù)據(jù)的時(shí)候,如果key不存在的活,不會(huì)出現(xiàn)報(bào)錯(cuò),會(huì)返回none。建議使用getXXX()的時(shí)候指定默認(rèn)值。
SQLite
SQLite是一個(gè)輕量級關(guān)系型數(shù)據(jù)庫,既然是關(guān)系型數(shù)據(jù)庫,那操作起來其實(shí)跟mysql、sql server差不多的。
需要注意的一點(diǎn)是,SQLite只有NULL、INTEGER、REAL(浮點(diǎn)數(shù))、TEXT(字符串)和BLOB(大數(shù)據(jù))五種類型,不存在BOOLEAN和DATE類型。
1)、創(chuàng)建數(shù)據(jù)庫
通過openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)方法創(chuàng)建,如果庫已創(chuàng)建,則打開數(shù)據(jù)庫。
2)、創(chuàng)建表
SQLiteDatabase沒有提供創(chuàng)建表的方法,所以要靠execSQL()方法來實(shí)現(xiàn)??疵忠仓纄xecSQL()用于直接執(zhí)行sql的。
db.execSQL(sql);
增
使用SQLiteDatabase的insert(String table, String nullColumnHack, ContentValues values)方法插入數(shù)據(jù)。ContentValues 類,類似于java中的Map,以鍵值對的方式保存數(shù)據(jù)。
ContentValues values=new ContentValues();
values.put("name", "liangjh");
values.put("password", "123456");
db.insert("t_user", "id", values);
刪
刪除數(shù)據(jù)就比較直接了。使用SQLiteDatabase的delete(String table, String whereClause, String[] whereArgs)實(shí)現(xiàn)。如果不想把參數(shù)寫在whereArgs里面,可以直接把條件寫在whereClause里面。
// 方式1 直接將條件寫入到條件里面(個(gè)人覺得容易被注入,但其實(shí)數(shù)據(jù)都在客戶端,沒啥安全性可言)
db.delete("t_user", "id=1", null);
// 方式2 條件分開寫,感覺比較安全
db.delete("t_user", "name=? and password =?", new String[]{"weiyg","112233"});
查
查詢有2個(gè)方法,query()和rawQuery()兩個(gè)方法,區(qū)別在于query()是將sql里面的各參數(shù)提取出query()對應(yīng)的參數(shù)中??蓞⒖枷旅胬印?/p>
// 使用rawQuery
// Cursor c = db.rawQuery("select * from t_user", null);
// db.rawQuery("select * from t_user where id=1", null);
// db.rawQuery("select * from t_user where id=?", new String[]{"1"});
// 使用query()
Cursor c = db.query("t_user", new String[]{"id","name"}, "name=?", new String[]{"weiyg"}, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()){
String msg="";
for(int i=0,j=c.getColumnCount();i<j;i++){
msg+="--"+c.getString(i);
}
Log.v("SQLite", "data:"+msg);
c.moveToNext();
}
改
使用SQLiteDatabase的update(String table, ContentValues values, String whereClause, String[] whereArgs)可以修改數(shù)據(jù)。whereClause和whereArgs用于設(shè)置其條件。ContentValues對象為數(shù)據(jù)。
ContentValues values=new ContentValues();
values.put("password", "111111");
// 方式1 條件寫在字符串內(nèi)
db.update("t_user", values, "id=1", null);
// 方式2 條件和字符串分開
db.update("t_user", values, "name=? or password=?",new String[]{"weiyg","123456"});
其它
無論何時(shí),打開的數(shù)據(jù)庫,記得關(guān)閉。
db.close()
另外使用beginTransaction()和endTransaction()可以設(shè)置事務(wù)。
File
文件儲存方式,很久以前講過,這里不說明。
ContentProvider
ContentProvider相對于其它的方式比較復(fù)雜,當(dāng)然其功能相對于其它的方式也是革命性的改變。它能夠?qū)崿F(xiàn)跨應(yīng)用之間的數(shù)據(jù)操作。利用ContentResolver對象的delete、update、insert、query等方法去操ContentProvider的對象,讓ContentProvider對象的方法去對數(shù)據(jù)操作。實(shí)現(xiàn)方式為:
在A程序中定義一個(gè)ContentProvider,重載其增刪查改等方法;
在A程序中的AndroidManifest.xml中注冊ContentProvider;
在B程序中通過ContentResolver和Uri來獲取ContentProvider的數(shù)據(jù),同樣利用Resolver的增刪查改方法來獲得和處理數(shù)據(jù)。
1)、在A程序定義一個(gè)Provider
新建一個(gè)類,繼承ContentProvider,并重載其delete()、insert()、query()、update()、getType()、onCreate()方法。譬如下面的例子,重載其onCreate和query方法。
public class MyProvider extends ContentProvider {
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreate() {
// 新建個(gè)數(shù)據(jù)庫并插入一條數(shù)據(jù)
SQLiteDatabase db=this.getContext().openOrCreateDatabase("test_db2.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE t_user (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)");
ContentValues values=new ContentValues();
values.put("name", "liangjh2");
db.insert("t_user", "id", values);
db.close();
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// 獲取數(shù)據(jù)
SQLiteDatabase db=this.getContext().openOrCreateDatabase("test_db2.db", Context.MODE_PRIVATE, null);
Cursor c = db.query("t_user", null, null, null, null, null, null);
db.close();
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
注冊ContentProvider
在AndroidManifest.xml中聲明ContentProvider,authorities屬性定義了ContentProvider的Uri標(biāo)識。關(guān)于Uri標(biāo)識屬另一個(gè)范疇,自行查詢。provider標(biāo)識要放在<application></application>里面。如果遇到了"Permission Denial: opening provide..."的錯(cuò)誤,可以試試在節(jié)點(diǎn)加“android:exported="true"”。
<application ...> ... <provider android:name=".MyProvider" android:authorities="com.example.androidtestdemo" android:exported="true"/> </application>
2)、在B程序獲取數(shù)據(jù)
用Context獲取到當(dāng)前的ContentResolver,根據(jù)Uri地址和ContentResolver的query方法獲取A程序的數(shù)據(jù)。Uri地址和A程序中AndroidManifest.xml定義的autorities要一致。當(dāng)然,同類可以進(jìn)行其它的操作。
Context ctx=MainActivity.this;
ContentResolver resolver =ctx.getContentResolver();
Uri uri=Uri.parse("content://com.example.androidtestdemo");
Cursor c = resolver.query(uri, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()){
for(int i=0,j=c.getColumnCount();i<j;i++){
Log.v("Android2",""+c.getString(i));
}
c.moveToNext();
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
- android中使用SharedPreferences進(jìn)行數(shù)據(jù)存儲的操作方法
- Android開發(fā)筆記之: 數(shù)據(jù)存儲方式詳解
- 在android開發(fā)中進(jìn)行數(shù)據(jù)存儲與訪問的多種方式介紹
- Android使用文件進(jìn)行數(shù)據(jù)存儲的方法
- Android 數(shù)據(jù)存儲之 FileInputStream 工具類及FileInputStream類的使用
- Android 數(shù)據(jù)存儲方式有哪幾種
- Android編程中的5種數(shù)據(jù)存儲方式
- Android數(shù)據(jù)存儲之SQLite使用
- Android通過記住密碼功能學(xué)習(xí)數(shù)據(jù)存儲類SharedPreferences詳解及實(shí)例
- Android平臺中實(shí)現(xiàn)數(shù)據(jù)存儲的5種方式
相關(guān)文章
Android實(shí)現(xiàn)圖片異步請求加三級緩存
這篇文章主要向大家詳細(xì)介紹了Android實(shí)現(xiàn)圖片異步請求加三級緩存的相關(guān)資料,需要的朋友可以參考下2016-02-02
Android開發(fā)實(shí)現(xiàn)TextView顯示豐富的文本
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)TextView顯示豐富的文本,涉及Android中TextView的使用技巧,需要的朋友可以參考下2015-12-12
android使用surfaceview+MediaPlayer播放視頻
這篇文章主要為大家詳細(xì)介紹了android使用surfaceview+MediaPlayer播放視頻,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
Android 8.0如何完美適配全局dialog懸浮窗彈出
這篇文章主要給大家介紹了關(guān)于Android 8.0如何完美適配全局dialog懸浮窗彈出的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起看看吧2018-07-07
Android超詳細(xì)講解組件AdapterView的使用
AdapterView組件是一組重要的組件,AdapterView本身是一個(gè)抽象基類,它派生的子類在用法上十分相似,從AdapterView派生出的三個(gè)子類:AdsListView、AdsSpinner、AdapterViewAnimator,這3個(gè)子類依然是抽象的,實(shí)際運(yùn)用時(shí)需要它們的子類2022-03-03
Android開發(fā)之拼音轉(zhuǎn)換工具類PinyinUtils示例
這篇文章主要介紹了Android開發(fā)之拼音轉(zhuǎn)換工具類PinyinUtils,涉及Android基于pinyin4j-2.5.0.jar包文件實(shí)現(xiàn)漢字轉(zhuǎn)拼音功能的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
android開發(fā)中ListView與Adapter使用要點(diǎn)介紹
項(xiàng)目用到ListView,由于要用到 ImageView ,圖片源不是在資源里面的,沒法使用資源 ID,因此無法直接使用SimpleAdapter,要自己寫一個(gè)Adapter。 在使用ListView和Adapter需要注意以下幾點(diǎn)2013-06-06
Android Studio配置Kotlin開發(fā)環(huán)境詳細(xì)步驟
這篇文章主要介紹了Android Studio配置Kotlin開發(fā)環(huán)境詳細(xì)步驟的相關(guān)資料,需要的朋友可以參考下2017-05-05

