0% found this document useful (0 votes)
31 views6 pages

Share Data Through Globalcontext

The document describes how to share data between classes using a global context in Kotlin. It creates a global context class with a shared variable, initializes the variable in one class, and retrieves the variable in another class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views6 pages

Share Data Through Globalcontext

The document describes how to share data between classes using a global context in Kotlin. It creates a global context class with a shared variable, initializes the variable in one class, and retrieves the variable in another class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Share Data through Global Context

1. Create class named globalcontext & create variable


2. Initialize variable in class(where we get data)
3. Call variabale in class(where we show data)

1. Create class named globalcontext & create variable

package com.example.stepcounter

import android.app.Application

class GlobalContext : Application() {


companion object {
lateinit var gender: String // A variable to hold the selected gender
}
}

2. Initialize variable in class(where we get data)


Main addition in this class is
GlobalContext.gender = selectedLayout!!
overallcode
package com.example.stepcounter.Activities

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.example.stepcounter.GlobalContext
import com.example.stepcounter.R
import
com.example.stepcounter.databinding.ActivityGenderSelectionScreenBinding
import com.example.stepcounter.mvvm.PersonRepository
import com.example.stepcounter.mvvm.PersonViewModel
import com.example.stepcounter.mvvm.PersonViewModelFactory
import com.example.stepcounter.mvvm.room.Person
import com.example.stepcounter.mvvm.room.PersonDatabase
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class GenderSelectionScreen : AppCompatActivity() {

private lateinit var binding: ActivityGenderSelectionScreenBinding


private var selectedLayout: String? = null

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
binding =
ActivityGenderSelectionScreenBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// Initialize the ViewModel
// val personDao = PersonDatabase.getDatabase(this).personDao()
// val repo = PersonRepository(personDao)
// val personViewModel =
ViewModelProvider(this,PersonViewModelFactory(repo)).get(PersonViewModel::c
lass.java)

binding.btnnextGSS.setOnClickListener {
if (selectedLayout != null) {
GlobalContext.gender = selectedLayout!!

// Navigate to the next activity or screen here


val intent = Intent(this, DataCollectorScreen::class.java)
// var selectedgender = selectedLayout.toString()
//intent.putExtra("selgender", selectedLayout)
startActivity(intent)
// saveGendersData()
}
}

// Set click listeners for the male and female layouts


binding.malelinearlayout.setOnClickListener {
selectGenderLayout("male")
}

binding.femalelinearlayout.setOnClickListener {
selectGenderLayout("female")
}
}

private fun selectGenderLayout(layoutName: String) {


if (layoutName != selectedLayout) {
// Unselect the previously selected layout
selectedLayout?.let {
if (it == "male") {
binding.malelinearlayout.backgroundTintList = null //
Reset background tint
binding.male.setTextColor(Color.BLACK) // Reset text
color
} else if (it == "female") {
binding.femalelinearlayout.backgroundTintList = null //
Reset background tint
binding.female.setTextColor(Color.BLACK) // Reset text
color
}
}

// Select the newly clicked layout


selectedLayout = layoutName
if (layoutName == "male") {
binding.malelinearlayout.backgroundTintList =
resources.getColorStateList(R.color.appblue)
binding.male.setTextColor(ContextCompat.getColor(this,
R.color.white))
} else if (layoutName == "female") {
binding.femalelinearlayout.backgroundTintList =
resources.getColorStateList(R.color.appblue)
binding.female.setTextColor(ContextCompat.getColor(this,
R.color.white))
}
}
}

private fun saveGendersData() {


val preferences =
applicationContext.getSharedPreferences("myPrefs", MODE_PRIVATE)
val editor = preferences.edit()
editor.putBoolean("isGenderData", true)
editor.apply()
}

3. Call variabale in class(where we show data)


Main addition in class is
val getgender = GlobalContext.gender // Retrieve the selected gender

overall code

package com.example.stepcounter.Activities
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.example.stepcounter.GlobalContext
import com.example.stepcounter.databinding.ActivityDataCollectorScreenBinding
import com.example.stepcounter.mvvm.PersonRepository
import com.example.stepcounter.mvvm.PersonViewModel
import com.example.stepcounter.mvvm.PersonViewModelFactory
import com.example.stepcounter.mvvm.room.Person
import com.example.stepcounter.mvvm.room.PersonDatabase
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Calendar

