Lab Sheet 8 - SQLite Database

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Indian Institute of Information Technology, Nagpur

IT Workshop - II (CSP 202)


Even Semester 2019-2020
Lab-8 (Android Programming)

Objectives:

1. SQLite Database
2. Sample Program
3. Programming Exercises

I. Introduction to SQLite Database:


Android SQLite is a commonly used database to store data for android applications. Its very lightweight
database which comes with Android Operating System. Android SQLite combines a clean SQL interface
with a very small memory footprint and decent speed. Every Android application can create its own SQLite
databases.
Android SQLite native API is not JDBC, as JDBC might be too much overhead for a memory-limited
smartphone. SQLite is a typical relational database, containing tables (which consists of rows and
columns), indexes etc. We can create our own tables to hold the data accordingly. This structure is referred
to as a schema.
SQLite is an opensource SQL database that stores data to a text file on a device. Android comes in with built
in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to
establish any kind of connections for it like JDBC,ODBC e.t.c. Once a database is created successfully its
located in data/data//databases/ accessible from Android Device Monitor.
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases
Android SQLite SQLiteOpenHelper:

SQLiteOpenHelper class is designed to perform following two basic operations:


1. Database Creation: When the application runs the first time – At this point, we do not yet have a
database. So we will have to create the tables, indexes, starter data, and so on.
2. Database Upgradation: When the application is upgraded to a newer schema – Our database will still
be on the old schema from the older edition of the app. We will have option to alter the database schema
to match the needs of the rest of the app. (We will see this part later…)
In order to create and upgrade a database as per our specifications,we need to create a custom subclass of
SQLiteOpenHelper implementing at least the following three methods:
i. Constructor : This takes the Context (e.g., an Activity), the name of the database, an optional cursor
factory (we’ll discuss this later), and an integer representing the version of the database schema you are
using (typically starting from 1 and increment later).

public DatabaseHelper(Context context) {


super(context, DB_NAME, null, DB_VERSION);
}
ii. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs one. It passes
a SQLiteDatabase object, pointing to a newly-created database, that can be populated with tables and
initial data.
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}

iii. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the schema
version we need does not match the schema version of the database, It passes a SQLiteDatabase object
and the old and new version numbers. Hence we can figure out the best way to convert the database
from the old schema to the new one.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
Android SQLite DBManager class:
DBManager class is defined to perform all database CRUD(Create, Read, Update and Delete) operations
including opening and closing the database.

Opening and Closing Android SQLite Database Connection:


Before performing any database operations like insert, update, delete records in a table, first open the
database connection by calling getWritableDatabase() method as shown below:

public DBManager open() throws SQLException {


dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}

The dbHelper is an instance of the subclass of SQLiteOpenHelper in above method.

To close a database connection the following method is invoked:

public void close() {


dbHelper.close();
}
Inserting new Record into Android SQLite database table:

The following code snippet shows how to insert a new record in the android SQLite database.

public void insert(String name, String desc) {


ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
Content Values creates an empty set of values using the given initial size.

Updating Record in Android SQLite database table:


The following snippet shows how to update a single record.
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues,
DatabaseHelper._ID + " = " + _id, null);
return i;
}

Android SQLite – Deleting a Record:


We just need to pass the id of the record to be deleted as shown below.
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id,
null);
}
Android SQLite Cursor:
A Cursor represents the entire result set of the query. Once the query is fetched a call to
cursor.moveToFirst() is made. Calling moveToFirst() does two things:

 It allows us to test whether the query returned an empty set (by testing the return value)
 It moves the cursor to the first result (when the set is not empty)

The following code is used to fetch all records:


public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT,
DatabaseHelper.DESC };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

Sample Program: This program takes input as name of the country and corresponding currency. Then does all
operations (create, insert, update and delete).
Output Screen when you run the program:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/idno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="25dp"
android:layout_marginBottom="30dp"
android:ems="10"
android:hint="ID No"
android:inputType="text"
app:layout_constraintBottom_toTopOf="@+id/country"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.516"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
app:layout_constraintVertical_bias="1.0" />

<EditText
android:id="@+id/currency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="99dp"
android:layout_marginTop="29dp"
android:layout_marginEnd="99dp"
android:layout_marginBottom="36dp"
android:ems="10"
android:hint="Enter Currency"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/addRecord"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/country" />

<EditText
android:id="@+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="99dp"
android:layout_marginTop="124dp"
android:layout_marginEnd="99dp"
android:layout_marginBottom="29dp"
android:ems="10"
android:hint="Enter Country"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/currency"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/addRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="82dp"
android:layout_marginTop="42dp"
android:layout_marginEnd="100dp"
android:layout_marginBottom="65dp"
android:text="ADD"
app:layout_constraintBottom_toTopOf="@+id/deleteRecord"
app:layout_constraintEnd_toStartOf="@+id/updateRecord"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/currency" />

<Button
android:id="@+id/updateRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="82dp"
android:layout_marginTop="110dp"
android:layout_marginEnd="100dp"
android:layout_marginBottom="65dp"
android:text="UPDATE"
app:layout_constraintBottom_toTopOf="@+id/showRecord"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/addRecord"
app:layout_constraintTop_toBottomOf="@+id/currency" />

<Button
android:id="@+id/deleteRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="82dp"
android:layout_marginEnd="100dp"
android:layout_marginBottom="227dp"
android:text="DELETE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/showRecord"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/showRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="82dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="100dp"
android:layout_marginBottom="227dp"
android:text="SHOW"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/deleteRecord"
app:layout_constraintTop_toBottomOf="@+id/updateRecord" />

</androidx.constraintlayout.widget.ConstraintLayout>

****************************************************************************************************
MainActivity.java

package com.example.country_currency;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


DatabaseHelper myDb;
EditText editCountry,editCurrency,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button btnviewUpdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Creating DatabaseHelper object which is used to create the database


myDb = new DatabaseHelper(this);

//Creating objects for all the components on the xml layout

editCountry = (EditText)findViewById(R.id.country);
editCurrency = (EditText)findViewById(R.id.currency);
editTextId = (EditText)findViewById(R.id.idno);
btnAddData = (Button)findViewById(R.id.addRecord);
btnviewAll = (Button)findViewById(R.id.showRecord);
btnviewUpdate= (Button)findViewById(R.id.updateRecord);
btnDelete= (Button)findViewById(R.id.deleteRecord);

//Invoking the functions for the operations

AddData();
viewAll();
UpdateData();
DeleteData();
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Deleted",Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
editCountry.getText().toString(),
editCurrency.getText().toString());
if(isUpdate)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editCountry.getText().toString(),
editCurrency.getText().toString());
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Inserted",Toast.LENGTH_LONG).show();
}
}
);
}

public void viewAll() {


btnviewAll.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}

StringBuffer buffer = new StringBuffer();


while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Country :"+ res.getString(1)+"\n");
buffer.append("Currency :"+ res.getString(2)+"\n");
}

// Show all data


showMessage("Data",buffer.toString());
}
}
);
}

public void showMessage(String title,String Message){


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}

}
************************************************************************************
DatabaseHelper.java:
/*DatabaseHelper class creates the database, tables etc. It defines the columns for the tables. Also the sql
queries for all operations are written in this class.*/
package com.example.country_currency;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {


public static final String DATABASE_NAME = "Currency.db";
public static final String TABLE_NAME = "currency_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "COUNTRY";
public static final String COL_3 = "CURRENCY";

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,COUNTRY
TEXT,CURRENCY TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}

public boolean insertData(String country,String currency) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,country);
contentValues.put(COL_3,currency);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}

public Cursor getAllData() {


SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}

public boolean updateData(String id,String country,String currency) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,country);
contentValues.put(COL_3,currency);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}

Programming Exercises:

1. Write the above sample program and test the output. Understand each of the modules in the program with
the help of explanation given above the sample program.
2. Develop a user authentication page of your take home assignment using SQLite database.
3. Write a program using arraylist, listview and Sqlite Database. (Explore and give a try. Not mandatory).
4. Continue with take home assignment part-2.

*************************************************************************************

You might also like