Thu. Dec 26th, 2024

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:id="@+id/main">

<!-- EditText for Name -->
<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textSize="16sp"
android:padding="10dp" />

<!-- EditText for Location -->
<EditText
android:id="@+id/editLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Location"
android:inputType="text"
android:textSize="16sp"
android:padding="10dp" />

<!-- EditText for Designation -->
<EditText
android:id="@+id/editDesignation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Designation"
android:inputType="text"
android:textSize="16sp"
android:padding="10dp" />

<!-- Save Button -->
<Button
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"
android:textSize="18sp"
android:padding="12dp"
android:layout_marginTop="20dp"
android:background="@android:color/holo_blue_light" />

</LinearLayout>
</layout>

MainActivity.kt

package com.androindian.sqlite

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import com.androindian.sqlite.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
var binding: ActivityMainBinding?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding= DataBindingUtil.setContentView(this,R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

var dbhelper=DbHelper(this@MainActivity)

binding?.btnSave?.setOnClickListener{
var name=binding?.editName?.text?.toString()
var location=binding?.editLocation?.text.toString()
var designation=binding?.editDesignation?.text.toString()

dbhelper.insertUserDetails(name,location,designation)
Toast.makeText(this@MainActivity,"Saved Sucessfully",Toast.LENGTH_LONG).show()

var intent=Intent(this@MainActivity,DetailsActivity::class.java)
startActivity(intent)
}
}
}

Dbhelper.kt

package com.androindian.sqlite

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 DbHelper(context: Context?) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
val CREATE_TABLE = ("CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_LOC + " TEXT,"
+ KEY_DESG + " TEXT" + ")")
db.execSQL(CREATE_TABLE)
}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users)
// Create tables again
onCreate(db)
}

// **** CRUD (Create, Read, Update, Delete) Operations ***** //
// Adding new User Details
fun insertUserDetails(name: String?, location: String?, designation: String?) {
//Get the Data Repository in write mode
val db = this.writableDatabase
//Create a new map of values, where column names are the keys
val cValues = ContentValues()
cValues.put(KEY_NAME, name)
cValues.put(KEY_LOC, location)
cValues.put(KEY_DESG, designation)
// Insert the new row, returning the primary key value of the new row
val newRowId = db.insert(TABLE_Users, null, cValues)
db.close()
}

// Get User Details
@SuppressLint("Range")
fun GetUsers(): ArrayList<HashMap<String, String>> {
val db = this.writableDatabase
val userList = ArrayList<HashMap<String, String>>()
val query = "SELECT name, location, designation FROM " + TABLE_Users
val cursor = db.rawQuery(query, null)
while (cursor.moveToNext()) {
val user = HashMap<String, String>()
user["name"] = cursor.getString(cursor.getColumnIndex(KEY_NAME))
user["designation"] = cursor.getString(cursor.getColumnIndex(KEY_DESG))
user["location"] = cursor.getString(cursor.getColumnIndex(KEY_LOC))
userList.add(user)
}
return userList
}

// Get User Details based on userid
@SuppressLint("Range")
fun GetUserByUserId(userid: Int): ArrayList<HashMap<String, String>> {
val db = this.writableDatabase
val userList = ArrayList<HashMap<String, String>>()
val query = "SELECT name, location, designation FROM " + TABLE_Users
val cursor = db.query(
TABLE_Users,
arrayOf(KEY_NAME, KEY_LOC, KEY_DESG),
KEY_ID + "=?",
arrayOf(userid.toString()),
null,
null,
null,
null
)
if (cursor.moveToNext()) {
val user = HashMap<String, String>()
user["name"] = cursor.getString(cursor.getColumnIndex(KEY_NAME))
user["designation"] = cursor.getString(cursor.getColumnIndex(KEY_DESG))
user["location"] = cursor.getString(cursor.getColumnIndex(KEY_LOC))
userList.add(user)
}
return userList
}

// Delete User Details
fun DeleteUser(userid: Int) {
val db = this.writableDatabase
db.delete(TABLE_Users, KEY_ID + " = ?", arrayOf(userid.toString()))
db.close()
}

// Update User Details
fun UpdateUserDetails(
location: String?,
designation: String?,
id: Int
): Int {
val db = this.writableDatabase
val cVals = ContentValues()
cVals.put(KEY_LOC, location)
cVals.put(KEY_DESG, designation)
return db.update(TABLE_Users, cVals, "$KEY_ID = ?", arrayOf(id.toString()))
}

companion object {
private const val DB_VERSION = 1
private const val DB_NAME = "usersdb"
private const val TABLE_Users = "userdetails"
private const val KEY_ID = "id"
private const val KEY_NAME = "name"
private const val KEY_LOC = "location"
private const val KEY_DESG = "designation"
}
}

activity_data.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
<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"
tools:context=".DetailsActivity"
android:orientation="vertical">


<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/list"
android:layout_margin="10dp"/>

</LinearLayout>
</layout>

DeatilsActivity.kt

package com.androindian.sqlite

import android.os.Bundle
import android.widget.SimpleAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.ListAdapter
import com.androindian.sqlite.databinding.ActivityDetailsBinding

class DetailsActivity : AppCompatActivity() {
var binding:ActivityDetailsBinding?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding= DataBindingUtil.setContentView(this,R.layout.activity_details)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
var dbHelper=DbHelper(this@DetailsActivity)

var uselist=dbHelper.GetUsers()

val adapter: android.widget.ListAdapter = SimpleAdapter(
this@DetailsActivity,
uselist,
R.layout.custom,
arrayOf("name", "designation", "location"),
intArrayOf(R.id.name, R.id.designation, R.id.location))
binding?.list?.adapter=adapter
}
}

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/location"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/designation"
android:layout_margin="10dp"/>

</LinearLayout>

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *