1、SQLiteHelper裏定義一個接口SQLiteDateTable,它包括onCreate和onUpgrade兩個方法。sql
public interface SQLiteDateTable{
public void onCreate(SQLiteDatabase database);
public void onUpgrade(SQLiteDatabase database);
}app
2、用SQLiteDAOBase實現SQLiteDateTable接口,而且是一個抽象類(abstract)ide
public abstract class SQLiteDAOBase implements SQLiteDateTableui
3、UserDAO繼承SQLiteDAOBase,實現了onCreate和onUpgrade方法,在onCreate方法裏寫建表語句,什麼DAO就建立什麼表(UserDAO就只建立user表),這樣比較適合團隊開發。sqlite
@Override
public void onCreate(SQLiteDatabase database) {
StringBuilder sql=new StringBuilder();
sql.append("Create TABLE [users](");
sql.append(" [userid] integer PRIMARY KEY AUTOINCREMENT NOT NULL");
sql.append(" ,[userName] varchar(20) NOT NULL");
sql.append(" ,[createDate] datetime NOT NULL");
sql.append(" ,[state] int NOT NULL");
sql.append(" )");
database.execSQL(sql.toString());
initDefaultData(database);
}
@Override
public void onUpgrade(SQLiteDatabase database) {
}繼承
4、因此在SQLiteHelper裏的onCreate方法裏能夠經過反射動態建表。無論哪一個DAO,只要實現了SQLiteDateTable接口,就能執行onCreate方法建表接口
@Override
public void onCreate(SQLiteDatabase db) {
List<String> list = CONFIG.getTables();
reflection = new Reflection();
for (int i = 0; i < list.size(); i++) {
//1.類名 2.構造方法要傳的參數 3.構造方法的參數類型(上下文的類型)
try {
SQLiteDateTable sqliteDataTable = (SQLiteDateTable) reflection
.newInstance(list.get(i), new Object[] { context },
new Class[] { Context.class});
sqliteDataTable.onCreate(db);
} catch (Exception e) {
e.printStackTrace();
}
}
}開發