Flutter database objectbox error - " Unsupported operation: Cannot create multiple Store instances for the same directory in the same isolate. Please use a single Store, close() the previous instance before opening another one or attach to it in another isolate ". I am using objectbox as my app database.How can I solve this problem. Here is my code -
// First File
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../objectbox.g.dart';
#Entity()
class MarkEvent {
int? id;
int habitId;
String dateTime;
MarkEvent({required this.dateTime, required this.habitId, this.id = 0});
}
class HabitDetailProvider with ChangeNotifier {
List<MarkEvent> marks = [];
Future<void> deleteMark(int id) async {
final index = marks.indexWhere((element) => element.id == id);
marks.removeAt(index);
var store = await openStore();
var box = store.box<MarkEvent>();
box.remove(id);
store.close();
// await DataBaseHelper.deleteEvent(id);
notifyListeners();
}
Future<void> addMark(MarkEvent mark) async {
marks.add(MarkEvent(dateTime: mark.dateTime, habitId: mark.habitId));
var store = await openStore();
var box = store.box<MarkEvent>();
box.put(mark);
store.close();
notifyListeners();
}
Future<void> fetchAndSetMarks() async {
var store = await openStore();
var box = store.box<MarkEvent>();
final markList = box.query().build().find();
store.close();
marks = markList
.map((e) => MarkEvent(dateTime: e.dateTime, habitId: e.habitId))
.toList();
notifyListeners();
}
}
// Another file
import 'package:flutter/material.dart';
import 'package:habit_app/objectbox.g.dart';
import '../model/habit_model.dart';
class HabitListNotifier with ChangeNotifier {
List<HabitModel> _habitList = [];
List<HabitModel> get Habit_List {
return [..._habitList];
}
Future<Store> get originalStore {
return openStore();
}
void addHabit(HabitModel habit) async {
HabitModel newHabit = HabitModel(
hour: habit.hour,
minutes: habit.minutes,
reminderHour: habit.reminderHour,
reminderMinute: habit.reminderMinute,
alarmId: habit.alarmId,
notificationText: habit.notificationText,
reason: habit.reason,
notificationId: habit.notificationId,
iconData: habit.iconData.toString(),
title: habit.title,
plan: habit.plan,
);
_habitList.add(newHabit);
var store = await originalStore;
var box = store.box<HabitModel>();
box.put(habit);
store.close();
notifyListeners();
}
void updateHabit(HabitModel newHabit) async {
final oldHabitIndex =
_habitList.indexWhere((habit) => habit.id == newHabit.id);
_habitList[oldHabitIndex] = newHabit;
var store = await originalStore;
var box = store.box<HabitModel>();
box.put(newHabit);
store.close();
notifyListeners();
}
Future<void> fetchAndSetHabits() async {
var store = await originalStore;
var box = store.box<HabitModel>();
var query = box.query().build();
_habitList = query.find();
store.close();
notifyListeners();
}
Future<void> deleteHabit(int id) async {
final existingHabit = _habitList.indexWhere((element) => element.id == id);
_habitList.removeAt(existingHabit);
var store = await originalStore;
var box = store.box<HabitModel>();
box.remove(id);
store.close();
notifyListeners();
}
}
// Another file
import 'package:flutter/material.dart';
import 'package:habit_app/providers/habit_provider.dart';
import 'package:provider/provider.dart';
import '../objectbox.g.dart';
class NoteModel {
int habitId;
int? id;
String dateTime;
String note;
NoteModel(
{required this.dateTime,
required this.habitId,
this.id = 0,
required this.note});
}
class Notes with ChangeNotifier {
List<NoteModel> notes = [];
List<NoteModel> get dupNoteList {
return notes;
}
Future<void> addNote(
NoteModel note, int habitId, BuildContext context) async {
notes.add(note);
var store = await Provider.of<HabitListNotifier>(context, listen: false)
.originalStore;
var box = store.box<NoteModel>();
box.put(note);
store.close();
fetchAndSetNotes(habitId);
notifyListeners();
}
Future<void> deleteNote(int id) async {
final index = notes.indexWhere((element) => element.id == id);
notes.removeAt(index);
var store = await openStore();
var box = store.box<NoteModel>();
box.remove(id);
store.close();
notifyListeners();
}
Future<void> updateNote(NoteModel newNote) async {
var store = await openStore();
var box = store.box<NoteModel>();
box.put(newNote);
store.close();
final oldNote = notes.indexWhere((habit) => habit.id == newNote.id);
notes[oldNote] = newNote;
notifyListeners();
}
Future<void> fetchAndSetNotes(int habitId) async {
var store = await openStore();
var box = store.box<NoteModel>();
var query = box.query().build();
final note = query.find();
store.close();
notes = note.where((notes) => notes.habitId == habitId).toList();
notifyListeners();
}
}
//Models file
import 'package:objectbox/objectbox.dart';
#Entity()
class NoteModel {
String habitId;
int? id;
String dateTime;
String note;
NoteModel({
required this.dateTime,
required this.habitId,
required this.note,
this.id = 0,
});
}
import 'dart:core';
import 'package:objectbox/objectbox.dart';
class ClockTime {
int? id;
int hour;
int minutes;
ClockTime(this.hour, this.minutes);
}
#Entity()
class HabitModel {
String title;
String reason;
String plan;
String iconData;
int? id;
int alarmId;
int notificationId;
String notificationText;
int hour;
int reminderHour;
int reminderMinute;
int minutes;
HabitModel({
required this.reason,
required this.notificationText,
required this.reminderHour,
required this.reminderMinute,
required this.notificationId,
required this.plan,
required this.alarmId,
required this.iconData,
required this.title,
this.id = 0,
required this.hour,
required this.minutes,
});
}
Related
Can someone share code to retrieve user details along with thumbnail image to be displayed on the basis of an input of a SamAccountName?
This has to be accomplished using ASP.NET Core and react. I am pretty new to these technologies, please help.
My trials as below
Controller code:
public Image ourTeam()
{
var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();
Image image = GetImage(userDetails.CN); //I get image data
//context.Response.ContentType = "image/jpeg";
var stream = new System.IO.MemoryStream();
if (image != null)
image.Save(stream, ImageFormat.Jpeg);
return image;
}
Component code:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}
export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
super();
this.state = { imageList: [], loading: true }; //initialize to default
fetch('api/Home/ourTeam')
.then(response => response.json() as Promise<ImageData[]>)
.then(data => {
this.setState({ imageList: data, loading: false });
});
}
public render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderImageTable(this.state.imageList);
return <div>
<h1>Team</h1>
{contents}
</div>;
}
private renderImageTable(imageList: ImageData[]) {
return <div className='table'>{
imageList.map(x =>
<img src={x.byteData} alt={x.CN} />)
}</div>;
}
}
export class ImageData {
CN: string = "";
byteData: string = "";
}
PFB the code on how I am authenticating and then retrieving image:
private Image GetImage(string cn)
{
string LDAP_PATH = "LDAP://" + "SOMEPATH.com";
string user = "USERID";
string password = "PASSWORD";
using (DirectoryEntry entry = new DirectoryEntry(LDAP_PATH, user, password))
{
{
DirectorySearcher search = new DirectorySearcher(entry);
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("distinguishedName");
search.Filter = "(&(objectClass=user)(sAMAccountName=" + cn + "))";
SearchResult result = search.FindOne();
if (result == null)
{
search.Filter = "(&(objectClass=user)(cn=" + cn + "))";
result = search.FindOne();
}
if (result != null)
{
DirectoryEntry entryUser = result.GetDirectoryEntry();
string propertyName = "thumbnailPhoto";
if (entryUser.Properties.Contains(propertyName))
{
byte[] img = entryUser.Properties[propertyName].Value as byte[];
MemoryStream memStream = new MemoryStream(img);
return Image.FromStream(memStream);
}
}
}
}
// User not authenticated
return null;
}
I assume you want to return the image as if you were just downloading a file.
First, return a byte[] from GetImage. You don't gain anything here by converting it to an Image object. If you needed to edit the image in code, then it would make sense. But since you're not, it doesn't matter.
So change this:
byte[] img = entryUser.Properties[propertyName].Value as byte[];
MemoryStream memStream = new MemoryStream(img);
return Image.FromStream(memStream);
To this:
return entryUser.Properties[propertyName].Value as byte[];
Then in your controller, return a FileContentResult, like this:
public ActionResult ourTeam()
{
var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();
byte[] image = GetImage(userDetails.CN);
return File(image, "image/jpeg");
}
This is a todo list app and uses a database to use the CRUD functions. When the user does a specific action such as tap or swipe i want to mark the task as complete. I am a bit new to databases and am unsure on how to use update item to update the status of a task (completed or not completed).
Could i get a suggestion on what is the correct way to update the _isDone value without deleting a task from the database
Tried to search for other examples of to do list apps but they delete the completed task intead of marking it as completed
database code -
//This is the database
String _itemName;
String _dateCreated;
int _id;
bool _isDone;
TodoItem(this._itemName, this._dateCreated, [this._isDone]);
TodoItem.map(dynamic obj) {
this._itemName = obj["itemName"];
this._dateCreated = obj["dateCreated"];
this._id = obj["id"];
this._isDone = obj["isDone"];
}
String get itemName => _itemName;
String get dateCreated => _dateCreated;
int get id => _id;
bool get isDone => _isDone;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["itemName"] = _itemName;
map["dateCreated"] = _dateCreated;
if (_id != null) {
map["id"] = _id;
}
return map;
}
TodoItem.fromMap(Map<String, dynamic> map) {
this._itemName = map["itemName"];
this._dateCreated = map["dateCreated"];
this._id = map["id"];
this._isDone = map["isDone"];
}
update item function -
Future<int> updateItem(TodoItem item) async {
var dbClient = await db;
return await dbClient.update("$tableName", item.toMap(),
where: "$columnId = ?", whereArgs: [item.id]);
}
please reference this document https://medium.com/flutter-community/using-sqlite-in-flutter-187c1a82e8b
In sqlite example below, update the whole record via a key, "id" here
updateClient(Client newClient) async {
final db = await database;
var res = await db.update("Client", newClient.toMap(),
where: "id = ?", whereArgs: [newClient.id]);
return res;
}
In your example, you update TodoItem and TodoItem include isDone field.
and your syntax is correct
another reference doc https://www.developerlibs.com/2018/07/flutter-sqlite-database-example.html
code snippet of this example
Future<bool> update(User user) async {
var dbClient = await db;
int res = await dbClient.update("User", user.toMap(),
where: "id = ?", whereArgs: <int>[user.id]);
return res > 0 ? true : false;
}
official document about use of sqlite https://flutter.dev/docs/cookbook/persistence/sqlite
code snippet of official document
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
// Update Fido's age.
await updateDog(Dog(
id: 0,
name: 'Fido',
age: 42,
));
You can build a Database Helper as the example and include your update function
import 'dart:async';
import 'dart:io' as io;
import 'package:flutter_database/database/model/user.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute(
"CREATE TABLE User(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, dob TEXT)");
}
Future<int> saveUser(User user) async {
var dbClient = await db;
int res = await dbClient.insert("User", user.toMap());
return res;
}
Future<List<User>> getUser() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM User');
List<User> employees = new List();
for (int i = 0; i < list.length; i++) {
var user =
new User(list[i]["firstname"], list[i]["lastname"], list[i]["dob"]);
user.setUserId(list[i]["id"]);
employees.add(user);
}
print(employees.length);
return employees;
}
Future<int> deleteUsers(User user) async {
var dbClient = await db;
int res =
await dbClient.rawDelete('DELETE FROM User WHERE id = ?', [user.id]);
return res;
}
Future<bool> update(User user) async {
var dbClient = await db;
int res = await dbClient.update("User", user.toMap(),
where: "id = ?", whereArgs: <int>[user.id]);
return res > 0 ? true : false;
}
}
i have some free days between projects so i decided to learn typescript.
Therefore i want to do a repository factory. The idea is simple, there is some API where i can access models crud actions. It is nice solution to have one generic repository for buisnes models. But still get the model class from CRUD methods.
What is the correct way to do it ? Can someone help me solve this? How to do it right ?
What i want to achive is:
var factory = new RepositoryFactory($resource, 'http://api.com');
var repo = factory.getRepository(User);
var user = repo.getAll();
I starded to do somethink like this:
IEntity:
'use strict';
export interface IEntity {
id: number;
}
IRepository:
'use strict';
import {IEntity} from "./IEntity";
export interface IRepository<T extends IEntity> {
getAll(params:Object): T[];
getById(id:number): T;
create(data:Object): T;
update(id:number, data:{id:number}): T;
remove(id:number): boolean;
}
RepositoryFactory
'use strict';
import {IEntity} from "./IEntity";
import {Repository} from "./Repository";
export default class RepositoryFactory {
protected $resource:any;
protected url:string;
constructor($resource:any, url:string) {
this.$resource = $resource;
this.url = url;
}
public getRepository<T extends IEntity>(model:T):Repository {
return new Repository(this.$resource, this.url, model)
}
}
`Repository`:
'use strict';
import {IRepository} from "./IRepository";
import {IEntity} from "./IEntity";
export default class Repository<T extends IEntity> implements IRepository<T> {
protected $resource:any;
protected resource:any;
protected url:string;
protected model:T;
constructor($resource:any, url:string, model:T) {
this.$resource = $resource;
this.url = url;
this.model = model;
this.resource = this.getResource(model.path);
}
getAll(params:Object):T[] {
let results = this.resource.query((typeof params === 'undefined' ? {} : params), this.onSuccess);
return this.returnPromise(results);
}
getById(id:number):T {
let model = this.resource.get({id: id}, this.onSuccess);
return this.returnPromise(model);
}
create(data:Object):T {
let model = new this.resource(data);
return model.$save().then(this.onSuccess);
}
update(id:number, data:Object):T {
data.id = id;
var model = new this.resource(data);
return model.$update().then(this.onSuccess);
}
remove(id:number):boolean {
var data = {id: id};
var model = new this.resource(data);
return model.$delete().then(this.onSuccess);
}
protected getResource(path:string) {
return this.$resource(this.url + path, {id: '#id'}, {
'update': {
method: 'PUT'
},
'get': {
method: 'GET'
},
'save': {
method: 'POST'
},
'query': {
method: 'GET'
},
'remove': {
method: 'DELETE'
},
'delete': {
method: 'DELETE'
}
});
}
protected onSuccess(response:any) {
if (this.checkPropertyExistence(response, 'data')) {
if (response.data instanceof Array) {
let results = response.data;
for (var key in results) {
if (results.hasOwnProperty(key)) {
results[key] = new this.model(results[key]);
}
}
return results;
} else {
return new this.model(response.data);
}
}
return response;
}
protected transformRequest(obj:Object) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
protected returnPromise(object:Object) {
return object.$promise.then(function (result) {
return result;
});
}
protected checkPropertyExistence(obj:Object, paths:string|string[]) {
for (var i = 0; i < paths.length; i++) {
if (!obj || !obj.hasOwnProperty(paths[i])) {
return false;
}
obj = obj[paths[i]];
}
return true;
}
}
User:
'use strict';
import {IEntity} from "./IEntity";
export default class User implements IEntity {
id:number;
name:string;
static _path:string = '/users';
constructor(id:number, name:string) {
this.id = id;
this.name = name;
}
static get path():string {
return this._path;
}
}
Hey guys i have menage to created working example for you.
The example shows how to create repository factory with typescript.
I have prepared this DEMO FIDDLE where you can press RUN on the right side, and the page with single button will appear. After clicking the button console.log will display getAll method results.
In example i have mocked data, simply to show that factory works. If anyone wants to improves it, feel free and welcome to do it!
How it works?
//create factory, you can do it in an abstract controller class
//and later extends controller by it so you can easy get access to repository
var factory = new RepositoryFactory();
//inject path for $resource (unused in example)
//and your model.entity namespace
var repo = factory.getRepository('/users', 'User');
//call repo method
var users = repo.getAll({});
When using angular create RepositoryFactory as a service. Thats all. You may also want to inject $resource to get the right data from API.
And here is a full example code:
interface IEntity {
id: number;
}
class Entity implements IEntity {
private _id:number;
private _name:string;
private _birth:Date;
constructor(parameters: {id:number, name:string, birth:Date}) {
this._id = parameters.id;
this._name = parameters.name;
this._birth = parameters.birth;
}
get id():number {
return this._id;
}
set id(value:number) {
this._id = value;
}
get name():string {
return this._name;
}
set name(value:string) {
this._name = value;
}
get birth():Date {
return this._birth;
}
set birth(value:Date) {
this._birth = value;
}
}
class RepositoryFactory {
public getRepository<T extends IEntity>(path:string, model:string):IRepository<T> {
return new Repository<T>(path, model)
}
}
interface IRepository<T extends IEntity> {
getAll(params:Object): T[];
getById(id:number): T;
create(data:Object): T;
update(id:number, data:{id:number}): T;
remove(id:number): boolean;
}
class Repository<T extends IEntity> implements IRepository<T> {
protected path:string;
protected model:string;
constructor(path:string, model:string) {
this.path = path;
this.model = model;
}
getAll(params:Object):T[] {
let results = [
{id:1, name: 'rafal', birth:new Date()},
{id:2, name: 'szymon', birth:new Date()},
{id:3, name: 'mateusz', birth:new Date()},
];
let entities= [];
for (var key in results) {
if (results.hasOwnProperty(key)) {
let entity = Object.create(window[this.model].prototype);
entity.constructor.apply(entity, new Array(results[key]));
entities.push(entity);
}
}
return entities;
}
getById(id:number):T {
let object = {id:id, name: 'test', birth:new Date()};
var entity = Object.create(window[this.model].prototype);
entity.constructor.apply(entity, new Array(object));
return entity;
}
create(data:Object):T {
var entity = Object.create(window[this.model].prototype);
entity.constructor.apply(entity, new Array(data));
return entity;
}
update(id:number, data:Object):T {
var entity = Object.create(window[this.model].prototype);
entity.constructor.apply(entity, new Array(data));
return entity;
}
remove(id:number):boolean {
return true;
}
}
var factory = new RepositoryFactory();
var repo = factory.getRepository('/users', 'Entity');
var users = repo.getAll({});
I'm trying to find the best solution to have a local database in my WP8.1 application.
I'm using the standard WP8.1 (non-SL) and Visual Studio 2013.
I've looked into SQLite but I couldn't manage to get it to work on my application/Visual Studio.
If I can use SQLite, I need someone to point me out the way to go. Else, please refer me the best solution.
Thanks in advance!
Here's a repository class that leverages SQLite:
public class ContactsRepository : IContactsRepository
{
SQLiteAsyncConnection _connection = null;
static ContactsRepository _repository = null;
private ContactsRepository()
{
}
public async Task Initialize()
{
_connection = new SQLiteAsyncConnection(Constants.DATABASE_FILE_NAME);
await EnsureTableExist<ContactReference>(_connection);
}
public static ContactsRepository Instance
{
get
{
if (_repository == null)
{
_repository = new ContactsRepository();
}
return _repository;
}
}
public async Task Add(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
else
{
await _connection.InsertAsync(new ContactReference()
{
CategoryName = category.Name,
ContactId = contact.Id
});
}
}
public async Task Update(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
Debug.Assert(result != null);
if (result == null)
{
throw new Exception("Unable to update category. Candidate not found");
}
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
}
public async Task<ObservableCollection<Contact>> Get(string categoryName)
{
var result = new ObservableCollection<Contact>();
var query = _connection.Table<ContactReference>().Where(c => c.CategoryName == categoryName);
var queryResult = await query.ToListAsync();
foreach(var contact in queryResult)
{
var phoneContacts = ResourceLocator.Instance[typeof(ObservableCollection<Contact>)] as ObservableCollection<Contact>;
var phoneContact = phoneContacts.Where(c => c.Id == contact.ContactId).FirstOrDefault();
Debug.Assert(phoneContact != null);
if (phoneContact != null)
{
result.Add(phoneContact);
}
}
return result;
}
public async Task<ObservableCollection<ContactReference>> Get()
{
var result = new ObservableCollection<ContactReference>();
var query = _connection.Table<ContactReference>();
var queryResult = await query.ToListAsync();
foreach (var contact in queryResult)
{
result.Add(contact);
}
return result;
}
private async Task EnsureTableExist<T>(SQLiteAsyncConnection connection) where T : new()
{
bool noTableExists = false;
try
{
var query = await connection.Table<T>().FirstOrDefaultAsync();
}
catch (SQLiteException ex)
{
if (ex.Message.Contains("no such table"))
{
noTableExists = true;
}
}
if (noTableExists)
{
await connection.CreateTableAsync<T>();
}
}
}
I am trying to retrieve data in flex database (AIR APPLICATION), below is code. everything is working properly except i am not able to retrieve data. ie.,when select statement is executed result handler is not called after execution
package
{
import flash.data.SQLConnection;
import flash.data.SQLMode;
import flash.data.SQLResult;
import flash.data.SQLSchemaResult;
import flash.data.SQLStatement;
import flash.data.SQLTableSchema;
import flash.errors.SQLError;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.utils.Timer;
import mx.core.FlexGlobals;
public class DB
{
public var conn:SQLConnection;
private var myTimer:Timer
private var selectStmt:SQLStatement;
private var insertStmt:SQLStatement;
public function DB()
{
conn = new SQLConnection();
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample1.db");
try
{
conn.openAsync(dbFile);
myTimer = new Timer(1000, 1);
myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
myTimer.start();
trace("the database was created successfully");
}
catch (error:SQLError)
{
trace("1 Error message:", error.message);
trace("Details:", error.details);
}
}
private function timerHandler(e:TimerEvent):void{
if(!doesTableExist(conn,"employee")){
createTable();
}
}
public function updateTrack():void{
insertStmt = new SQLStatement();
insertStmt.sqlConnection = conn;
var sql:String =
"INSERT INTO employee (name, tid) " +
"VALUES ('foo',2)";
insertStmt.text = sql;
insertStmt.addEventListener(SQLEvent.RESULT, insertResult);
insertStmt.addEventListener(SQLErrorEvent.ERROR, insertError);
insertStmt.execute();
}
public function getTracklist():void{
trace("excuting select");
selectStmt = new SQLStatement();
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT * FROM employee";
selectStmt.addEventListener(SQLEvent.RESULT, resultHandlernew);
selectStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);
selectStmt.execute();
}
private function resultHandlernew(e:SQLResult):void{
var result:SQLResult = selectStmt.getResult();
var numResults = result.data.length;
trace(numResults);
}
private function createTable():void{
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employee (" +
" id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT, " +
" tid INTEGER " +
")";
createStmt.text = sql;
createStmt.addEventListener(SQLEvent.RESULT, createResult);
createStmt.addEventListener(SQLErrorEvent.ERROR, createError);
createStmt.execute();
}
function insertResult(event:SQLEvent):void
{
trace("INSERT statement succeeded");
var result:SQLResult = insertStmt.getResult();
var primaryKey:Number = result.lastInsertRowID;
trace("primaryKey:"+primaryKey);
getTracklist();
}
function insertError(event:SQLErrorEvent):void
{
trace("3 Error message:", event.error.message);
trace("Details:", event.error.details);
}
public function doesTableExist(connection:SQLConnection, tableName:String):Boolean
{
var r:Boolean;
try{
connection.loadSchema();
var schema:SQLSchemaResult = connection.getSchemaResult();
for each (var table:SQLTableSchema in schema.tables)
{
if (table.name.toLowerCase() == tableName.toLowerCase())
{
r= true;
}
}
r = false;
}catch(e){
r = false;
}
return r;
}
private function createResult(event:SQLEvent):void
{
trace("Table created");
updateTrack();
}
private function createError(event:SQLErrorEvent):void
{
trace("2 Error message:", event.error.message);
trace("Details:", event.error.details);
}
private function openHandler(event:SQLEvent):void
{
trace("the database opened successfully");
}
private function errorHandler(event:SQLErrorEvent):void
{
trace("3 Error message:", event.error.message);
trace("Details:", event.error.details);
}
}
}