Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 【Android】通用系列 —— 數據持久化(通用的SQLite封裝)

【Android】通用系列 —— 數據持久化(通用的SQLite封裝)

編輯:關於Android編程

關鍵字

SQL SQLite 通用系列 數據存儲

摘要:

主要內容:
本文介紹了封裝後的SQLite,以便快速開發;
只保留必要的定制,重復的代碼封裝到一個通用類中;

說明

LouSQLite.java文件為通用的代碼,所有項目中不需要修改即可使用; MyCallBack.java文件是自定義的文件,關於項目的數據庫配置都在這裡進行,例如:數據庫名稱、數據庫版本號、table語句等; LouSQLite.java支持常用的CRUD操作(支持事務);

代碼

【用法】

使用方法

 lists =  Arrays.asList(
        new Phrase("窈窕淑女,君子好逑"),
        new Phrase("海上生明月,天涯共此時"),
        new Phrase("青青子衿,悠悠我心"),
        new Phrase("人生若只如初見")
);
LouSQLite.insert(MyCallBack.TABLE_PHRASE, lists);

// 更新到數據庫
LouSQLite.update(MyCallBack.TABLE_PHRASE, phrase, MyCallBack.KEY_PHRASE_ID + "=?", new String[]{phrase.getId()});

//  查找
List lists = LouSQLite.query(MyCallBack.TABLE_PHRASE, "select * from " + MyCallBack.TABLE_PHRASE, null);

// 從數據庫中刪除
LouSQLite.delete(MyCallBack.TABLE_PHRASE, MyCallBack.KEY_PHRASE_ID + "=?", new String[]{phrase.getId()});" data-snippet-id="ext.276d89f67b30182ceedfa7eb4506bd05" data-snippet-saved="false" data-codota-status="done">// 初始化
LouSQLite.init(mContext, MyCallBack.getInstance());
Phrase phrase = new Phrase("青青子衿,悠悠我心");

// 插入一個數據到數據庫
LouSQLite.insert(MyCallBack.TABLE_PHRASE, phrase);

// 插入一組數據
List lists =  Arrays.asList(
        new Phrase("窈窕淑女,君子好逑"),
        new Phrase("海上生明月,天涯共此時"),
        new Phrase("青青子衿,悠悠我心"),
        new Phrase("人生若只如初見")
);
LouSQLite.insert(MyCallBack.TABLE_PHRASE, lists);

// 更新到數據庫
LouSQLite.update(MyCallBack.TABLE_PHRASE, phrase, MyCallBack.KEY_PHRASE_ID + "=?", new String[]{phrase.getId()});

//  查找
List lists = LouSQLite.query(MyCallBack.TABLE_PHRASE, "select * from " + MyCallBack.TABLE_PHRASE, null);

// 從數據庫中刪除
LouSQLite.delete(MyCallBack.TABLE_PHRASE, MyCallBack.KEY_PHRASE_ID + "=?", new String[]{phrase.getId()});

【數據庫定制】

 createTablesSQL() {
        return Arrays.asList(
                TABLE_PHRASE_SQL,
                TABLE_FAVORITE_SQL
        );
    }

    @Override
    public String getName() {
        return DB_NAME;
    }

    @Override
    public int getVersion() {
        return DB_VERSION;
    }

    @Override
    public void doUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        switch (oldVersion) {
            case 0:
                db.execSQL(TABLE_FAVORITE_SQL); // 升級操作;
            case 1:
                break;
            default:
                break;
        }
    }


    @Override
    public  void assignValuesByInstance(String tableName, T t, ContentValues values) {

        switch (tableName) {
            case TABLE_PHRASE:
                if (t instanceof Phrase) {
                    Phrase phrase = (Phrase) t;
                    values.put(KEY_PHRASE_ID, phrase.getId());
                    values.put(KEY_PHRASE_CONTENT, phrase.getContent());
                    values.put(KEY_PHRASE_FAVORITE, phrase.getFavorite());
                }
                break;
            case TABLE_FAVORITE:
                if (t instanceof Phrase) {
                    Phrase phrase = (Phrase) t;
                    values.put(KEY_FAVORITE_ID, phrase.getId());
                    values.put(KEY_FAVORITE_CONTENT, phrase.getContent());
                    values.put(KEY_FAVORITE_FAVORITE, phrase.getFavorite());
                }
                break;
        }
    }

    @Override
    public Object newInstanceByCursor(String tableName, Cursor cursor) {
        switch (tableName) {
            case TABLE_PHRASE:
                return new Phrase(
                        cursor.getString(cursor.getColumnIndex(KEY_PHRASE_ID)),
                        cursor.getString(cursor.getColumnIndex(KEY_PHRASE_CONTENT)),
                        cursor.getInt(cursor.getColumnIndex(KEY_PHRASE_FAVORITE))
                );
            case TABLE_FAVORITE:
                return new Phrase(
                        cursor.getString(cursor.getColumnIndex(KEY_FAVORITE_ID)),
                        cursor.getString(cursor.getColumnIndex(KEY_FAVORITE_CONTENT)),
                        cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE_FAVORITE))
                );
        }

        return null;
    }

}
" data-snippet-id="ext.2f8e0087efc4bc22327aa5b639d59242" data-snippet-saved="false" data-codota-status="done">//: MyCallBack.java
package com.lyloou.lou.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lyloou.lou.bean.Phrase;

