我要访问数据库并将数据插入SQLite数据库。要访问数据库,我试图使我创建的扩展SQLiteOpenHelper
类的DBHelper类无效。 DBHelper
类的构造函数是:
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
因此,我尝试使用此代码使该类有趣化
DBHelper myDb = new DBHelper(getContext());
当getContext()
函数用作DBHelper
类的构造函数的参数时,它给出错误消息“无法解析方法getContext();”。
DBHelper类如下:
package com.violator.it17250_test1.Database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.violator.it17250_test1.UserProfile;
public class DBHelper extends SQLiteOpenHelper {
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + UserProfile.Users.TABLE_NAME + " (" +
UserProfile.Users.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
UserProfile.Users.COLUMN_NAME_USERNAME + " TEXT," +
UserProfile.Users.COLUMN_NAME_DOB + " TEXT, " +
UserProfile.Users.COLUMN_NAME_GENDER + "TEXT )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + UserProfile.Users.TABLE_NAME;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "users1.db";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
DBHelper myDb = new DBHelper(getContext());
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void addInfo(){
// Gets the data repository in write mode
SQLiteDatabase db = myDb.getWritableDatabase();
}
}
答案 0 :(得分:0)
getContext()
是View
类的方法,因此您可以像这样使用它:
DBHelper myDb = new DBHelper(view.getContext());
其中view
是一些View
。
如果要在活动类中实例化该类,则可以使用:
DBHelper myDb = new DBHelper(this);
或
DBHelper myDb = new DBHelper(getApplicationContext());