我是SQL Lite数据库操作的新手。
我在本教程中编写了一个DB处理类SQL Lite tutorial
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "PersonalAssistant";
// TASKS table name
private static final String TABLE_TASKS = "TASKS";
// Tasks Table Columns names
private static final String KEY_ID = "id";
private static final String UUID = "uuid";
private static final String ACTION = "action";
private static final String TIME = "time";
private static final String DAY = "day";
private static final String RECEPIENTS = "receipients";
private static final String BODY = "body";
private static final String SUBJECT = "subject";
private static final String STATUS = "status";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement," +UUID + " TEXT,"+ ACTION + " TEXT,"
+ TIME + " TEXT," + DAY + " TEXT," + RECEPIENTS+ " TEXT," +BODY + " TEXT," + " TEXT," +SUBJECT + " TEXT," +SUBJECT + " TEXT," +")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
// Create tables again
onCreate(db);
}
// add task to table
public void addTask(Task task)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ACTION, task.getAction());
values.put(UUID, task.getUuid());
values.put(TIME, task.getTime());
values.put(DAY, task.getDay());
values.put(RECEPIENTS, task.getReceipients());
values.put(BODY, task.getBody());
values.put(SUBJECT, task.getSubject());
values.put(STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
} .............
我的问题是如何从我的应用程序活动中调用此类进行数据库操作?
如何将我的类与其他未扩展SQLiteOpenHelper的活动进行实例化?
我可以将类和方法定义为静态,但这是一个好习惯吗?
答案 0 :(得分:2)
您可以通过实例化DatabaseHandler
类中的对象来实现:
DabataseHandler dbHandler;
dbHandler = new DatabaseHandler(getApplicationContext());
然后,您可以使用Databasehandler
在dbHandler
课程中使用方法。
例如:
Task myTask = new Task();
dbHandler.addTask(myTask);
答案 1 :(得分:0)
我经常使用Singleton模式从所有不同的活动中访问Sqlite DB。
我自己接受的以下问题的答案描述了提供代码的方法: