java - 为什么我的 SQLiteOpenHelper 构造函数中出现 "incompatible types: Bla cannot be converted to Context"?

标签 java android sqlite android-sqlite sqliteopenhelper

我正在使用 this tutorial 在我的 Android 项目中实现 SQLite 功能.

我有这个 SQLiteOpenHelper 代码:

public class HHSSQLiteHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "HHS.db";
    private static final String TABLE_VENDORS = "vendors";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_VENDORID = "vendorId";
    public static final String COLUMN_COMPANYNAME = "companyName";

    public HHSSQLiteHandler(Context context, String vendor,
                       SQLiteDatabase.CursorFactory factory, int company) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }
    . . .

...但尝试以这种方式实例化该类:

protected void onPostExecute(String result) {
    try {
        JSONArray jsonArr = new JSONArray(result);
        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            String vendorId = jsonObj.getString("vendorId");
            String companyName = jsonObj.getString("companyName");
            // Prepare for writing to db
            Vendor vend = new Vendor();
            vend.setVendorId(vendorId);
            vend.setCompanyName(companyName);
            HHSSQLiteHandler sqliteHandler = new HHSSQLiteHandler(this, null, null, 1);
            sqliteHandler.addVendor(vend);
        }
    } catch (JSONException j) {
        System.out.println(j.getMessage());
        Log.i("jsonEx", j.getMessage());
    }
}

...在“HHSSQLiteHandler sqliteHandler = new HHSSQLiteHandler(this, null, null, 1);”上给我“错误:类型不兼容:MainActivity.GetVendorsTask 无法转换为上下文”行。

它到底在期待什么?我拿什么来安抚它?

最佳答案

嵌套类中的

this 指的是嵌套类实例 (GetVendorsTask),而不是外部类实例 (MainActivity)。用例如限定它MainActivity.this 引用外部类实例,如果它是 Context(例如 Activity),它将起作用。

关于java - 为什么我的 SQLiteOpenHelper 构造函数中出现 "incompatible types: Bla cannot be converted to Context"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874726/

相关文章:

java - 尝试从 URI 获取文件名时出现致命的运行时异常

java - 使用正则表达式匹配非单词字符但不匹配笑脸

Android SQLiteOpenHelper 现有数据库

sql - 如果有不同的方法可以完成相同的任务,我该如何选择最佳的 SQL 查询?

c# - 通过网络连接到 SQLite 数据库

java - Android O 固定快捷方式 - CREATE_SHORTCUT Intent 过滤器

java - 如何有效地从数据库检索数据以填充 selectonemenu

android - EditText 警告

java - 了解 Java 中的泛型方法

android - 同时支持多种语言?