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ù),支持基本類型的簡(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)用程序讀、寫。這是默認(rèn)模式。
- MODE_APPEND 該模式會(huì)檢查文件是否存在,存在就將數(shù)據(jù)寫到文件末尾,否則就創(chuàng)建新文件。
- MODE_WORLD_READABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀,但不能寫。該模式已棄用。
- MODE_WORLD_WRITEABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序?qū)憽?strong>該模式已棄用。
ContentProvider
基本概念
屬于Android四大組件之一,用于進(jìn)程間進(jìn)行數(shù)據(jù)交互,從而能夠讓其他的應(yīng)用保存或讀取此Content Provider的各種數(shù)據(jù)類型。簡(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父類的類
- 定義一個(gè)名為CONTENT_URI,并且是
public static final的Uri類型的類變量,必須為其指定一個(gè)唯一的字符串值,最好的方案是以類的全名稱。 - 創(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ǔ)用戶名稱并顯示用戶名稱,使用SQLite)
public class MyUsers {
public static final String AUTHORITY = “com.wissen.MyContentProvider”;
// BaseColumn類中已經(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類。
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ù),如文本、圖片、音頻等。使用方法類似于java文件存儲(chǔ)。
基本使用
文件寫入
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();
}
}
寫入文件若不存在,則會(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形狀圖形與狀態(tài)列表圖形及九宮格圖片超詳細(xì)講解
這篇文章主要介紹了Android形狀圖形與狀態(tài)列表圖形及九宮格圖片的應(yīng)用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-09-09
詳解android 用webview加載網(wǎng)頁(yè)(https和http)
這篇文章主要介紹了詳解android 用webview加載網(wǎng)頁(yè)(https和http),詳細(xì)的介紹了兩個(gè)錯(cuò)誤的解決方法,有興趣的可以了解一下2017-11-11
Android Theme以及解決啟動(dòng)黑屏的方法詳解
這篇文章主要給大家介紹了關(guān)于Android Theme以及解決啟動(dòng)黑屏的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
AndroidStudio利用android-support-multidex解決64k的各種異常
這篇文章主要為大家詳細(xì)介紹了AndroidStudio利用android-support-multidex解決64k的各種異常,感興趣的小伙伴們可以參考一下2016-09-09
詳解Android應(yīng)用中preference首選項(xiàng)的編寫方法
這篇文章主要介紹了Android應(yīng)用中preference首選項(xiàng)的編寫方法,或許Apple將其翻譯為'偏好設(shè)置'更直觀些,即用戶對(duì)應(yīng)用的一些個(gè)性化調(diào)整菜單,需要的朋友可以參考下2016-04-04
Android 自定義TextView實(shí)現(xiàn)滑動(dòng)解鎖高亮文字
這篇文章主要介紹了Android 自定義TextView實(shí)現(xiàn)滑動(dòng)解鎖高亮文字的相關(guān)資料,需要的朋友可以參考下2018-03-03
android開(kāi)發(fā)基礎(chǔ)教程—SharedPreferences讀寫
本文介紹SharedPreferences的讀與寫的實(shí)現(xiàn)思路,感興趣的朋友可以了解下2013-01-01
adb通過(guò)wifi連接android設(shè)備流程解析
這篇文章主要介紹了adb通過(guò)wifi連接android設(shè)備流程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12

