Launcher開發之SQLiteDatabase數據庫管理(二)

nbsp;       在Android開發中SQLite3經常會用到,上文添加Widget的功能中,Launcher重啓後,已經被添加到界面上的widget需要在初始化的時候一併加載到界面上,這裏就用到數據庫來管理widget的顯示與否和位置等參數.

        先說一下Android中數據庫的使用關鍵點:

1.標準T-sql語句

2.Cursor的使用,sql查詢返回的數據到用Cursor存儲,遍歷Cursor讀取數據,數據讀取結束則關閉Cursor。另外注意在使用CursorAdapter的時候應該掌握好關閉Cursor的時機,在使用CursorAdapter綁定到界面顯示的時候不能關閉Cursor,如果關閉了,界面就不顯示數據了,所以要在CursorAdapter未使用的時候才能關閉Cursor。

3.使用SQLiteHelper管理數據庫會讓數據庫操作非常簡單


下面是使用SQLiteHelper封裝的數據庫管理的類,已加註釋,不理解的地方可以評論:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseManager extends SQLiteOpenHelper {

    public static final String DB_NAME = "launcher";
    public static final String TABLE_WIDGET = "widget";
    public static final String TABLE_WIDGET_WIDGETID = "widgetID";
    public static final String TABLE_WIDGET_VISIBILITY = "visiblility";
    private static final String SQL_TABLE_WIDGET_CREATE = "create table " + TABLE_WIDGET + " ("
            + "_id INTEGER PRIMARY KEY autoincrement,"
            + TABLE_WIDGET_WIDGETID + " INTEGER NOT NULL, "
            + TABLE_WIDGET_VISIBILITY + " INTEGER" + " default 1)";
    
    private static SQLiteDatabase mSQLiteDatabase;
    private static DatabaseManager mDatabaseManager;
    private static final String TAG = "DatabaseManager";
    private static final int VERSION = 2;

    public DatabaseManager(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }
    
    
    /**
     * 重載簡化構造函數
     * @param context
     */
    public DatabaseManager(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    
    public static DatabaseManager getInstance(Context context){
        if (mDatabaseManager == null) {
            mDatabaseManager = new DatabaseManager(context);
        }
        return mDatabaseManager;
    }
    
    /**
     * 獲取數據庫實例,這裏用兩個靜態變量是爲了APK在運行是始終只有一個SQLiteDatabase實例,
     * 在退出APK的時候能安全的關閉SQLiteDatabase;
     * 如果覺得有必要Cursor的管理可以在這個類中創建一個Cursor管理器,因爲cursor也需要及時的關閉
     * ,否則會有大量的錯誤日誌打印,不過也不必太擔心, 因爲系統對此做了處理,但是會比較消耗內存,健康的設計必須很好的管理SQLiteDatabase
     * 
     * @param context
     * @return 返回SQLiteDatabase實例
     */
    public static SQLiteDatabase getDatabase(Context context) {
        if (mDatabaseManager == null) {
            mDatabaseManager = new DatabaseManager(context);
        }
        if (mSQLiteDatabase == null) {
            mSQLiteDatabase = mDatabaseManager.getWritableDatabase();
        }
        return mSQLiteDatabase;
    }

    
    /**
     * 保存widgetid到數據庫
     * @param context
     * @param widgetId
     */
    public void insertWidget(Context context, int widgetId) {
        ContentValues values = new ContentValues();
        values.put(DatabaseManager.TABLE_WIDGET_WIDGETID, widgetId);
        String where = TABLE_WIDGET_WIDGETID + " = " + widgetId;
        Cursor cursor = getDatabase(context).query(TABLE_WIDGET, null, where,
                null, null, null, null);
        if (cursor != null && cursor.getCount() >= 1) {
            getDatabase(context).update(TABLE_WIDGET, values, where, null);
        } else {
            getDatabase(context).insert(TABLE_WIDGET, null, values);
        }
    }
    
    
    /**
     * 獲取已加載的widget
     * @param context
     * @return
     */
    public int[] getAddedWidgetArray(Context context){
        Cursor cursor = getDatabase(context).query(TABLE_WIDGET, new String[]{TABLE_WIDGET_WIDGETID}, null, null, null, null, null);
        if(cursor != null){
            Log.v(TAG, "cursor:"+cursor.getCount());
            int[] widgets = new int[cursor.getCount()];
            int i =0;
            for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
                widgets[i] = cursor.getInt(cursor.getColumnIndex(TABLE_WIDGET_WIDGETID));
                ++i;
            }
            cursor.close();
            return widgets;
        }
        return null;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 在這裏創建表
        db.execSQL(SQL_TABLE_WIDGET_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion) {
            // todo sth,有時在更新APK的時候數據庫改變較大,需要更新某些表,在這裏作相應處理,比如拷貝用戶數據到新的表中
            db.execSQL("drop table "+TABLE_WIDGET);
            db.execSQL(SQL_TABLE_WIDGET_CREATE);
        }
    }

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章