Create sqlite database in android using java script

Hi friends,

1 month back I was assigned a project where we need to make our own Phone Gap like mechanism.

You can know more about phone gap here. Basically the project is mixture of HTML5,JavaScript,jQuery and Android-Java.

There are lot of stuff to which I can share with you but which I found most interesting is connecting sqlite database using javascript code. (Yea really !!! I was wondering whether it is possible or not.) After some r&d and help of few I am able to find out the things.

Here are the steps to create database from javascript.

Step 1 : Create a simple android project.

You can name it JavaScriptTest or any name say I hate Java Script 🙂

Step 2: Create an activity which has webview in it.

public class JavaScriptTestActivity extends Activity {
/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView=new WebView(this);
webView.setInitialScale(1);
webView.requestFocus(View.FOCUS_DOWN);
webView.requestFocusFromTouch();

final String databasePath = this.getApplicationContext().getDir(“database”, Context.MODE_PRIVATE).getPath();
WebSettings settings = webView.getSettings();
settings.setDatabasePath(databasePath);
settings.setAppCacheMaxSize(5*1024*1024);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setUseWideViewPort(true);
settings.setLoadsImagesAutomatically(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setAllowFileAccess(false);
settings.setUseWideViewPort(false);
settings.setSupportZoom(false);
settings.setSavePassword(false);
settings.setSupportMultipleWindows(false);

webView.setWebChromeClient(new WebChromeClient()
{
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}

@Override
public void onExceededDatabaseQuota(String url,
String databaseIdentifier, long currentQuota,
long estimatedSize, long totalUsedQuota,
WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(5 * 1024 * 1024);
}
});

// Above lines are necessary to load javascript and allowing your webview to create sqlite database so KEEP THEM AS IT IS.
setContentView(webView);
webView.loadUrl(“file:///android_asset/index.html”);
}

}

Step 3 : Create a Java Script file, named it db.js

Please put above created file in assets folder. db.js will hold content like this . Magic is here 🙂 .

function loaddb()
{
var db = openDatabase(‘testdb’, ‘1.0’, ‘my database’, 2 * 1024 * 1024);

db.transaction(function (tx)
{
tx.executeSql(‘CREATE TABLE IF NOT EXISTS person (_id INTEGER, person_name TEXT, address TEXT)’);

tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(1, “Hardik Trivedi”, “Ahmedabad,Gujarat,India”)’);
tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(2, “Sonam Kapoor”, “Mumbai,Maharashtra,India”)’);
tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(3, “Rajnikanth”, “There is no specific address of him :)”)’);

});
}

Step 4 : Create index.html (here also you can create file with any name)

For now index.html is pretty decent page just having two script tag and few html tags

<html>
<head>
<script src=”db.js”></script>
<script src=”jquery.js”></script>

</head>
<body>
<div>
<script language=”javascript”>
$(document).ready(function() {
alert(“Hello”);
loaddb();
});
</script>
</div>
<h4>Hello Friends !!!!!!</h4>
</body >

</html>

In above code I have added two js files. db.js holds function to handle database and jquery.js has $document.ready function’s definition.

Please find sample code here.

Enjoy the concept. Cheers !!!

4 thoughts on “Create sqlite database in android using java script

  1. But how javascript know which testdb to open and where it resides? And also database are kept in separate package in Android.

  2. Hello, I’m new to java or javascript, so thanks for your post. Now, how to add/edit/delete record from DB? Where DB is stored? and finally I need to know from data stored in DB that certain condition is met to trigger an alarm, how can I do that?. I appreciate your comments via email. Have a nice day.

  3. I’m fairly certain this is a WebSQL implementation rather than SQLite per se, as is subject to size limits of WebSQL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s