【问题标题】:DBHelper class cannot be instantiated (a subclass of SQLiteOpenHelper) inside the same classDBHelper 类不能在同一个类中实例化(SQLiteOpenHelper 的子类)
【发布时间】:2018-10-14 07:06:55
【问题描述】:

我想访问数据库并将数据插入 SQLite 数据库。为了访问数据库,我尝试实例化我创建的扩展 SQLiteOpenHelper 类的 DBHelper 类。 DBHelperclass 的构造函数是:

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();
}


}

【问题讨论】:

    标签: java android sqlite android-sqlite sqliteopenhelper


    【解决方案1】:

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

    DBHelper myDb = new DBHelper(this); 
    


    DBHelper myDb = new DBHelper(getApplicationContext());
    

    【讨论】:

    • BHelper mydb = new DBHelper(view.getContext());当使用这个时,它会给出一个错误提示“无法解析符号视图”
    • 在您的活动中使用任何View,而不是view
    • 当使用 View 而不是查看它“给出错误非静态方法 'getContext()' 不能从静态上下文中引用”谢谢!
    • 不要使用View 它是一个类名。在您的活动中使用视图的名称,或仅使用 this
    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2014-03-14
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多