不能在同一类中实例化DBHelper类(SQLiteOpenHelper的子类)

时间:2018-10-14 07:06:56

标签: java android sqlite android-sqlite sqliteopenhelper

我要访问数据库并将数据插入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();
}


}

1 个答案:

答案 0 :(得分:0)

getContext()View类的方法,因此您可以像这样使用它:
DBHelper myDb = new DBHelper(view.getContext());
其中view是一些View
如果要在活动类中实例化该类,则可以使用:

DBHelper myDb = new DBHelper(this); 


DBHelper myDb = new DBHelper(getApplicationContext());