无法将 sql 查询转换为 android 中的字符串 []

cannot conver sql query to string[] in android

我正在尝试将查询中的字符串放入字符串[],但我遇到了一个错误:

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);
    }

为什么会发生这种情况以及如何解决这个问题?

您不是在循环游标行,而是在循环列。此外,您忘记了初始化 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();

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

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

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