0% found this document useful (0 votes)
5 views

Exercise 8 - SQLite_Course

The document outlines the steps to create an Android application using Kotlin for performing CRUD operations on a Course entity with SQLiteOpenHelper. It includes setting up the project, creating a data model, implementing a database helper class, designing the user interface, and handling user interactions. Additionally, it briefly describes a second lab focused on creating a 'goods.db' database and managing product data.

Uploaded by

chiendv.23ite
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)
5 views

Exercise 8 - SQLite_Course

The document outlines the steps to create an Android application using Kotlin for performing CRUD operations on a Course entity with SQLiteOpenHelper. It includes setting up the project, creating a data model, implementing a database helper class, designing the user interface, and handling user interactions. Additionally, it briefly describes a second lab focused on creating a 'goods.db' database and managing product data.

Uploaded by

chiendv.23ite
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/ 12

SQLITE

*Lab 1:
Creating a Android application for CRUD operations on a Course (Int id, String
name, and String description), using SQLiteOpenHelper.

Solution:
To create a Kotlin Android application that performs CRUD (Create, Read, Update, Delete)
operations on a Course entity using SQLiteOpenHelper, you'll follow these steps:
1. Set up your Android project.
2. Create a data model for the Course.
3. Implement the SQLite database helper class.
4. Create the user interface for performing CRUD operations.
5. Implement the logic to handle user interactions and database operations.
Step 1: Set up your Android project
- File > New > New project > Empty Views Activity > Click Next
1
- Enter Project name, location, language (kotlin), min SDK, Groovy DSL > Click
Finish
Step 2: Create a data model for the Course
Right click on Package folder > New > Kotlin Class > Data Class: Course

data class Course(


val id: Int,
val name: String,
val description: String
)

Step 3: Implement the SQLite database helper class


Right click on Package folder > New > Kotlin Class > Class: DatabaseHelper
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

// Class and Constructor


// Constructor: Create Database
class DatabaseHelper(context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION)
{

companion object {
private const val DATABASE_NAME = "courses.db"
private const val DATABASE_VERSION = 1
private const val TABLE_COURSES = "courses"
private const val COLUMN_ID = "id"
private const val COLUMN_NAME = "name"
private const val COLUMN_DESCRIPTION = "description"
}

override fun onCreate(db: SQLiteDatabase) {


// Create Table
val createTableStatement = ("CREATE TABLE $TABLE_COURSES

2
(" +
"$COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+
"$COLUMN_NAME TEXT, " +
"$COLUMN_DESCRIPTION TEXT)")
db.execSQL(createTableStatement)
}

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


newVersion: Int) {
//Drop Table
db.execSQL("DROP TABLE IF EXISTS $TABLE_COURSES")
onCreate(db)
}

fun addCourse(course: Course): Boolean {


val db = this.writableDatabase

// Get values
val contentValues = ContentValues().apply {
put(COLUMN_NAME, course.name)
put(COLUMN_DESCRIPTION, course.description)
}

// Insert
val result = db.insert(TABLE_COURSES, null,
contentValues)

db.close()
return result != -1L // Returns true if insert was
successful
}

@SuppressLint("Range")
fun getCourses(): List<Course> {
val courseList = mutableListOf<Course>()
val db = this.readableDatabase

// Read courses
val cursor: Cursor = db.rawQuery("SELECT * FROM
$TABLE_COURSES", null)

// Add to List
if (cursor.moveToFirst()) {
do {
val id =
cursor.getInt(cursor.getColumnIndex(COLUMN_ID))

3
val name =
cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
val description =
cursor.getString(cursor.getColumnIndex(COLUMN_DESCRIPTION))
courseList.add(Course(id, name, description))
} while (cursor.moveToNext())
}

cursor.close()
db.close()
return courseList
}

fun updateCourse(course: Course): Boolean {


val db = this.writableDatabase

// Get values
val contentValues = ContentValues().apply {
put(COLUMN_NAME, course.name)
put(COLUMN_DESCRIPTION, course.description)
}

// Update course
val result = db.update(TABLE_COURSES, contentValues,
"$COLUMN_ID = ?", arrayOf(course.id.toString()))

db.close()
return result > 0 // Returns true if result > 0
}

fun deleteCourse(id: Int): Boolean {


val db = this.writableDatabase

// Delete course
val result = db.delete(TABLE_COURSES, "$COLUMN_ID = ?",
arrayOf(id.toString()))

db.close()
return result > 0 // Returns true if result > 0
}
}

Step 4: Create a layout for RecyclerView Item


Right click on res/layout > New > Layout resources file > Name: item_course

4
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:padding="16dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/textViewCourseName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"/>

<TextView
android:id="@+id/textViewCourseDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginTop="4dp"
android:textColor="@android:color/darker_gray"/>
</LinearLayout>

<!-- Buttons Container -->


<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">

<Button
android:id="@+id/buttonUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"

5
android:textColor="@android:color/white" />

<Button
android:id="@+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="@android:color/white"
android:layout_marginStart="8dp" />
</LinearLayout>

</LinearLayout>

</androidx.cardview.widget.CardView>

Step 5: Create Adapter class for RecyclerView


Right click on Package folder > New > Kotlin Class > Class: CourseAdapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class CourseAdapter(
private val context: Context,
private var courses: List<Course>,
private val onUpdateClick: (Course) -> Unit,
private val onDeleteClick: (Int) -> Unit
) : RecyclerView.Adapter<CourseAdapter.CourseViewHolder>() {

inner class CourseViewHolder(itemView: View) :


RecyclerView.ViewHolder(itemView) {
val textViewName: TextView =
itemView.findViewById(R.id.textViewCourseName)
val textViewDescription: TextView =
itemView.findViewById(R.id.textViewCourseDescription)
val buttonUpdate: Button =
itemView.findViewById(R.id.buttonUpdate)
val buttonDelete: Button =
itemView.findViewById(R.id.buttonDelete)

init {
buttonUpdate.setOnClickListener {

6
val course = courses[adapterPosition]
onUpdateClick(course)
}

buttonDelete.setOnClickListener {
val courseId = courses[adapterPosition].id
onDeleteClick(courseId)
}
}
}

override fun onCreateViewHolder(parent: ViewGroup, viewType:


Int): CourseViewHolder {
val view =
LayoutInflater.from(context).inflate(R.layout.item_course,
parent, false)
return CourseViewHolder(view)
}

override fun onBindViewHolder(holder: CourseViewHolder,


position: Int) {
val course = courses[position]
holder.textViewName.text = course.name
holder.textViewDescription.text = course.description
}

override fun getItemCount() = courses.size

fun updateCourses(newCourses: List<Course>) {


courses = newCourses
notifyDataSetChanged()
}
}

Step 6: MainActivity:
- Activity_Main.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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

7
<EditText
android:id="@+id/editTextCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Course Name"
android:padding="12dp"
android:layout_marginTop="16dp" />

<EditText
android:id="@+id/editTextCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Course Description"
android:padding="12dp"
android:layout_marginTop="8dp" />

<Button
android:id="@+id/buttonAddCourse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Course"
android:layout_marginTop="16dp"
android:textColor="@android:color/white"
android:layout_gravity="center" />

<!-- RecyclerView wrapped in CardView for better aesthetics


-->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="4dp"
app:cardCornerRadius="8dp"
android:layout_marginTop="16dp">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewCourses"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp" />
</androidx.cardview.widget.CardView>

</LinearLayout>
- MainActivity.kt
import android.os.Bundle
import android.view.View

8
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

private lateinit var databaseHelper: DatabaseHelper


private lateinit var editTextCourseName: EditText
private lateinit var editTextCourseDescription: EditText
private lateinit var buttonAddCourse: Button
private lateinit var recyclerViewCourses: RecyclerView
private lateinit var courseAdapter: CourseAdapter
private var courses: MutableList<Course> = mutableListOf()
private var selectedCourseId: Int? = null

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)

ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.mai
n)) { v, insets ->
val systemBars =
insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top,
systemBars.right, systemBars.bottom)
insets
}

