on passing the version to the on create method and integer(int) of the id that i want to fetch from the database,i get an error saying "int isn't a type"error Image
class NewsDbProvider {
Database db;
int() async {
Directory documentsDirectory =await getApplicationDocumentsDirectory();
final path = join(documentsDirectory.path, "items.db");
db = await openDatabase(
path,
version: 1,
onCreate: (Database newDb,int version){
newDb.execute("""
CREATE TABLE Items
(
)
""");
}
);
}
fetchItem(int id) async{
db.query(
"Items",
columns: null,
where: 'id = ?',
whereArgs: {id},
);
}
}
You named a method of NewsDbProvider as int, which is why the keyword isn't being recognised anymore. Try renaming it.
Related
I'm having problem with foreign key while adding a new habit and inserting it's data in db and I don't really know why, because everything seems right. the error is:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: DatabaseException(FOREIGN KEY constraint failed (code 787)) sql 'INSERT OR FAIL INTO Habits (userId, text, emoji, period, startPeriod) VALUES (?, ?, ?, ?, NULL)' args [1, habit, ☺, [1,2,3,4,5,6,7]]
error accrued here:
class DataService {...
late final Database db;
Future<void> addHabit(Habit newHabit) async {
final newHabitId = await HabitsDb.createHabit(db, newHabit);//error accrued here
final days = (await HabitsDb.getAllDays(db)).map((e) => Day.fromDb(e, []));
for (final day in days) {
if (newHabit.startPeriod != null &&
newHabit.startPeriod!.compareTo(day.date) > 0) {
continue;
}
if (newHabit.period.contains(day.date.weekday)) {
await HabitsDb.createHabitDay(
db, day.date.millisecondsSinceEpoch, newHabitId);
}
}
await _reloadDaysInCache();
_loadHabits();
} ...}
then:
class HabitsDb{...
static Future<int> createHabit(Database db, Habit habit) async {
return db.insert(HabitsTable.tableName, await habit.toDb(),
conflictAlgorithm: ConflictAlgorithm.fail);
}...}
model:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
...
Future<Map<String, dynamic>> toDb() async {
print(text);
print(userId);
return {
//HabitsTable.id: id,
HabitsTable.userId: userId,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}...}
creating table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id INTEGER PRIMARY KEY AUTOINCREMENT,
$userId INTEGER NOT NULL,
$text TEXT NOT NULL,
$emoji TEXT NOT NULL,
$period TEXT NOT NULL,
$startPeriod INTEGER,
FOREIGN KEY($userId) REFERENCES ${UsersTable.tableName}(id));''';
}
if more code is needed you can check https://github.com/sarasoltan/habit_tracker
plz help if you know how to solve this error.
I have an issue with userId in Habits table. it is a foreign key from id in Users Table. but I keep getting the error "Unhandled Exception: Null check operator used on a null value " from AddHabitDialogController class.
obviously userId should never be null. where is the issue? how can I solve it?
if more code is needed you can check : https://github.com/sarasoltan/habit_tracker
Users Table:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
#override
String toString() => 'Person, ID: $id, email: $email';
#override
bool operator ==(covariant Users other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
Habits table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$userId integer not null,
$text text not null,
$emoji text not null,
$period text not null,
$startPeriod integer,
FOREIGN Key($userId) REFERENCES ${UsersTable.tableName}(${UsersTable.id}));''';
User model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
Habit model class:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
Habit(
{
//required this.id,
required this.userId,
required this.text,
required this.emoji,
required this.period,
this.startPeriod});
Habit.fromDb(Map<String, dynamic> map) {
id = map[HabitsTable.id] as int;
userId = map[HabitsTable.userId] as int;
text = map[HabitsTable.text] as String;
emoji = map[HabitsTable.emoji];
period = (jsonDecode(map[HabitsTable.period]) as List<dynamic>)
.map((e) => e as int)
.toList();
if (map[HabitsTable.startPeriod] != null) {
startPeriod =
DateTime.fromMillisecondsSinceEpoch(map[HabitsTable.startPeriod]);
} else {
startPeriod = null;
}
}
Map<String, dynamic> toDb() {
Users? owner;
return {
//HabitsTable.id: id,
HabitsTable.userId: owner!.id,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}
AddHabitDialogController(error):
class AddHabitDialogController {
Users? owner;
//final user = FirebaseAuth.instance.currentUser;
//String get owneruserId => AuthService.firebase().currentUser!.id;
final List<bool> period = [true, true, true, true, true, true, true];
int? id;
int? userId;
String? emoji;
String? text;
StartPeriod startPeriod = StartPeriod.none;
final StreamController<bool> _addBtnEnabledCtrl = StreamController();
Stream<bool> get addBtnEnabled => _addBtnEnabledCtrl.stream;
final StreamController<StartPeriod> _selectedStartPeriodCtrl =
StreamController();
Stream<StartPeriod> get selectedStartPeriod =>
_selectedStartPeriodCtrl.stream;
final StreamController<bool> _loadingCtrl = StreamController();
Stream<bool> get loading => _loadingCtrl.stream;
void changePeriodValue(int index, bool newValue) {
period[index] = newValue;
_updateAddBtnEnabledState();
}
void changeTextValue(String newValue) {
text = newValue;
_updateAddBtnEnabledState();
}
void changeEmojiValue(String newEmoji) {
emoji = newEmoji;
_updateAddBtnEnabledState();
}
void changeStartPeriod(StartPeriod newValue) {
startPeriod = newValue;
_selectedStartPeriodCtrl.add(startPeriod);
}
Future<void> addHabit(BuildContext context) async {
_loadingCtrl.add(true);
final dataService = GetIt.I.get<DataService>();
final List<int> forPeriod = [];
for (int i = 0; i < period.length; i++) {
if (period[i]) {
forPeriod.add(i + 1);
}
}
final habit = Habit(
//id: id!,
userId: owner!.id, //error from here
emoji: emoji!,
text: text!,
period: forPeriod,
startPeriod: _calculateStartPeriodDateTime());
await dataService.addHabit(habit);
_loadingCtrl.add(false);
Navigator.of(context).pop();
}
void _updateAddBtnEnabledState() {
_addBtnEnabledCtrl.add((text?.isNotEmpty ?? false) &&
(emoji?.isNotEmpty ?? false) &&
period.where((e) => e).isNotEmpty);
}
DateTime? _calculateStartPeriodDateTime() {
final now = DateTime.now();
switch (startPeriod) {
case StartPeriod.today:
return DateTime(now.year, now.month, now.day);
case StartPeriod.thisMonth:
return DateTime(now.year, now.month);
case StartPeriod.thisYear:
return DateTime(now.year);
case StartPeriod.none:
default:
return null;
}
}
void dispose() {
_addBtnEnabledCtrl.close();
_loadingCtrl.close();
_selectedStartPeriodCtrl.close();
}
}
enum StartPeriod { none, today, thisMonth, thisYear }
Because the local variable of AddHabitDialogController owner can't be referenced before it is declared
class AddHabitDialogController {
Users? owner; // -> you did not assign this owner?
I was learning to use sqlflite in my flutter application..when i upgraded it for the first time it worked absolutely fine..but then I wanted to add one more column but i actually don't know query for that.. so I tried the query shown below, but when I try to save my data, I get this error:
E/SQLiteLog(22556): (1) table tbl_employee has no column named employee_gender
I/flutter (22556): DatabaseException(table tbl_employee has no column named employee_gender (code 1 SQLITE_ERROR): , while compiling: INSERT OR REPLACE INTO tbl_employee (employee_name, employee_Student, employee_depertment, employee_DOB, employee_gender) VALUES (?, ?, ?, ?, ?)) sql 'INSERT OR REPLACE INTO tbl_employee (employee_name, employee_Student, employee_depertment, employee_DOB, employee_gender) VALUES (?, ?, ?, ?, ?)' args [Adrita, teacher, CMT, 19/00/2020, 2]}
This is my database class:
class DBHelper{
static final String CREATE_TABLE_EMPLOYEE = '''
create table $TABLE_EMPLOYEE(
$COL_EMP_ID integer primary key autoincrement,
$COL_EMP_NAME text not null,
$COL_EMP_PROFESSION text not null,
$COL_EMP_DEPARTMENT text not null
)
''';
static Future<Database> open() async{// to initialize data we used this method
final dbpath = await getDatabasesPath();//directory
final path = Path.join(dbpath,'employee.db');//main Path
return openDatabase(path,version: 3,onCreate: (db, version) async{
await db.execute(CREATE_TABLE_EMPLOYEE);
}, onUpgrade: (db, oldVersion, newVersion) async{
if(newVersion == 2){
db.execute(''' alter table $TABLE_EMPLOYEE add column $COL_EMP_DOB text ''');
}
if(newVersion == 3){
db.execute('''alter table $TABLE_EMPLOYEE add column $COL_RADIO_BUTTON integer ''');
}
},);
}
static Future<int> insertEmployee(String table, Map<String, dynamic> map) async {// insert method
final db = await open();
return await db.insert(table, map, conflictAlgorithm: ConflictAlgorithm.replace);
}
static Future<int> updateEmployee(EmployeeTeacherModel employeemodel) async{
final db = await open();
return await db.update(TABLE_EMPLOYEE, employeemodel.toMap(), where: '$COL_EMP_ID = ?', whereArgs: [employeemodel.id]);
}
static Future<int> DeleteEmployee(int id) async{
final db = await open();
return await db.delete(TABLE_EMPLOYEE,where: '$COL_EMP_ID = ?', whereArgs: [id]);
}
static Future<List<EmployeeTeacherModel>> getAllEmployees() async{
final db = await open();
final List<Map<String, dynamic>> map = await db.query(TABLE_EMPLOYEE, orderBy: COL_EMP_NAME);
return List.generate(map.length, (index){
return EmployeeTeacherModel.fromMap(map[index]);
});
}
static Future<EmployeeTeacherModel> getEmployeeByid(int id) async{
final db = await open();
final List<Map<String, dynamic>> emps = await db.query(TABLE_EMPLOYEE, where: '$COL_EMP_ID=?',whereArgs: [id]);
if(emps.length>0){
return EmployeeTeacherModel.fromMap(emps.first);
}
return null;
}
}
Here's the Model class:
final String TABLE_EMPLOYEE = "tbl_employee";
final String COL_EMP_ID = "employee_id";
final String COL_EMP_NAME = "employee_name";
final String COL_EMP_DEPARTMENT = "employee_depertment";
final String COL_EMP_PROFESSION = "employee_Student";
final String COL_EMP_DOB = "employee_DOB";
final String COL_RADIO_BUTTON = "employee_gender";
class EmployeeTeacherModel {
int id;
String name;
String depertment;
String Dob;
String profession;
int gender;
EmployeeTeacherModel({this.id, this.name, this.depertment, this.profession, this.Dob, this.gender});
Map<String,dynamic> toMap(){//method to insert data into database
var map = <String, dynamic>{//method
COL_EMP_NAME : name,
COL_EMP_PROFESSION: profession,
COL_EMP_DEPARTMENT: depertment,
COL_EMP_DOB: Dob,
COL_RADIO_BUTTON: gender,
};
if(id !=null){
map[COL_EMP_ID] = id;
}
return map;
}
EmployeeTeacherModel.fromMap(Map<String,dynamic> map){//named constructor to return emoloyee model obj
id = map[COL_EMP_ID];
name = map[COL_EMP_NAME];
profession = map[COL_EMP_PROFESSION];
depertment = map[COL_EMP_DEPARTMENT];
Dob = map[COL_EMP_DOB];
gender = map[COL_RADIO_BUTTON];
}
#override
String toString() {
return 'EmployeeTeacherModel{id: $id, name: $name, depertment: $depertment, Dob: $Dob, profession: $profession, gender: $gender}';
}
}
I've being trying to create a match string function which will read a SQLLite (javascript created) Database from qml and match the string (web address given to it in my case), this is my Database file code:
.pragma library
var db;
// opens database at launch
function openDB()
{
db = openDatabaseSync("BookmarksDB","1.0","Bookmarks Database",1000000);
createTable();
}
// creates table if it doesn't exist, otherwise ignores
function createTable()
{
db.transaction(
function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, url TEXT, creationdate TEXT, modified DATETIME)");
}
)
}
// deletes table
function dropTable()
{
db.transaction(
function(tx) {
tx.executeSql("DROP TABLE IF EXISTS bookmarks");
}
)
}
// creates a single bookmark record
function createBookmark(bookmarkItem)
{
db.transaction(
function(tx) {
tx.executeSql("INSERT INTO bookmarks (title, url, creationdate, modified) VALUES(?,?,?,?)",[bookmarkItem.title, bookmarkItem.url, bookmarkItem.creationdate, bookmarkItem.modified]);
}
)
}
// updates a single bookmark record
function updateBookmark(bookmarkItem)
{
db.transaction(
function(tx) {
tx.executeSql("UPDATE bookmarks SET title = ?, url = ?, creationdate = ?, modified = ? WHERE id = ?",
[bookmarkItem.title, bookmarkItem.url, bookmarkItem.creationdate, bookmarkItem.modified, bookmarkItem.id]);
}
)
}
// deletes a single bookmark record
function deleteBookmark(id)
{
db.transaction(
function(tx) {
tx.executeSql("DELETE FROM bookmarks WHERE id = ?", [id]);
}
)
}
// read list of bookmarks
function readBookmarkList(model)
{
model.clear();
var sqlstring = "SELECT id, title, url, creationdate FROM bookmarks";
db.readTransaction(
function(tx) {
var rs;
rs = tx.executeSql(sqlstring);
for (var i = 0; i < rs.rows.length; i++) {
model.append(rs.rows.item(i))
}
}
)
}
// read a single bookmark item
function readBookmarkItem(id) {
var data = {}
db.readTransaction(
function(tx) {
var rs = tx.executeSql("SELECT * FROM bookmarks WHERE id=?", [id])
if(rs.rows.length === 1) {
data = rs.rows.item(0)
}
}
)
return data;
}
// create a default bookmark item
function defaultItem()
{
return {title: "", url: "", creationdate: new Date(), modified: new Date()}
}
I was wanting to create something like,
function checkUrl(url){
if(dbvalues == url) {
return true
}
else{return false}
}
}
But I haven't a clue how to read all the data from the tables and get it to compare with the url given in the function.
Can somebody please help me out?
I'm a complete noob with SQL stuff
Using Qt Quick 1.1 on Symbian
Why don't you try something like
function checkURL(url) {
var exists
db.readTransaction(function(tx) {
var sql = "SELECT url FROM bookmarks WHERE url=? LIMIT 1";
var rs = tx.executeSql(sql, [url])
exists = rs.rows.length > 0
})
return exists
}
LIMIT 1 clause will tell DB engine to stop searching when it finds the first row matching your criteria.
Haven't tried this myself, but it should work.
$result = $client->call($session, 'catalog_product.update', array('123', array(
'name' => 'Product333222'
)
)
);
Here '123' is the Sku of product. Sku is not working here in update Api.
If i give Product ID in place of Sku it is working fine.
So what is the Issue behind that.
If anyone Knows please let me know.
Thanks.
Magento is a bit dull here.
Long story short:
If you are using a numeric value without specifying an identification type its assuming you are doing your works on a product id. If you where to insert "abc" as a value (not numeric) it will be treated as if it were a SKU.
Best way to solve this is to use an identification type (in your case "SKU") in your api call.
Please see this for more info on using the identification type. http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.update.html
Or see: Magento 1.5, numeric SKUs and productIdentifierType
Short story long:
The following function gets called trough the api
app/code/core/Mage/Catalog/Model/Api/Resource.php
protected function _getProduct($productId, $store = null, $identifierType = null)
{
$product = Mage::helper('catalog/product')->getProduct($productId, $this->_getStoreId($store), $identifierType);
if (is_null($product->getId())) {
$this->_fault('product_not_exists');
}
return $product;
}
As you can see that function is calling the following function in the product helper:
public function getProduct($productId, $store, $identifierType = null) {
$loadByIdOnFalse = false;
if ($identifierType == null) {
if (is_string($productId) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $productId)) {
$identifierType = 'sku';
$loadByIdOnFalse = true;
} else {
$identifierType = 'id';
}
}
/** #var $product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product');
if ($store !== null) {
$product->setStoreId($store);
}
if ($identifierType == 'sku') {
$idBySku = $product->getIdBySku($productId);
if ($idBySku) {
$productId = $idBySku;
}
if ($loadByIdOnFalse) {
$identifierType = 'id';
}
}
if ($identifierType == 'id' && is_numeric($productId)) {
$productId = !is_float($productId) ? (int) $productId : 0;
$product->load($productId);
}
return $product;
}
Without specifying an $identifierType here and using a sku like '123' the thrid line is going to do a preg match with will result in true. Thus using its else function threating it as an ID in stead of sku.
In the end:
So, do your call like:
$result = $client->call($session, 'catalog_product.update', array('123', array(
'name' => 'Product333222'
), null, 'sku'));