gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:53:22 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com