在Android中使用多个数据库表时的代码设计

时间:2013-12-05 07:54:05

标签: android sqlite

有些人编写了一个包含列和表名的封闭类,以及一个扩展 SqlliteOpenHelper 类的静态类。但是,如果数据库中有多个表,则很容易变得臃肿。是否有任何代码设计Android社区遵循以保持此数据库相关代码清洁?我还在学习Android,我无法在互联网上找到它。大多数人在教程中只使用一个表,他们并不真正关心这方面。

1 个答案:

答案 0 :(得分:3)

您可以为DB Helper编写单独的类,并为每个表编写单独的类。并将所有方法(insert / update / delete / get)写入这些类中。

我给你一个示例代码,它将为您提供如何实现逻辑的想法。

助手类

public class DatabaseHelper extends SQLiteOpenHelper {

    private static DatabaseHelper sInstance = null;

    private static final String DATABASE_NAME = "database_name";
    private static final int DATABASE_VERSION = 1;

    public static DatabaseHelper getInstance(Context context) {

        if (sInstance == null) {
            sInstance = new DatabaseHelper(context.getApplicationContext());
        }
        return sInstance;
    }

    /**
     * Constructor should be private to prevent direct instantiation. make call
     * to static factory method "getInstance()" instead.
     */
    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Table1.CREATE_TABLE_TABLE1);
        db.execSQL(Table2.CREATE_TABLE_TABLE2);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // write here for update code

    }
}

与表相关的单独的类

public class Table1 {
    private static final String TABLE = "Table_1";  
    public static final String CREATE_TABLE_TABLE1 = "CREATE TABLE "
            + TABLE + " (_id INTEGER PRIMARY KEY, name  TEXT)";

    private Context mContext = null; 

    public Table1(Context mContext) {
        this.mContext = mContext; 
    }

    // And write this Table related stuffs 
    public long insert(String aStringValue) {
        // Here you can get helper as 
        SQLiteDatabase db = DatabaseHelper.getInstance(this.mContext).getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("name", aStringValue);
        // insert row
        return db.insert(TABLE, null, values);
    }

    public Cursor getAll(String aStringValue) { 
        //TODO Even instead of getting Cursor you can get List.
        // So you have to design some models and fill them into here. 
        // For example you can read at http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
        // Read above how to create a Model and use them. 

        String selectQuery = "SELECT  * FROM " + TABLE;
        SQLiteDatabase db = DatabaseHelper.getInstance(this.mContext).getReadableDatabase();
        return db.rawQuery(selectQuery, null);
    }
}

// Same as Table_1 
public class Table2 {
    private static final String TABLE = "Table_2";  
    public static final String CREATE_TABLE_TABLE1 = "CREATE TABLE "
            + TABLE + " (_id INTEGER PRIMARY KEY, name  TEXT)";

    // And write this Table related stuffs 
    // Same as Table 1.
}