Exercise 8 - SQLite_Course
Exercise 8 - SQLite_Course
*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
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"
}
2
(" +
"$COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+
"$COLUMN_NAME TEXT, " +
"$COLUMN_DESCRIPTION TEXT)")
db.execSQL(createTableStatement)
}
// 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
}
// 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
}
// Delete course
val result = db.delete(TABLE_COURSES, "$COLUMN_ID = ?",
arrayOf(id.toString()))
db.close()
return result > 0 // Returns true if result > 0
}
}
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>
<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>
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>() {
init {
buttonUpdate.setOnClickListener {
6
val course = courses[adapterPosition]
onUpdateClick(course)
}
buttonDelete.setOnClickListener {
val courseId = courses[adapterPosition].id
onDeleteClick(courseId)
}
}
}
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" />
<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
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()
// 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()
}
*Lab 2:
- Create a database in sqlite, named “goods.db”
- Create a table, named “product”
Id ProductName Product Description ProductPrice
11
3 Headphone Kzz… 1000.000
12