Open In App

How to Read Data From SQLite Database in Android using Jetpack Compose?

Last Updated : 28 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android using Jetpack Compose. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in our ListView using Jetpack Compose.

What we are going to build in this article? 
We will be working on the existing application which we have built in our previous article. In that application, we are simply adding the course list part where we can get to see our list of courses. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Creating a Model class for storing our data. 

Navigate to app>java>your app’s package name> Right-click on it>New Kotlin class/file and specify its name as CourseModel and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




data class CourseModel(
    // on below line we are creating variables for name and job
    var courseName: String,
    var courseDuration: String,
    var courseTracks: String,
    var courseDescription: String
)


Step 3: Updating DBHandler class for performing read operation in SQLite database.

Navigate to app>java>your app’s package name>DBHandler.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
 
class DBHandler  // creating a constructor for our database handler.
    (context: Context?) :
    SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
    // below method is for creating a database by running a sqlite query
    override fun onCreate(db: SQLiteDatabase) {
        // on below line we are creating an sqlite query and we are
        // setting our column names along with their data types.
        val query = ("CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + NAME_COL + " TEXT,"
                + DURATION_COL + " TEXT,"
                + DESCRIPTION_COL + " TEXT,"
                + TRACKS_COL + " TEXT)")
 
        // at last we are calling a exec sql method to execute above sql query
        db.execSQL(query)
    }
 
    // this method is use to add new course to our sqlite database.
    fun addNewCourse(
        courseName: String?,
        courseDuration: String?,
        courseDescription: String?,
        courseTracks: String?
    ) {
        // on below line we are creating a variable for
        // our sqlite database and calling writable method
        // as we are writing data in our database.
        val db = this.writableDatabase
        // on below line we are creating a
        // variable for content values.
        val values = ContentValues()
        // on below line we are passing all values
        // along with its key and value pair.
        values.put(NAME_COL, courseName)
        values.put(DURATION_COL, courseDuration)
        values.put(DESCRIPTION_COL, courseDescription)
        values.put(TRACKS_COL, courseTracks)
        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values)
        // at last we are closing our
        // database after adding database.
        db.close()
    }
 
    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
        onCreate(db)
    }
 
    companion object {
        // creating a constant variables for our database.
        // below variable is for our database name.
        private const val DB_NAME = "coursedb"
 
        // below int is our database version
        private const val DB_VERSION = 1
 
        // below variable is for our table name.
        private const val TABLE_NAME = "mycourses"
 
        // below variable is for our id column.
        private const val ID_COL = "id"
 
        // below variable is for our course name column
        private const val NAME_COL = "name"
 
        // below variable id for our course duration column.
        private const val DURATION_COL = "duration"
 
        // below variable for our course description column.
        private const val DESCRIPTION_COL = "description"
 
        // below variable is for our course tracks column.
        private const val TRACKS_COL = "tracks"
    }
 
    // we have created a new method for reading all the courses.
    fun readCourses(): ArrayList<CourseModel>? {
        // on below line we are creating a database for reading our database.
        val db = this.readableDatabase
 
        // on below line we are creating a cursor with query to read data from database.
        val cursorCourses: Cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
 
        // on below line we are creating a new array list.
        val courseModelArrayList: ArrayList<CourseModel> = ArrayList()
 
        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModelArrayList.add(
                    CourseModel(
                        cursorCourses.getString(1),
                        cursorCourses.getString(4),
                        cursorCourses.getString(2),
                        cursorCourses.getString(3)
                    )
                )
            } while (cursorCourses.moveToNext())
            // moving our cursor to next.
        }
        // at last closing our cursor and returning our array list.
        cursorCourses.close()
        return courseModelArrayList
    }
}


Step 4: Create a new Compose Activity to display the list of courses. 

Navigate to app>java>your app’s package name>Right click on it>New>Compose and select Empty Compose Activity and name it as ViewCourses and add below code to it. Comments are added in the code to get to know in detail. 

Kotlin




import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
 
