在android中数据库通常以文件的形式存储在磁盘中,而内存数据库是将数据驻留在内存中,因此可以作为一种缓存技术方案。 那么在android如何使用sqlite的内存数据库呢?

看SQLiteDatabase的源码:

/**     * Create a memory backed SQLite database.  Its contents will be destroyed     * when the database is closed.     *     * 

Sets the locale of the database to the the system's current locale. * Call {@link #setLocale} if you would like something else.

* * @param factory an optional factory class that is called to instantiate a * cursor when query is called * @return a SQLiteDatabase object, or null if the database can't be created */ public static SQLiteDatabase create(CursorFactory factory) { // This is a magic string with special meaning for SQLite. return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY); }

CREATE_IF_NECESSARY 表示:当数据库不存在时将被创建。  通过方法注释可以知道此方法可以创建内存数据库,并当数据库关闭时数据将被清除。

另外一种方法,请看SQLiteOpenHelper源码:

public synchronized SQLiteDatabase getWritableDatabase() {                boolean success = false;        SQLiteDatabase db = null;        if (mDatabase != null) mDatabase.lock();        try {            mIsInitializing = true;            if (mName == null) {                db = SQLiteDatabase.create(null);            } else {                db = mContext.openOrCreateDatabase(mName, 0, mFactory, mErrorHandler);            }            ...            onOpen(db);            success = true;            return db;        } finally {            mIsInitializing = false;            if (success) {                if (mDatabase != null) {                    try { mDatabase.close(); } catch (Exception e) { }                    mDatabase.unlock();                }                mDatabase = db;            } else {                if (mDatabase != null) mDatabase.unlock();                if (db != null) db.close();            }        }    }

从代码中可以知道,当mName(数据库名称)为null时,将创建内存数据库。

我写了一个demo请看代码:

package dw.test;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.provider.BaseColumns;import android.util.Log;public final class MemoryDbTester {private static final String LOG_TAG = MemoryDbTester.class.getSimpleName();private static final String TABLE_NAME = "t_user";private SQLiteDatabase mMemoryDb;private MemoryDbTester(){mMemoryDb = createMemoryDb();}private static MemoryDbTester sDefault = new MemoryDbTester();public static MemoryDbTester getDefault(){return sDefault;}public interface Columns extends BaseColumns {public static final String UNAME = "uname";}/** * 创建内存数据库 */private SQLiteDatabase createMemoryDb(){SQLiteDatabase database = SQLiteDatabase.create(null);String t_user_sql = "CREATE TABLE "+TABLE_NAME+"(_id integer primary key autoincrement,"+Columns.UNAME+" varchar(10))";database.execSQL(t_user_sql);return database;}/** * 向内存数据库中插入一条数据 */public void testInsert() {SQLiteDatabase db = mMemoryDb;check(db);ContentValues values = new ContentValues();values.put(Columns.UNAME, "dw");db.insert(TABLE_NAME, null, values);}/** * 查询内存数据库中的数据 */public void testQuery(){SQLiteDatabase db = mMemoryDb;check(db);Cursor c = db.rawQuery("select uname from t_user", null);while(c.moveToNext()){String name = c.getString(0);Log.i(LOG_TAG, "NAME:" + name);}}@Overrideprotected void finalize() throws Throwable {releaseMemory();super.finalize();}public void releaseMemory(){SQLiteDatabase db = mMemoryDb;if(db!=null){db.close();mMemoryDb = null;}}private void check(SQLiteDatabase db) {if(db==null || !db.isOpen()){throw new IllegalStateException("memory database already closed");}}}




更多相关文章

  1. Android中SQLite操作示例
  2. Android内存泄漏监测(MAT)及解决办法
  3. Android联系人数据库全解析(5)
  4. Android(安卓)Studio
  5. Android(安卓)Sqlite数据库中基础的增删改查操作
  6. android操作xml
  7. 为Android软件创建快捷方式
  8. android操作xml
  9. Android(安卓)开发系列 2 Activity

随机推荐

  1. 文件读写
  2. android仿UC墨迹天气左右拖动效果
  3. 异常:java.lang.RuntimeException: Unable
  4. android studio 降低项目版本错误,no reso
  5. Android--AT9G45开发板移植
  6. android httpclient
  7. android 修改状态栏和标题栏颜色
  8. 2010.12.19——— android 设置组件的高
  9. 2011.07.05——— android notifyDataSet
  10. android 全屏显示