为什么我会在我的SQLiteOpenHelper构造函数中获得“不兼容的类型:Bla无法转换为Context”?

时间:2014-04-04 23:36:07

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

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

究竟是什么期待?我该通过什么来安抚它呢?

1 个答案:

答案 0 :(得分:8)

嵌套类中的

this引用嵌套类实例(GetVendorsTask),而不引用外部类实例(MainActivity)。用例如资格证明MainActivity.this引用外部类实例,如果它是Context(例如Activity),它将起作用。