0% found this document useful (0 votes)
29 views12 pages

RoomDatabase (MVVM)

The document describes setting up an MVVM architecture in Android using Room database to store and retrieve user profile data. It includes entities, DAO, database, repository, viewmodel and screens to collect and display data.
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)
29 views12 pages

RoomDatabase (MVVM)

The document describes setting up an MVVM architecture in Android using Room database to store and retrieve user profile data. It includes entities, DAO, database, repository, viewmodel and screens to collect and display data.
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/ 12

ROOM(MVVM)

1.PERSON(ENTITY)
2. PERSON DAO (dao)
3. PersonDATABASE(database)
4. PersonRepository(repository)
5. Person Viewmodel(viewmodel)
6. Person ViewModelFactory(ViewmodelFactory)
7. DataCollectorScreen(where we can get data)
8. HomeScreen(where we show data)

1.PERSON(ENTITY)
package com.example.stepcounter.mvvm.room

import androidx.room.Entity
import androidx.room.PrimaryKey

// Person.kt
//First, let's create a Person data class with an auto-generated primary key:
@Entity(tableName = "persons")
data class Person(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val gender: String,
val name: String,
val height: Float,
val weight: Float,
var dob: String,
//var age: Int = 0

)
2. PERSON DAO (dao)
package com.example.stepcounter.mvvm.room

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query

// PersonDao.kt
//second, create a PersonDao interface for Room database operations:
@Dao
interface PersonDao {
@Insert
fun insert(person: Person)

@Query("SELECT * FROM persons")


fun getAllPersons(): LiveData<List<Person>>

@Query("SELECT name FROM persons LIMIT 1")


fun getUserName(): String

@Query("SELECT gender FROM persons LIMIT 1")


fun getUserGender(): String

@Query("SELECT height FROM persons LIMIT 1")


fun getUserHeight(): Float

@Query("SELECT weight FROM persons LIMIT 1")


fun getUserWeight(): Float

// @Query("SELECT dob FROM persons LIMIT 1")


// fun getUserDob(): String
//}

@Query("SELECT dob FROM persons LIMIT 1")


fun getUserDob(): String
}

3. PersonDATABASE(database)
package com.example.stepcounter.mvvm.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

// PersonDatabase.kt
//Now, create a PersonDatabase for setting up the Room database:
@Database(entities = [Person::class], version = 1, exportSchema = false)
abstract class PersonDatabase : RoomDatabase() {
abstract fun personDao(): PersonDao

companion object {
@Volatile
private var INSTANCE: PersonDatabase? = null

fun getDatabase(context: Context): PersonDatabase {


return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
PersonDatabase::class.java,
"person_database"
).build()
INSTANCE = instance
instance
}
}
}
}

4. PersonRepository(repository)
package com.example.stepcounter.mvvm

import androidx.lifecycle.LiveData
import androidx.room.Query
import com.example.stepcounter.mvvm.room.Person
import com.example.stepcounter.mvvm.room.PersonDao

// PersonRepository.kt
//Now, create a PersonRepository to manage data operations:
class PersonRepository(private val personDao: PersonDao) {
suspend fun insertPerson(person: Person) {
personDao.insert(person)
}

val allPersons: LiveData<List<Person>> = personDao.getAllPersons()


fun getUserName(): String {
return personDao.getUserName() // Implement this function in your
PersonDao
}
fun getUserGender(): String {
return personDao.getUserGender() // Implement this function in your
PersonDao
}
fun getUserHeight(): Float {
return personDao.getUserHeight() // Implement this function in your
PersonDao
}
fun getUserWeight(): Float {
return personDao.getUserWeight() // Implement this function in your
PersonDao
}

fun getUserDob(): String {


return personDao.getUserDob() // Implement this function in your
PersonDao
}
// fun getUserDob(): Int {
// return personDao.getUserDob() // Implement this function in your
PersonDao
// }

5. Person Viewmodel(viewmodel)
package com.example.stepcounter.mvvm

import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.stepcounter.mvvm.room.Person
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import javax.inject.Inject

// PersonViewModel.kt
//Create a PersonViewModel to manage data in your UI:

class PersonViewModel ( val repository: PersonRepository) : ViewModel() {


fun insertPerson(person: Person) {
GlobalScope.launch {
repository.insertPerson(person)
}

}
suspend fun getUserName(): String {
// Assuming you have a function in your repository to get the user's
name
return repository.getUserName()
}

suspend fun getUserGender(): String {


// Assuming you have a function in your repository to get the
user's gender
return repository.getUserGender()
}

suspend fun getUserHeight(): Float {


// Assuming you have a function in your repository to get the user's
gender
return repository.getUserHeight()
}
suspend fun getUserWeight(): Float {
// Assuming you have a function in your repository to get the user's
gender
return repository.getUserWeight()
}

suspend fun getUserDob(): String {


// Assuming you have a function in your repository to get the user's
gender
return repository.getUserDob()
}

// suspend fun getUserDob(): Int {


// // Assuming you have a function in your repository to get the user's
gender
// return repository.getUserDob()
// }

6. Person ViewModelFactory(ViewmodelFactory)
package com.example.stepcounter.mvvm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class PersonViewModelFactory(private val repository: PersonRepository) :


ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PersonViewModel(repository) as T
}
}