class ViewCourses : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on the below line we are specifying the theme as the scaffold.
                    Scaffold(
                        // in scaffold we are specifying the top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling our method to display UI
                        readDataFromDatabase(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
@Composable
fun readDataFromDatabase(context: Context) {
    // on below line we are creating and initializing our array list
    lateinit var courseList: List<CourseModel>
    courseList = ArrayList<CourseModel>()
 
    val dbHandler: DBHandler = DBHandler(context);
    courseList = dbHandler.readCourses()!!
 
    // on below line we are creating a lazy column for displaying a list view.
    LazyColumn {
        // on below line we are setting data for each item of our listview.
        itemsIndexed(courseList) { index, item ->
            // on below line we are creating a card for our list view item.
            Card(
                // on below line we are adding padding from our all sides.
                modifier = Modifier.padding(8.dp),
                // on below line we are adding elevation for the card.
                elevation = 6.dp
            ) {
                // on below line we are creating a row for our list view item.
                Column(
                    // for our row we are adding modifier to set padding from all sides.
                    modifier = Modifier.padding(8.dp).fillMaxWidth(),
                    horizontalAlignment = Alignment.Start,
                    verticalArrangement = Arrangement.Center
                ) {
                    // on the below line we are creating a text.
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our model class.
                        text = courseList[index].courseName,
 
                        // on below line we are adding padding
                        // for our text from all sides.
                        modifier = Modifier.padding(4.dp),
 
                        // on below line we are adding color for our text
                        color = Color.Black, textAlign = TextAlign.Center
                    )
                    // on below line inside row we are adding spacer
                    Spacer(modifier = Modifier.width(5.dp))
 
                    // on the below line we are creating a text.
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our model class.
                        text = "Course Tracks : " + courseList[index].courseTracks,
 
                        // on below line we are adding padding
                        // for our text from all sides.
                        modifier = Modifier.padding(4.dp),
 
                        // on below line we are adding color for our text
                        color = Color.Black, textAlign = TextAlign.Center
                    )
                    // on below line inside row we are adding spacer
                    Spacer(modifier = Modifier.width(5.dp))
 
                    // on the below line we are creating a text.
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our model class.
                        text = "Course Duration : " + courseList[index].courseDuration,
 
                        // on below line we are adding padding
                        // for our text from all sides.
                        modifier = Modifier.padding(4.dp),
 
                        // on below line we are adding color for our text
                        color = Color.Black, textAlign = TextAlign.Center
                    )
                    // on below line inside row we are adding spacer
                    Spacer(modifier = Modifier.width(5.dp))
 
                    // on the below line we are creating a text.
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our model class.
                        text = "Description : " + courseList[index].courseDescription,
 
                        // on below line we are adding padding
                        // for our text from all sides.
                        modifier = Modifier.padding(4.dp),
 
                        // on below line we are adding color for our text
                        color = Color.Black, textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}


Step 4 : Adding a new button for opening ViewCourses activity in our MainActivity.kt file. 

Navigate to MainActivity.kt file and add below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject
 
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat.startActivity
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
 
 
class MainActivity : ComponentActivity() {
 
 
    @RequiresApi(Build.VERSION_CODES.M)
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
 
                    // on the below line we are specifying the theme as the scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying the top bar.
                        topBar = {
 
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying title for our top bar.
                                title = {
 
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling our method to display UI
                        addDataToDatabase(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
// on below line we are creating battery status function.
@Composable
fun addDataToDatabase(
    context: Context
) {
 
    val activity = context as Activity
    // on below line creating a variable for battery status
    val courseName = remember {
        mutableStateOf(TextFieldValue())
    }
    val courseDuration = remember {
        mutableStateOf(TextFieldValue())
    }
    val courseTracks = remember {
        mutableStateOf(TextFieldValue())
    }
    val courseDescription = remember {
        mutableStateOf(TextFieldValue())
    }
 
 
    // on below line we are creating a column,
    Column(
        // on below line we are adding a modifier to it,
        modifier = Modifier
            .fillMaxSize()
            // on below line we are adding a padding.
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
 
        var dbHandler: DBHandler = DBHandler(context)
 
        // on below line we are adding a text for heading.
        Text(
            // on below line we are specifying text
            text = "SQlite Database in Android",
            // on below line we are specifying text color, font size and font weight
            color = greenColor, fontSize = 20.sp, fontWeight = FontWeight.Bold
        )
 
        // on below line adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a text field.
        TextField(
            // on below line we are specifying value for our email text field.
            value = courseName.value,
            // on below line we are adding on value change for text field.
            onValueChange = { courseName.value = it },
            // on below line we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your course name") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a text field.
        TextField(
            // on below line we are specifying value for our email text field.
            value = courseDuration.value,
            // on below line we are adding on value change for text field.
            onValueChange = { courseDuration.value = it },
            // on below line we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your course duration") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
 
 
        // on below line we are creating a text field.
        TextField(
            // on below line we are specifying value for our email text field.
            value = courseTracks.value,
            // on below line we are adding on value change for text field.
            onValueChange = { courseTracks.value = it },
            // on below line we are adding place holder as text
            placeholder = { Text(text = "Enter your course tracks") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a text field.
        TextField(
            // on below line we are specifying value for our email text field.
            value = courseDescription.value,
            // on below line we are adding on value change for text field.
            onValueChange = { courseDescription.value = it },
            // on below line we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your course description") },
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .fillMaxWidth(),
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // on below line we are adding single line to it.
            singleLine = true,
        )
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(15.dp))
 
        // on below line creating a button to check battery charging status
        Button(onClick = {
            dbHandler.addNewCourse(
                courseName.value.text,
                courseDuration.value.text,
                courseDescription.value.text,
                courseTracks.value.text
            )
            Toast.makeText(context, "Course Added to Database", Toast.LENGTH_SHORT).show()
        }) {
            // on below line adding a text for our button.
            Text(text = "Add Course to Database", color = Color.White)
        }
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(15.dp))
 
        // on below line creating a button to open view course activity
        Button(onClick = {
            val i = Intent(context, ViewCourses::class.java)
            context.startActivity(i)
        }) {
            // on below line adding a text for our button.
            Text(text = "Read Courses to Database", color = Color.White)
        }
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads