SQL Demo

Serete Itebete
This example shows how to interact with Android SDK internal database SQLite to perform a simple action of inserting and querying data from a database table and database display content.
Our simple data format is: [row id] [time recorded] [Hello Android Event]
To make this possible requires;
1. An Activity SQLDemoIn this example, the sqldemo activity has four important methods related to our database;
AddEvent - ability to add a string type event into the database note the use of the getWritableDatabase() method to the database handler instance,
GetEvents - ability to query database and here note the getReadableDatabase() method useage together with the startManagingCursor(cursor) and therefore return a cursor (walker),
ShowEvents - display of the data submitted by GetEvents cursor that was returned and loop through all the data,
onDestroy - always release database instance back to system;
SQLDemo.java
Code:
package org.example.sqldemo;
import static android.provider.BaseColumns._ID;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
public class SQLDemo extends Activity {
EventDataSQLHelper eventsData;
TextView output;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
output = (TextView) findViewById(R.id.output);
eventsData = new EventDataSQLHelper(this);
addEvent("Hello Android Event");
Cursor cursor = getEvents();
showEvents(cursor);
}
@Override
public void onDestroy() {
eventsData.close();
}
private void addEvent(String title) {
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EventDataSQLHelper.TIME, System.currentTimeMillis());
values.put(EventDataSQLHelper.TITLE, title);
db.insert(EventDataSQLHelper.TABLE, null, values);
}
private Cursor getEvents() {
SQLiteDatabase db = eventsData.getReadableDatabase();
Cursor cursor = db.query(EventDataSQLHelper.TABLE, null, null, null, null,
null, null);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
StringBuilder ret = new StringBuilder("Saved Events:\n\n");
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
long time = cursor.getLong(1);
String title = cursor.getString(2);
ret.append(id + ": " + time + ": " + title + "\n");
}
output.setText(ret);
}
}
2. Database helperHandles all the database connections, creation of the necessary table and has additions like database upgrade information thrown in to code in case of future database upgrades.
EventDataSQLHelper.java
Code:
package org.example.sqldemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
/** Helper to the database, manages versions and creation */
public class EventDataSQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
// Table name
public static final String TABLE = "events";
// Columns
public static final String TIME = "time";
public static final String TITLE = "title";
public EventDataSQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "( " + BaseColumns._ID
+ " integer primary key autoincrement, " + TIME + " integer, "
+ TITLE + " text not null);";
Log.d("EventsData", "onCreate: " + sql);
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;
String sql = null;
if (oldVersion == 1)
sql = "alter table " + TABLE + " add note text;";
if (oldVersion == 2)
sql = "";
Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}
Output
Sourcehttp://marakana.com/static/tutorials/SQLDemo.zip
Edited 11 times. Last edit by Robin Singh on Mar 17, 2011 at 1:38:28 AM (about one year ago).

Ivan Greene
Ivan Greene
thanks for posting this, very helpful example for me
--Ivan

Cb 03
d
Coltech
Hello, I want to ask that If I have a sqlite database which created by others program, so Can I copy this into assets and use its as a normal file??????????
thanks!!!!!!!!!

Marko Gargenta
@MarkoGargenta
Marakana, Inc.
That's not how it works. SQLiteOpenHelper is responsible for creating/updating the database.

Bt Tro
None
Thank you so much!!! I tried several other tutorials for sql but none worked. This one did!
Thanks, very clear and easy to see what's up (esp after spending hours upon hours with other tutorials).

Max Meyer
Thank you for this example, it helped a lot; but when the app is closed, there is a message: Sorry! The application SQL Demo (process org.example.sqldemo) has stopped unexpectedly.
The database is being closed in onDestroy() - so what can it be then?

Marko Gargenta
@MarkoGargenta
Marakana, Inc.
Markus, you may want to look at the logcat for clues. Do adb logcat from your command line terminal and try to find the last exception.

Max Meyer
E/AndroidRuntime( 272): FATAL EXCEPTION: main
E/AndroidRuntime( 272): android.app.SuperNotCalledException: Activity {org.example.sqldemo/org.example.sqldemo.SQLDemo} did not call through to super.onDestroy()

Marko Gargenta
@MarkoGargenta
Marakana, Inc.
So there you go, answer is right there. Your onDestroy() should call super.onDestroy() first.

Kiran k j
art technology
what is the deference between the above example and the example shown below
http://www.devx.com/wireless/Article/40842/1954
Is there any advantage????

Someone Someone
Someone
Hi Guys,
I had a very simple question. I am not able to understand the lifecycle of a SQLLite DB (table and data).
So it seems like onCreate, the DB Table is created. So is the onCreate not called every time the application is started?
I want to build an application which will persist the data on the SQLLiteDB. During repeat visits of the user, i want to use this historically entered data.
Can someone clarify how this works or guide me to the appropriate documentation on the internet?
Thanks

