這將是最好的使用活動來處理數據庫活動和寫/讀,只是讓你的片段與活動(這是谷歌反正推薦)溝通。你可以DBOpenHelper看起來是這樣的:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Dev Paul
*/
public class DataBaseOpenHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
//Table Names
public static final String REPS_TABLE = "repsTable";
//Reps Table Columns
public static final String R_COLUMN_ID = "repId";
public static final String R_COLUMN_STRING_DATA = "repStringData";
public static final String R_COLUMN_GOOD_FORM = "repGoodForm";
/**
* Table create statements for the reps objects.
*/
private static final String CREATE_REPS_TABLE = "CREATE TABLE "
+ REPS_TABLE + " (" + R_COLUMN_ID + " INTEGER, "
+ R_COLUMN_STRING_DATA + " TEXT, "
+ R_COLUMN_GOOD_FORM + " INTEGER " + ")";
/**
* Default constructor.
* @param context from the calling activity.
*/
public DataBaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_REPS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//drop the tables if they exist.
db.execSQL("DROP TABLE IF EXISTS " + REPS_TABLE);
// create new tables
onCreate(db);
}
}
這是我的應用程序,我工作的一個組成部分,並最終可能是開源的反正。那麼你的數據源類可以是這個樣子......
/**
* Created by Dev Paul
*/
public class DataSource {
private Context mContext;
private DataBaseOpenHelper dataBaseOpenHelper;
private SQLiteDatabase db;
private boolean isOpened;
/**
* Class that helps with obtaining data from the data base. This should do all interfacing to
* the data base. No calls should be directly made to {@code DataBaseOpenHelper}.
* @param context the context of the calling activity.
*/
public DataSource(Context context) {
this.mContext = context;
dataBaseOpenHelper = new DataBaseOpenHelper(context);
}
/**
* Checks to see if the database has been openned.
* @return
*/
public boolean isOpened() {
return isOpened;
}
/**
* Get a writeable database. This must be called.
*/
public void open() {
db = dataBaseOpenHelper.getWritableDatabase();
isOpened = true;
}
/**
* Close the database. This must be called.
*/
public void close() {
dataBaseOpenHelper.close();
isOpened = false;
}
//handle getting and creating data methods....
}
然後你只需要處理越來越設定使用適當的SQL語法查詢語句中的數據。所以在你的活動中,你只需要創建一個新的DataSource對象並調用dataSource.open()來打開數據庫。然後在您的活動的onDestroy()
方法中調用dataSource.close(),以便不泄漏任何元素。