SQL Demo

December 23, 2009 1:18:37 PM PST (3 years ago). Seen 68,768 times. 20 replies.
Photo Serete Itebete
Member since Dec 23, 2009
Location: Oakland
Forum Posts: 17
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 SQLDemo

In 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 helper

Handles 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


Source
http://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).
April 13, 2010 9:15:22 PM PDT (3 years ago)
Photo Ivan Greene
Ivan Greene
Member since Apr 13, 2010
Forum Posts: 1
thanks for posting this, very helpful example for me

--Ivan
May 21, 2010 7:21:02 AM PDT (3 years ago)
Photo Cb 03
d
Coltech
Member since May 21, 2010
Forum Posts: 1
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!!!!!!!!!
May 21, 2010 8:01:04 AM PDT (3 years ago)
Photo Marko Gargenta
@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 227
That's not how it works. SQLiteOpenHelper is responsible for creating/updating the database.
November 10, 2010 3:02:07 PM PST (2 years ago)
Photo Bt Tro
None
Member since Nov 10, 2010
Forum Posts: 1
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).
January 25, 2011 4:19:22 AM PST (2 years ago)
Photo Max Meyer
Member since Jan 25, 2011
Forum Posts: 2
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?
January 25, 2011 4:28:22 AM PST (2 years ago)
Photo Marko Gargenta
@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 227
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.
January 25, 2011 5:32:33 AM PST (2 years ago)
Photo Max Meyer
Member since Jan 25, 2011
Forum Posts: 2
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()
January 25, 2011 5:53:29 AM PST (2 years ago)
Photo Marko Gargenta
@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 227
So there you go, answer is right there. Your onDestroy() should call super.onDestroy() first.
January 31, 2011 1:51:24 AM PST (2 years ago)
Photo Kiran k j
art technology
Member since Jan 31, 2011
Forum Posts: 1
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????
February 10, 2011 7:02:55 PM PST (2 years ago)
Photo Someone Someone
Someone
Member since Feb 10, 2011
Forum Posts: 1
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
March 7, 2011 4:35:59 AM PST (2 years ago)
Photo Neeraj Jaiswal
J2me Devloper
I-Tek
Member since Mar 3, 2011
Forum Posts: 1
Hi i had implemented the same app but the db file i get unable to open in Microsoft access.
pls do help?
March 17, 2011 1:38:28 AM PDT (2 years ago)
Photo Robin Singh
Pro
Member since Mar 17, 2011
Forum Posts: 1
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
June 1, 2011 6:31:17 AM PDT (one year ago)
Photo Alexander Shemshurenko
Commercial/Private Business
Member since Jun 1, 2011
Forum Posts: 1
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.
July 3, 2011 4:23:04 AM PDT (one year ago)
Photo Jeyakumaran Mayooresan
Software Engineer
Eyepax IT Consulting
Member since Jun 24, 2011
Forum Posts: 6
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 :)
July 12, 2011 11:49:33 PM PDT (one year ago)
Photo Pratik Dasa
Android developer
Husker Infotech
Member since Jul 12, 2011
Forum Posts: 1
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
October 7, 2011 8:13:08 PM PDT (one year ago)
Photo Vinay Kumar Mopidevi
Android developer
CSC
Member since Jun 25, 2011
Forum Posts: 1
thanks marakana
October 18, 2011 6:36:34 AM PDT (one year ago)
Photo Santhosh Kumar
Software Engineer
Span infotech
Member since May 9, 2011
Forum Posts: 1
The most simplest example for android database and its usage. Thanks very much..
November 2, 2011 3:47:57 AM PDT (one year ago)
Photo Christer Ottosson
Private
Member since Nov 2, 2011
Forum Posts: 1
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).
January 16, 2012 4:59:07 AM PST (one year ago)
Photo Tony Gil
1filmes
Member since Jan 16, 2012
Forum Posts: 1
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);
}

}



November 15, 2012 10:39:10 AM PST (27 weeks ago)
Photo Thomas K
None
Member since Nov 15, 2012
Forum Posts: 1
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! :)