我正在开发一个Android项目,其中我有一个应用程序的中央数据库,它可以在同一应用程序中的不同活动中访问/输入。我还是有点小白,当谈到Android和遵循各种教程,而只是让自己稍微卡住:/Android:如何创建数据库管理类的对象然后使用它?
我遇到的问题是这样的,如果贴在下面的代码是我“基础“类是我将通过对象和方法访问的类,我如何使用正确的参数创建对象以使其工作?
我尝试使用以下语法在不同的类中创建DatabaseAdmin类的对象: DatabaseAdmin db = new DatabaseAdmin(); 但它是说我需要添加参数,上下文。 当我输入参数为: DatabaseAdmin db = new DatabaseAdmin(getApplicationContext()); 该应用程序保持关闭多个错误,所以我认为这不是解决方案。
想法?如何创建一个可以访问此类的对象,并使用所有可用的方法访问此类,之后,是否需要执行任何异常来使用/调用它? (PS,道歉,如果我包含了太多的代码,试图削减它,不知道是否重要,可能是线索。如果代码太多,请让我知道,我会修剪它进一步)
这里是我的代码:
//imports Cropped for space saving
//This class manages the database for the entire application
public class DatabaseAdmin extends Activity
{
DatabaseHelper dbhelper;
Context ctx;
//Create an object of the SQLite database which we can use to open and close it
SQLiteDatabase db;
//SQL Variables
public static final String TABLE_NAME = "table";
public static final String COLUMN_NAME_AT_RISK = "at_risk";
public static final String TEXT_TYPE = " TEXT";
public static final String COMMA = ",";
//String to create the database
public static final String SQL_CREATE_DATABASE =
"CREATE TABLE " +
TABLE_NAME + " (" +
COLUMN_NAME_AT_RISK + " REAL 1417"
")";
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "RSRToolbox.db";
public DatabaseAdmin(Context ctx) {
this.ctx = ctx;
dbhelper = new DatabaseHelper(ctx);
}
//DatabaseHelper
private class DatabaseHelper extends SQLiteOpenHelper {
//Constructor for DatabaseHelper
public DatabaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
//Creates database
try {
db.execSQL(SQL_CREATE_DATABASE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST commissions");
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
//Method to open the database
public DatabaseAdmin openDB(){
db = dbhelper.getWritableDatabase();
return this;
}
//Method for closing the database
public void closeDB(){
dbhelper.close();
}
//Method to insert data into the database
public long InsertData(String column_name, String value){
ContentValues content = new ContentValues();
content.put(column_name, value);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor getData(String[] column_name){
return db.query(TABLE_NAME, column_name, null, null, null, null, null);
}
}
删除此:'延伸Activity'。它没有。 – 323go
我会这样做,谢谢。 – Silmarilos