Skip to content

Instantly share code, notes, and snippets.

@anandrex5
Created July 13, 2022 18:04
Show Gist options
  • Save anandrex5/8339ec5f17b709d299e31b7fb1666521 to your computer and use it in GitHub Desktop.
Save anandrex5/8339ec5f17b709d299e31b7fb1666521 to your computer and use it in GitHub Desktop.
SQLite Implementation Kotlin
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mysql_lite">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MySQL_Lite"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.mysql_lite"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def multidex_version = "2.0.1"
implementation "androidx.multidex:multidex:$multidex_version"
}
package com.example.mysql_lite
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, DATABASE_NAME, 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 = "GEEKS_FOR_GEEKS"
// below is the variable for database version
private val DATABASE_VERSION = 1
// below is the variable for table name
val TABLE_NAME = "gfg_table"
// 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"
}
}
package com.example.mysql_lite
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
@SuppressLint("Range")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 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()
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.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(DBHelper.AGE_COL)) + "\n")
}
// at last we close our cursor
cursor.close()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment