You are on page 1of 6

Share Data through intent (from one activity

through other activity)

1. Gender Selection Screen(where we send data)

2. Data Collector Screen(where we receive data)

1. Gender Selection Screen(where we send data)


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.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::cl
ass.java)

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

// val selectedGender = Person(0L, selectedLayout!!)


// GlobalScope.launch {
// personViewModel.insertPerson(selectedGender)
// }

// 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()
}

2. Data Collector Screen(where we receive data)


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.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 = 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