Using database in phonegap applications or not? - android

I'm new to PhoneGap, I'm making an application, it has like 500 words with definition of each word.
I have web developing background, in web developing, we create a database, and work with it, no matter the website is visited or not, data is there.
But in PhoneGap, it likes that we make a database every time that the application ran, and drop the table if it exist next time ( i dont know if i understood it right ).
So, if it's like that, it doesnt make any sense for me to use database at all !!
I want to know is there a way, that when user install the app on the phone, Data transfer automaticly, and it just be there when we need it ? ( not creating the table with the entries every time we need it ! )

Of course you don't have to create the DB at each app start and drop everything when you close the app. You can even version your DB. Here's a brief example:
db = window.openDatabase("mydbname", "",
"App Name", <size_in_bytes>);
console.log("version is: " + db.version);
if (db.version == "") {
// EMPTY STRING -> VERY FIRST ACCESS -> CREATE THE DB!
db.changeVersion("", "1", createDB,
function(error) {
console.log("ERROR DB from empty: " + JSON.stringify(error))
},
function() {
console.log("version 1, done!");
}
);
} else {
// We have the DB!
[...]
}
And you put the CREATE stuff and eventually INSERT stuff in the createDB function.
Everything according to the API:
window.openDatabase(name, version, display_name, size);

Related

Why is my SQLite database file not showing any data?

Aim -
I am trying to store longitude and latitude data from the geolocation API using React native. I created a .db file put it into the /assets/ folder in android. First, instead of the location data, I am trying to insert or retrieve any kind of data.
ERROR -
It shows that there is no table named Test when I try to console.log() it.
Problem -
Whenever I try to insert data into the database I don't see any new data added and also When I try to read an already populated database I see nothing. Where am I wrong? I am fairly new to this.
What is the response returned by the SQL transaction. I console.log it but couldn't understand.
Where should be the transaction function be located?
I am using DBbrowser for SQLite
OS - MacOS
CODE -
I am using this function to send or receive data.
sendData = () => {
// var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'a', createFromLocation : "~test.sqlite"}, this.openCB, this.errorCB);
db.transaction(txn => {
txn.executeSql(
// "INSERT INTO Test (latitude,longitude) VALUES(?,?)",
'SELECT * FROM Test',
[], //Argument to pass for the prepared statement
(res) => {
// let row = res.rows.(1);
console.log(res);
} //Callback function to handle the result response
);
});
};
// I mapped this button to send data.
<TouchableOpacity onPress={this.sendData} style={styles.button}>
<Text> SEND DATA</Text
</TouchableOpacity>
You won't be able to modify a database stored in the assets folder. The typical method is before ever trying to open the database to insert records, you first check to see if the database exists in your apps data folder (not sure if React has the same folder structures or not). If the database doesn't exist in the data folder, then you copy your clean database from assets to the data folder, then open the database from the data folder. As long as the app isn't deleted off the device, the database in the data folder will persist, along with all of the data you have inserted into it. Once the app has been deleted and reinstalled, the database will have to be copied from assets once again and will be clean, with no new data in it.
I don't know if the same data folder structure applies to React, but in native Android I use:
"/data/data/com.mycompany.myapp/databases/"
OR
DB_PATH = myContext.getFilesDir().getParentFile().getPath() + "/databases/";

Unable to find SQLite on Android

I have this android application that I am developing in Unity. I am using SQLite to save and access my data.
When I run my code on Unity editor it works fine. But when I tried it in my android device after some changes in the database, it did not work. So I undid those changes and use Android Device Monitor to check what was happening. I found out that, even though it looked to be working, it was throwing a Unity error: Unable to find SQLite.
I just can't understand what is going on. It works on Unity editor, and, before changes in my database, it also worked (or that was what it seemed) on android device.
This is the code I use to connect to database:
private void conecta()
{
if (Application.platform != RuntimePlatform.Android)
{
dbFile = Application.dataPath + "/StreamingAssets/" + databasefile;
}
else
{
dbFile = Application.persistentDataPath + "/" + databasefile;
if (!File.Exists(dbFile))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + databasefile);
while (!load.isDone)
{
}
File.WriteAllBytes(dbFile, load.bytes);
}
}
print("aaaaaaaaaaaaaaa");
connection = new SqliteConnection("URI=file:" + dbFile);
print("bbbbbbbbbbbbbb");
}
On my project, I have some dll in my Plugins folder.
And I have libsqlite3.so in my Android folder that can be seen in the picture.
I don't understand what's going on, because when I run the app it accesses the database data and stores more data, but apparently it also throws this error. Can anyone please help me?
If this information is not enough, please let me know. I will complete my question.
UPDATE
I now know the exact line of code that is giving the error. I use the code above to establish a connection with the SQLite database in some scripts. But in this specific script, which is attached to the first screen of the application, the error is coming from this line:
connection = new SqliteConnection("URI=file:" + dbFile);
I don't know why. I use that code as a method and use it some times in this script. I have some buttons that only become interactable if I have data in my database. And when I run it on my device they became interactable. That's why I did not see the error until yesterday when I changed the database file. Below you can see the error when accessing the new column and the table structure in database.
I added one column in two tables, and when I try to access one of those columns it throws an error saying that the table does not have a column with that name.
NEW UPDATE
I got tired of this error and deleted my database file. After that I did a new one, with columns I addes before. What happened was that the Unable to find SQLite continues. After taht it keeps saying that my table does not have the especific column I added in the other file. I don't understant what's going on. That new database had the column from the very begining.
I still don't know what was the problem with the app. But I did a new database file with a different name and it is now working.

Storage of SQLite database using Android and Phonegap

I'm developing a Android Cordova/Phonegap app where I want to use a SQLite database. I used the example from the official documentation.
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
// Query the database
//
function queryDB(tx) {
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
//
function querySuccess(tx, results) {
var len = results.rows.length;
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
}
}
// Transaction error callback
//
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
// Transaction success callback
//
function successCB() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(queryDB, errorCB);
}
// device APIs are available
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
Although this seems to work (the database is created and filled without errors, and I get the written data back with the query), I'm wondering how the database is stored on my device. For debugging I use a hardware phone with Android 4.1.1.
The database is located under /data/data/<myapppackage>/app_database/file__0/0000000000000001.db. Now I wanted to export the database and analyze it manually on my pc with SQLiteManager, but it seems the changes are not written to the db file.
However, when examining the directory /data/data/<myapppackage>/app_database/file__0/ i found the two temporary files 0000000000000001.db-shm and 0000000000000001.db-wal, whose timestamps are changed every time I perform a database operation, but never the db file itself.
My question is, why are the changes never written to the persistent database file? There does not seem to be a way to close a database connection with phonegap, and even killing the app manually doesn't write the changes to the .db file. I'm not sure what I did wrong.
Anyone seeing the problem here?
tx.executeSql('DROP TABLE IF EXISTS DEMO');
This line above deletes the table named DEMO everytime you start your PhoneGap mobile application
And I just wanted to tell you I love your code. It gives a very good clue about "what to do" for anyone's PhoneGap or Cordova application. It will greatly help anyone who is entering the world of SQLite for the first time.
Your code is very clean to read and understand compared to the codes written on Cordova/PhoneGap SQLite plugin official website on GitHub.
My friend, who also works as the CTO of a company, and has a plenty of experience with SQLite, told me that it is not necessary to close a SQLite database connection manually, and also greatly recommended SQLite.
And for anyone else looking for SQLite for PhoneGap/Cordova information -
Let's say you have a table named mytable and want to store values "beautiful" and "dolphin"
When you want to perform an operation on the SQLite of a mobile device, such as a tablet or phone, remember to call it this way
Have the following in your source code
function insertNewLine(tx)
{
tx.executeSql("INSERT INTO mytable (word, meaning) VALUES (?,?)", [ var1 , var2 ]);
}
and store "beautiful" inside var1 and "dolphin" inside var2 and
do the following statement in order to execute the SQL insert statement and then save inside the device.
db.transaction(insertNewLine);
Do not directly call insertNewLine(tx)
Do not directly call tx.executeSql( /* SQL INSERT STATEMENT */ ); in your JavaScript sourcecode
And do not include the values straight into the SQL query statement and then run the SQL statement that includes the values you want to store in the database.
In other words, the following is incorrect
tx.executeSql('INSERT INTO mytable (word, meaning) values (beautiful, dolphin)');
The above is incorrect because the values you want to store, "beautiful" and "dolphin" are included inside the SQL statement. They should be separate.
The following is the correct way to run the INSERT SQL
tx.executeSql("INSERT INTO mytable (word, meaning) VALUES (?,?)", [ var1 , var2 ]);
// Notice that the values you want to store, beautiful and dolphin
// are separate from the SQL INSERT INTO statement
and then perform the entire database transaction by including the following in your JavaScript code
db.transaction(insertNewLine);
not the below code
tx.executeSql("INSERT....."); // this will not save your values onto the device
not the below code either
insertNewLine(tx); // this will not save your values onto the device either.
And to use the SELECT SQL statement, have the following code
// Get all lines in the table
//
function viewthelastglory(tx)
{
tx.executeSql( 'SELECT * FROM CUSTOMTABLE', [], querySuccess, errorcode );
}
// Deal with the lines
//
function querySuccess(tx, results)
{
var len = results.rows.length; var queryresult = "all entries ";
for (var i = 0 ; i < len ; i++)
{
queryresult = queryresult +
" Row - " + i +
" Word - " + results.rows.item(i).word +
" Meaning - " + results.rows.item(i).meaning;
}
// and now, you can use the queryresult variable to use the values
}
function errorcode(errorhaha)
{
alert("Error Code " + errorhaha.code + " Error Message " + errorhaha.message);
}
And then, perform the database transaction
db.transaction(viewthelastglory);
If you are trying to choose one from SQLite, WebSQL and IndexedDB, please remember that I searched around stackoverflow for a while and learned that
Nobody likes IndexedDB because of its complexity
IndexedDB is incompatible with many types and versions of mobile OS
WebSQL has been deprecated by W3C
WebSQL returns 673K results but SQLite returns 1800K results. IndexedDB returns 300K results on Google
Among IndexedDB, SQLite and WebSQL, SQLite is the only one with an official website.
The following command at the command line while you are in the directory of your Cordova project will install the SQLite plugin into your Cordova project
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
The solution is : Debug your app with emulator instead of physical device.
Run your app with emulator instead of physical device. You will find your database file in /data/data/YOUR_PACKAGE_NAME/app_database/. You can pull the database file and browse the tables and data.
In WAL mode, any changes are written to the -wal file; the database file itself does not get updated until a checkpoint is done.
If there is a -wal file, you must copy it, too.

