0% found this document useful (0 votes)
25 views30 pages

Unit 5

The document provides a comprehensive guide on storing Android application data using SQLite and JSON, detailing CRUD operations and database setup. It explains SQLite's features, installation steps, and how to view and manage databases in Android Studio. Additionally, it includes code examples for creating a database, inserting data, and performing update and delete operations using Kotlin.

Uploaded by

ridham26kamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views30 pages

Unit 5

The document provides a comprehensive guide on storing Android application data using SQLite and JSON, detailing CRUD operations and database setup. It explains SQLite's features, installation steps, and how to view and manage databases in Android Studio. Additionally, it includes code examples for creating a database, inserting data, and performing update and delete operations using Kotlin.

Uploaded by

ridham26kamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit-5: Storing Android application data using

Database and JSON


[Any open-source database can be used. MySQL or SQLite
is preferable]

5.1 Setting up virtual server on local computer


5.3 CRUD operations (Create, Read, Update, Delete) using APP:
5.3.1 Create and insert data to the database
5.3.2 Read, Update and Delete data from database.
5.4 Accessing user’s current location
5.5

-(ACTION_IMAGE_CAPTURE Intent
of MediaStore class.)

❖ What is SQLite?
➢ SQLite is a C-Language library which implements a SQL
database engine.
➢SQLite is a database engine written in the C
programming language.
➢ It boasts that it is the most used database engine in the
world-as it is bundled in mobile and desktop software of all
kinds. Some of the key features of SQLite include:
● Stability: SQLite is resilient in the face of corrupt inputs,
including maliciously designed database files and SQL
strings.
● Cross-Platform Compatible: Databases can be copied
between 64 and 32 bit systems.
● Backwards Compatible: Backwards compatibility
constraints mean that SQLite is only able to store
values that are NULL, integers, floating-point numbers,
text, and BLOBs.
● Small Size: The entire library is less then 600Kb.
● Precompiled Binaries

Most programming languages have built-in support for SQLite,


including:C, C#, C++, Java, JavaScript, LiveCode, Lue,
Objective-C, Perl, PHP, Python, Ruby, Visual Basic and Xojo.

The SQLite source code is actively developed and the developers


plan to continue support until 2050.

❖ How to Install SQLite On Windows

Step 1: Download the SQLite ZIP File

You can download this file from the SQLite website given
below - https://www.sqlite.org/download.html.

Step 2: Unzip the file

Right click on the ZIP file and extract it to C:\SQLite


Step 3: Open SQLite

Double click the sqlite3 file to open the software:

The software will then open in the command line and you can
execute any sql commands:
● Here, you successfully installed Sqlite.
● Now,Download DB browser for sqlite from here
https://sqlitebrowser.org/dl/

DB browser for SQlite in picture given below:

❖ How to View and Locate SQLite Database in


Android Studio?
Step 1: Open android studio project which has SQLite
database connection
Step 2: Connect a device

Step 3: Search for Device File Explorer in android studio

Device file explorer can be found in the bottom-right


corner of the android studio screen. Click on Device file
explorer.
Step 4: Search application package name

To search your package name go to data > data>


package name. Click on package name.

Step 5: Download the database

Now, select database and download database whose


extension will be .sqlite, for that right-click on the
database name and save file at any desired location but
remember the location then click on ok in Save As
dialog box.
Step 6: Download SQLite browser

Now to view the database we required SQLite browser,


you can download SQLite browser from
https://sqlitebrowser.org/dl/. Download a suitable
SQLite browser for your device from the above link and
open it.

Step 7: Search saved database file

Click on the open database this will open a dialog box


choose a database file. Now go to that location where
you have saved the database previously and then select
the database file and click on open.

Step 8: View saved data in tables


To view data saved in the table click on Browse data,
now that’s it we have completed our today’s task

❖ Create Database And Insert Data in it


➢ Kotlin Android SQLite
SQLite is an open-source relational database that is used to
perform database operations on Android devices such as
storing, manipulating or retrieving persistent data from the
database.

By default SQLite database is embedded in android. So, there


is no need to perform any database setup or administration
task.

The SQLiteOpenHelper class provides the functionality to


use the SQLite database.

➢ SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used
for database creation and version management. For
performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.

➢ Constructors of SQLiteOpenHelper class


There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(context: Creates an object of

Context, name: String, factory: SQLiteOpenHelper for

SQLiteDatabase.CursorFactory, creating, opening and

version: Int) managing the database.

SQLiteOpenHelper(context: Creates an object of

Context, name: String, factory: SQLiteOpenHelper for

SQLiteDatabase.CursorFactory, creating, opening and


version: Int, errorHandler: managing the database.

DatabaseErrorHandler) It specifies the error

handler.

➢ Methods of SQLiteOpenHelper class


There are several methods available in the
SQLiteOpenHelper class. Some of them are mentioned
below:

Method Description

public abstract void Called only once when

onCreate(SQLiteDatabase db) the database is created

for the first time.

Public abstract void Called when the

onUpgrade(SQLiteDatabase db, database needs to

int oldVersion, int newVersion) upgrade.


public synchronized void close () Closes the database

object.

public void called when the

onDowngrade(SQLiteDatabase database needs to

db, int oldVersion, int downgrade.

newVersion)

➢ SQLiteDatabase class
It contains methods to be performed on the SQLite database
such as create, update, delete, select etc.

➢ Methods of SQLiteDatabase class


There are many methods in the SQLiteDatabase class. Some
of them are as follows:

Method Description
execSQL(String sql): Executes the SQL query, not a select

Unit query.

insert(String table, Inserts a record on the database.

String The table specifies the table name,

nullColumnHack, nullColumnHack doesn't allow

ContentValues completely null values. If the second

values): Long argument is null, android will store

null values if values are empty. The

third argument specifies the values

to be stored.

update(String table, Updates a row.

ContentValues

values, String

whereClause, String[]

whereArgs): Int
query(String table, Returns a cursor over the resultset.

String[] columns,

String selection,

String[]

selectionArgs, String

groupBy, String

having, String

orderBy): Cursor

Example: Create Database And Insert Data


in it

AndroidManifest.xml
<uses-permission
android:name="android.permission.READ_EXTERNAL_STOR
AGE" />

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

xmlns:android="http://schemas.android.com/apk/res/a
ndroid"

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"
android:orientation="vertical"
tools:context=".MainActivity">

<!-- Edit text to enter name -->


<EditText
android:id="@+id/enterName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:textSize="22sp"
android:layout_margin="20sp"/>

<!-- Edit text to enter age -->


<EditText
android:id="@+id/enterAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="22sp"
android:hint="Enter Age"/>

<!-- Button to add Name -->


<Button
android:id="@+id/addName"
android:layout_width="150sp"
android:layout_gravity="center"
android:text="Add Name"
android:textColor="#ffffff"
android:textSize="20sp"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"/>

<!-- Button to print Name -->


<Button
android:id="@+id/printName"
android:layout_width="150sp"
android:layout_gravity="center"
android:text="Print Name"
android:textColor="#ffffff"
android:textSize="20sp"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!-- Text view to get all name -->


<TextView
android:id="@+id/Name"
android:textAlignment="center"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text="Name\n\n"
android:textSize="22sp"
android:padding="10sp"
android:textColor="#000000"/>

<!-- Text view to get all ages -->


<TextView
android:layout_weight="1"
android:id="@+id/Age"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text="Age\n\n"
android:textSize="22sp"
android:padding="10sp"
android:textColor="#000000"/>

</LinearLayout>

</LinearLayout>

Mainactivity.kt
package com.example.crudsqlite

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import
androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import
com.example.crudsqlite.ui.theme.CrudsqliteTheme

