I'm trying to use sambas database as I need it for the web version of my app but I'm struggling with it.
I have an OpeningTimes form in my app that I save to db as a Map.
The logic I use in the saving method is: Load the form from db using the userName parameter of the OpeningTimes object I pass in , if none is found then save it, if instead a record is found then update it with the passed in object. I'm using flutter_bloc to manage it all so in OpeningTimesBloc when the form is saved to db, it loads it and yield it so to update UI to last saved sate. The problem is that when loading from db after updating, the loaded value is not the one passed in update method( eg monMorAct: to be updated from true to false):
flutter: updateOpeningTimes() : update opening time received {userName: zazza zenigata, monMorOp: 10:00, monMorCl: 19:00, monMorAct: false, monAftOp: , monAftCl: , monAftAct: false, tueMorOp: , tueMorCl: , tueMorAct: false, tueAftOp: , tueAftCl: , tueAftAct: false, wedMorOp: , wedMorCl: , wedMorAct: false, wedAftOp: , wedAftCl: , wedAftAct: false, thuMorOp: , thuMorCl: , thuMorAct: false, thuAftOp: , thuAftCl: , thuAftAct: false, friMorOp: , friMorCl: , friMorAct: false, friAftOp: , friAftCl: , friAftAct: false, satMorOp: , satMorCl: , satMorAct: false, satAftOp: , satAftCl: , satAftAct: false, sunMorOp: , sunMorCl: , sunMorAct: false, sunAftOp: , sunAftCl: , sunAftAct: false}
but when loading it:
flutter: loadOpeningTimes() snapshot is: Record(openingTimeStorage, 1) {userName: zazza zenigata, monMorOp: 10:00, monMorCl: 19:00, monMorAct: true, monAftOp: , monAftCl: , monAftAct: false, tueMorOp: , tueMorCl: , tueMorAct: false, tueAftOp: , tueAftCl: , tueAftAct: false, wedMorOp: , wedMorCl: , wedMorAct: false, wedAftOp: , wedAftCl: , wedAftAct: false, thuMorOp: , thuMorCl: , thuMorAct: false, thuAftOp: , thuAftCl: , thuAftAct: false, friMorOp: , friMorCl: , friMorAct: false, friAftOp: , friAftCl: , friAftAct: false, satMorOp: , satMorCl: , satMorAct: false, satAftOp: , satAftCl: , satAftAct: false, sunMorOp: , sunMorCl: , sunMorAct: false, sunAftOp: , sunAftCl: , sunAftAct: false}
Can you spot what I am doing wrong?
As always thank you very much for your time and help.
This is the singleton:
import 'dart:async';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
class AppDatabase {
// Singleton instance
static final AppDatabase _singleton = AppDatabase._();
// Singleton accessor
static AppDatabase get instance => _singleton;
// Completer is used for transforming synchronous code into asynchronous code.
Completer<Database> _dbOpenCompleter;
// A private constructor. Allows us to create instances of AppDatabase
// only from within the AppDatabase class itself.
AppDatabase._();
// Sembast database object
Database _database;
// Database object accessor
Future<Database> get database async {
// If completer is null, AppDatabaseClass is newly instantiated, so database is not yet opened
if (_dbOpenCompleter == null) {
_dbOpenCompleter = Completer();
// Calling _openDatabase will also complete the completer with database instance
_openDatabase();
}
// If the database is already opened, awaiting the future will happen instantly.
// Otherwise, awaiting the returned future will take some time - until complete() is called
// on the Completer in _openDatabase() below.
return _dbOpenCompleter.future;
}
Future _openDatabase() async {
// Get a platform-specific directory where persistent app data can be stored
final appDocumentDir = await getApplicationDocumentsDirectory();
// Path with the form: /platform-specific-directory/demo.db
final dbPath = join(appDocumentDir.path, 'demo.db');
final database = await databaseFactoryIo.openDatabase(dbPath);
// Any code awaiting the Completer's future will now start executing
_dbOpenCompleter.complete(database);
}
}
This is the bloc:
class OpeningTimesBloc extends Bloc<OpeningTimesEvent, OpeningTimesState> {
OpeningTimesRepository _openingTimesRepository = OpeningTimesRepository();
#override
OpeningTimesState get initialState => InitialState();
#override
Stream<OpeningTimesState> mapEventToState(OpeningTimesEvent event) async* {
if (event is LoadOpeningTimes) {
print('GetOpeningTimes event received');
yield* _mapLoadOpeningTimesToState(event);
}
if (event is SaveOpeningTimes) {
yield* _mapSaveOpeningTimesToState(event);
}
}
Stream<OpeningTimesState> _mapLoadOpeningTimesToState(
LoadOpeningTimes event) async* {
OpeningTimes openingTimes = await _openingTimesRepository.loadOpeningTimes(
userName: event.user.name);
print(
'_mapLoadOpeningTimesToState() loaded openingTimes is: ${openingTimes.toMap().toString()}');
yield ShopOpeningTimes(openingTimes);
}
Stream<OpeningTimesState> _mapSaveOpeningTimesToState(
SaveOpeningTimes event) async* {
await _openingTimesRepository.saveOpeningTimes(event.openingTimes);
add(LoadOpeningTimes(event.user));
}
}
this is the repository:
import 'package:sembast/sembast.dart';
class OpeningTimesRepository {
// name for the storage
static const String openingTimeStorage = 'openingTimeStorage';
// storage reference
final _openingTimesFolder = intMapStoreFactory.store(openingTimeStorage);
// database instance
Future<Database> get _db async => await AppDatabase.instance.database;
Future saveOpeningTimes(OpeningTimes openingTimes) async {
print(
'saveOpeningTimes(): save opening times received ${openingTimes.toMap().toString()}'); // prints correct
final snapshot = await loadOpeningTimes(userName: openingTimes.userName);
print('saveOpeningTimes() snapshot is $snapshot');
if (snapshot == null) {
print('opening times are to save');
await _openingTimesFolder.add(await _db, openingTimes.toMap());
} else {
print('opening times are to update');
await updateOpeningTimes(openingTimes);
}
}
Future updateOpeningTimes(OpeningTimes openingTimes) async {
print(
'updateOpeningTimes() : update opening time received ${openingTimes.toMap().toString()}'); // correct
final Finder finder = Finder(filter: Filter.byKey(openingTimes.userName));
await _openingTimesFolder.update(await _db, openingTimes.toMap(),
finder: finder);
}
Future<OpeningTimes> loadOpeningTimes({String userName}) async {
print(
'loadOpeningTimes() called userName is $userName'); // prints correct userName
final finder = Finder(sortOrders: [SortOrder('userName')]);
final snapshot =
await _openingTimesFolder.findFirst(await _db, finder: finder);
print('loadOpeningTimes() snapshot is: ${snapshot}'); // correct
return OpeningTimes.fromMap(snapshot.value);
}
}
and this is the model:
import 'package:flutter/material.dart';
class OpeningTimes {
int id;
final String userName;
final String monMorOp;
final String monMorCl;
final bool monMorAct;
final String monAftOp;
final String monAftCl;
final bool monAftAct;
final String tueMorOp;
final String tueMorCl;
final bool tueMorAct;
final String tueAftOp;
final String tueAftCl;
final bool tueAftAct;
final String wedMorOp;
final String wedMorCl;
final bool wedMorAct;
final String wedAftOp;
final String wedAftCl;
final bool wedAftAct;
final String thuMorOp;
final String thuMorCl;
final bool thuMorAct;
final String thuAftOp;
final String thuAftCl;
final bool thuAftAct;
final String friMorOp;
final String friMorCl;
final bool friMorAct;
final String friAftOp;
final String friAftCl;
final bool friAftAct;
final String satMorOp;
final String satMorCl;
final bool satMorAct;
final String satAftOp;
final String satAftCl;
final bool satAftAct;
final String sunMorOp;
final String sunMorCl;
final bool sunMorAct;
final String sunAftOp;
final String sunAftCl;
final bool sunAftAct;
OpeningTimes(
{#required this.userName,
#required this.monMorOp,
#required this.monMorCl,
#required this.monMorAct,
#required this.monAftOp,
#required this.monAftCl,
#required this.monAftAct,
#required this.tueMorOp,
#required this.tueMorCl,
#required this.tueMorAct,
#required this.tueAftOp,
#required this.tueAftCl,
#required this.tueAftAct,
#required this.wedMorOp,
#required this.wedMorCl,
#required this.wedMorAct,
#required this.wedAftOp,
#required this.wedAftCl,
#required this.wedAftAct,
#required this.thuMorOp,
#required this.thuMorCl,
#required this.thuMorAct,
#required this.thuAftOp,
#required this.thuAftCl,
#required this.thuAftAct,
#required this.friMorOp,
#required this.friMorCl,
#required this.friMorAct,
#required this.friAftOp,
#required this.friAftCl,
#required this.friAftAct,
#required this.satMorOp,
#required this.satMorCl,
#required this.satMorAct,
#required this.satAftOp,
#required this.satAftCl,
#required this.satAftAct,
#required this.sunMorOp,
#required this.sunMorCl,
#required this.sunMorAct,
#required this.sunAftOp,
#required this.sunAftCl,
#required this.sunAftAct});
#override
List<Object> get props => [
userName,
monMorOp,
monMorCl,
monMorAct,
monAftOp,
monAftCl,
monAftAct,
tueMorOp,
tueMorCl,
tueMorAct,
tueAftOp,
tueAftCl,
tueAftAct,
wedMorOp,
wedMorCl,
wedMorAct,
wedAftOp,
wedAftCl,
wedAftAct,
thuMorOp,
thuMorCl,
thuMorAct,
thuAftOp,
thuAftCl,
thuAftAct,
friMorOp,
friMorCl,
friMorAct,
friAftOp,
friAftCl,
friAftAct,
satMorOp,
satMorCl,
satMorAct,
satAftOp,
satAftCl,
satAftAct,
sunMorOp,
sunMorCl,
sunMorAct,
sunAftOp,
sunAftCl,
sunAftAct
];
factory OpeningTimes.fromMap(Map<String, dynamic> map) => new OpeningTimes(
userName: map['userName'],
monMorOp: map['monMorOp'],
monMorCl: map['monMorCl'],
monMorAct: map['monMorAct'],
monAftOp: map['monAftOp'],
monAftCl: map['monAftCl'],
monAftAct: map['monAftAct'],
tueMorOp: map['tueMorOp'],
tueMorCl: map['tueMorCl'],
tueMorAct: map['tueMorAct'],
tueAftOp: map['tueAftOp'],
tueAftCl: map['tueAftCl'],
tueAftAct: map['tueAftAct'],
wedMorOp: map['wedMorOp'],
wedMorCl: map['wedMorCl'],
wedMorAct: map['wedMorAct'],
wedAftOp: map['wedAftOp'],
wedAftCl: map['wedAftCl'],
wedAftAct: map['wedAftAct'],
thuMorOp: map['thuMorOp'],
thuMorCl: map['thuMorCl'],
thuMorAct: map['thuMorAct'],
thuAftOp: map['thuAftOp'],
thuAftCl: map['thuAftCl'],
thuAftAct: map['thuAftAct'],
friMorOp: map['friMorOp'],
friMorCl: map['friMorCl'],
friMorAct: map['friMorAct'],
friAftOp: map['friAftOp'],
friAftCl: map['friAftCl'],
friAftAct: map['friAftAct'],
satMorOp: map['satMorOp'],
satMorCl: map['satMorCl'],
satMorAct: map['satMorAct'],
satAftOp: map['satAftOp'],
satAftCl: map['satAftCl'],
satAftAct: map['satAftAct'],
sunMorOp: map['sunMorOp'],
sunMorCl: map['sunMorCl'],
sunMorAct: map['sunMorAct'],
sunAftOp: map['sunAftOp'],
sunAftCl: map['sunAftCl'],
sunAftAct: map['sunAftAct'],
);
Map<String, dynamic> toMap() => {
'userName': userName,
'monMorOp': monMorOp,
'monMorCl': monMorCl,
'monMorAct': monMorAct,
'monAftOp': monAftOp,
'monAftCl': monAftCl,
'monAftAct': monAftAct,
'tueMorOp': tueMorOp,
'tueMorCl': tueMorCl,
'tueMorAct': tueMorAct,
'tueAftOp': tueAftOp,
'tueAftCl': tueAftCl,
'tueAftAct': tueAftAct,
'wedMorOp': wedMorOp,
'wedMorCl': wedMorCl,
'wedMorAct': tueMorAct,
'wedAftOp': wedAftOp,
'wedAftCl': wedAftCl,
'wedAftAct': wedAftAct,
'thuMorOp': thuMorOp,
'thuMorCl': thuMorCl,
'thuMorAct': thuMorAct,
'thuAftOp': thuAftOp,
'thuAftCl': thuAftCl,
'thuAftAct': thuAftAct,
'friMorOp': friMorOp,
'friMorCl': friMorCl,
'friMorAct': friMorAct,
'friAftOp': friAftOp,
'friAftCl': friAftCl,
'friAftAct': friAftAct,
'satMorOp': satMorOp,
'satMorCl': satMorCl,
'satMorAct': satMorAct,
'satAftOp': satAftOp,
'satAftCl': satAftCl,
'satAftAct': satAftAct,
'sunMorOp': sunMorOp,
'sunMorCl': sunMorCl,
'sunMorAct': sunMorAct,
'sunAftOp': sunAftOp,
'sunAftCl': sunAftCl,
'sunAftAct': sunAftAct
};
}
Updated repository methods to use autogenerated key:
static const String openingTimeStorage = 'openingTimeStorage';
// storage reference
final _openingTimesFolder = intMapStoreFactory.store(openingTimeStorage);
// database instance
Future<Database> get _db async => await AppDatabase.instance.database;
Future saveOpeningTimes(OpeningTimes openingTimes) async {
print(
'saveOpeningTimes(): save opening times received ${openingTimes.toMap().toString()}'); // prints correct
final snapshot = await loadOpeningTimes();
print('saveOpeningTimes() snapshot is $snapshot');
if (snapshot == null) {
print('opening times are to save');
await _openingTimesFolder.add(await _db, openingTimes.toMap());
return;
} else {
print('opening times are to update');
await updateOpeningTimes(openingTimes);
}
}
Future updateOpeningTimes(OpeningTimes openingTimes) async {
print(
'updateOpeningTimes() : update opening time received ${openingTimes.toMap().toString()}'); // correct
final Finder finder = Finder(
filter: Filter.byKey(
_openingTimesFolder.record(openingTimes.id).get(await _db)));
await _openingTimesFolder.update(await _db, openingTimes.toMap(),
finder: finder);
}
Future<OpeningTimes> loadOpeningTimes() async {
final finder = Finder(sortOrders: [SortOrder('userName')]);
final snapshot =
await _openingTimesFolder.findFirst(await _db, finder: finder);
if (snapshot != null) {
print('loadOpeningTimes() snapshot is: $snapshot'); // correct
OpeningTimes openingTimes = OpeningTimes.fromMap(snapshot.value);
openingTimes.id = snapshot.key;
return openingTimes;
} else {
return null;
}
}
on updating I get flutter: Erros is Invalid argument(s): Record key cannot be null.
In updateOpeningTimes your filter looks incorrect.
final Finder finder = Finder(filter: Filter.byKey(openingTimes.userName));
Here you are looking for objects with the userName as the key but the key is an int (autogenerated) here so it cannot match. You should have something like:
final Finder finder = Finder(filter: Filter.equals('userName', userName));
In loadOpeningTimes, you just take the first record sorted by userName. If you look for an explicit userName, you should use the same finder than for update.
As a side note, it is a lot faster to load records by key: store.record(key).get(db)
I am building a money budgeting app where the user can split their monthly salary in 5 areas: food, social, education, travel, savings. I have a register and log in screen. This is in Flutter/dart and I'm using sqlite.
Some of the data to store:
id, username, password, email, monthly_salary, food_initial, food_final, social_initial, social_final, education_initial, education_final, travel_initial, travel_final, savings_initial, savings_final
The 'initial' refers to a value that the user will input for themselves based on the division of the monthly salary. (ie. $5000 a month/5 containers = 1000 for each container. but, the user can edit this value of 1000 as their initial budgeted money). The 'final' refers to the user's remaining money (under the assumption they don't go over) for that container.
The initial and final values get reset at the end of the month. However, I would like to save their previous month's final values so the user can see a backlog of what they did.
I initially had 2 tables for my database. One was for the USER_DATA and the other was BUDGETS table. However, after struggling to figure out how to do CRUD operations for two tables, I decided to make it all into one table. But, after experiencing trouble with one table, I want to move back to more than one table. I'm confused now on:
1. How to use CRUD operations when having more than one table on DB?
2. Do I have to build a new model class in order to have more than one table?
3. How to save some of the user's data on database, but have to wait for the rest of the information to come in (later on while they're using the app)?
When making the constructor for the model class, and then referring to the model class in the UI, it requires me to bring in all of the parameters I have, but I don't have all of those values ready yet. The user still needs to register before they can input their salary and etc. Would I have to use the Future class to get over this hurdle?
I've watched a lot of videos on others building their databases in sqlite and with Flutter but all of them usually do a simple To-Do list app where they will need to fill in every column of the table and I haven't seen one yet that includes several tables. (ie. columns: id, description, priority, date)
--
I think have a good basis now on the UI side and using TextFormFields to access the information, but connecting the database/creating it properly is confusing me.
I am also considering writing the database in a .sql file now before proceeding. I have been teaching myself Flutter through tutorials (as background knowledge).
I know this is a bit long and all over the place, but I would greatly appreciate anyone who has experience with the sqlite environment in Flutter to please help me understand how to do this correctly.
Thank you. Also, if there is any more clarification/code needed, let me know.
Model class:
import 'dart:core';
class UserData {
//user table
int _userid;
String _username;
String _password;
String _email;
String _first_name;
String _last_name;
String _date;
int _month_id;
bool _subtract; //did the user subtract money from their funds? true/false
double _month_salary;
String _log_details;
/////////////budget table
double _edu_budget_initial;
double _edu_budget_final;
double _travel_budget_initial;
double _travel_budget_final;
double _living_budget_initial;
double _living_budget_final;
double _savings_budget_initial;
double _savings_budget_final;
double _social_budget_initial;
double _social_budget_final;
// using [___] around your user's data entry makes it optional in the table
// otherwise, these are all required fields
UserData(
this._username,
this._email,
this._first_name,
this._last_name,
this._password,
this._date,
this._month_id,
this._subtract,
this._month_salary,
this._log_details,
this._edu_budget_final,
this._edu_budget_initial,
this._living_budget_final,
this._living_budget_initial,
this._savings_budget_final,
this._savings_budget_initial,
this._social_budget_final,
this._social_budget_initial,
this._travel_budget_final,
this._travel_budget_initial);
//created a Named Constructor for the ability to create multiple constructors in one class
UserData.withId(
this._userid,
this._username,
this._password,
this._first_name,
this._last_name,
this._email,
this._date,
this._month_id,
this._subtract,
this._month_salary,
this._log_details,
this._edu_budget_final,
this._edu_budget_initial,
this._living_budget_final,
this._living_budget_initial,
this._savings_budget_final,
this._savings_budget_initial,
this._social_budget_final,
this._social_budget_initial,
this._travel_budget_final,
this._travel_budget_initial);
//UserData.budgetTable(this.date, this.month_id, this.log_details, this.edu_budget_final, this.edu_budget_initial, this.living_budget_final, this.living_budget_initial,
//this.month_salary, this.savings_budget_final, this.savings_budget_initial, this.social_budget_final,
//this.social_budget_initial, this.travel_budget_final, this.travel_budget_initial);
//getters:
//userdata table
int get userid => _userid;
String get username => _username;
String get password => _password;
String get email => _email;
String get firstname => _first_name;
String get lastname => _last_name;
String get date => _date;
//budget table
int get month_id => _month_id;
bool get subtract => _subtract;
double get month_salary => _month_salary;
String get log_details => _log_details;
double get living_budget_initial => _living_budget_initial;
double get living_budget_final => _living_budget_final;
double get social_budget_initial => _social_budget_initial;
double get social_budget_final => _social_budget_final;
double get edu_budget_initial => _edu_budget_initial;
double get edu_budget_final => _edu_budget_final;
double get travel_budget_initial => _travel_budget_initial;
double get travel_budget_final => _travel_budget_final;
double get savings_budget_initial => _savings_budget_initial;
double get savings_budget_final => _savings_budget_final;
//setters:
/*
set userid(int newUserID) {
//adding condition before storing what user put in
if (newUserID <= 12) {
this._userid = newUserID;
}
}
*/
set username(String newUsername) {
if (newUsername.length <= 30) {
this._username = newUsername;
}
}
set password(String newPassword) {
if (newPassword.length <= 30)
this._password = newPassword;
}
set email(String newEmail) {
if (newEmail.length <= 50)
this._email = newEmail;
}
set first_name(String newFirstName) {
if (newFirstName.length <= 30)
this._first_name = newFirstName;
}
set last_name(String newLastName) {
if (newLastName.length <= 30)
this._last_name = newLastName;
}
set month_id(int newMonthId) {
if (newMonthId <= 12) {
this._month_id = newMonthId;
}
}
set month_salary(double newMonthSalary) {
this._month_salary = newMonthSalary;
}
set date(String newDate) {
this._date = newDate;
}
set log_details(String newLogDetails) {
if (newLogDetails.length <= 255)
this._log_details = newLogDetails;
}
set subtract(bool newSubtract) {
this._subtract = newSubtract;
}
set living_budget_initial(double newLBI) {
if (newLBI <= 10) this._living_budget_initial = newLBI;
}
set living_budget_final(double newLBF) {
if (newLBF <= 10) this._living_budget_final = newLBF;
}
set social_budget_initial(double newSOBI) {
if (newSOBI <= 10) this._social_budget_initial = newSOBI;
}
set social_budget_final(double newSOBF) {
if (newSOBF <= 10) this._social_budget_final = newSOBF;
}
set edu_budget_initial(double newEBI) {
if (newEBI <= 10) this._edu_budget_initial = newEBI;
}
set edu_budget_final(double newEBF) {
if (newEBF <= 10) this._edu_budget_final = newEBF;
}
set travel_budget_initial(double newTBI) {
if (newTBI <= 10) this._travel_budget_initial = newTBI;
}
set travel_budget_final(double newTBF) {
if (newTBF <= 10) this._travel_budget_final = newTBF;
}
set savings_budget_initial(double newSBI) {
if (newSBI <= 10) this._savings_budget_initial = newSBI;
}
set savings_budget_final(double newSBF) {
if (newSBF <= 10) this._savings_budget_final = newSBF;
}
// converting object into Map objects
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
var userid;
if (userid != null) {
map['userid'] = _userid;
}
map['userid'] = _userid;
map['username'] = _username;
map['password'] = _password;
map['email'] = _email;
map['first_name'] = _first_name;
map['last_name'] = _last_name;
//
map['month_id'] = _month_id;
map['month_salary'] = _month_salary;
map['date'] = _date;
map['log_details'] = _log_details;
map['subtract'] = _subtract;
map['living_budget_initial'] = _living_budget_initial;
map['living_budget_final'] = _living_budget_final;
map['social_budget_initial'] = _social_budget_initial;
map['social_budget_final'] = _social_budget_final;
map['edu_budget_initial'] = _edu_budget_initial;
map['edu_budget_final'] = _edu_budget_final;
map['travel_budget_initial'] = _travel_budget_initial;
map['travel_budget_final'] = _travel_budget_final;
map['savings_budget_initial'] = _savings_budget_initial;
map['savings_budget_final'] = _savings_budget_final;
return map;
}
//converts map objects into objects
UserData.fromMapObject(Map<String, dynamic> map) {
this._userid = map['userid'];
this._username = map['username'];
this._password = map['password'];
this._email = map['email'];
this.first_name = map['first_name'];
this.last_name = map['last_name'];
//
this._month_id = map['month_id'];
this._month_salary = map['month_salary'];
this._date = map['date'];
this._log_details = map['log_details'];
this._subtract = map['subtract'];
this._living_budget_initial = map['living_budget_initial'];
this._living_budget_final = map['living_budget_final'];
this._social_budget_initial = map['social_budget_initial'];
this._social_budget_final = map['social_budget_final'];
this._edu_budget_initial = map['edu_budget_initial'];
this._edu_budget_final = map['edu_budget_final'];
this._travel_budget_initial = map['travel_budget_initial'];
this._travel_budget_final = map['travel_budget_final'];
this._savings_budget_initial = map['savings_budget_initial'];
this._savings_budget_final = map['savings_budget_final'];
}
}
Database helper class:
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:jewell_1/user_data.dart';
class DbHelper {
// Create a private instance of the class
static final DbHelper _dbhelper = new DbHelper._internal();
String DB_name = "user_data.db";
static final int DATABASE_VERSION = 2;
String userDataTable = 'user_data_table';
String colUserId = 'userid';
String colUsername = 'username';
String colPassword = 'password';
String colEmail = 'email';
String colFirstName = 'first_name';
String colLastName = 'last_name';
String colDate = 'date';
String colMonthId = 'month_id';
String colSubtract = 'subtract';
String colMonthSalary = 'month_salary';
String colLogDetails = 'log_details';
String colLBI = 'living_budget_initial';
String colLBF = 'living_budget_final';
String colSOBI = 'social_budget_initial';
String colSOBF = 'social_budget_final';
String colEBI = 'edu_budget_initial';
String colEBF = 'edu_budget_final';
String colTBI = 'travel_budget_initial';
String colTBF = 'travel_budget_final';
String colSBI = 'savings_budget_initial';
String colSBF = 'savings_budget_final';
// Create an empty private named constructor
DbHelper._internal();
// Use the factory to always return the same instance
factory DbHelper() {
return _dbhelper;
}
static Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
Future<Database> initializeDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + "todos.db";
var dbTodos = await openDatabase(path, version: DATABASE_VERSION, onCreate: _createDb);
return dbTodos;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $userDataTable($colUserId INETEGER PRIMARY KEY, $colUsername TEXT," +
"$colPassword TEXT, $colEmail TEXT, $colFirstName TEXT,"
"$colLastName TEXT, $colDate TEXT, $colMonthId INTEGER,"
" $colSubtract BOOLEAN, $colMonthSalary DOUBLE, $colLogDetails TEXT,"
" $colEBI DOUBLE, $colEBF DOUBLE, $colTBI DOUBLE, $colTBF DOUBLE, "
" $colLBI DOUBLE, $colLBF DOUBLE, $colSBI DOUBLE, $colSBF DOUBLE,"
" $colSOBI DOUBLE, $colSOBF DOUBLE)");
}
Future<int> insertData(UserData data) async {
Database db = await this.db;
var result = await db.insert(userDataTable, data.toMap());
return result;
}
Future<List> getDatas() async {
Database db = await this.db;
var result =
await db.rawQuery("SELECT * FROM $userDataTable order by $colUserId ASC");
return result;
}
Future<int> getCount() async {
Database db = await this.db;
var result = Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT (*) FROM $userDataTable"));
return result;
}
Future<int> updateData(UserData data) async {
var db = await this.db;
var result = await db
.update(userDataTable, data.toMap(), where: "$colUserId=?", whereArgs: [data.userid]);
return result;
}
Future<int> deleteData(int id) async {
int result;
var db = await this.db;
result = await db.rawDelete("DELETE FROM $userDataTable WHERE $colUserId=$id");
return result;
}
}
To be more specific, I am confused on not writing the query of a new table, but rather at this point:
var result = await db.insert(userDataTable, data.toMap());
return result;
The result is only containing my userDataTable and if I create another table, then am I supposed to add another var result? I tried to have:
var result2 = await db.insert(budgetsTable, data.toMap());
This seemed wrong. Also, I didn't know how to return both results.
That was specifically where/when I started to scavenge the internet of people who have made CRUD operations using more than one table on sqlite with Flutter.
I am working on Android SMS app. Part of it has to fetch inbox data (address, date, body) and fill list view. This works fine through following code :
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
lvMsg.setAdapter(adapter);
I want to insert function call to display meaningful date-time string instead of milliseconds number fetched from db. My function code:
public static String millisToDate(String TimeMillis) {
String finalDate;
long tm = Long.parseLong(TimeMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tm);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}
Any attempt to call function compile, but app crashes. How should I connect function?
This answer was helpful too:
Code looks like this:
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == aCursor.getColumnIndex("date")) {
String createDate = aCursor.getString(aColumnIndex);
TextView textView = (TextView) aView;
textView.setText(millisToDate(createDate));
return true;
}
return false;
}
});
lvMsg.setAdapter(adapter);
public static String millisToDate(String TimeMillis) {
String finalDate;
long tm = Long.parseLong(TimeMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tm);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}