从 SQLite 游标中获取所有行列到一个对象中

Get all row columns from SQLite cursor into an object

我有一个游标读取 SQLite 数据库并获取很多列,我将这些列存储在很多数组中

private ArrayList<String> column1,column2,column3,column4, ... column n;
public getCursorData(Cursor cursor){
    if(cursor.moveToFirst()){
        do{
            column1.add(Cursor.getString("column1"));
            column2.add(Cursor.getString("column2"));
            column3.add(Cursor.getString("column3"));
            column4.add(Cursor.getString("column4"));
            ...
            columnn.add(Cursor.getString("columnN"));
        }while(cursor.moveToNext());
    }
}

我正在寻找一种将它们存储在单个对象(或数组、列表或其他对象)中的方法,但我不知道该怎么做

private Object[] object;
public getCursorData(Cursor cursor){
    if(cursor.moveToFirst()){
        int i=0;
        do{
            for(int f=0;f<cursor.getColumnCount();f++){
                object[i].put(cursor.getColumnName(i), cursor.getString(i)); // I don't know what I am doing!
            }
            i++;
        }while(cursor.moveToNext());
    }
}

使用数组的不同尝试,其中每一列都是一个整数。

private String[][] data;
public getCursorData(Cursor cursor){
    if(cursor.moveToFirst()){
        int i=0;
        do{
            for(int f=0;f<cursor.getColumnCount();f++){
                data[i][f]=cursor.getString(f); // this is line 30
            }
            i++;
        }while(cursor.moveToNext());
    }
}

最后一次尝试失败,在第 30 行抛出以下错误 java.lang.NullPointerException: Attempt to read from null array(我在代码注释中标记了这一行)

我认为您可以创建一个自定义对象来映射这些值。类似于:

public class TableData {
    public String mColumn1;
    public String mColumn2;
    public String mColumn3;
    public String mColumn4;
    public String mColumn5;
}

public ArrayList<TableData> getCursorData(Cursor cursor) {

    ArrayList<TableData> resultList = new ArrayList();

    if(cursor.moveToFirst()){
        do{
            TableData row = new TableData();
            row.mColumn1 = Cursor.getString("column1");
            row.mColumn2 = Cursor.getString("column2");
            row.mColumn3 = Cursor.getString("column3");
            ...
            resultList.add(row);
        } while(cursor.moveToNext());
    }

    return resultList;
}

编辑:

如果你想保持你的方法,你应该:

private String[][] data;

public void getCursorData(Cursor cursor) {
    if (cursor.moveToFirst()) {
        data = new String[cursor.getCount()][]; // You have to instantiate your bi-dimensional array
        int i = 0;
        do {
            data[i] = new String[cursor.getColumnCount()];
            for (int f = 0; f < cursor.getColumnCount(); f++) {
                data[i][f] = cursor.getString(f);
            }
            i++;
        } while (cursor.moveToNext());
    }
}