Which database to use for android application? - android

I need some database on my phonegap android application. I read about WebSQL and tried it, and I don't know if it stays after I close the app or it must be made every time i open the app. I need to keep data when app closes so i can use it when i open it again. What database should I use?
P.S. If u have some tutorial it would be nice. Thanks

The best option to store data in database for an Android Application using PhoneGap must be SQLite:
Android Storage Options
but you can use too WebSQL:
SQLite database on PhoneGap
See this question suggested by sajad:
How to implement an SQLite database in Phonegap?
and a Tutorial:
Create Android App with SQLite using Phonegap

Follow this tutorial to learn how to use/create SQLite database in phonegrap (from official doc).
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
This method will create a new SQL Lite Database and return a Database
object. Use the Database Object to manipulate the data.
Syntax + Tutorial:
window.openDatabase(name, version, display_name, size);
Example from the page:
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")');
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
alert("success!");
}
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
I found this tutorial too.

To view the data stored in the database, follow these steps:
Click on Windows > Open Perspective > DDMS. Go to File Explorer.
Then /data/data/package_name/databases.But here we cannot see the tables and table data.
For viewing the table details Eclipse has a plugin. Download it from http://androidcode-sqlite.blogspot.in/2013/04/sqlitemanager-plugin-for-eclipse-android.html.
Now put the jar in the folder eclipse/dropins/.
Click on Java Build Path > Libraries > Add External JARs > Choose Your Path to the SQLite JAR File! Add it.
Restart the eclipse and now you can see the SQLite Manager plugin on the top right of the File Explorer window.
Click on (database name), then click on “open file in SQLite Manager...”.
Here, click on “Questoid SQLite Manager” tab and you can see your table in “Database Structure” tab.
Then, click on “Browse Data” tab to view your table data.

Related

SQLDelight multiple table creation

I am experimenting with KMM but I have an issue with SQLDelight. Here is the code sample of the AppDatabase.sq file.
CREATE TABLE Data (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL
);
-- ====>> Add this new table <<==== (QUESTION 1)
CREATE TABLE Settings (
version TEXT NOT NULL
);
insertItem:
INSERT INTO Data(id, content) VALUES(?,?);
removeAll:
DELETE FROM Data;
selectById:
SELECT * FROM Data WHERE id = ?;
updateById:
UPDATE Data SET content = ? WHERE id = ?;
-- ====>> I want this to be run on DB creation <<==== (QUESTION 2)
INSERT INTO Settings(version) VALUES ('1.0.0');
getVersion:
SELECT version FROM Settings;
When I run the application I receive:
android.database.sqlite.SQLiteException: no such table: Settings (code 1 SQLITE_ERROR): , while compiling: SELECT version FROM Settings.
If I open the databases created by the app using the App Inspection of Android Studio it seems that only Data table exist and other autogenerated tables which have nothing to do with my tables.
My 2 questions (see comments in SQL code for number reference) are:
How can I create this table (Settings) from .sq file?
How can insert a new value into my table without call any function from actual code?
In case you need the whole project is here but in a previous version because the changes I want to implement are not working!
I have cloned your Github project, added the code you provided here and it works just fine. Both of the tables get created and the Settings table has "1.0.0" version row.
Have you uninstalled the application on the phone and installed it again? It's possible you're still using the old version of the database since you haven't provided any migrations for SQLDelight to do.

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/";

How to store data in sqlite database using jQuery-mobile dreamviewer cc with phonegap in android?

Am new in developing android app in Dreamweaver CC with Phone-gap. I designed simple form in that having 4 fields I need to store this fields in sqlite database? In eclipse import sqlite database and open database connection and then create table and store data. This is working fine, I need to do same here in Dreamweaver CC?
import android.database.sqlite.SQLiteDatabase;
SQLiteDatabase db;
db = this.openOrCreateDatabase("QAOD", MODE_PRIVATE, null);
db.execSQL("INSERT INTO TableName(Id) VALUES(18)");
This format code is working fine in eclipse android but I need use this code and store data in sqlite in Dreamweaver CC with Phone-gap. Help me or suggest me to store data.
You mentioned you are using Phonegap. These are the steps to create and add records to sqlite database in Android
First: Add Plugin
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
Second: Open Database
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
}
Third: Use it (Create, Update or Delete)
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function(res) {
console.log("PRAGMA res: " + JSON.stringify(res));
});
You can read more here...

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.

How to access an existing sqlite database in Android?

So far we have developed apps in android that create database on runtime. We like to know how can we access a pre-built or existing database/sqlite file in our android app? Please provide detail
Take a look at the documentation for android.database.sqlite.SQLiteDatabase.
In particular, there's an openDatabase() command that will access a database given a file path.
SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, 0);
Just specify the path to your database as the path variable, and it should work.
I have followed the same road and found two issues:
Include the _id field on any table you create and make sure it is
part of the columns to return when you query any table.
You may run into an error like Failed to open the database. closing
it.. This is because we are copying the database from an existing
file instead of creating tables on top of a db created by the sqlite
android API and the table android_metadata may not exist. For
creating it just run the following query on your db:
CREATE TABLE android_metadata (locale TEXT);
And add the corresponding locale, for example en_US
First copy your SDCARD and give it's path in the variable "DBNAME" in the following example.
it will be something like "/sdcard/persons.db" if you are directly pulling it to sdcard.
Use this for accessing database in application :
Context context = getApplicationContext();
context.getDatabasePath(DataBaseHelper.database_Name);

Categories

Resources