Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android開發系列:三大數據存儲方式完整解析

編輯:Android 程式設計入門

在 Android 實際開發中,數據處理是不可避免的一環。有些數據是一次性的,每次進入 App 都要刷新;有些則具時效性(如用戶帳號數據),這就要求我們採用一定的數據保存措施。本文將分享 Android 中幾種常用的數據保存方法。

一、SharedPreferences(輕量級鍵值存儲)

小數據量存儲最常用的就是 SharedPreferences。它是一個輕量級存儲類,特別適合保存軟體配置參數。使用時,數據背後以 XML 檔存放,位於 /data/data/<package name>/shared_prefs 目錄下,本質上也是一種文件存儲。以下代碼示範用鍵值對方式把字串存進 XML:

public static void openSharep(Context context,String name){ SharedPreferences sharedPreferences=context.getSharedPreferences(name,Context.MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putString("name","hello"); editor.commit(); } 

需要注意的是,SharePreferences 主要保存標識類的有限數據;至於卸載或更新 App 時它是否保留,可能與系統版本有關。

二、文件存儲

若需保存大量數據,常用方式有兩種:文件存儲與 SQLite 數據庫。先看文件存儲——透過輸出流即可把資訊寫入文件:

String fileName = etFileName.getText().toString(); String fileContent = etFileContent.getText().toString(); FileOutputStream out = null; try { out = context.openFileOutput(fileName, Context.MODE_PRIVATE); out.write(fileContent.getBytes("UTF-8")); Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); }finally { try{ out.close(); }catch (Exception e){ e.printStackTrace(); } } 

讀取時則用輸入流:

String fileName=etFileName.getText().toString(); FileInputStream in=null; ByteArrayOutputStream bout=null; byte[] buf=new byte[1024]; bout=new ByteArrayOutputStream(); int length=0; try{ in=context.openFileInput(fileName); while((length=in.read(buf))!=-1){ bout.write(buf,0,length); } byte[] content = bout.toByteArray(); tvInfo.setText(new String(content,"UTF-8")); }catch (Exception e){ e.printStackTrace(); } tvInfo.invalidate(); try{ in.close(); bout.close(); } catch(Exception e){} 

可見文件系統無非就是中規中矩的文件讀寫操作。

三、SQLite 數據庫(結構化存儲)

數據庫保存的文件相較普通文件具有更好的結構性,操作數據時更有條理。在 Android 中定義數據庫操作對象很簡單,只需讓類繼承 SQLiteOpenHelper 即可:

public class SqliteTest extends SQLiteOpenHelper { private static final int VERSION = 1; private static final String DB_NAME = "test.db"; public SqliteTest(Context context) { super(context, DB_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS person" + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("ALTER TABLE person ADD COLUMN other STRING"); } }

拿到數據庫對象後,就能進行插入等操作,並善用事務提升效能:

private SQLiteDatabase db; private SqliteTest helper; private void getSqliteDb(){ db=helper.getWritableDatabase(); } private void addData(List<Person> persons){ db.beginTransaction(); //開始事務 try { for (Person person : persons) { db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info}); } db.setTransactionSuccessful(); //設置事務成功完成 } finally { db.endTransaction(); //結束事務 } } 

最後來看 SQLiteOpenHelper 的源碼,理解為何實現該類後就能操作數據庫。呼叫 getWritableDatabase 時,程式會同步呼叫 getDatabaseLocked:

public SQLiteDatabase getWritableDatabase() { synchronized (this) { return getDatabaseLocked(true); } } 
private SQLiteDatabase getDatabaseLocked(boolean writable) { if (mDatabase != null) { if (!mDatabase.isOpen()) { mDatabase = null; } else if (!writable || !mDatabase.isReadOnly()) { return mDatabase; } } if (mIsInitializing) { throw new IllegalStateException("getDatabase called recursively"); } SQLiteDatabase db = mDatabase; try { mIsInitializing = true; if (db != null) { if (writable && db.isReadOnly()) { db.reopenReadWrite(); } } else if (mName == null) { db = SQLiteDatabase.create(null); } else { db = mContext.openOrCreateDatabase(mName, mEnableWriteAheadLogging ? Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0, mFactory, mErrorHandler); } onConfigure(db); final int version = db.getVersion(); if (version != mNewVersion) { db.beginTransaction(); try { if (version == 0) { onCreate(db); } else { if (version > mNewVersion) { onDowngrade(db, version, mNewVersion); } else { onUpgrade(db, version, mNewVersion); } } db.setVersion(mNewVersion); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } onOpen(db); mDatabase = db; return db; } finally { mIsInitializing = false; if (db != null && db != mDatabase) { db.close(); } } } 

呼叫這個方法後,系統便會提供一個 SQLiteDatabase 對象,我們就能利用它的方法進行數據庫操作了。(SQLiteDatabase 層的源碼作者尚未深入研究,如有疏漏歡迎指正。)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved