Android sqlite分页上传离线订单后删除

1、判断订单表的的总数是否大于0,如果大于0开始上传订单

 public int getOrderCount() {
        String query = "SELECT COUNT(*) FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);

        int count = 0;

        if (cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }

        cursor.close();

        return count;
    }

2、每一页20条数据的查询

public List query(String condition) {
        String sql = String.format("SELECT * FROM %s WHERE %s LIMIT %d;", TABLE_NAME, condition,20);
        List infoList = new ArrayList<>();
        // 执行记录查询动作,该语句返回结果集的游标
        //参数一:SQL查询
        //参数二:selectionArgs
        //您可以在查询的 where 子句中包含 ?s,它将被 selectionArgs 中的值替换。这些值将绑定为字符串。
        Cursor cursor = db.rawQuery(sql, null);
//        Logger.json(JSON.toJSONString(cursor));
        // 循环取出游标指向的每条记录
        while (cursor.moveToNext()) {
            DBOrder dbOrder = new DBOrder();
            dbOrder.sn = cursor.getString(cursor.getColumnIndex("sn"));
            dbOrder.card_no = cursor.getString(cursor.getColumnIndex("card_no"));
            dbOrder.total_amount = cursor.getString(cursor.getColumnIndex("total_amount"));
            dbOrder.rowid = cursor.getLong(cursor.getColumnIndex("id"));
            dbOrder.update_time = cursor.getString(cursor.getColumnIndex("update_time"));
            dbOrder.is_metering = cursor.getString(cursor.getColumnIndex("is_metering"));
            dbOrder.terminal_params = cursor.getString(cursor.getColumnIndex("terminal_params"));
            dbOrder.ftoken = cursor.getString(cursor.getColumnIndex("ftoken"));
            dbOrder.uid = cursor.getString(cursor.getColumnIndex("uid"));
            dbOrder.is_off = cursor.getString(cursor.getColumnIndex("is_off"));
            dbOrder.pay_type = cursor.getString(cursor.getColumnIndex("pay_type"));
            infoList.add(dbOrder);
        }
        //查询完毕,关闭数据库游标
        cursor.close();
        return infoList;
    }

3、获取infoList后传给后台,如果code返回200,收集ids删除掉传入的数据,在循环到第一步,直到彻底上传完为止

 List ids = new ArrayList<>();
                        for (DBOrder dbOrder : dbOrders){
                            ids.add(dbOrder.rowid);
                        }
public void delOrder(List ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        StringBuilder idList = new StringBuilder();
        for (Long id : ids) {
            if (idList.length() > 0) {
                idList.append(",");
            }
            idList.append(id);
        }

        Logger.d("删除:" + ids);
        // 构建删除条件,将传入的ID列表拼接成适当的条件
        String condition = "id IN (" + idList.toString() + ")";

        // 执行删除操作
        db.delete(TABLE_NAME, condition, null);
    }

分页加载数据: 如果数据库中的数据量很大,不要一次性加载所有数据到 List 中。而是分页加载,每次加载一小部分数据。这可以减轻内存负担。

你可能感兴趣的:(android,sqlite,java)