【问题标题】:Android SQLLiteDataBase cursor returning 0 rowsAndroid SQLLiteDataBase 游标返回 0 行
【发布时间】:2011-06-15 18:33:28
【问题描述】:

在我的一生中,我无法让光标返回任何数据。我已经验证了它们是数据库中的数据并且我的插入工作正常。官方错误是:

CursorIndexOutOfBoundsException: 请求索引 0,大小为 0

顶级声明:

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
    this.db = this.DBHelper.getWritableDatabase();
}

我的功能:

public String getRandomEntry()
    {
    int rand;
    Random random = new Random();
    int numEntries = (int)this.getCount();

    if(numEntries == 0)
        return "ERROR: Database is empty.";
    rand = random.nextInt(numEntries);

    Cursor cursor = DBHelper.getWritableDatabase().rawQuery(
            "SELECT * FROM " + DATABASE_TABLE 
            + " WHERE " + COLUMN_A + " = " + 0, null);

    Log.i("numEntries", Integer.toString(numEntries));
    Log.i("rand", Integer.toString(rand));
    Log.i("cursor", Integer.toString(cursor.getCount()));

    cursor.moveToFirst();
    return cursor.getString(0);
}

我也尝试过这样抓取光标:

Cursor cursor = db.rawQuery(
            "SELECT * FROM " + DATABASE_TABLE 
            + " WHERE " + COLUMN_A + " = " + 0, null);

请给我你的想法!谢谢!!

【问题讨论】:

  • +1 使用SQLiteOpenHelper-class
  • 在数据库中... COLUMN_A = 0? ... rand 是干什么用的?
  • STRING COLUMN_A = "_id";,对不起,应该包括那个。
  • 我取出随机数以将问题隔离到光标。无论我是否查找 COLUMN_A = 0,1,2....(其中 COLUMN_A 是数据库中的 _id 列)。

标签: java android sql database cursor


【解决方案1】:

这里似乎没有什么是随机的。看来您每次都在寻找值为 0 的 column_a。

我会假设 column_a 的值为 0。

【讨论】:

  • 我取出随机数以将问题隔离到光标。无论我是否查找 COLUMN_A = 0,1,2....(其中 COLUMN_A 是数据库中的 _id 列)。
  • 如果不添加'where'子句,光标会是什么样子?
  • 添加了两条记录。如果没有“where”,日志会正确报告 cursor.getCount() = 2。
  • ID 是什么?您可以使用光标中的一个 id 运行 where 吗?
  • 认为我发现了问题,我创建了这样的表:private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + "(" + COLUMN_A + " " + TYPE_A + ", " + COLUMN_B + " " + TYPE_B + ", " + COLUMN_C + " " + TYPE_C + ", " + COLUMN_D + " " + TYPE_D + ");"; 其中:public static final String TYPE_A = "INTEGER PRIMARY KEY AUTOINCREMENT"; 每次我运行(甚至执行 db.delete)时,自动增量都不会重置,所以它在 45、46、47 等处添加记录现在...如何重置自动增量?
【解决方案2】:

首先尝试这样查询:

String args[] = new String[]{"0"};

Cursor cursor = db.rawQuery(
        "SELECT * FROM " + DATABASE_TABLE + " WHERE " + COLUMN_A + " = ?", args);

如果您在那里查询返回行,这无助于使用外部工具检查您的数据库。

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2014-06-18
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多