7. DataCollectorScreen(where we can get 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) {

}
}
}

8. HomeScreen(where we show data)

package com.example.stepcounter.Activities

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.example.stepcounter.R
import com.example.stepcounter.databinding.ActivityHomeScreenBinding
import com.example.stepcounter.mvvm.PersonRepository
import com.example.stepcounter.mvvm.PersonViewModel
import com.example.stepcounter.mvvm.PersonViewModelFactory
import com.example.stepcounter.mvvm.room.PersonDatabase
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import kotlin.properties.Delegates

class HomeScreen : AppCompatActivity(),


NavigationView.OnNavigationItemSelectedListener {

private lateinit var binding: ActivityHomeScreenBinding


private lateinit var drawerLayout: DrawerLayout

lateinit var drawer: ImageView


lateinit var username: String
lateinit var usergender: String

// var userheight by Delegates.notNull<Float>()


// var userweight by Delegates.notNull<Float>()
// //var userweight : Float? = null
// // lateinit var userdob:String
// lateinit var userdob:Float
var i = 0

override fun onCreate(savedInstanceState: Bundle?) {


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

val personDao = PersonDatabase.getDatabase(this).personDao()


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

val navigationView =
binding.navigationDraw // Replace this with your actual navigation
drawer view
val headerView: View = navigationView.getHeaderView(0)
val navUsername: TextView = headerView.findViewById(R.id.drawername)
val navGender = binding.navigationDraw.menu.findItem(R.id.gender)
val navHeight = binding.navigationDraw.menu.findItem(R.id.height)
val navWeight = binding.navigationDraw.menu.findItem(R.id.weight)
val navDob = binding.navigationDraw.menu.findItem(R.id.age)

//////change drawer items name/////


lifecycleScope.launch(Dispatchers.IO) {
username = personViewModel.getUserName()
navUsername.text = username
usergender = personViewModel.getUserGender()
navGender.setTitle(usergender)
val userheight = personViewModel.getUserHeight()
navHeight.setTitle("" + userheight + " FEET")
val userweight = personViewModel.getUserWeight()
navWeight.setTitle("" + userweight + " KG")
var userdob = personViewModel.getUserDob()
var diff=calculateAge(userdob)
navDob.setTitle("Age: "+diff)

//////////////////Achievement Screen/////////

binding.btnachievementHS.setOnClickListener {
val intent = Intent(this, ChallengesScreen::class.java)
startActivity(intent)
}

//////////////////ROUTINE PLANNER Screen/////////

binding.btnRoutinePlannerHS.setOnClickListener {

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


startActivity(intent)
}
//////////////////START BUTTON/////////

binding.btnStartHS.setOnClickListener {

Handler().postDelayed(object : Runnable {
override fun run() {
// set the limitations for the numeric
// text under the progress bar
if (i <= 100) {
binding.progresstext.text = "" + i
binding.progressBar.progress = i
i++
Handler().postDelayed(this, 200)
} else {
Handler().removeCallbacks(this)
}
}
}, 200)

//////////////////Notification Screen/////////

binding.includedtoolbarHS.tablerNoti.setOnClickListener {
val intent = Intent(this, NotificationScreen::class.java)
startActivity(intent)
}

////////DRAWER OPEN //////////


drawer = binding.includedtoolbarHS.btnOpen
drawerLayout = binding.drawer

val toggle =
ActionBarDrawerToggle(this, drawerLayout, R.string.open_nav,
R.string.close_nav)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
binding.navigationDraw.setNavigationItemSelectedListener(this)
binding.includedtoolbarHS.btnOpen.setOnClickListener {
binding.drawer.open()
}

override fun onBackPressed() {


if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
onBackPressedDispatcher.onBackPressed()
}
}

override fun onNavigationItemSelected(item: MenuItem): Boolean {


when (item.itemId) {
R.id.exit -> drawerLayout.closeDrawer(GravityCompat.START)
R.id.tmsc -> {
Toast.makeText(this, "Terms and conditions",
Toast.LENGTH_SHORT).show()
}
}
return true
}
fun calculateAge(birthdate: String?): Int {
// if (birthdate.isNullOrBlank()) {
// return 0 // or any default value
// }
val df = SimpleDateFormat("dd/MM/yyyy")
val doborg: Date = df.parse(birthdate)
val birth = Calendar.getInstance()
birth.time = doborg
val today = Calendar.getInstance()
var yearDifference = (today[Calendar.YEAR] - birth[Calendar.YEAR])
if (today[Calendar.MONTH] < birth[Calendar.MONTH]) {
yearDifference--
} else {
if (today[Calendar.MONTH] == birth[Calendar.MONTH]
&& today[Calendar.DAY_OF_MONTH] <
birth[Calendar.DAY_OF_MONTH]
) {
yearDifference--
}
}
return yearDifference
}
}

You might also like