Ошибка GAL при вставке данных API в БД на флаттер - PullRequest
0 голосов
/ 31 октября 2019

Здравствуйте, просто хотел попробовать свои силы на флаттере после того, как услышал об этом. И поэтому решил попробовать несколько дизайнов интерфейса, пока я не ознакомился с ним. А потом переключился на Backend. где я должен проанализировать данные, полученные из API, в локальную базу данных. но я продолжаю сталкиваться с рядом ошибок. И мой последний - это. Я не знаю, имеет ли это отношение к моему классу модели, поэтому я добавлю его также для хорошей меры.

Это мой код в dbhelper.dart, который позволяет вставлять в БД. Весь код

import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:exper/models/sector.dart';
import 'package:exper/models/sectors.dart';

class DBHelper {
  static Database _db;
  // Create the Table colums
  static const String TABLE = 'sectors';
  static const String SECTOR = 'sector';
  static const String SUB_CATEGORY = 'sub_category';
  static const String DISBURSED_AMOUNT = 'disbursed_amount';
  static const String COMMUNITY = 'comunity';
  static const String PROJECT_DESCRIPTION = 'project_description';
  static const String FUNDING_SOURCE = "funding_source";
  static const String COMPLETION_STATUS = 'completion_status';
  static const String CONTRACTOR = 'contracter';
  static const String LATITUDE = 'latitude =';
  static const String PROJECT_ID = "project_id";
  static const String FUNCTIONAL_STATUS = 'functional_status';
  static const String PROJECT_NAME = 'project_name';
  static const String CONTACT_PERSON_TEL = 'contact_person_tel';
  static const String OUTSTANDING_AMOUNT = 'outstanding_amount';
  static const String OWNERSHIP = 'ownership';
  static const String DATE = 'date';
  static const String CONTRACT_SUM = 'contract_sum';
  static const String CONTACT_PERSON = 'contact_person';
  static const String ADDITIONAL_AMOUNT = "additional_amount";
  static const String DISTRICT = 'district';
  static const String REGION = 'region';
  static const String LONGITUDE = 'longitude';
  static const String SUB_SECTOR = 'sub_sector';
  static const String CONSTITUENCY = 'constituency';
  static const String DB_NAME = "sectors.db";

  // Initialize the Database
  Future<Database> get db async {
    if (null != _db) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  initDb() async {
    // Get the Device's Documents directory to store the Offline Database...
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, DB_NAME);
    var db = await openDatabase(path, version: 1, onCreate: populateDb);
    return db;
  }

  void populateDb(Database db, int version) async {
    // Create the DB Table
    await db.execute('CREATE TABLE $TABLE ($SECTOR TEXT PRIMARY KEY,'
    '$SUB_CATEGORY TEXT, $DISBURSED_AMOUNT NUM, $COMMUNITY TEXT, $PROJECT_DESCRIPTION TEXT, $FUNDING_SOURCE TEXT, $COMPLETION_STATUS NUM , $CONTRACTOR TEXT, $LATITUDE NUM, $PROJECT_ID TEXT, $FUNCTIONAL_STATUS TEXT, $PROJECT_NAME TEXT, $CONTACT_PERSON_TEL TEXT, $OUTSTANDING_AMOUNT NUM, $OWNERSHIP TEXT, $DATE TEXT, $CONTRACT_SUM NUM, $CONTACT_PERSON TEXT, $ADDITIONAL_AMOUNT NUM, $DISTRICT TEXT, $REGION TEXT, $LONGITUDE NUM, $SUB_SECTOR TEXT, $CONSTITUENCY TEXT)');
  }

  // Method to insert the Sector record to the Database
  Future<Sector> save(Sector sector) async {
    var dbClient = await db;
    // this will insert the Sector object to the DB after converting it to a json
    sector.sector = (await dbClient.insert(TABLE, sector.toJson())) as String;
    return sector;
  }

  // Method to return all Sectors from the DB
  Future<Sectors> getSectors() async {
    var dbClient = await db;
    // specify the column names you want in the result set
    List<Map> maps = await dbClient.query(TABLE, columns: [SECTOR, SUB_CATEGORY, DISBURSED_AMOUNT, COMMUNITY]);
    Sectors allSectors = Sectors();

    List<Sector> sectors = [];
    if (maps.length > 0) {
      for (int i = 0; i < maps.length; i++) {
        sectors.add(Sector.fromJson(maps[i]));
      }
    }
    allSectors.sectors = sectors;
    return allSectors;
  }

  // Method to delete a sector and its details from the Database
  Future<int> delete(int id) async {
    var dbClient = await db;
    return await dbClient.delete(TABLE, where: '$SECTOR = ?', whereArgs: [id]);
  }

  // Method to Update an Sector in the Database
  Future<int> update(Sector sector) async {
    var dbClient = await db;
    return await dbClient.update(TABLE, sector.toJson(),
        where: '$SECTOR = ?', whereArgs: [sector.sector]);
  }

  // Method to Truncate the Table
  Future<void> truncateTable() async {
    var dbClient = await db;
    return await dbClient.delete(TABLE);
  }

  // Method to Close the Database
  Future close() async {
    var dbClient = await db;
    dbClient.close();
  }
}

Класс модели sector.dart

import 'package:json_annotation/json_annotation.dart';

part 'sector.g.dart';

@JsonSerializable()
class Sector {
    Sector();

    String sector;
    String sub_category;
    num disbursed_amount;
    String community;
    String project_description;
    String funding_source;
    num completion_status;
    String contractor;
    num latitude;
    String project_id;
    String functional_status;
    String project_name;
    String contact_person_tel;
    num outstanding_amount;
    String ownership;
    String date;
    num contract_sum;
    String contact_person;
    num additional_amount;
    String district;
    String region;
    num longitude;
    String sub_sector;
    String constituency;

    factory Sector.fromJson(Map<String,dynamic> json) => _$SectorFromJson(json);
    Map<String, dynamic> toJson() => _$SectorToJson(this);
}

Я продолжаю получать сообщение об ошибке после запуска программы в разделе Вставка

Это код ошибки, который я получаю в разделе Вставка

Exception has occurred.


 *SqfliteDatabaseException (DatabaseException(datatype mismatch (code 20 SQLITE_MISMATCH[20])) sql 'INSERT INTO sectors (sector, sub_category, disbursed_amount, community, project_description, funding_source, completion_status, contractor, latitude, project_id, functional_status, project_name, contact_person_tel, outstanding_amount, ownership, date, contract_sum, contact_person, additional_amount, district, region, longitude, sub_sector, constituency) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' args [Education, Construction, 132471.6, Asouso, Construction of 6unit classroom block at Asouso, GETFUND, 100.0, M/S Day services Ltd, 8.075973, BAPA0011, In use, 6 unit classroom block, N/A, 0.0, Government, 2018-08-30T15:15:07.693Z, 164875.15, N/A, 0.0, SENE EAST, BRONG AHAFO, -0.291576, Basic, Sene East]})*
...