将所有行列从SQLite游标获取到对象

时间:2019-07-10 20:29:54

标签: java android sqlite object android-cursor

我有一个游标读取一个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(我在代码注释中标记了此行)

1 个答案:

答案 0 :(得分:1)

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

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