没有得到数据库的所有项目

时间:2016-12-28 19:15:58

标签: android android-sqlite

我只获得arraylist的大小而不是数据库类返回的arraylist项目,这里到目前为止我所做的,问题是我只从数据库中获取一个项目。

MainActivity

//inside oncreate
List<Integer> id=new ArrayList<>();
List<Integer> retrieve_id=new ArrayList<>();

for(int i=0;i<300;i++){
    id.add(i);
}
database.addAll(id);

//method to get all data
public void getData(){

    List<Integer> id=new ArrayList<>();
    id=database.getAllData();
    Log.e("Returned size:",""+id.size());
}

在数据库类

        public static final String TABLE_NAME ="IdHelper";
        public static final String ID="id";
        public static final String CREATE_TABLE_ID = "CREATE TABLE "
                + TABLE_NAME
                + " ( "
                + ID
                + " INTEGER ) ";
        public static final String DROP_TABLE_ID = "DROP TABLE IF EXISTS " + TABLE_NAME;
        public static final String SELECT_ALL_ID = "select * from " + TABLE_NAME_ID + ";";


    public boolean addAll(List<Integer> id){

        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL(DROP_TABLE_ID);
        db.execSQL(CREATE_TABLE_ID);
        ContentValues values = new ContentValues();

        for(int i=0;i<id.size();i++){
            values.put(ID,id.get(i));
            Log.e("DBValues",id.get(i).toString());
        }

        db.insert(TABLE_NAME_ID, null, values);
        db.close();

        if (isInserted == -1)
            return false;
        else
            return true;

        return true;
    }

    public List<Integer> getAllData(){
        List<Integer> idList = new LinkedList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(SELECT_ALL_ID, null);
        if (cursor.moveToFirst()) {
            do {
                idList.add(Integer.valueOf(cursor.getString(cursor.getColumnIndex(ID))));
                Log.e("Ranjan","Return/" + cursor.getString(cursor.getColumnIndex(ID)));
            } while (cursor.moveToNext());
        }
        return idList;
    }
}

1 个答案:

答案 0 :(得分:0)

修改此更改: -

public static final String SELECT_ALL_ID =&#34; select * from&#34; + TABLE_NAME +&#34 ;;&#34;;

将此db.insert(TABLE_NAME_ID, null, values);行放在for循环中: -

for(int i=0;i<id.size();i++){
            values.put(ID,id.get(i));
            Log.e("DBValues",id.get(i).toString());
            db.insert(TABLE_NAME_ID, null, values);
        }