// DatabaseHelper
databaseHelper = DatabaseHelper(this)

// Views
editTextCourseName =
findViewById(R.id.editTextCourseName)
editTextCourseDescription =
findViewById(R.id.editTextCourseDescription)
buttonAddCourse = findViewById(R.id.buttonAddCourse)
recyclerViewCourses =
findViewById(R.id.recyclerViewCourses)

// RecyclerView

9
recyclerViewCourses.layoutManager =
LinearLayoutManager(this)
courseAdapter = CourseAdapter(this, courses, { course -
> updateCourse(course) }, { id -> deleteCourse(id) })
recyclerViewCourses.adapter = courseAdapter

// Add Course
buttonAddCourse.setOnClickListener {
addOrUpdateCourse() }
loadCourses()
}

// Add or Update
private fun addOrUpdateCourse() {
val name = editTextCourseName.text.toString()
val description =
editTextCourseDescription.text.toString()

if (name.isNotEmpty() && description.isNotEmpty()) {


// id == null > Add
if (selectedCourseId == null) {
// Add new course
val course = Course(0, name, description) // ID
will be auto-incremented
if (databaseHelper.addCourse(course)) {
loadCourses()
clearInputFields()
}
} else {
// id != null > Update existing course
val course = Course(selectedCourseId!!, name,
description)
if (databaseHelper.updateCourse(course)) {
loadCourses() // Refresh the list after
update
clearInputFields()
selectedCourseId = null
buttonAddCourse.text = "Add Course" //
Reset button text
buttonAddCourse.visibility = View.VISIBLE
// Show the button again
}
}
}
}

// Update data

10
private fun loadCourses() {
courses.clear()
courses.addAll(databaseHelper.getCourses())
courseAdapter.updateCourses(courses)
}

// Clear views
private fun clearInputFields() {
editTextCourseName.text.clear()
editTextCourseDescription.text.clear()
}

// Click buton Update


private fun updateCourse(course: Course) {
editTextCourseName.setText(course.name)
editTextCourseDescription.setText(course.description)
selectedCourseId = course.id

buttonAddCourse.text = "Update Course" // Change button


text to indicate updating
buttonAddCourse.visibility = View.VISIBLE // Show the
button during editing
}

// Click buton Delete


private fun deleteCourse(id: Int) {
if (databaseHelper.deleteCourse(id)) {
loadCourses()
}
}
}

*Lab 2:
- Create a database in sqlite, named “goods.db”
- Create a table, named “product”
Id ProductName Product Description ProductPrice

1 Laptop Abc… 20.000.000

2 Smartphone Xyz… 15.000.00

11
3 Headphone Kzz… 1000.000

- MainActivity: Load data into the recyclerview


- AddNewActivity: Insert data
- UpdateActivity: Update/Delete data

12

You might also like