【问题标题】:Access SQLite from BaseAdapter从 BaseAdapter 访问 SQLite
【发布时间】:2015-07-01 23:09:11
【问题描述】:

我有一个基本适配器类,并想使用光标从它访问一个 SQLite 表,但我在上下文中遇到了问题。我是否以正确的方式获取上下文?

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

【问题讨论】:

  • 您是否在其他要使用inflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 的目标中使用Activity 参数?看我的回答

标签: android sqlite android-context baseadapter


【解决方案1】:

你得到的例外是因为你试图在null 对象上执行方法——从文本中很明显。

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

bh = new DbHelper(context);

并且繁荣 Null 指针异常!
我认为那很清楚:)

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2012-11-12
    • 2016-12-10
    • 2016-08-15
    相关资源
    最近更新 更多