class DataCollectorScreen : AppCompatActivity() {


private lateinit var binding: ActivityDataCollectorScreenBinding

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
binding = ActivityDataCollectorScreenBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)

// Create an InputMethodManager

// Create an InputMethodManager
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
val eddob = findViewById<EditText>(com.example.stepcounter.R.id.eddob)
val height =
findViewById<EditText>(com.example.stepcounter.R.id.edheight)
val weight =
findViewById<EditText>(com.example.stepcounter.R.id.edweight)

DateInputMask(eddob);

// Initialize the ViewModel


val personDao = PersonDatabase.getDatabase(this).personDao()
val repo = PersonRepository(personDao)
val personViewModel = ViewModelProvider(this,
PersonViewModelFactory(repo)).get(
PersonViewModel::class.java
)

val getgender = GlobalContext.gender // Retrieve the selected gender

// val getgender = intent.getStringExtra("selgender")


val name = binding.edname.text
binding.btnnextDCS.setOnClickListener {
if (name.isEmpty() || height.text.isEmpty() ||
weight.text.isEmpty() || eddob.text.isEmpty()) {
// Check if any field is missing and display a toast message
Toast.makeText(this, "Please fill in all fields",
Toast.LENGTH_SHORT).show()
} else {
val selectedPerson = Person(
0L,
getgender!!,
name.toString(),
height.text.toString().toFloat(),
weight.text.toString().toFloat(),
eddob.text.toString()
)
GlobalScope.launch {
personViewModel.insertPerson(selectedPerson)
}

//val agedif=calculateAge()
//val age = calculateAge(eddob.text.toString())
// selectedPerson.dob = age.toString() // Add an age property
to your Person data class
// selectedPerson.dob = "Age"

val intent = Intent(this, HomeScreen::class.java)


startActivity(intent)
saveData()
}
}
}
fun saveData() {
val preferences = applicationContext.getSharedPreferences("myPrefs",
MODE_PRIVATE)
val editor = preferences.edit()
editor.putBoolean("isSaveData", true)
editor.apply()
}

class DateInputMask(private val input: EditText) : TextWatcher {


private var current = ""
private val ddmmyyyy = "DDMMYYYY"
private val cal = Calendar.getInstance()

init {
input.addTextChangedListener(this)
}

override fun beforeTextChanged(s: CharSequence, start: Int, count:


Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int,
count: Int) {
if (s.toString() == current) {
return
}
var clean = s.toString().replace("[^\\d.]|\\.".toRegex(), "")
val cleanC = current.replace("[^\\d.]|\\.".toRegex(), "")
val cl = clean.length
var sel = cl
var i = 2
while (i <= cl && i < 6) {
sel++
i += 2
}
//Fix for pressing delete next to a forward slash
if (clean == cleanC) sel--
if (clean.length < 8) {
clean = clean + ddmmyyyy.substring(clean.length)
} else {
//This part makes sure that when we finish entering numbers
//the date is correct, fixing it otherwise
var day = clean.substring(0, 2).toInt()
var mon = clean.substring(2, 4).toInt()
var year = clean.substring(4, 8).toInt()
mon = if (mon < 1) 1 else if (mon > 12) 12 else mon
cal[Calendar.MONTH] = mon - 1
year = if (year < 1900) 1900 else if (year > 2100) 2100 else
year
cal[Calendar.YEAR] = year
// ^ first set year for the line below to work correctly
//with leap years - otherwise, date e.g. 29/02/2012
//would be automatically corrected to 28/02/2012
day =
if (day > cal.getActualMaximum(Calendar.DATE))
cal.getActualMaximum(Calendar.DATE) else day
clean = String.format("%02d%02d%02d", day, mon, year)
}
clean = String.format(
"%s/%s/%s", clean.substring(0, 2),
clean.substring(2, 4),
clean.substring(4, 8)
)
sel = if (sel < 0) 0 else sel
current = clean
input.setText(current)
input.setSelection(if (sel < current.length) sel else
current.length)
}

override fun afterTextChanged(s: Editable) {

}
}
}

You might also like