0% found this document useful (0 votes)
669 views6 pages

Sqllite in Android

This document provides an overview of using SQLite databases in Android applications. It discusses how to create and connect to a SQLite database, create tables, insert records, and query the database. Code samples are provided to demonstrate opening a database, defining table schemas with CREATE statements, inserting records with ContentValues, and querying the database with a Cursor to retrieve and display records. The document also includes a sample Android activity and database helper class to showcase interacting with a SQLite database to add, retrieve, and display event data from a table.

Uploaded by

shahulsifu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
669 views6 pages

Sqllite in Android

This document provides an overview of using SQLite databases in Android applications. It discusses how to create and connect to a SQLite database, create tables, insert records, and query the database. Code samples are provided to demonstrate opening a database, defining table schemas with CREATE statements, inserting records with ContentValues, and querying the database with a Cursor to retrieve and display records. The document also includes a sample Android activity and database helper class to showcase interacting with a SQLite database to add, retrieve, and display event data from a table.

Uploaded by

shahulsifu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

SQLLITE DATABASE

Example 1:
SQLite is an open-source server-less database engine. SQLite supports transacations and has no configuration required. SQLite adds
powerful data storage to mobile and embedded apps.

Creating and connecting to a database:

Import android.database.sqlite.SQLiteDatabase into the application.

Use openOrCreateDatabase() method to create or connect to a database.

Sample code pasted below,

package example.SQLiteTest;

import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;

public class SQLiteTest extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}

public SQLiteDatabase openOrCreateDatabase (String name, int mode,


SQLiteDatabase.CursorFactory factory)
Since: API Level 1

Open a new private SQLiteDatabase associated with this Context's application package. Create the
database file if it doesn't exist.

Parameters

name The name (unique in the application package) of the database.


Operating mode. Use 0 or MODE_PRIVATE for the default operation,
mode
MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
factory An optional factory class that is called to instantiate a cursor when query is called.
Returns
 The contents of a newly created database with the given name.
Creating Tables:
execSQL() statement is used to execute queries.

execSQL() statement is used to execute queries.

Before creating tables, certain database properties should be set using the following methods,

setVersion(), setLocale(), and setLockingEnabled().

Append this code to the previous example for creating tables (tbl_countries and tbl_states)..

db.setVersion(1);

db.setLocale(Locale.getDefault());

db.setLockingEnabled(true);

final String CREATE_TABLE_COUNTRIES =

"CREATE TABLE tbl_countries ("

+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"

+ "country_name TEXT);";

final String CREATE_TABLE_STATES =

"CREATE TABLE tbl_states ("

+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"

+ "state_name TEXT);";

db.execSQL(CREATE_TABLE_COUNTRIES);

db.execSQL(CREATE_TABLE_STATES);

void android.database.sqlite.SQLiteDatabase.execSQL(String sql) throws SQLException

public void execSQL (String sql)


Since: API Level 1

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to
use insert(String, String, ContentValues), update(String, ContentValues,
String, String[]), et al, when possible.

When using enableWriteAheadLogging(), journal_mode is automatically managed by this class. So,


do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using
enableWriteAheadLogging()

Parameters
the SQL statement to be executed. Multiple statements separated by semicolons are not
sql
supported.
Throws

SQLException if the SQL string is invalid

Inserting Records:

import android.content.ContentValues;

Use ContentValues instance to create a series of table field to data matchings that will be passed into an insert() method.

Code snipped pasted below..

ContentValues values = new ContentValues();

values.put("country_name", "India");

db.insert("tbl_countries", null, values);

sqlite> select * from tbl_countries;

select * from tbl_countries;

1|India

long android.database.sqlite.SQLiteDatabase.insert(String table, String nullColumnHack,


ContentValues values)

public long insert (String table, String nullColumnHack, ContentValues values)


Since: API Level 1

Convenience method for inserting a row into the database.

Parameters

table the table to insert the row into


optional; may be null. SQL doesn't allow inserting a completely empty row
without naming at least one column name. If your provided values is empty,
nullColumnHack no column names are known and an empty row can't be inserted. If not set to
null, the nullColumnHack parameter provides the name of nullable column
name to explicitly insert a NULL into in the case where your values is empty.
this map contains the initial column values for the row. The keys should be the
values
column names and the values the column values
Returns
 the row ID of the newly inserted row, or -1 if an error occurred
Example 2:
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].
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:

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);
}
}

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.

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);
}

You might also like