This is an old post, please refer:
https://github.com/brodysoft/Cordova-SQLitePlugin - a Cordova/PhoneGap plugin to open and use sqlite databases on Android/iOS/WP(8) with HTML5 Web SQL API
It is really hard to wait for too much time when a phonegap application runs for first time and create all its database stuff, which gives a really bad impression to the user who just downloaded the app for its iPhone or Android device. I have a little approach to save the long time taken for database creation at very first run of the app, that is; we should copy a Pre-Populated Database file to the native location of device.
Source code: https://github.com/gauravstomar/PrepopulateDB
You can create a basic database for app with the help of tools like SQLite Database Browser or if you already have a database in your app you can directly get the database files (you need Databases.db and file__0/0000000000000001.db files) from the following ways:
In case of Android: in File Explore(in Eclipse) go to data > data > [YOUR APP NAME] > app_database
In case of iOS: go to Finder (in MAC) go to Library > Application Support > iPhone Simulator > [YOUR SIMULATOR VERSION] > Applications > [YOUR UNIQUE APP ID] > Library > WebKit > Databases
NOTE: for iOS and Android apps both of files are same we don't need to grab both files for same phonegap apps.
With these files all what you need to do is; just put them in to bundle of app that is assets folder in case of Android and Root folder in case of iOS.
Now you have to copy the files at the native location of application at the time of first boot of application, and make sure that the files should copy before your very first SQLite query. To copy these files you can use the following code snippet based on your environment. JAVA (Android)
https://github.com/brodysoft/Cordova-SQLitePlugin - a Cordova/PhoneGap plugin to open and use sqlite databases on Android/iOS/WP(8) with HTML5 Web SQL API
It is really hard to wait for too much time when a phonegap application runs for first time and create all its database stuff, which gives a really bad impression to the user who just downloaded the app for its iPhone or Android device. I have a little approach to save the long time taken for database creation at very first run of the app, that is; we should copy a Pre-Populated Database file to the native location of device.
Source code: https://github.com/gauravstomar/PrepopulateDB
You can create a basic database for app with the help of tools like SQLite Database Browser or if you already have a database in your app you can directly get the database files (you need Databases.db and file__0/0000000000000001.db files) from the following ways:
In case of Android: in File Explore(in Eclipse) go to data > data > [YOUR APP NAME] > app_database
In case of iOS: go to Finder (in MAC) go to Library > Application Support > iPhone Simulator > [YOUR SIMULATOR VERSION] > Applications > [YOUR UNIQUE APP ID] > Library > WebKit > Databases
NOTE: for iOS and Android apps both of files are same we don't need to grab both files for same phonegap apps.
With these files all what you need to do is; just put them in to bundle of app that is assets folder in case of Android and Root folder in case of iOS.
in Eclipse: | in XCode: |
Now you have to copy the files at the native location of application at the time of first boot of application, and make sure that the files should copy before your very first SQLite query. To copy these files you can use the following code snippet based on your environment. JAVA (Android)
//Use this code in your bootstrapping steps like in onCreate() try { String pName = this.getClass().getPackage().getName(); this.copy("Databases.db","/data/data/"+pName+"/app_database/"); this.copy("0000000000000001.db","/data/data/"+pName+"/app_database/file__0/"); } catch (IOException e) { e.printStackTrace(); } //Copy Paste this function in the class where you used above part void copy(String file, String folder) throws IOException { File CheckDirectory; CheckDirectory = new File(folder); if (!CheckDirectory.exists()) { CheckDirectory.mkdir(); } InputStream in = getApplicationContext().getAssets().open(file); OutputStream out = new FileOutputStream(folder+file); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }Objective C (iOS)
//For PhoneGapDelegate.m - (void)webViewDidStartLoad:(UIWebView *)theWebView { NSString *databaseName = @"0000000000000001.db"; NSString *masterName = @"Databases.db"; NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryDir = [libraryPaths objectAtIndex:0]; NSString *masterPath = [libraryDir stringByAppendingPathComponent:@"WebKit/Databases/"]; NSString *databasePath = [libraryDir stringByAppendingPathComponent:@"WebKit/Databases/file__0/"]; NSString *masterFile = [masterPath stringByAppendingPathComponent:masterName]; NSString *databaseFile = [databasePath stringByAppendingPathComponent:databaseName]; BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; success = [fileManager fileExistsAtPath:databasePath]; if(success) return; NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; NSString *masterPathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:masterName]; [fileManager createDirectoryAtPath:databasePath withIntermediateDirectories:YES attributes:nil error:NULL]; [fileManager copyItemAtPath:databasePathFromApp toPath:databaseFile error:nil]; [fileManager copyItemAtPath:masterPathFromApp toPath:masterFile error:nil]; [fileManager release]; }
hi,
ReplyDeleteso, how do we execute opening a SQLite Db in our js files?
hello,
ReplyDeletecould you please help me in showing how to access Sqlite in your js file? tnx
thank you.. its nice..
ReplyDeletecan you please show us your html file as well. I keep getting sqlite error that says cannot open the file.
ReplyDeleteI use your method but I keep getting sqlite error that cannot open file. Can you please show your javascript code as well? thanks
ReplyDeleteHi Gaurav, I have a problem. I have pre-populated a .db file thru android native code. I have renamed the db file as 0000000000000001.db. I have placed this file and Databases.db under my Assets folder. Now when I am copying these 2 files to "data/data/"+pName+"/app_database/file__0/" folder, Phonegap is unable to find this file. And a new file is creatd each time Phonegap application loads. the name of this file is 0000000000000002.db in the same folder and it is a blank database.
ReplyDeleteSo am I missing something? or did I do something wrong.
regards
santu ghosh
Hi Gaurav, I have a problem. I have pre-populated a .db file thru android native code. I have renamed the db file as 0000000000000001.db. I have placed this file and Databases.db under my Assets folder. Now when I am copying these 2 files to "data/data/"+pName+"/app_database/file__0/" folder, Phonegap is unable to find this file. And a new file is creatd each time Phonegap application loads. the name of this file is 0000000000000002.db in the same folder and it is a blank database.
ReplyDeleteSo am I missing something? or did I do something wrong.
regards
santu ghosh
Santu. I think you need to copy DB files to the different filders.
ReplyDeletethis.copy("Databases.db","/data/data/"+pName+"/app_database/");
but
this.copy("0000000000000001.db","/data/data/"+pName+"/app_database/file__0/");
Please tell the steps to convert a native DB file to PhoneGap like style(0000000000000001.db and Databases.db)?
DeletePlease tell the steps to convert the native Android DB file to phonegap like style(0000000000000001.db and Databases.db)?
ReplyDeletethanks gaurav for writing this post. its really very useful. keep it up.
ReplyDeleteDear Gaurav,
ReplyDeleteI am having prepopulated database in SQLITE
When I am Pushing it to Device, I can see it in File Explorer.
But, I am not getting how to use this pushed database in javascript code.
Whenever I am using
window.openDatabase("DBName", "1.0", "New DB Demo", 200000);
It creates new databse with the name app_database:DBName
Any idea about why this is happening?
Thanks,
Amol
Dear Gaurav,
ReplyDeleteI am having prepopulated database in SQLITE
When I am Pushing it to Device, I can see it in File Explorer.
But, I am not getting how to use this pushed database in javascript code.
Whenever I am using
window.openDatabase("DBName", "1.0", "New DB Demo", 200000);
It creates new databse with the name app_database:DBName
Any idea about why this is happening?
Thanks,
Amol
Hi Gaurav, This article is very useful but now i have a problem. I have being developed phonegap application for iOS that is used pre populated .db file. This solution is working fine for below iOS 5.1. But I upgraded to IOS 5.1 , this solution does not to work.
ReplyDeleteCan you give me a solution for that. I am stuck now.
Thank you
Hi Gaurav!
ReplyDeleteThank you very much for share useful code. I have a question, how I can add rows and save in the Prepopulate database?
Thank you Gaurav!
ReplyDeleteHow I can insert aditional data into a Prepopulate database, and use them later close and open the app?
Hi Gourav, your trick is working fine for high end devices & android 2.3.
ReplyDeleteBut i have problem low end devices & android 2.2.
Can you help me?
Hi... Can you tell me where can I put the code listed above. I am developing for Android without any prior knowledge in JAVA. Can you explain in specific details ? Thanks
ReplyDeleteThanks for this post.. I'm getting a FileNotFound exception... Please help...
ReplyDeleteThanks for this post.. I'm getting a FileNotFound exception... Please help...
ReplyDeleteFound my 'bug'... Placed the DB files in a wrong folder.. Placed them in 'assets/www' instead of 'assets'... Awesome way to pre-populate a database! Thanks!!!
ReplyDeleteIs is possible to do the same with BlackBerry WebWorks
ReplyDeleteIs it possible to do the same with BlackBerry WebWorks?
ReplyDeleteHi Gaurav, how do i achieve same task for blackberry webworks platform. plz reply
ReplyDeletedid you find a solution to ur problem
Deletei also need to do the same thing
use a pre populated db for blackberry webworks
any help would be highly appreciated
thanks
did you find a solution to ur problem
Deletei also need to do the same thing
use a pre populated db for blackberry webworks
any help would be highly appreciated
thanks
were you able to do the same thing using blackberry???
Deletewere you able to do the same thing using blackberry webworks>???
DeleteGreat! It works.
ReplyDeleteGaurav, this is very nice. Thank you. For your objective C code, can this run every time the app runs or do you somehow need to tell it to only run the first time the app loads?
ReplyDeleteHi Guarav,
ReplyDeleteThis is really great.
For the Objective C code, do i need to tell this code to only run the first time, or does it automatically know to only run this code when the app first runs?
A more up to date version that I worked with and made a guest post on Ray Camden's website:
ReplyDeletehttp://www.raymondcamden.com/index.cfm/2012/7/27/Guest-Blog-Post-Shipping-a-populated-SQLite-DB-with-PhoneGap
A more recent version of the methods described here:
ReplyDeletehttp://www.raymondcamden.com/index.cfm/2012/7/27/Guest-Blog-Post-Shipping-a-populated-SQLite-DB-with-PhoneGap
Hello Gaurav,
ReplyDeleteI have integrated above code in my Phonegap application for iOS. Database is successfully loading in my case, as I have compared 0000000000000001.db with my original database and both are same. In javascript, I have open database like this:
function onBodyLoad() {
var db = window.openDatabase("0000000000000001", "1.0", "MDStand DB", 1000000);
db.transaction(queryDB,errorDB);
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM mds_menu',[],querySuccess,errorDB);
}
function querySuccess(tx, results) {
alert('success');
}
function errorDB(err) {
alert("Error processing SQL: "+err.code);
}
Everytime it shows me alert "Error processing SQL : undefined"
Let me know, if I am missing anything over here.
Thank You.
I have integrated above code in Phonegap app for iOS. In my case, database is successfully loading as 0000000000000001.db is exactly the same as my original database. I am stuck here with retrieving the records from database. Below is my code, I have used for the same:
ReplyDeletefunction onBodyLoad() {
var db = window.openDatabase("0000000000000001", "1.0", "MDStand DB", 1000000);
db.transaction(queryDB,null);
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM mds_menu',[],querySuccess,errorDB);
}
function querySuccess(tx, results) {
alert('success');
}
function errorDB(err) {
alert("Error processing SQL: "+err.code);
}
Everytime, I am getting erro alert "Error processing SQL: undefined".
Please help me out in this. Let me know, if I am missing anything over here.
Thank You.
I am also having the same issue..how to solve this one..
DeleteIs anyone using a prepopulated database on iOS 5.1 and if so, how are you doing it? Thank you!
ReplyDeleteIs anyone using a prepopulated database on iOS 5.1 and if so, how are you doing it? Thank you!
ReplyDeleteMuy interesante este tema, como seria si si estoy trabajando con html5 js y css3 como podria hacer esto mismo algún manual o algo que me recomiendes
ReplyDeletehow to upload 000000001.db file to server by using file transfer api of phonegap?
ReplyDeletei am uploading 000000001.db file to server by using file transfer api of phonegap but it gives me error
file not found error code=1
can anyone help me out how to get rid of this thing.
do you know how to connect remote database with phonegap??can you give an example plssss
ReplyDeleteits not worked for me for android can u sepicified any method for android
ReplyDeleteits not worked for me in android can u please specified the methods clearly or any other
ReplyDeleteWhere do you add the Java code, the whole point of using PhoneGap is to avoid using Java, can you at least mention where this code is to be added.
ReplyDeleteHi Gaurav,
ReplyDeleteI have a problem while using the db file in ios 5.1 and later, I'm not able fetch the records from the db using.
Hi Gaurav,
ReplyDeleteI have a problem while using the db file in ios 5.1 and later, I'm not able fetch the records from the db using.
Hi Gaurav,
ReplyDeleteI'm unable to fetch the records from the .db file in ios5.1 and later, even though my db is successfully copied to webkit.
Thanks in Advance
Hi,
ReplyDeleteI need a solution regarding phonegap application database..
I am creating database using this command,
var db = window.openDatabase(g_dbName, "1.0", "My Databae", 1000000);
I need to know the path of this database in my mobile device.
Please help!
Hi Gaurav, I have been trying to get this to work to no avail. I'm using corodova 3.0 and still no dice. I used your code to copy the database but i get a logcat error saying "no such table" and an alert in my app saying "Error Processing SQL: undefined". What could be going wrong? Do you need me to send a snippet of code for you to take a look at briefly.
ReplyDeleteThanks so much for reading.
Hi Gaurav, I have been trying to get this to work to no avail. I'm using corodova 3.0 and still no dice. I used your code to copy the database but i get a logcat error saying "no such table" and an alert in my app saying "Error Processing SQL: undefined". What could be going wrong? Do you need me to send a snippet of code for you to take a look at briefly.
ReplyDeleteThanks so much for reading.
Hi Gaurav,
ReplyDeleteI have tried for weeks to get this working to no avail. I get logcat errors saying "no such table" and an SQL error "undefined" when i try to perform queries on the database. Is there anything I should be doing? Can i send a snippet of code for you to look at as I have used your code exactly as it is.
Thanks
Hi Gaurav,
ReplyDeleteI've implemented your code but when i look at my AVD monitor, the file doesnt copy. What do i do?
Database doesnt copy, cant seem to get it working. Have used your code exactly as you've outlined. Please help
ReplyDeleteHello,
ReplyDeleteThanks!
I have used same code to copy Db file to respective folder for ios and android in my local development but when my app is ready to build and upload to build.phonegap.com what should I do to copy same DB file for ios and android.
Because there is no java files in zip folder which is uploaded to build.phonegap.com.
Please help me to solve my problem of build app.
Also Please tell me how to add SQLite plugin when building app.
Regards,
Naresh
Hello
ReplyDeleteHello,
ReplyDeleteHow to copy SQLite DB file to respective folder of ios and android when uploading on build.phonegap.com.
Regards,
Naresh
Just for those on the latest Cordova & IOS 7 /w jQuery Mobile 1.4.0 RC1:
ReplyDeleteI have made the above work by adding the DBs (both Database.db & 0000000000000001.db) to
-(void)webViewDidStartLoad in the MainViewController.m OBJ-C file (PhoneGapDelegate.m is no longer).
I am not 100% certain if "0000000000000001.db" as the name is important, but when I tried to use a different name it kept creating the 0000000000000001.db file (likely due to the GUID entry in Database.db) so best stick to the program =).
The below returned the number of rows returned as part of the SELECT for my particular DB without a problem
---8<---- test.js file --------
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
db = window.openDatabase("0000000000000001.db", "1.0", "Test DB", 1000000);
db.transaction(queryDB, errorCB);
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM product', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
alert(results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
I also invented a js library for html5 sqlite, of course phonegap/cordova, will you take a look?
ReplyDeletehttps://github.com/leotsai/html5sqlite
Hello gaurav may I know that can we direct store my android database to phonegap database.??
ReplyDeleteor can we use one database for both android and phonegap??
Hi Gaurav,
ReplyDeleteI used above code, it works fine for android below 4.4 versions. But i got error for 4.4+ versions as "error processing sql" also i found that android 4.4 creates a app_webview folder in which it generates DB.
can i get the proper solution for this issue.
Thanks
Hi Gaurav,
ReplyDeleteI used above code, it works fine for android below 4.4 versions. But i got error for 4.4+ versions as "error processing sql" also i found that android 4.4 creates a app_webview folder in which it generates DB.
can i get the proper solution for this issue.
Thanks
Hi Gaurav,
ReplyDeleteI used above code, it works like charm for me for android below 4.4 versions.
But for 4.4+ it gives error as "error processing SQL" also i found android 4.4+ generates app_webview directory for creating Db.
can i know the proper solution or how it works for android 4.4+ versions.
Thanks.
Hi Gaurav,
ReplyDeleteI used above code for to set my prepopulated DB in android. Above code works for below abdroid 4.4 versions.
But 4.4 and above version it gets issues.
Can i know the solution for this.
Hi Gaurav,
ReplyDeleteI used above code for to set my prepopulated DB in android. Above code works for below abdroid 4.4 versions.
But 4.4 and above version it gets issues.
Can i know the solution for this.
Thanks.
Hi Gaurav,
ReplyDeleteI used above code for to set my prepopulated DB in android. Above code works for below abdroid 4.4 versions.
But 4.4 and above version it gets issues.
Can i know the solution for this.
Hi Gaurav,
ReplyDeletethis works like a charm for 2 years but after I update to Android 4.4.2. The APP report this error:
"Error was could not prepare statment (1 so such table: reservations) (code 5)".
I believe the database was created but empty so the APP can't find any table reservations...
Any idea?
Tks a lot for any reply.
Great post . It takes me almost half an hour to read the whole post. Definitely this one of the informative and useful post to me. Thanks for the share.wordpress development in delhi Elesoftech is a leading offshare web development,mobile application, iphone application
ReplyDeleteHi,
ReplyDeleteEveryone who has posted questions...
Can u provide a sample example code for Android and iOS ..??
So others can get help and no need to post anymore questions..
Any help is appreciated.
Thanks in Advance
Good able to copy the database and easily accessible
ReplyDeleteIs it possible to achieve exactly this using only javascript or JQuery? Please assist
ReplyDeleteHi,
ReplyDeletethis code works perfectly when I use it in android versions < 19, but, in Android 4.4+, it's not working; the database is not being copied to the right folder. What can I do to solve this problem?
Hi.
ReplyDeleteYou forgot mention what are database.db and file__0/0000000000000001.db. I am having a file name "abc.sqlite", then, how can i convert it into 2 former files.
Thanks
Cominform is your partner for efficient, custom-tailored business software-solutions. The Cominform team develops on innovative platforms and in line with cutting-edge standards. Here are options for Web Desktop,Web-Desktop, SAML Cordova Plugin , SQL Cordova Plugin , SAML Phonegap Plugin and SQL Phonegap Plugin.
ReplyDelete