Neeraj Jaiswal
J2me Devloper
I-Tek
Hi i had implemented the same app but the db file i get unable to open in Microsoft access.
pls do help?

Robin Singh
Pro
Dear All,
I am new to the android community.
Can someone guide me as to how can I use MS SQL server 2005 in Android OS 2.2 to carry out some of the analytics?
Thanks in anticipation.
Regards
Robin

Alexander Shemshurenko
Commercial/Private Business
Hi
I get exception when i try to open database, exception message reads:
"open database error unable to open file"
Another thing is onCreate method never called.
Any ideas?
Thanks.

Jeyakumaran Mayooresan
Software Engineer
Eyepax IT Consulting
Thanks a lot :)
There are many tutorials on net either more complex or just an introduction. Even android developer site's documentation on content providers is very poor.
All are not good for newbies like me.
This tutorial indeed the must read for all Android dev beginners. WAY TO GO MARKANA :)

Pratik Dasa
Android developer
Husker Infotech
Hey Thanx a lot......
Its such a great example to create database in android and this code is very easy to understand and its working fine for me.....Thanx a lot

Vinay Kumar Mopidevi
Android developer
CSC
thanks marakana

Santhosh Kumar
Software Engineer
Span infotech
The most simplest example for android database and its usage. Thanks very much..

Christer Ottosson
Private
I get impressed about the positive comments so I tried to lod the tutorial in my Eclips to studie it but it did not work for me.
I imported the SQLDemo foalder into the workspace in Eclips.
I have Eclipse SDK Version: 3.6.2 and and Android SDK tools rev 12.
Do I need anything more.
Edited one time. Last edit by Christer Ottosson on Nov 2, 2011 at 4:56:46 AM (about one year ago).

Tony Gil
1filmes
thank you, marko. i have read one your books on android apps and come to your site often for tutorial info.
i was wondering how to use multiple tables, so i downloaded your code and played around with it the very least possible. i decided to create a second table called "venues" and i later "joined" it with table "events" using the "_id" field as a key (i said i was trying to make this as simple as possible).
this is the code (i changed package name and activity names, but the rest is BASICALLY the same):
Code:
package com.tg.zdelDB01a;
import android.app.Activity;
import android.os.Bundle;
import static android.provider.BaseColumns._ID;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.TextView;
public class ZdelDB01aActivity extends Activity {
SQLHelper eventsData;
TextView output;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
output = (TextView) findViewById(R.id.output);
eventsData = new SQLHelper(this);
addEvent("Hello Android Event");
String zdelTempStr01 = "VN_"+(String.valueOf(System.currentTimeMillis())).substring(String.valueOf(System.currentTimeMillis()).length()-4);
addVenue(zdelTempStr01);
Cursor cursor = getEvents();
showEvents(cursor);
}
@Override
public void onDestroy() {
eventsData.close();
}
private void addEvent(String title) {
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SQLHelper.TIME, System.currentTimeMillis());
values.put(SQLHelper.TITLE, title);
db.insert(SQLHelper.TABLE01, null, values);
}
private void addVenue(String venue) {
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SQLHelper.VENUE, venue);
db.insert(SQLHelper.TABLE02, null, values);
}
private Cursor getEvents() {
SQLiteDatabase db = eventsData.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT events._id, events.time, events.title, venues.venue FROM events LEFT JOIN venues ON events.[_id] = venues.[_id]", null);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
StringBuilder ret = new StringBuilder("Saved Events:\n\n");
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
long time = cursor.getLong(1);
String title = cursor.getString(2);
String venue = cursor.getString(3);
ret.append(id + ": " + time + ": " + title + " AT " + venue + "\n");
}
output.setText(ret);
}
}
and the DB Helper (NOTE: i did not fix the onUpgrade method, feel free to do so)
Code:
package com.tg.zdelDB01a;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
/** Helper to the database, manages versions and creation */
public class SQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
// Table name
public static final String TABLE01 = "events";
public static final String TABLE02 = "venues";
// Columns
public static final String TIME = "time";
public static final String TITLE = "title";
public static final String VENUE = "venue";
String sql01 = "create table " + TABLE01 + "( " + BaseColumns._ID
+ " integer primary key autoincrement, " + TIME + " integer, "
+ TITLE + " text not null);";
String sql02 = "create table " + TABLE02 + "( " + BaseColumns._ID
+ " integer primary key autoincrement, "
+ VENUE + " text not null);";
public SQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("EventsData", "onCreate: SQL01 " + sql01);
Log.d("EventsData", "onCreate: SQL02 " + sql02);
db.execSQL(sql01);
db.execSQL(sql02);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;
String sql = null;
if (oldVersion == 1)
sql = "alter table " + TABLE01 + " add note text;";
if (oldVersion == 2)
sql = "";
Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}

Thomas K
None
So,... you showed how to write and read out of the db, but what if i wanna update an existing record? Could you please give a short example? Thanks a lot! :)