Android數(shù)據(jù)存儲(chǔ)方式操作模式解析
SharedPreferences
在開(kāi)發(fā)過(guò)程中,數(shù)據(jù)存取是較為頻繁的,今天我們來(lái)了解下android幾種常見(jiàn)的數(shù)據(jù)存取方式。
在Android中,sharePreferences是一種輕量級(jí)的數(shù)據(jù)存儲(chǔ)方式,采用鍵值對(duì)的存儲(chǔ)方式,存儲(chǔ)少量數(shù)據(jù),支持基本類(lèi)型的簡(jiǎn)單數(shù)據(jù)存儲(chǔ)。
基本用法
- 根據(jù)Context獲取SharedPreferences對(duì)象
- 利用edit()方法獲取Editor對(duì)象。
- 通過(guò)Editor對(duì)象存儲(chǔ)key-value鍵值對(duì)數(shù)據(jù)。
- 通過(guò)commit()方法提交數(shù)據(jù)。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//獲取SharedPreferences對(duì)象
Context ctx = MainActivity.this;
//第一個(gè)參數(shù)指定存儲(chǔ)文件名,第二個(gè)參數(shù)指定操作模式
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
//存入數(shù)據(jù)
Editor editor = sp.edit();
editor.putString("STRING_KEY", "string");
editor.putInt("INT_KEY", 0);
editor.putBoolean("BOOLEAN_KEY", true);
editor.commit();
//返回STRING_KEY的值 設(shè)定默認(rèn)值
Log.d("SP", sp.getString("STRING_KEY", "none"));
//如果NOT_EXIST不存在,則返回值為"none"
Log.d("SP", sp.getString("NOT_EXIST", "none"));
//刪除指定數(shù)據(jù)
editor.remove("STRING_KEY");
editor.commit();
//清空數(shù)據(jù)
editor.clear();
editor.commit();
}
}
操作模式
- MODE_PRIVATE 指定該SharedPreferences數(shù)據(jù)只能被本應(yīng)用程序讀、寫(xiě)。這是默認(rèn)模式。
- MODE_APPEND 該模式會(huì)檢查文件是否存在,存在就將數(shù)據(jù)寫(xiě)到文件末尾,否則就創(chuàng)建新文件。
- MODE_WORLD_READABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀,但不能寫(xiě)。該模式已棄用。
- MODE_WORLD_WRITEABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序?qū)憽?strong>該模式已棄用。
ContentProvider
基本概念
屬于Android四大組件之一,用于進(jìn)程間進(jìn)行數(shù)據(jù)交互,從而能夠讓其他的應(yīng)用保存或讀取此Content Provider的各種數(shù)據(jù)類(lèi)型。簡(jiǎn)單來(lái)說(shuō),一個(gè)程序可以通過(guò)實(shí)現(xiàn)一個(gè)Content Provider的抽象接口將自己的數(shù)據(jù)暴露出去。外界根本看不到,也不用看到這個(gè)應(yīng)用暴露的數(shù)據(jù)在應(yīng)用當(dāng)中是如何存儲(chǔ)的,或者是用數(shù)據(jù)庫(kù)存儲(chǔ)還是用文件存儲(chǔ),還是通過(guò)網(wǎng)上獲得。
統(tǒng)一資源標(biāo)識(shí)符(URI)
content://com.example.myapplication.provider/tablename/1
- content 主題名,URI前綴。
- com.example.myapplication.provider 授權(quán)信息,Content Provider唯一標(biāo)識(shí)符。
- tablename Content Provider 指向數(shù)據(jù)庫(kù)中的某個(gè)表名。
- 1 表中某個(gè)記錄,若無(wú)指定,返回全部記錄。
基本使用
創(chuàng)建Content Provider
- 創(chuàng)建一個(gè)繼承了ContentProvider父類(lèi)的類(lèi)
- 定義一個(gè)名為CONTENT_URI,并且是
public static final的Uri類(lèi)型的類(lèi)變量,必須為其指定一個(gè)唯一的字符串值,最好的方案是以類(lèi)的全名稱(chēng)。 - 創(chuàng)建數(shù)據(jù)存儲(chǔ)系統(tǒng)。大多數(shù)Content Provider使用Android文件系統(tǒng)或SQLite數(shù)據(jù)庫(kù)來(lái)保持?jǐn)?shù)據(jù),但是也可以以任何你想要的方式來(lái)存儲(chǔ)。但是,必須為其定義一個(gè)叫_id的列,它用來(lái)表示每條記錄的唯一性。
示例代碼(存儲(chǔ)用戶(hù)名稱(chēng)并顯示用戶(hù)名稱(chēng),使用SQLite)
public class MyUsers {
public static final String AUTHORITY = “com.wissen.MyContentProvider”;
// BaseColumn類(lèi)中已經(jīng)包含了 _id字段
public static final class User implements BaseColumns {
public static final Uri CONTENT_URI = Uri.parse(content://com.example.MyContentProvider”);
// 表數(shù)據(jù)列
public static final String USER_NAME = “USER_NAME”;
}
}
如上代碼定義了Content Provider的Content_URI和數(shù)據(jù)列,然后再基于此定義Content Provider類(lèi)。
package com.wissen.testApp.android;
public class MyContentProvider extends ContentProvider {
private SQLiteDatabase sqlDB;
private DatabaseHelper dbHelper;
private static final String DATABASE_NAME = “Users.db”;
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = “User”;
private static final String TAG = “MyContentProvider”;
//定義SQLite接口
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//創(chuàng)建用于存儲(chǔ)數(shù)據(jù)的表
db.execSQL(”Create table ” + TABLE_NAME + “( _id INTEGER PRIMARY KEY AUTOINCREMENT, USER_NAME TEXT);”);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(”DROP TABLE IF EXISTS ” + TABLE_NAME);
onCreate(db);
}
}
@Override
public int delete(Uri uri, String s, String[] as) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
sqlDB = dbHelper.getWritableDatabase();
long rowId = sqlDB.insert(TABLE_NAME, “”, contentvalues);
if (rowId > 0) {
Uri rowUri = ContentUris.appendId(MyUsers.User.CONTENT_URI.buildUpon(), rowId).build();
getContext().getContentResolver().notifyChange(rowUri, null);
return rowUri;
}
throw new SQLException(”Failed to insert row into ” + uri);
}
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return (dbHelper == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
SQLiteDatabase db = dbHelper.getReadableDatabase();
qb.setTables(TABLE_NAME);
Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
return 0;
}
}
如上所示,我們封裝了SQLite操作于Content Provider,是我們可以不再關(guān)注數(shù)據(jù)源的操作細(xì)節(jié),而直接使用Content Provider進(jìn)行數(shù)據(jù)的存取。
文件存儲(chǔ)
Android文件存儲(chǔ)可以用來(lái)存放大量數(shù)據(jù),如文本、圖片、音頻等。使用方法類(lèi)似于java文件存儲(chǔ)。
基本使用
文件寫(xiě)入
public void save() {
try {
FileOutputStream outStream=this.openFileOutput("a.txt",Context.MODE_WORLD_READABLE)
outStream.write(text.getText().toString().getBytes());
outStream.close();
//成功消息提示
Toast.makeText(MyActivity.this,"Saved",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
寫(xiě)入文件若不存在,則會(huì)創(chuàng)建一個(gè)新的文件,保存在/data/data/files文件目錄下。
文件讀取
public void load()
{
try {
FileInputStream inStream=this.openFileInput("a.txt");
ByteArrayOutputStream stream=new ByteArrayOutputStream();
//分塊讀取
byte[] buffer=new byte[1024];
int length=-1;
while((length=inStream.read(buffer))!=-1) {
stream.write(buffer,0,length);
}
stream.close();
inStream.close();
text.setText(stream.toString());
Toast.makeText(MyActivity.this,"Loaded",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
總結(jié)
本文簡(jiǎn)單介紹了Android幾個(gè)簡(jiǎn)單的數(shù)據(jù)存儲(chǔ)方式,包括簡(jiǎn)單數(shù)據(jù)存取,文件存儲(chǔ),以及如何封裝Content Provider,更多關(guān)于Android數(shù)據(jù)存儲(chǔ)操作模式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Android SharedPreferences數(shù)據(jù)存儲(chǔ)詳解
- Android 通過(guò)SQLite數(shù)據(jù)庫(kù)實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)管理
- Android四種數(shù)據(jù)存儲(chǔ)的應(yīng)用方式
- Android基礎(chǔ)教程數(shù)據(jù)存儲(chǔ)之文件存儲(chǔ)
- 詳解Android數(shù)據(jù)存儲(chǔ)—使用SQLite數(shù)據(jù)庫(kù)
- 詳解Android的網(wǎng)絡(luò)數(shù)據(jù)存儲(chǔ)
- Android 文件數(shù)據(jù)存儲(chǔ)實(shí)例詳解
- 5種Android數(shù)據(jù)存儲(chǔ)方式匯總
- Android數(shù)據(jù)存儲(chǔ)幾種方式講解
相關(guān)文章
Android Studio 中的Gradle構(gòu)建系統(tǒng)示例
這篇文章主要介紹了Android Studio 中的Gradle構(gòu)建系統(tǒng)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
Android實(shí)現(xiàn)中國(guó)象棋附源碼下載
這篇文章主要詳細(xì)介紹了Android實(shí)現(xiàn)中國(guó)象棋的具體代碼,供大家參考,感興趣的小伙伴們可以參考一下2016-05-05
Android列表組件ListView使用詳解之動(dòng)態(tài)加載或修改列表數(shù)據(jù)
今天小編就為大家分享一篇關(guān)于Android列表組件ListView使用詳解之動(dòng)態(tài)加載或修改列表數(shù)據(jù),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03
Android實(shí)現(xiàn)文字滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)文字滾動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
Android控件RecyclerView實(shí)現(xiàn)混排效果仿網(wǎng)易云音樂(lè)
這篇文章主要為大家詳細(xì)介紹了Android控件RecyclerView實(shí)現(xiàn)混排效果,仿網(wǎng)易云音樂(lè),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
Android開(kāi)發(fā)筆記XML數(shù)據(jù)解析方法及優(yōu)缺點(diǎn)
XML數(shù)據(jù)是一種常見(jiàn)的數(shù)據(jù)格式,Android開(kāi)發(fā)中需要對(duì)其進(jìn)行解析。常用的XML解析方式有DOM、SAX、Pull和Json等,每種方式都有其優(yōu)缺點(diǎn)。開(kāi)發(fā)者可以根據(jù)具體需求選擇合適的解析方式,提高數(shù)據(jù)解析效率和性能2023-05-05