import java.util.Arrays;
import java.util.List;

/**
 * 類描述:
 * 創建人: Lou
 * 創建時間: 2016/7/13 14:22
 * 修改人: Lou
 * 修改時間:2016/7/13 14:22
 * 修改備注:
 */
public class MyCallBack implements LouSQLite.ICallBack {
    private static final String TAG = "MyCallBack";

    private MyCallBack() {
    }

    private static LouSQLite.ICallBack INSTANCE;

    public static LouSQLite.ICallBack getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MyCallBack();
        }
        return INSTANCE;
    }

    ///////////////////////////////////////////////////////////////////////////
    // db config
    ///////////////////////////////////////////////////////////////////////////
    public static final String DB_NAME = "DBNAME.db";
    public static final int DB_VERSION = 1;


    ///////////////////////////////////////////////////////////////////////////
    // table phrase
    ///////////////////////////////////////////////////////////////////////////
    public static final String TABLE_PHRASE = "phrase";
    public static final String KEY_PHRASE_ID = "PHRASE_ID";
    private static final String KEY_PHRASE_CONTENT = "PHRASE_CONTENT";
    private static final String KEY_PHRASE_FAVORITE = "PHRASE_FAVORITE";
    private static final String TABLE_PHRASE_SQL = "create table " + TABLE_PHRASE + " (" +
            "id integer primary key autoincrement, " +
            KEY_PHRASE_ID + " text, " +
            KEY_PHRASE_CONTENT + " text, " +
            KEY_PHRASE_FAVORITE + " integer" +
            ")";


    ///////////////////////////////////////////////////////////////////////////
    // table favorite
    ///////////////////////////////////////////////////////////////////////////
    public static final String TABLE_FAVORITE = "favorite";
    public static final String KEY_FAVORITE_ID = "FAVORITE_ID";
    private static final String KEY_FAVORITE_CONTENT = "FAVORITE_CONTENT";
    private static final String KEY_FAVORITE_FAVORITE = "FAVORITE_FAVORITE";
    private static final String TABLE_FAVORITE_SQL = "create table " + TABLE_FAVORITE + " (" +
            "id integer primary key autoincrement, " +
            KEY_FAVORITE_ID + " text, " +
            KEY_FAVORITE_CONTENT + " text," +
            KEY_FAVORITE_FAVORITE + " integer" +
            ")";


    ///////////////////////////////////////////////////////////////////////////
    // overrite
    ///////////////////////////////////////////////////////////////////////////
    @Override
    public List createTablesSQL() {
        return Arrays.asList(
                TABLE_PHRASE_SQL,
                TABLE_FAVORITE_SQL
        );
    }

    @Override
    public String getName() {
        return DB_NAME;
    }

    @Override
    public int getVersion() {
        return DB_VERSION;
    }

    @Override
    public void doUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        switch (oldVersion) {
            case 0:
                db.execSQL(TABLE_FAVORITE_SQL); // 升級操作;
            case 1:
                break;
            default:
                break;
        }
    }


    @Override
    public  void assignValuesByInstance(String tableName, T t, ContentValues values) {

        switch (tableName) {
            case TABLE_PHRASE:
                if (t instanceof Phrase) {
                    Phrase phrase = (Phrase) t;
                    values.put(KEY_PHRASE_ID, phrase.getId());
                    values.put(KEY_PHRASE_CONTENT, phrase.getContent());
                    values.put(KEY_PHRASE_FAVORITE, phrase.getFavorite());
                }
                break;
            case TABLE_FAVORITE:
                if (t instanceof Phrase) {
                    Phrase phrase = (Phrase) t;
                    values.put(KEY_FAVORITE_ID, phrase.getId());
                    values.put(KEY_FAVORITE_CONTENT, phrase.getContent());
                    values.put(KEY_FAVORITE_FAVORITE, phrase.getFavorite());
                }
                break;
        }
    }

    @Override
    public Object newInstanceByCursor(String tableName, Cursor cursor) {
        switch (tableName) {
            case TABLE_PHRASE:
                return new Phrase(
                        cursor.getString(cursor.getColumnIndex(KEY_PHRASE_ID)),
                        cursor.getString(cursor.getColumnIndex(KEY_PHRASE_CONTENT)),
                        cursor.getInt(cursor.getColumnIndex(KEY_PHRASE_FAVORITE))
                );
            case TABLE_FAVORITE:
                return new Phrase(
                        cursor.getString(cursor.getColumnIndex(KEY_FAVORITE_ID)),
                        cursor.getString(cursor.getColumnIndex(KEY_FAVORITE_CONTENT)),
                        cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE_FAVORITE))
                );
        }

        return null;
    }

}
//: Pharse.java
package com.lyloou.lou.bean;

