【问题标题】:cannot conver sql query to string[] in android无法在android中将sql查询转换为字符串[]
【发布时间】:2016-08-24 05:42:02
【问题描述】:

我正在尝试将查询中的字符串放入字符串 [],但出现错误:

FATAL EXCEPTION: main
    java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

这是我的代码:

private void getCitiesArray() {
    DonorDbHelper donorDbHelper = new DonorDbHelper(getActivity());
    String[] cityColumnName = new String[]{DonorContract.CitiesEntry.COLUMN_NAME};

    Cursor c = donorDbHelper.getReadableDatabase().query(DonorContract.CitiesEntry.TABLE_NAME,
            cityColumnName,
            null, null, null, null, null
    );
    c.moveToFirst();
    String[] test = null;
    int count = c.getCount();
    for (int i = 1; i < count ; i++){
        test[i-1] = c.getString(i);
        Log.d("111", "city #" + i + " - " + c.getString(i));
    }
    c.close();
}

日期基准:

@Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        final String SQL_CREATE_CITIES_TABLE = "CREATE TABLE " + CitiesEntry.TABLE_NAME + " (" +
                CitiesEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                CitiesEntry.COLUMN_CITY_ID + " INTEGER NOT NULL," +
                CitiesEntry.COLUMN_NAME + " TEXT NOT NULL," +
                CitiesEntry.COLUMN_REGION + " INTEGER NOT NULL, " +
                "UNIQUE ( " + CitiesEntry.COLUMN_CITY_ID + " ) ON CONFLICT REPLACE);";

sqLiteDatabase.execSQL(SQL_CREATE_CITIES_TABLE);
    }

为什么会发生以及如何解决?

【问题讨论】:

  • 请显示您的数据库类...

标签: android cursor illegalstateexception


【解决方案1】:

您不是循环游标行而是循环列。此外,您忘记初始化 String 数组。

c.moveToFirst();
int count = c.getCount();
String[] strings = new String[count];
for (int i = 0; i < count ; ++i){
    strings[i] = c.getString(0);
    Log.d("111", "city #" + i + " - " + c.getString(i));
    c.moveToNext();
}
c.close();

这里我循环返回的行并将第一列的值保存为字符串。

【讨论】:

  • 是的,你是对的!谢谢!但万一: c.getString(0);它总是返回相同的(第一个)字符串。我需要把所有数据,但不仅仅是首先放入 string[]
  • 你能帮我如何将所有行作为字符串返回吗?
  • @AndriyAntonov 我刚刚给你看了。此代码将每一行的第一列值添加到字符串数组中。
  • 对不起,我想念 c.moveToNext,它返回给我相同的值...非常感谢!
【解决方案2】:

这是一个例子。试试这个:

Cursor cu=db.query(Helper.TABLE_NAME, column, null, null, null, null,null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    相关资源
    最近更新 更多