Master Sync Database

Hi am syncing my database with server for any incremental values on click of a button. Below is the code which checks all the values and inserts if the data is missing but from android perspective is there any optimized technique to do the sync
//new fields
public void updatenewfileds(ArrayList<String> s) {
ArrayList<String> da = new ArrayList<String>();
try {
String manu = "select MANUFACTURERID from ManufacturerDesc";
Cursor cc = mDb.rawQuery(manu,null);
Log.d("Cursor count", "Count =" + cc.getCount());
if (cc != null && cc.getCount() > 0) {
if (cc.moveToFirst());
do {
da.add(cc.getString(cc.getColumnIndex("MANUFACTURERID")));
System.out.println("here got all alreday avilable ids"+ cc.getString(cc.getColumnIndex("MANUFACTURERID")));
} while (cc.moveToNext());
cc.close();
} else {
cc.close();
}
// need to add only missing data
for(int i = 0; i<da.size(); i++){
boolean flag = false;
System.out.println(flag);
for(int j=0; j<i; j++){
if(da.get(i).equals(s.get(i*2))){
flag = true;
break;
}
}
if(flag == false){
String sql = "insert into ManufacturerDesc values('"+ s.get(i*2)+"','"+ s.get(i*2+1)+"');";
System.out.println("item inserted into db"+ s.get(i*2) +"******" + s.get(i*2+1) );
mDb.execSQL(sql);
}
}
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>" + mSQLException.toString());
throw mSQLException;
}
}
This would be my suggestion, the [] are just to emphasize, as I might get back to it:
Design your Android database tables like: { _id, [server_id], .. your data .. }
On all your tables on the server add a [time_changed] timestamp.
Whenever your device gets synced with the server, the server should additionally send a last sync timestamp e.g. System.currentTimeMilliseconds() (letting the server do this to avoid relying on synced clocks). This timestamp is stored on the android device and used whenever requesting a new sync.
When the server receives a sync request the stored last sync timestamp is yet again handed to the server from the device. Now a simple query can extract all the relevant added data since the timestamp (minus some constant to ensure you get everything). For example SELECT * FROM Mydata WHERE (time_changed > (last_sync-5000)); 5000 being 5 seconds.
Now as you receive data from the server, remember to add the [server_id], which is just the autoincremented _id from the server. This enables you to deduce whether some of thee received rows are known (which is likely with the minus 5 seconds above).
The deduction is a simple query on the device e.g: Do I already have a row with [server_id], if not we add it, if yes then skip it.
With this method you avoid to send more and more information over time, as you only send the rows that are changed after the last sync (plus a bit more).
If you edit rows on your server, simply update time_changed again to reflect the edit . Then it will automatically be included and overwritten on the device during the next sync.
If you plan on doing a lot of database operations on the android device, I would suggest trying MotoDev, it can be plugged in to eclipse and has some nice database features. Including a database perspective and automatic generation of ContentProviders (nice classes to make database operations simple).
Giving a full explanation or guide to do all this is way out of the scope of this answer. It should merely give you an idea as to how it can be done, and if you wish to improve your syncing process, you now have some guidance.
Regarding mechanism as autoincrement and timestamp on a database, there is plenty of examples to find on the interwebz.
Happy coding :)