import java.util.UUID;

/**
 * 類描述:
 * 創建人: Lou
 * 創建時間: 2016/7/12 9:49
 * 修改人: Lou
 * 修改時間:2016/7/12 9:49
 * 修改備注:
 */
public class Phrase {
    private String mId;
    private String mContent;
    private int mFavorite; // 0表示未收藏,1表示已收藏;

    public Phrase(String content) {
        this(UUID.randomUUID().toString(), content, 0);
    }

    public Phrase(String content, int favorite) {
        this(UUID.randomUUID().toString(), content, favorite);
    }

    public Phrase(String id, String content, int favorite) {
        mId = id;
        mContent = content;
        mFavorite = favorite;
    }

    public String getId() {
        return mId;
    }

    public void setId(String id) {
        mId = id;
    }

    public String getContent() {
        return mContent;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public int getFavorite() {
        return mFavorite;
    }

    public void setFavorite(int favorite) {
        mFavorite = favorite;
    }
}

【通用源碼】

 createTablesSQL();

         void assignValuesByInstance(String tableName, T t, ContentValues values);

         T newInstanceByCursor(String tableName, Cursor cursor);
    }

    private static final String ILLEGAL_OPREATION = "非法操作,請先進行初始化操作:LouSQLite.init()";

    private static LouSQLite INSTANCE;

    public static void init(Context context, ICallBack callBack) {
        if (INSTANCE == null) {
            INSTANCE = new LouSQLite(context, callBack);
        }
    }


    public static  void insert(String tableName, T t) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
            db.insert(tableName, null, values);
            values.clear();
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  void insert(String tableName, List ts) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (T t : ts) {
                INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
                db.insert(tableName, null, values);
                values.clear();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  void update(String tableName, T t, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {

            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
            db.update(tableName, values, whereClause, whereArgs);
            values.clear();
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }


    public static  void update(String tableName, List ts, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (T t : ts) {
                INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
                db.update(tableName, values, whereClause, whereArgs);
                values.clear();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static void delete(String tableName, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(tableName, whereClause, whereArgs);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  List query(String tableName, @NonNull String queryStr, @Nullable String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        List lists = new ArrayList<>();
        SQLiteDatabase db = INSTANCE.getReadableDatabase();
        db.beginTransaction();
        try {
            db.setTransactionSuccessful();
            Cursor cursor = db.rawQuery(queryStr, whereArgs);
            if (cursor.moveToFirst()) {
                do {
                    T tt = INSTANCE.mCallBack.newInstanceByCursor(tableName, cursor);
                    if (tt != null) {
                        lists.add(tt);
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        } finally {
            db.endTransaction();
            db.close();
        }

        return lists;
    }


    ///////////////////////////////////////////////////////////////////////////
    // Self
    ///////////////////////////////////////////////////////////////////////////
    private final ICallBack mCallBack;

    private static final String TAG = "LouSQLite";


    private LouSQLite(@NonNull Context context, @NonNull ICallBack callBack) {
        super(context, callBack.getName(), null, callBack.getVersion());
        mCallBack = callBack;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        for (String create_table : mCallBack.createTablesSQL()) {
            db.execSQL(create_table);
            Log.d(TAG, "create table " + "[ \n" + create_table + "\n ]" + " successful! ");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        mCallBack.doUpgrade(sqLiteDatabase, oldVersion, newVersion);
    }
}
" data-snippet-id="ext.11a8b43c3fe96cada084d84e93618e2f" data-snippet-saved="false" data-codota-status="done">//: LouSQLite.java
package com.lyloou.lou.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * 類描述:一個通用的SQLite,通過簡單的配置快速搭建一個數據庫存儲方案;
 * 創建人: Lou
 * 創建時間: 2016/7/13 10:10
 * 修改人: Lou
 * 修改時間:2016/7/13 10:10
 * 修改備注:
 */
public class LouSQLite extends SQLiteOpenHelper {

    public interface ICallBack {
        String getName();

        int getVersion();

        void doUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

        List createTablesSQL();

         void assignValuesByInstance(String tableName, T t, ContentValues values);

         T newInstanceByCursor(String tableName, Cursor cursor);
    }

    private static final String ILLEGAL_OPREATION = "非法操作,請先進行初始化操作:LouSQLite.init()";

    private static LouSQLite INSTANCE;

    public static void init(Context context, ICallBack callBack) {
        if (INSTANCE == null) {
            INSTANCE = new LouSQLite(context, callBack);
        }
    }


    public static  void insert(String tableName, T t) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
            db.insert(tableName, null, values);
            values.clear();
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  void insert(String tableName, List ts) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (T t : ts) {
                INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
                db.insert(tableName, null, values);
                values.clear();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  void update(String tableName, T t, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {

            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
            db.update(tableName, values, whereClause, whereArgs);
            values.clear();
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }


    public static  void update(String tableName, List ts, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (T t : ts) {
                INSTANCE.mCallBack.assignValuesByInstance(tableName, t, values);
                db.update(tableName, values, whereClause, whereArgs);
                values.clear();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static void delete(String tableName, String whereClause, String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        SQLiteDatabase db = INSTANCE.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(tableName, whereClause, whereArgs);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public static  List query(String tableName, @NonNull String queryStr, @Nullable String[] whereArgs) {
        if (INSTANCE == null) {
            throw new IllegalStateException(ILLEGAL_OPREATION);
        }

        List lists = new ArrayList<>();
        SQLiteDatabase db = INSTANCE.getReadableDatabase();
        db.beginTransaction();
        try {
            db.setTransactionSuccessful();
            Cursor cursor = db.rawQuery(queryStr, whereArgs);
            if (cursor.moveToFirst()) {
                do {
                    T tt = INSTANCE.mCallBack.newInstanceByCursor(tableName, cursor);
                    if (tt != null) {
                        lists.add(tt);
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        } finally {
            db.endTransaction();
            db.close();
        }

        return lists;
    }


    ///////////////////////////////////////////////////////////////////////////
    // Self
    ///////////////////////////////////////////////////////////////////////////
    private final ICallBack mCallBack;

    private static final String TAG = "LouSQLite";


    private LouSQLite(@NonNull Context context, @NonNull ICallBack callBack) {
        super(context, callBack.getName(), null, callBack.getVersion());
        mCallBack = callBack;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        for (String create_table : mCallBack.createTablesSQL()) {
            db.execSQL(create_table);
            Log.d(TAG, "create table " + "[ \n" + create_table + "\n ]" + " successful! ");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        mCallBack.doUpgrade(sqLiteDatabase, oldVersion, newVersion);
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved