从 BaseAdapter 访问 SQLite

Access SQLite from BaseAdapter

我有一个基本适配器 Class 并想使用游标从它访问 SQLite Table,但我对上下文有疑问。我获取上下文的方式正确吗?

public class GetAllEntrysListViewAdapter extends BaseAdapter {

private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater = null;
public Cursor cursor;
private SQLiteDatabase dbase;
DbHelper dbh;
private Context context;
String pos;

public GetAllEntrysListViewAdapter(JSONArray jsonArray, Activity a) {
    this.dataArray = jsonArray;
    this.activity = a;
    inflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public GetAllEntrysListViewAdapter(Context context) {
    this.context = context;
}
//...
dbh = new DbHelper(context);
        cursor = getLikes(dbh);
        cursor.moveToFirst();
        if (cursor.moveToFirst()) {
            do {
                if (Integer.parseInt(cursor.getString(2)) == 1) {
                    cell.likeImage.setImageResource(R.drawable.heart_filled);
                }
            }
            while(cursor.moveToNext());
        }
        else {
            cursor.close();
        }
        cursor.close();
}
public Cursor getLikes(DbHelper dbh) {
    dbase = dbh.getReadableDatabase();
    String columns[] = {dbh.LIKES_MARKERID, dbh.LIKES_POSITION, dbh.LIKES_LIKE};
    String selection = dbh.LIKES_MARKERID + " LIKE ? AND " + dbh.LIKES_POSITION + " LIKE ? ";
    String args[] = {pinboard.markerID.toString(), pos};
    Cursor cursor = dbase.query(dbh.TABLE_LIKES, columns, selection, args , null, null, null, null);
    return cursor;
}

这是我收到的错误消息:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference

你得到的异常是因为你试图在 null 对象上执行方法 - 从前文本中显而易见。

为什么?
您有两个构造函数 - 很简单,这不是问题所在。其中之一是将 Context 保存到 context 导致错误发生的变量(变量)。
现在,在第二个构造函数中,您 不是 设置 context 变量,因此它会一直蜂鸣 null 然后您尝试在此处使用它:

bh = new DbHelper(context);

并且 Boom Null 指针异常 !
我认为这很清楚:)

所以只需将您的代码更改为:

public GetAllEntrysListViewAdapter(JSONArray jsonArray, Context context) {
    this.dataArray = jsonArray;
    this.context= context;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

(我打赌你不会需要 Activity,99.99% 的时间都不需要它)