what is the exact process of using the Database in phonegap android?

I am new to Phonegap. I am trying to implement an application in Phonegap Android. For the past two days,I am scouting for a proper way of accessing the database and retrieving it from the same.I did not find an answer to my questions
I have learnt that Phonegap does not support SQLLITE but supports the W3C Web SQL Database Specification and W3C Web Storage.
At the same time I noticed few plugins for Phonegap 1.5..which does not exist now. At the same time i found that W3c database provides a limited storage of 5MB for iOS.
I found this SQL Plugin for Phonegap Android PhoneGap-SQLitePlugin-Android Is it advicable to use this or any other method. Please,guide me.
So,if you have any sort of example of accessing the database that can be followed please share it.
I made an app recently that required this, targetting the Android and iOS. You can use a combination of the following ::
1. LocalStorage ::
Check for localStorage
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
Set an item into LocalStorage
localStorage.setItem("bar", foo);
or
localStorage["bar"] = foo;
Get an item from LocalStorage
var foo = localStorage.getItem("bar");
or
var foo = localStorage["bar"];
2. SQLite Database (more convenient, more persistive)
Set up your DB
var shortName = 'BHCAppDB';
var version = '1.0';
var displayName = 'BHCAppDB';
var maxSize = 65535;
if (!window.openDatabase){
alert('!! Databases are not supported in this Device !! \n\n We are sorry for the inconvenience and are currently working on a version that will work on your phone');
}
db = openDatabase(shortName, version, displayName,maxSize);
createAllTables(db);
Create your Tables
function createAllTables(db){
db.transaction(function(transaction){
transaction.executeSql("CREATE TABLE IF NOT EXISTS Profile(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, gender TEXT,age INTEGER)");
}
Execute an SQL Query
transaction(function(transaction){
var rowCount = 'SELECT * FROM Profile';
transaction.executeSql(rowCount,[],function(transaction,result){
if(result.rows.length == 0){
var sqlString = 'INSERT INTO Profile (name,gender,age) VALUES("自己","Female",18)';
transaction.executeSql(sqlString);
}
});
});
3. Native Storage on all devices
This is the best part of Phonegap. You can call a native plugin class on all the devices using the Phonegap plugin call. During the call, you can pass parameters to the class, and the native class can store your data in the OS itself.
For example :: in iOS, you create a plugin .h & .m class and register it with the Cordova.plist file. Once that's done, you need to send a call to the class from JavaScript using Phonegap. Once the parameters have been received using NSDictionary or any other NSArray type, you can call a CoreData class to store UNLIMITED amounts of data. You'll never run out of memory .
This can be done in a similar fashion for all the rest of the OS's also :)
For Encryption try the following :: SQLCipher
Here is some additional information on working with an existing SQLite database. In this example encrypted.db is that brand new database you create and pragma.
ATTACH DATABASE 'encrypted.db' AS encrypted KEY 'secret'; -- create a new encrypted database
CREATE TABLE encrypted.t1(a,b); -- recreate the schema in the new database (you can inspect all objects using SELECT * FROM sqlite_master)
INSERT INTO encrypted.t1 SELECT * FROM t1; -- copy data from the existing tables to the new tables in the encrypted database
DETACH DATABASE encrypted;

Categories

Resources