Sat. Jul 27th, 2024

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fstTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="Name" />
    <EditText
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:ems="10"/>
    <TextView
        android:id="@+id/secTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Location"
        android:layout_marginLeft="100dp" />
    <EditText
        android:id="@+id/txtLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:ems="10" />
    <TextView
        android:id="@+id/thirdTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Designation"
        android:layout_marginLeft="100dp" />
    <EditText
        android:id="@+id/txtDesignation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:ems="10" />
    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:text="Save" />
</LinearLayout>

MainActivity.kt

package com.androindian.sqlite

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    var name: EditText? = null
    var loc: EditText? = null
    var desig: EditText? = null
    var saveBtn: Button? = null
    var intent: Intent? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        name = findViewById(R.id.txtName)
        loc = findViewById(R.id.txtLocation)
        desig = findViewById(R.id.txtDesignation)
        saveBtn = findViewById(R.id.btnSave)
        saveBtn?.setOnClickListener(View.OnClickListener {
            val username = """
                ${name?.getText()}
                
                """.trimIndent()
            val location = loc?.getText().toString()
            val designation = desig?.getText().toString()
            val dbHandler = DbHandler(this@MainActivity)
            dbHandler.insertUserDetails(username, location, designation)
            intent = Intent(this@MainActivity, DetailsActivity::class.java)
            startActivity(intent)
            Toast.makeText(applicationContext, "Details Inserted Successfully", Toast.LENGTH_SHORT)
                .show()
        })
    }
}

Dbhelper.kt

package com.androindian.sqlite

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class DbHandler(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"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Data">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="data"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>

DeatilsActivity.kt

package com.androindian.sqlite

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity

class DetailsActivity : AppCompatActivity() {
    var intent: Intent? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
        val db = DbHandler(this)
        val userList = db.GetUsers()
        val lv = findViewById<View>(R.id.user_list) as ListView
        val adapter: ListAdapter = SimpleAdapter(
            this@DetailsActivity,
            userList,
            R.layout.list_row,
            arrayOf("name", "designation", "location"),
            intArrayOf(R.id.name, R.id.designation, R.id.location)
        )
        lv.adapter = adapter
        val back = findViewById<View>(R.id.btnBack) as Button
        back.setOnClickListener {
            intent = Intent(this@DetailsActivity, MainActivity::class.java)
            startActivity(intent)
        }
    }
}

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/designation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/designation"
        android:layout_alignBottom="@+id/designation"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>

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 *