class MainActivity : ComponentActivity() {


@SuppressLint("Range")
override fun onCreate(savedInstanceState:
Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout1)

val addName:Button =
findViewById(R.id.addName)
val printName:Button =
findViewById(R.id.printName)
val enterName:EditText =
findViewById(R.id.enterName)
val enterAge:EditText =
findViewById(R.id.enterAge)
// below code is to add on click
// listener to our add name button
addName.setOnClickListener{

// below we have created


// a new DBHelper class,
// and passed context to it
val db = DBhelper(this, null)

// creating variables for values


// in name and age edit texts
val name = enterName.text.toString()
val age = enterAge.text.toString()

// calling method to add


// name to our database
db.addName(name, age)

// Toast to message on the screen


Toast.makeText(this, name + " added to
database", Toast.LENGTH_LONG).show()

// at last, clearing edit texts


enterName.text.clear()
enterAge.text.clear()
}

// below code is to add on click


// listener to our print name button
printName.setOnClickListener{

// creating a DBHelper class


// and passing context to it
val db = DBhelper(this, null)

// below is the variable for cursor


// we have called method to get
// all names from our database
// and add to name text view
val cursor = db.getName()
// moving the cursor to first position
and
// appending value in the text view
cursor!!.moveToFirst()
val Name:TextView =
findViewById(R.id.Name)
val Age:TextView =
findViewById(R.id.Age)

Name.append(cursor.getString(cursor.getColumnIndex(
DBhelper.NAME_COl)) + "\n")

Age.append(cursor.getString(cursor.getColumnIndex(D
Bhelper.AGE_COL)) + "\n")

// moving our cursor to next


// position and appending values
while(cursor.moveToNext()){

Name.append(cursor.getString(cursor.getColumnIndex(
DBhelper.NAME_COl)) + "\n")

Age.append(cursor.getString(cursor.getColumnIndex(D
Bhelper.AGE_COL)) + "\n")
}

// at last we close our cursor


cursor.close()
}

}
}
MyDBhelper.kt
package com.example.crudsqlite

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

class DBhelper(context: Context, factory:


SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, "MYDB", factory,
DATABASE_VERSION) {

// below is the method for creating a database by a


sqlite query
override fun onCreate(db: SQLiteDatabase) {
// below is a sqlite query, where column names
// along with their data types is given
val query = ("CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, " +
NAME_COl + " TEXT," +
AGE_COL + " TEXT" + ")")

// we are calling sqlite


// method for executing our query
db.execSQL(query)
}

override fun onUpgrade(db: SQLiteDatabase, p1: Int,


p2: Int) {
// this method is to check if table already
exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}

// This method is for adding data in our database


fun addName(name: String, age: String) {

// below we are creating


// a content values variable
val values = ContentValues()

// we are inserting our values


// in the form of key-value pair
values.put(NAME_COl, name)
values.put(AGE_COL, age)

// here we are creating a


// writable variable of
// our database as we want to
// insert value in our database
val db = this.writableDatabase

// all values are inserted into database


db.insert(TABLE_NAME, null, values)

// at last we are
// closing our database
db.close()
}

// below method is to get


// all data from our database
fun getName(): Cursor? {

// here we are creating a readable


// variable of our database
// as we want to read value from it
val db = this.readableDatabase

// below code returns a cursor to


// read data from the database
return db.rawQuery("SELECT * FROM " +
TABLE_NAME, null)

companion object {
// here we have defined variables for our
database

// below is variable for database name


private val DATABASE_NAME = "MYDB"

// below is the variable for database version


private val DATABASE_VERSION = 1

// below is the variable for table name


val TABLE_NAME = "STUD"

// below is the variable for id column


val ID_COL = "id"

// below is the variable for name column


val NAME_COl = "name"

// below is the variable for age column


val AGE_COL = "age"
}
}
Output:-

❖ Update and Delete operation

DBhelper.kt
package com.example.crudsqlite

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

class DBhelper(context: Context, factory:


SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, "MYDB", factory,
DATABASE_VERSION) {

override fun onCreate(db: SQLiteDatabase) {


val query = ("CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, " +
NAME_COl + " TEXT," +
AGE_COL + " TEXT" + ")")
db.execSQL(query)
}

override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2:


Int) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
// This method is for adding data in our database
fun addName(name: String, age: String) {
val values = ContentValues()

values.put(NAME_COl, name)
values.put(AGE_COL, age)
val db = this.writableDatabase
db.insert(TABLE_NAME, null, values)
}
//View all records
fun getName(): Cursor? {
val db = this.readableDatabase
return db.rawQuery("SELECT * FROM " + TABLE_NAME,
null)
}
//Update
fun update_tbl(name: String, age: String) {
val db = this.writableDatabase
val values = ContentValues()
values.put(NAME_COl, name)
values.put(AGE_COL, age)
db.update(TABLE_NAME, values, "name=?",
arrayOf(name))
db.close() }
//Delete
fun delete_data(name:String,age: String) {
val db = this.writableDatabase
db.delete(TABLE_NAME,"name=?", arrayOf(name))
db.close()
}
//create object
companion object {
private val DATABASE_NAME = "MYDB"
private val DATABASE_VERSION = 1
val TABLE_NAME = "STUD"
val ID_COL = "id"
val NAME_COl = "name"
val AGE_COL = "age"
}
}

MainActivity.kt
package com.example.crudsqlite

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity

class MainActivity : ComponentActivity() {


@SuppressLint("Range")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout1)

val addName:Button = findViewById(R.id.addName)


val printName:Button = findViewById(R.id.printName)
val updateName:Button = findViewById(R.id.btn_update)
val deleteName:Button = findViewById(R.id.btndelete)
val enterName:EditText = findViewById(R.id.enterName)
val enterAge:EditText = findViewById(R.id.enterAge)
addName.setOnClickListener{
val db = DBhelper(this, null)
val name = enterName.text.toString()
val age = enterAge.text.toString()
db.addName(name,age)
enterName.text.clear()
enterAge.text.clear()}

printName.setOnClickListener{
val db = DBhelper(this, null)
val cursor = db.getName()
cursor!!.moveToFirst()
val Name:TextView = findViewById(R.id.Name)
val Age:TextView = findViewById(R.id.Age)
Name.append(cursor.getString(cursor.getColumnIndex
(DBhelper.NAME_COl)) + "\n")

Age.append(cursor.getString(cursor.getColumnIndex
(DBhelper.AGE_COL)) + "\n")

while(cursor.moveToNext()){
Name.append(cursor.getString(cursor.getColumnIndex
(DBhelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex
(DBhelper.AGE _COL)) + "\n") }}
updateName.setOnClickListener {
val myDb = DBhelper(this, null)
myDb.update_tbl(name =
enterName.text.toString(),age = enterAge.text.toString())
enterName.text.clear()
enterAge.text.clear()}
deleteName.setOnClickListener {
val mydb = DBhelper(this,null)
mydb.delete_data(name =
enterName.text.toString(), age = enterAge.text.toString())
enterName.text.clear()
enterAge.text.clear() }
}
}
layout1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

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"
android:orientation="vertical"
tools:context=".MainActivity">

<!-- Edit text to enter name -->


<EditText
android:id="@+id/enterName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:textSize="22sp"
android:layout_margin="20sp"/>

<!-- Edit text to enter age -->


<EditText
android:id="@+id/enterAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="22sp"
android:hint="Enter Age"/>

<!-- Button to add Name -->


<Button
android:id="@+id/addName"
android:layout_width="403dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20sp"
android:text="Add Name"
android:textColor="#ffffff"
android:textSize="20sp" />

<!-- Button to print Name -->


<Button
android:id="@+id/printName"
android:layout_width="403dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20sp"
android:text="Print Name"
android:textColor="#ffffff"
android:textSize="20sp" />

<Button
android:id="@+id/btn_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update" />

<Button
android:id="@+id/btndelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!-- Text view to get all name -->


<TextView
android:id="@+id/Name"
android:textAlignment="center"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text="Name\n\n"
android:textSize="22sp"
android:padding="10sp"
android:textColor="#000000"/>

<!-- Text view to get all ages -->


<TextView
android:layout_weight="1"
android:id="@+id/Age"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text="Age\n\n"
android:textSize="22sp"
android:padding="10sp"
android:textColor="#000000"/>

</LinearLayout>

</LinearLayout>

Output:-

You might also like