Android數(shù)據(jù)存儲方式操作模式解析
SharedPreferences
在開發(fā)過程中,數(shù)據(jù)存取是較為頻繁的,今天我們來了解下android幾種常見的數(shù)據(jù)存取方式。
在Android中,sharePreferences是一種輕量級的數(shù)據(jù)存儲方式,采用鍵值對的存儲方式,存儲少量數(shù)據(jù),支持基本類型的簡單數(shù)據(jù)存儲。
基本用法
- 根據(jù)Context獲取SharedPreferences對象
- 利用edit()方法獲取Editor對象。
- 通過Editor對象存儲key-value鍵值對數(shù)據(jù)。
- 通過commit()方法提交數(shù)據(jù)。
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //獲取SharedPreferences對象 Context ctx = MainActivity.this; //第一個參數(shù)指定存儲文件名,第二個參數(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 該模式會檢查文件是否存在,存在就將數(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ù)類型。簡單來說,一個程序可以通過實現(xiàn)一個Content Provider的抽象接口將自己的數(shù)據(jù)暴露出去。外界根本看不到,也不用看到這個應(yīng)用暴露的數(shù)據(jù)在應(yīng)用當(dāng)中是如何存儲的,或者是用數(shù)據(jù)庫存儲還是用文件存儲,還是通過網(wǎng)上獲得。
統(tǒng)一資源標(biāo)識符(URI)
content://com.example.myapplication.provider/tablename/1
- content 主題名,URI前綴。
- com.example.myapplication.provider 授權(quán)信息,Content Provider唯一標(biāo)識符。
- tablename Content Provider 指向數(shù)據(jù)庫中的某個表名。
- 1 表中某個記錄,若無指定,返回全部記錄。
基本使用
創(chuàng)建Content Provider
- 創(chuàng)建一個繼承了ContentProvider父類的類
- 定義一個名為CONTENT_URI,并且是
public static final
的Uri類型的類變量,必須為其指定一個唯一的字符串值,最好的方案是以類的全名稱。 - 創(chuàng)建數(shù)據(jù)存儲系統(tǒng)。大多數(shù)Content Provider使用Android文件系統(tǒng)或SQLite數(shù)據(jù)庫來保持?jǐn)?shù)據(jù),但是也可以以任何你想要的方式來存儲。但是,必須為其定義一個叫_id的列,它用來表示每條記錄的唯一性。
示例代碼(存儲用戶名稱并顯示用戶名稱,使用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)建用于存儲數(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ù)的存取。
文件存儲
Android文件存儲可以用來存放大量數(shù)據(jù),如文本、圖片、音頻等。使用方法類似于java文件存儲。
基本使用
文件寫入
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(); } }
寫入文件若不存在,則會創(chuàng)建一個新的文件,保存在/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é)
本文簡單介紹了Android幾個簡單的數(shù)據(jù)存儲方式,包括簡單數(shù)據(jù)存取,文件存儲,以及如何封裝Content Provider,更多關(guān)于Android數(shù)據(jù)存儲操作模式的資料請關(guān)注腳本之家其它相關(guān)文章!
- Android SharedPreferences數(shù)據(jù)存儲詳解
- Android 通過SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)存儲管理
- Android四種數(shù)據(jù)存儲的應(yīng)用方式
- Android基礎(chǔ)教程數(shù)據(jù)存儲之文件存儲
- 詳解Android數(shù)據(jù)存儲—使用SQLite數(shù)據(jù)庫
- 詳解Android的網(wǎng)絡(luò)數(shù)據(jù)存儲
- Android 文件數(shù)據(jù)存儲實例詳解
- 5種Android數(shù)據(jù)存儲方式匯總
- Android數(shù)據(jù)存儲幾種方式講解
相關(guān)文章
Android Studio 中的Gradle構(gòu)建系統(tǒng)示例
這篇文章主要介紹了Android Studio 中的Gradle構(gòu)建系統(tǒng)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11Android列表組件ListView使用詳解之動態(tài)加載或修改列表數(shù)據(jù)
今天小編就為大家分享一篇關(guān)于Android列表組件ListView使用詳解之動態(tài)加載或修改列表數(shù)據(jù),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03Android控件RecyclerView實現(xiàn)混排效果仿網(wǎng)易云音樂
這篇文章主要為大家詳細(xì)介紹了Android控件RecyclerView實現(xiàn)混排效果,仿網(wǎng)易云音樂,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Android開發(fā)筆記XML數(shù)據(jù)解析方法及優(yōu)缺點
XML數(shù)據(jù)是一種常見的數(shù)據(jù)格式,Android開發(fā)中需要對其進(jìn)行解析。常用的XML解析方式有DOM、SAX、Pull和Json等,每種方式都有其優(yōu)缺點。開發(fā)者可以根據(jù)具體需求選擇合適的解析方式,提高數(shù)據(jù)解析效率和性能2023-05-05