0% found this document useful (0 votes)
19 views

Week 2 Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Week 2 Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

WEEK-2

1. Discuss about life cycle of activity in student Registra-

tion process
Ans:
The lifecycle of an activity in the student registration process can be di-
vided into several stages. Here's a discussion on the typical lifecycle stages
of an activity in the student registration process:

1. OnCreate: This is the first callback method called after the activity is
created. Here, the activity initializes the user interface, sets up listen-
ers, and performs any initializations required for the registration
process.

2. OnStart: This method is called when the activity becomes visible to


the user. It prepares the activity to interact with the user by setting up
UI components and resuming any operations that were paused.

3. OnResume: This method is called when the activity is about to start


interacting with the user. It ensures that the activity is in the fore-
ground and ready to receive user input. Here, any necessary data re-
trieval or refreshing of the registration process can take place.

4. OnPause: This method is called when the activity loses focus but re-
mains visible to the user. It allows the activity to pause ongoing opera-
tions, release resources, and save any necessary data.

5. OnStop: This method is called when the activity is no longer visible


to the user. It typically releases resources and performs cleanup tasks,
preparing for the activity to be either destroyed or restarted.

6. OnDestroy: This method is called when the activity is being de-


stroyed. It releases any resources that were allocated for the registra-
tion process and performs final cleanup.

7. Recreation/Restart: If needed, the activity can be recreated or


restarted during the registration process, for example, if the user ro-
tates the device. In such cases, the lifecycle stages mentioned above
are repeated.

It's important to note that the specific implementation and flow of the ac-
tivity lifecycle may vary depending on the programming framework or
platform being used, such as Android, web-based registration systems, or
desktop applications.

2. Create an android application for course registration


using multiple activities.
Ans: Created an android application for course registration, storing the
data in local mobile device db using SQLLite and showing enrolled stu-
dents in a recyclerview involving different activites. The entire code is
written in kotlin.

The following procedure steps are given below.

Step-1 : We are going to need a SplashActivity, RegisteredList page for


showing registered students and RegisterActivity page for registering the
course.

Step-2 : Once class files are created, we then create their respective xml
files for UI design activity_main.xml, activity_registration_list.xml and ac-
tivity_register.xml

Step-3 : activity_registration_list.xml will contain a textView for titlebar,


a recyclerview for showing the list and a button which will navigate to the
RegisterActivity page.
Step-4 : In activity_register.xml, there will be only a TextView (Name)
and an AutoCompleteTextView field (Course).

Step-5 : In activity_main.xml, only one TextView will be placed in center


which shows the App Name since its a splash page.

Step-6 : 3000 millisecond delay will be there in SplashActivity once its


over it will be navigated to RegisteredList automatically.

Step-7 : In RegisteredList, implement the click listener for register button


and navigate it to RegisterActivity using Intent class and StartActivity
function.

Step-8 : Create a custom adapter for RecyclerView called Recycler-


Adapter and inflate the activity_list_row (custom layout) which we created
for the item in the list. The item row layout contains 3 TextViews and a
button (Id, Name, Course and a delete button). Set the custom adapter to
Recyclerview in RegisteredList class.

Step-9 : Created a Data model bean class called ListItemModel which


contains name, course and id.

Step-10 : Create a class called DBHandler which extends SQLLiteOpen-


Helper class and override the methods to perform CRUD operations in lo-
cal DB.

Step-11 : Create a method called register having name and course as argu-
ments for inserting values in db and returns boolean flag based on the sta-
tus of the operation.

Step-12 : Create a method called getData to fetch records from db which


returns a cursor object and create a deleteRecord method having id as ar-
gument for deleting a specific record.

Step-13 : Create a dbHandler class object in RegisteredList class. Using


that object we call the getData method and populate the data in recy-
clerview. Call the deleteRecord method to delete that specific record based
on click of delete button in recycler adapter class.
Step-14 : Create a dbHandler class object in RegisterActivity class. Using
that object we call the register method on click of submit button. Get the
name from the edit text and create an array with static data to populate in
AutoCompleteTextView dropdown.

SplashActivity.kt
package com.example.courseregapp

import android.content.Intent

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.os.Handler

import android.os.Looper

class SplashActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

Handler(Looper.getMainLooper()).postDelayed({

startActivity(Intent(this, RegisteredList::class.java))

}, 3000)

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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"

tools:context=".SplashActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Course Registration Application"

android:textAppearance="@style/TextAppearance.Material3.HeadlineLarge"

android:textStyle="bold"

android:gravity="center"

android:elegantTextHeight="true"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

DBHandler.kt
package com.example.courseregapp

import android.content.ContentValues

import android.content.Context

import android.database.Cursor

import android.database.sqlite.SQLiteDatabase

import android.database.sqlite.SQLiteOpenHelper
class DBHandler(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) {

val query = ("CREATE TABLE " + TABLE_NAME + " ("

+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

NAME_COl + " TEXT," +

COURSE_COL + " TEXT" + ")")

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 register(name: String, course: String ): Boolean {

val values = ContentValues()

values.put(NAME_COl, name)

values.put(COURSE_COL, course)

val db = this.writableDatabase
val value = db.insert(TABLE_NAME, null, values).toInt()

db.close()

return value != -1

// below method is to get

// all data from our database

fun getData(): Cursor? {

val db = this.readableDatabase

return db.rawQuery("SELECT * FROM $TABLE_NAME", null)

fun deleteRecord(id: Int): Boolean {

val db = this.writableDatabase

val status = db.delete(TABLE_NAME, "$ID_COL=?", arrayOf(id.toString()))

db.close()

return status != 0

companion object{

private const val DATABASE_NAME = "COURSE_ENROLLMENT"

private const val DATABASE_VERSION = 1

const val TABLE_NAME = "StudentEnrollment"

const val ID_COL = "id"

const val NAME_COl = "name"

const val COURSE_COL = "course"

}
}

ListItemModel.kt
package com.example.courseregapp

data class ListItemModel(var id: Int, var name: String, var course: String)

RegisteredList.kt
package com.example.courseregapp

import android.content.Intent

import android.os.Bundle

import android.util.Log

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

import androidx.recyclerview.widget.LinearLayoutManager

import com.example.courseregapp.databinding.ActivityRegistrationListBinding

class RegisteredList : AppCompatActivity(), RecyclerAdapter.RowClickListener {

private lateinit var mBinding: ActivityRegistrationListBinding

private val dbHandler: DBHandler by lazy { DBHandler(this,null) }

private var list = ArrayList<ListItemModel>()

private lateinit var adapter: RecyclerAdapter


override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

mBinding = ActivityRegistrationListBinding.inflate(layoutInflater)

setContentView(mBinding.root)

initViews()

private fun initViews() {

mBinding.apply {

rvView.layoutManager = LinearLayoutManager(this@RegisteredList)

btnRegister.setOnClickListener {

startActivity(Intent(this@RegisteredList, RegisterActivity::class.java))

private fun populateView() {

val cursor = dbHandler.getData()

cursor?.let {

if (list.isNotEmpty())

list.clear()

while(it.moveToNext()) {

list += ListItemModel(it.getInt(0), it.getString(1), it.getString(2))

override fun onResume() {


super.onResume()

Log.e("LIST COUNT BEFORE ==== ", " ${list.size}")

populateView()

adapter = RecyclerAdapter(list, this)

mBinding.rvView.adapter = adapter

Log.e("LIST COUNT AFTER ==== ", " ${list.size}")

override fun onItemClickListener(id: Int, pos: Int) {

if (dbHandler.deleteRecord(id)) {

Toast.makeText(this, "Deletion Successful", Toast.LENGTH_SHORT).show()

if (list.isNotEmpty()) {

list.removeAt(pos)

adapter?.notifyItemRemoved(pos)

adapter?.notifyItemRangeChanged(pos, list.size)

mBinding.rvView.adapter = adapter

} else {

Toast.makeText(this, "Deletion Failed", Toast.LENGTH_SHORT).show()

activity_registration_list.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/rlt_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".RegisteredList">

<TextView

android:id="@+id/tv_view"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="16dp"

android:textAppearance="@style/TextAppearance.Material3.HeadlineLarge"

android:textStyle="bold"

android:text="Enrolled Students"

android:textColor="@color/white"

android:elevation="10dp"

android:background="@color/dark_blue"/>

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/rv_view"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@+id/tv_view"

android:layout_above="@+id/btn_register"

android:background="@color/gray"

android:scrollbars="vertical"

android:overScrollMode="always"

tools:listitem="@layout/activity_list_row"

tools:itemCount="2"/>
<Button

android:id="@+id/btn_register"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_margin="5dp"

android:padding="16dp"

android:text="Register"/>

</RelativeLayout>

RecyclerAdapter.kt
package com.example.courseregapp

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 RecyclerAdapter(private var mList: List<ListItemModel>, private val listener: RowClickLis-


tener): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {

class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {

val tvName: TextView = itemView.findViewById(R.id.tv_name)

val tvCourse: TextView = itemView.findViewById(R.id.tv_course)


val tvId: TextView = itemView.findViewById(R.id.tv_id)

val btnDelete: Button = itemView.findViewById(R.id.btn_delete)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

val view = LayoutInflater.from(parent.context)

.inflate(R.layout.activity_list_row, parent, false)

return ViewHolder(view)

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

holder.let {

it.tvId.text = mList[position].id.toString() ?: "000"

it.tvName.text = mList[position].name

it.tvCourse.text = mList[position].course

it.btnDelete.setOnClickListener {

listener.onItemClickListener(mList[position].id, position)

override fun getItemCount(): Int = mList.size

interface RowClickListener {

fun onItemClickListener(id: Int, pos: Int)

}
activity_list_row.xml
<?xml version="1.0" encoding="utf-8"?>

<androidx.cardview.widget.CardView

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

app:cardElevation="6dp">

<RelativeLayout

android:id="@+id/rlt_sub_container"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<TextView

android:id="@+id/tv_id"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="20dp"

android:layout_centerVertical="true"

android:layout_alignParentStart="true"

android:textColor="@color/black"

android:text="001"

android:textSize="20sp"/>
<LinearLayout

android:id="@+id/llt_container"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_toEndOf="@id/tv_id"

android:layout_toStartOf="@id/btn_delete"

android:orientation="vertical">

<TextView

android:id="@+id/tv_name"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="10dp"

android:ellipsize="end"

android:maxLines="1"

android:text="ARUN SIVANANDAN"

android:textSize="20sp"

android:textStyle="bold" />

<TextView

android:id="@+id/tv_course"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="10dp"

android:layout_marginBottom="10dp"

android:ellipsize="end"

android:maxLines="2"
android:text="BCA"

android:textSize="20sp"

android:textStyle="bold" />

</LinearLayout>

<Button

android:id="@+id/btn_delete"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_alignParentTop="true"

android:layout_alignBottom="@id/llt_container"

android:layout_marginEnd="5dp"

android:text="Delete"

android:textColor="@color/white"

android:textStyle="bold"

android:backgroundTint="@color/red" />

</RelativeLayout>

</androidx.cardview.widget.CardView>

RegisterActivity.kt
package com.example.courseregapp

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.ArrayAdapter

import android.widget.Toast

import com.example.courseregapp.databinding.ActivityRegisterBinding
class RegisterActivity : AppCompatActivity() {

private var courseList = arrayOf<String>("B.E", "B.Sc", "M.E", "M.Sc", "B.A", "M.A",


"B.C.A", "M.C.A", "B.Tech", "M.Tech", "B.Com", "M.Com")

private lateinit var mBinding: ActivityRegisterBinding

private val dbHandler : DBHandler by lazy {

DBHandler(this, null)

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

mBinding = ActivityRegisterBinding.inflate(layoutInflater)

setContentView(mBinding.root)

initViews();

private fun initViews() {

mBinding.apply {

val adapter = ArrayAdapter<String>(this@RegisterActivity, android.R.lay-


out.simple_list_item_1, courseList)

acTv.threshold = 1;//start searching from 1 character

acTv.setAdapter(adapter)

btnSubmit.setOnClickListener {

if (dbHandler.register(edtName.text.toString(), acTv.text.toString())) {

Toast.makeText(this@RegisterActivity, "Insertion Successful",


Toast.LENGTH_SHORT).show()

finish()

} else {
Toast.makeText(this@RegisterActivity, "Insertion Failed. Try again!",
Toast.LENGTH_SHORT).show()

activity_register.xml
<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
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"

tools:context=".RegisterActivity">

<TextView

android:id="@+id/tv_view"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@color/dark_blue"

android:elevation="10dp"

android:padding="16dp"

android:text="Register Course"

android:textAppearance="@style/TextAppearance.Material3.HeadlineLarge"

android:textColor="@color/white"
android:textStyle="bold"

app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.textfield.TextInputLayout

android:id="@+id/textInputLayout"

style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

app:boxBackgroundMode="outline"

app:boxCornerRadiusBottomEnd="16dp"

app:boxCornerRadiusBottomStart="16dp"

app:boxCornerRadiusTopEnd="16dp"

app:boxCornerRadiusTopStart="16dp"

app:helperText="Please provide your name in Caps"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/tv_view">

<com.google.android.material.textfield.TextInputEditText

android:id="@+id/edt_name"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:textColor="@color/dark_blue"

android:textColorHint="@color/black" />

</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_dropdown"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

app:boxBackgroundMode="outline"

app:boxCornerRadiusBottomEnd="16dp"

app:boxCornerRadiusBottomStart="16dp"

app:boxCornerRadiusTopEnd="16dp"

app:boxCornerRadiusTopStart="16dp"

app:helperText="Search and select the course from the dropdown"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/textInputLayout"

style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense.Exposed-
DropdownMenu">

<com.google.android.material.textfield.MaterialAutoCompleteTextView

android:id="@+id/ac_tv"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:textSize="18sp"

android:textColor="@color/dark_blue"/>

</com.google.android.material.textfield.TextInputLayout>

<Button

android:id="@+id/btn_submit"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="30dp"
android:layout_marginStart="10dp"

android:layout_marginEnd="10dp"

android:padding="16dp"

android:text="Submit"

android:textSize="18sp"

android:textColor="@color/white"

android:backgroundTint="@color/dark_blue"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/til_dropdown" />

</ androidx.constraintlayout.widget.ConstraintLayout>

Out- put:
3. Create an android application for simple basic calcula-
tor.
Ans: A basic simple calculator android application has been created using
kotlin. Below mentioned are the class and layout files with output screen-
shots for reference.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools">

<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.CalcApp"

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>

<meta-data

android:name="android.app.lib_name"

android:value="" />

</activity>

</application>

</manifest>

activity_calculator.xml
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:tools="http://schemas.android.com/tools"

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

<variable

name="data"

type="com.example.calcapp.DataModel" />

<variable

name="activity"

type="com.example.calcapp.MainActivity" />

</data>

<androidx.constraintlayout.widget.ConstraintLayout

android:layout_width="match_parent"
android:layout_height="match_parent"

android:background="@color/black"

tools:context=".MainActivity">

<LinearLayout

android:id="@+id/frameLayout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

app:layout_constraintBottom_toTopOf="@id/tabLayout"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent">

<TextView

android:id="@+id/textview_calculate_1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:textAlignment="textEnd"

android:textSize="@dimen/text_size_normal"

android:text="@{data.calculateBefore}"

android:textColor="@android:color/darker_gray"

android:maxLines="1" />

<TextView

android:id="@+id/textview_calculate"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:textAlignment="textEnd"

android:textSize="@dimen/text_size_large"
android:text="@{data.calculate}"

android:textColor="@color/white"

android:maxLines="1"/>

</LinearLayout>

<TableLayout

android:id="@+id/tabLayout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@color/orange"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent">

<TableRow

android:id="@+id/tr_one"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="@dimen/margin"

android:weightSum="4">

<Button

android:id="@+id/button_clear"

android:onClick="@{activity.onClickAction}"

android:text="@string/clear"

android:textAllCaps="true"

style="@style/Btn_Left"/>

<ImageButton
android:id="@+id/button_backspace"

android:layout_width="@dimen/width"

android:layout_height="@dimen/height"

android:layout_weight="1"

android:layout_marginStart="@dimen/margin"

android:src="@drawable/ic_baseline_backspace_24"

android:onClick="@{activity.onClickAction}"

android:background="?attr/colorPrimary"

style="@style/Widget.AppCompat.Button"/>

<Button

android:id="@+id/button_percentage"

android:text="@string/percentage"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_divide"

android:text="@string/divide"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Right"/>

</TableRow>

<TableRow

android:id="@+id/tr_two"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="@dimen/margin"

android:weightSum="4">
<Button

android:id="@+id/button_seven"

android:text="@string/seven"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_eight"

android:text="@string/eight"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left" />

<Button

android:id="@+id/button_nine"

android:text="@string/nine"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_multiply"

android:text="@string/multiply"

android:textAllCaps="false"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Right"/>

</TableRow>

<TableRow

android:id="@+id/tr_three"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin"

android:weightSum="4">

<Button

android:id="@+id/button_four"

android:text="@string/four"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_five"

android:text="@string/five"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_six"

android:text="@string/six"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_subtract"

android:text="@string/subtract"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Right"/>

</TableRow>

<TableRow

android:id="@+id/tr_four"
android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="@dimen/margin"

android:gravity="center"

android:weightSum="4">

<Button

android:id="@+id/button_one"

android:text="@string/one"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_two"

android:text="@string/two"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_three"

android:text="@string/three"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Left"/>

<Button

android:id="@+id/button_add"

android:text="@string/add"

android:onClick="@{activity.onClickAction}"

style="@style/Btn_Right"/>

</TableRow>
<TableRow

android:id="@+id/tr_five"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="@dimen/margin"

android:weightSum="3">

<Button

android:id="@+id/button_dot"

android:layout_width="@dimen/width"

android:layout_height="@dimen/height"

android:layout_weight=".74"

android:layout_marginStart="@dimen/margin"

android:background="?attr/colorPrimary"

android:textColor="@color/white"

android:text="@string/dot"

android:textSize="@dimen/text_size_small"

android:onClick="@{activity.onClickAction}" />

<Button

android:id="@+id/button_zero"

android:layout_width="@dimen/width"

android:layout_height="@dimen/height"

android:layout_weight=".75"

android:layout_marginStart="@dimen/margin"

android:background="?attr/colorPrimary"

android:textColor="@color/white"

android:text="@string/zero"

android:textSize="@dimen/text_size_small"
android:onClick="@{activity.onClickAction}" />

<Button

android:id="@+id/button_equalTo"

android:layout_width="@dimen/width"

android:layout_height="@dimen/height"

android:layout_weight="1.51"

android:layout_marginStart="@dimen/margin"

android:layout_marginEnd="@dimen/margin"

android:background="?attr/colorPrimary"

android:textColor="@color/white"

android:text="@string/equalTo"

android:textSize="@dimen/text_size_small"

android:textAllCaps="false"

android:onClick="@{activity.onClickAction}" />

</TableRow>

</TableLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>

MainActivity.xml
package com.example.calcapp

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle
import android.view.View

import androidx.databinding.DataBindingUtil

import com.example.calcapp.databinding.ActivityCalculatorBinding

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityCalculatorBinding

private val dataModel: DataModel by lazy {

DataModel("", "")

private var isAdd = false

private var isSubtract = false

private var isDivide = false

private var isMultiply = false

private var isPercentage = false

private var isShowAnswer = false

private var valueOne: String = ""

private var valueTwo: String = ""

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

binding = DataBindingUtil.setContentView(this, R.layout.activity_calculator)

binding.apply {

activity = this@MainActivity

data = dataModel

// textviewCalculate.setHorizontallyScrolling(true)

// textviewCalculate.movementMethod = ScrollingMovementMethod()

}
onLongClickListenerAction()

fun onClickAction(view: View) {

when (view.id) {

R.id.button_clear -> {

clearData()

binding.data = dataModel

R.id.button_backspace -> {

if (dataModel.calculate.length > 1)

dataModel.calculate = dataModel.calculate.substring(0, dataModel.calculate.length - 1)

else

dataModel.calculate = ""

binding.data = dataModel

R.id.button_percentage -> concatData(getString(R.string.percentage))

R.id.button_divide -> concatData(getString(R.string.divide))

R.id.button_multiply -> concatData(getString(R.string.multiply))

R.id.button_add -> concatData(getString(R.string.add))

R.id.button_subtract -> concatData(getString(R.string.subtract))

R.id.button_dot -> concatData(getString(R.string.dot))

R.id.button_one -> concatData(1)

R.id.button_two -> concatData(2)

R.id.button_three -> concatData(3)

R.id.button_four -> concatData(4)

R.id.button_five -> concatData(5)

R.id.button_six -> concatData(6)

R.id.button_seven -> concatData(7)

R.id.button_eight -> concatData(8)


R.id.button_nine -> concatData(9)

R.id.button_zero -> concatData(0)

R.id.button_equalTo -> {

addValues()

if (isAdd)

dataModel.calculateBefore = "$valueOne+$valueTwo"

else if (isSubtract)

dataModel.calculateBefore = "$valueOne-$valueTwo"

else if (isDivide)

dataModel.calculateBefore = valueOne + getString(R.string.divide) + valueTwo

else if (isMultiply)

dataModel.calculateBefore = "$valueOne x $valueTwo"

dataCalculate()

binding.data = dataModel

private fun concatData (value: Any) {

dataModel.apply {

when (value) {

getString(R.string.add) -> {

if (isShowAnswer) {

calculateBefore = ""

valueOne = ""

valueTwo = ""

isShowAnswer = false

if ((calculate.length == 1 && calculate.substring(0) == "-") ||


(calculateBefore.isNotEmpty() && calculateBefore.substring(calculateBe-
fore.length-1) != "+"))

return

if (calculate.isNotEmpty()) {

// If calculate has a number then add + and assign to calculateBefore

isAdd = true

addValues()

calculateBefore = "$valueOne+$valueTwo"

calculate = ""

getString(R.string.subtract) -> {

// If calculate is empty and trying to add -

if (isShowAnswer) {

calculateBefore = ""

valueOne = ""

valueTwo = ""

isShowAnswer = false

if (calculate.isEmpty() && calculateBefore.isNotEmpty() && calculateBe-


fore.substring(calculateBefore.length-1) != "-") {

calculate = calculate.plus(value)

} else if (calculate.isEmpty() && calculateBefore.isEmpty()) {

calculate = calculate.plus(value)

} else if (calculate.isNotEmpty() && calculate.substring(calculate.length-1) != "-") {

// If calculate has a number then add - and assign to calculateBefore,

// provided the last character should not be -

isSubtract = true

addValues()

calculateBefore = "$valueOne-$valueTwo"
calculate = ""

getString(R.string.multiply) -> {

if (isShowAnswer) {

calculateBefore = ""

valueOne = ""

valueTwo = ""

isShowAnswer = false

if ((calculate.length == 1 && calculate.substring(0) == "-") ||

(calculateBefore.isNotEmpty() && calculateBefore.substring(calculateBe-


fore.length-1) != "x"))

return

if (calculate.isNotEmpty()) {

// If calculate has a number then add * and assign to calculateBefore

isMultiply = true

addValues()

calculateBefore = "$valueOne x $valueTwo"

calculate = ""

getString(R.string.divide) -> {

if (isShowAnswer) {

calculateBefore = ""

valueOne = ""

valueTwo = ""

isShowAnswer = false

if ((calculate.length == 1 && calculate.substring(0) == "-") ||


(calculateBefore.isNotEmpty() && calculateBefore.substring(calculateBe-
fore.length-1) != getString(R.string.divide)))

return

if (calculate.isNotEmpty()) {

// If calculate has a number then add / and assign to calculateBefore

isDivide = true

addValues()

calculateBefore = valueOne + getString(R.string.divide) + valueTwo

calculate = ""

getString(R.string.percentage) -> {

if (isShowAnswer) {

calculateBefore = ""

valueOne = ""

valueTwo = ""

isShowAnswer = false

if ((calculate.length == 1 && calculate.substring(0) == "-") ||

(calculateBefore.isNotEmpty() && calculateBefore.substring(calculateBe-


fore.length-1) != "%"))

return

if (calculate.isNotEmpty()) {

// If calculate has a number then add / and assign to calculateBefore

isPercentage = true

addValues()

calculateBefore = "$valueOne%$valueTwo"

calculate = ""

} else -> {
calculate = calculate.plus(value)

binding.data = this

private fun addValues () {

dataModel.apply {

if (calculate.isNotEmpty()) {

if (valueOne.isEmpty()) {

valueOne = calculate

} else {

valueTwo = calculate

private fun dataCalculate() {

dataModel.apply {

var total = 0.0

val numOne: Double

val numTwo: Double

if (valueOne.isNotEmpty() && valueTwo.isNotEmpty()) {

if (valueOne.substring(0) == "-" && valueTwo.substring(0) == "-" ) {

numOne = if (valueOne.length == 2) {

valueOne.substring(1).toDouble()

} else {

valueOne.substring(1, valueOne.length).toDouble()
}

numTwo = if (valueTwo.length == 2) {

valueTwo.substring(1).toDouble()

} else {

valueTwo.substring(1, valueTwo.length).toDouble()

if (isAdd) {

total = (-numOne + -numTwo)

} else if (isSubtract) {

total = (-numOne - -numTwo)

} else if (isMultiply) {

total = (-numOne * -numTwo)

} else if (isDivide) {

total = (-numOne / -numTwo)

} else if (isPercentage) {

total = ((-numOne / 100.0f) * -numTwo)

} else if (valueOne.isNotEmpty() && valueOne.substring(0) == "-" ) {

numOne = if (valueOne.length == 2) {

valueOne.substring(1).toDouble()

} else {

valueOne.substring(1, valueOne.length).toDouble()

numTwo = if (valueTwo.length > 1) {

valueTwo.substring(0, valueTwo.length).toDouble()

} else {

valueTwo.substring(0).toDouble()

if (isAdd) {

total = (-numOne + numTwo)


} else if (isSubtract) {

total = (-numOne - numTwo)

} else if (isMultiply) {

total = (-numOne * numTwo)

} else if (isDivide) {

total = (-numOne / numTwo)

} else if (isPercentage) {

total = ((-numOne / 100.0f) * numTwo)

} else if (valueTwo.isNotEmpty() && valueTwo.substring(0) == "-" ) {

numOne = if (valueOne.length > 1) {

valueOne.substring(0, valueOne.length).toDouble()

} else {

valueOne.substring(0).toDouble()

numTwo = if (valueTwo.length == 2) {

valueTwo.substring(1).toDouble()

} else {

valueTwo.substring(1, valueTwo.length).toDouble()

if (isAdd) {

total = (numOne + -numTwo)

} else if (isSubtract) {

total = (numOne - -numTwo)

} else if (isMultiply) {

total = (numOne * -numTwo)

} else if (isDivide) {

total = (numOne / -numTwo)

} else if (isPercentage) {

total = ((numOne / 100.0f) * -numTwo)


}

} else {

numOne = if (valueOne.length > 1)

valueOne.substring(0, valueOne.length).toDouble()

else

valueOne.substring(0).toDouble()

numTwo = if (valueTwo.length > 1)

valueTwo.substring(0, valueTwo.length).toDouble()

else

valueTwo.substring(0).toDouble()

if (isAdd) {

total = (numOne + numTwo)

} else if (isSubtract) {

total = (numOne - numTwo)

} else if (isMultiply) {

total = (numOne * numTwo)

} else if (isDivide) {

total = (numOne / numTwo)

} else if (isPercentage) {

total = ((numOne / 100.0f) * numTwo)

if (isAdd || isSubtract || isMultiply || isPercentage || isDivide) {

calculate = if (isDecimalDigit() || isDivide) {

if (isDivide && (numTwo == 0.0)) {

"Can't divide by 0"

} else {

total.toString()

} else {
total.toInt().toString()

isShowAnswer = true

isAdd = false

isSubtract = false

isMultiply = false

isDivide = false

isPercentage = false

binding.data = this

valueOne = ""

valueTwo = ""

private fun clearData () {

dataModel.apply {

calculateBefore = ""

calculate = ""

valueOne = ""

valueTwo = ""

private fun onLongClickListenerAction() {

binding.buttonBackspace.setOnLongClickListener {

clearData()
binding.data = dataModel

true

private fun isDecimalDigit() : Boolean = valueOne.contains(".") || valueTwo.contains(".")

Output :

You might also like