Add initial implementation of habit tracking app with database and UI components

This commit is contained in:
bobbert committed 2026-02-24 22:51:28 +00:00
commit f838d1f628
23 files changed
+1929

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.ksp)
}
android {
namespace = "com.example.madwellbeingapp"
compileSdk {
version = release(36) {
minorApiLevel = 1
}
}
defaultConfig {
applicationId = "com.example.madwellbeingapp"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
// Room
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
ksp(libs.androidx.room.compiler)
// Navigation Compose
implementation(libs.androidx.navigation.compose)
// ViewModel Compose
implementation(libs.androidx.lifecycle.viewmodel.compose)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.ui.test.manifest)
}
+44
View File
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".HabitApp"
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.MadWellbeingApp">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.MadWellbeingApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".notification.HabitReminderReceiver"
android:exported="false" />
<receiver
android:name=".notification.BootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,43 @@
package com.example.madwellbeingapp
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import com.example.madwellbeingapp.data.HabitDatabase
import com.example.madwellbeingapp.data.repository.HabitRepository
/**
* Application subclass that provides the database and repository singletons.
*/
class HabitApp : Application() {
val database by lazy { HabitDatabase.getDatabase(this) }
val repository by lazy {
HabitRepository(database.habitDao(), database.habitLogDao())
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Habit Reminders",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Daily reminders for your habits"
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}
companion object {
const val CHANNEL_ID = "habit_reminders"
}
}
@@ -0,0 +1,105 @@
package com.example.madwellbeingapp
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.madwellbeingapp.ui.screens.AddEditHabitScreen
import com.example.madwellbeingapp.ui.screens.HabitDetailScreen
import com.example.madwellbeingapp.ui.screens.HomeScreen
import com.example.madwellbeingapp.ui.theme.MadWellbeingAppTheme
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
class MainActivity : ComponentActivity() {
private val notificationPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* granted or not */ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
// Request notification permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
setContent {
MadWellbeingAppTheme {
HabitNavGraph()
}
}
}
}
@Composable
fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "home") {
composable("home") {
HomeScreen(
viewModel = viewModel,
onAddHabit = { navController.navigate("add_habit") },
onHabitClick = { id -> navController.navigate("habit_detail/$id") }
)
}
composable("add_habit") {
AddEditHabitScreen(
viewModel = viewModel,
existingHabit = null,
onNavigateBack = { navController.popBackStack() }
)
}
composable(
route = "edit_habit/{habitId}",
arguments = listOf(navArgument("habitId") { type = NavType.IntType })
) { backStackEntry ->
val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
// Observe the habit so the form is pre-populated
val allHabits by viewModel.allHabits.collectAsState()
val habit = allHabits.find { it.id == habitId }
if (habit != null) {
AddEditHabitScreen(
viewModel = viewModel,
existingHabit = habit,
onNavigateBack = { navController.popBackStack() }
)
}
}
composable(
route = "habit_detail/{habitId}",
arguments = listOf(navArgument("habitId") { type = NavType.IntType })
) { backStackEntry ->
val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
HabitDetailScreen(
habitId = habitId,
viewModel = viewModel,
onNavigateBack = { navController.popBackStack() },
onEditHabit = { id -> navController.navigate("edit_habit/$id") }
)
}
}
}
@@ -0,0 +1,35 @@
package com.example.madwellbeingapp.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitLog
@Database(entities = [Habit::class, HabitLog::class], version = 1, exportSchema = false)
abstract class HabitDatabase : RoomDatabase() {
abstract fun habitDao(): HabitDao
abstract fun habitLogDao(): HabitLogDao
companion object {
@Volatile
private var INSTANCE: HabitDatabase? = null
fun getDatabase(context: Context): HabitDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
HabitDatabase::class.java,
"habit_database"
).build()
INSTANCE = instance
instance
}
}
}
}
@@ -0,0 +1,32 @@
package com.example.madwellbeingapp.data.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.example.madwellbeingapp.data.model.Habit
import kotlinx.coroutines.flow.Flow
@Dao
interface HabitDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(habit: Habit): Long
@Update
suspend fun update(habit: Habit)
@Delete
suspend fun delete(habit: Habit): Int
@Query("SELECT * FROM habits ORDER BY name ASC")
fun getAllHabits(): Flow<List<Habit>>
@Query("SELECT * FROM habits WHERE id = :id")
fun getHabitById(id: Int): Flow<Habit?>
@Query("SELECT * FROM habits WHERE id = :id")
suspend fun getHabitByIdOnce(id: Int): Habit?
}
@@ -0,0 +1,33 @@
package com.example.madwellbeingapp.data.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.madwellbeingapp.data.model.HabitLog
import kotlinx.coroutines.flow.Flow
@Dao
interface HabitLogDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(log: HabitLog): Long
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId ORDER BY date DESC")
fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>>
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId AND date = :date LIMIT 1")
suspend fun getLogForDate(habitId: Int, date: Long): HabitLog?
@Query("DELETE FROM habit_logs WHERE habitId = :habitId AND date = :date")
suspend fun deleteLogForDate(habitId: Int, date: Long): Int
@Query("SELECT COUNT(*) FROM habit_logs WHERE habitId = :habitId AND completed = 1")
fun getCompletedCount(habitId: Int): Flow<Int>
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId AND completed = 1 ORDER BY date DESC")
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog>
@Query("SELECT * FROM habit_logs WHERE date = :date")
fun getLogsForDate(date: Long): Flow<List<HabitLog>>
}
@@ -0,0 +1,27 @@
package com.example.madwellbeingapp.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Represents a habit tracked by the user.
*/
@Entity(tableName = "habits")
data class Habit(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String,
val category: HabitCategory,
val startDate: Long, // epoch millis – auto-set on creation
val targetFrequency: Int, // times per week the user wants to complete this habit
val reminderEnabled: Boolean = true,
val reminderHour: Int = 9, // default 09:00
val reminderMinute: Int = 0
)
enum class HabitCategory(val displayName: String) {
HEALTH("Health"),
STUDY("Study"),
FITNESS("Fitness"),
WELLBEING("Wellbeing")
}
@@ -0,0 +1,30 @@
package com.example.madwellbeingapp.data.model
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
/**
* Daily completion log for a habit.
* Unique constraint on (habitId, date) so a habit can only be logged once per day.
*/
@Entity(
tableName = "habit_logs",
foreignKeys = [
ForeignKey(
entity = Habit::class,
parentColumns = ["id"],
childColumns = ["habitId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index(value = ["habitId", "date"], unique = true)]
)
data class HabitLog(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val habitId: Int,
val date: Long, // epoch millis – normalised to start-of-day
val completed: Boolean = true
)
@@ -0,0 +1,55 @@
package com.example.madwellbeingapp.data.repository
import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitLog
import kotlinx.coroutines.flow.Flow
/**
* Single source of truth for habit and log data.
* Abstracts the data sources away from the ViewModels.
*/
class HabitRepository(
private val habitDao: HabitDao,
private val habitLogDao: HabitLogDao
) {
// ── Habits ──────────────────────────────────────────────
val allHabits: Flow<List<Habit>> = habitDao.getAllHabits()
fun getHabitById(id: Int): Flow<Habit?> = habitDao.getHabitById(id)
suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id)
suspend fun insertHabit(habit: Habit): Long = habitDao.insert(habit)
suspend fun updateHabit(habit: Habit) = habitDao.update(habit)
suspend fun deleteHabit(habit: Habit) = habitDao.delete(habit)
// ── Logs ────────────────────────────────────────────────
fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>> =
habitLogDao.getLogsForHabit(habitId)
fun getLogsForDate(date: Long): Flow<List<HabitLog>> =
habitLogDao.getLogsForDate(date)
suspend fun getLogForDate(habitId: Int, date: Long): HabitLog? =
habitLogDao.getLogForDate(habitId, date)
suspend fun toggleLog(habitId: Int, date: Long) {
val existing = habitLogDao.getLogForDate(habitId, date)
if (existing != null) {
habitLogDao.deleteLogForDate(habitId, date)
} else {
habitLogDao.insert(HabitLog(habitId = habitId, date = date, completed = true))
}
}
fun getCompletedCount(habitId: Int): Flow<Int> =
habitLogDao.getCompletedCount(habitId)
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> =
habitLogDao.getCompletedLogsDesc(habitId)
}
@@ -0,0 +1,33 @@
package com.example.madwellbeingapp.notification
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.example.madwellbeingapp.HabitApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
/**
* Re-schedules all habit alarms after the device reboots.
*/
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
val app = context.applicationContext as HabitApp
CoroutineScope(Dispatchers.IO).launch {
val habits = app.repository.allHabits.first()
for (habit in habits) {
if (habit.reminderEnabled) {
HabitNotificationScheduler.schedule(
context, habit.id, habit.name,
habit.reminderHour, habit.reminderMinute
)
}
}
}
}
}
}
@@ -0,0 +1,60 @@
package com.example.madwellbeingapp.notification
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.Calendar
/**
* Schedules daily reminders for individual habits using AlarmManager.
*/
object HabitNotificationScheduler {
fun schedule(context: Context, habitId: Int, habitName: String, hour: Int, minute: Int) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, HabitReminderReceiver::class.java).apply {
putExtra("habit_id", habitId)
putExtra("habit_name", habitName)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
habitId,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if (before(Calendar.getInstance())) {
add(Calendar.DAY_OF_YEAR, 1)
}
}
// Use repeating alarm — fires daily
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
}
fun cancel(context: Context, habitId: Int) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, HabitReminderReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context,
habitId,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
alarmManager.cancel(pendingIntent)
}
}
@@ -0,0 +1,50 @@
package com.example.madwellbeingapp.notification
import android.Manifest
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.example.madwellbeingapp.HabitApp
import com.example.madwellbeingapp.MainActivity
import com.example.madwellbeingapp.R
/**
* Receives the alarm broadcast and posts a notification for the habit.
*/
class HabitReminderReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val habitId = intent.getIntExtra("habit_id", -1)
val habitName = intent.getStringExtra("habit_name") ?: "your habit"
// Tap notification → open app
val tapIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val tapPending = PendingIntent.getActivity(
context, habitId, tapIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(context, HabitApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Habit Reminder 🔔")
.setContentText("Time to work on \"$habitName\"!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(tapPending)
.setAutoCancel(true)
.build()
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
== PackageManager.PERMISSION_GRANTED
) {
NotificationManagerCompat.from(context).notify(habitId, notification)
}
}
}
@@ -0,0 +1,258 @@
package com.example.madwellbeingapp.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitCategory
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
/**
* Screen for creating or editing a habit.
* When [existingHabit] is provided the form is pre-filled for editing.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEditHabitScreen(
viewModel: HabitViewModel,
existingHabit: Habit? = null,
onNavigateBack: () -> Unit
) {
val isEditing = existingHabit != null
var name by remember { mutableStateOf(existingHabit?.name ?: "") }
var selectedCategory by remember {
mutableStateOf(existingHabit?.category ?: HabitCategory.HEALTH)
}
var targetFrequency by remember {
mutableStateOf((existingHabit?.targetFrequency ?: 7).toString())
}
var reminderEnabled by remember { mutableStateOf(existingHabit?.reminderEnabled ?: true) }
var reminderHour by remember { mutableIntStateOf(existingHabit?.reminderHour ?: 9) }
var reminderMinute by remember { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) }
var nameError by remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
if (isEditing) "Edit Habit" else "New Habit",
fontWeight = FontWeight.Bold
)
},
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primary,
titleContentColor = MaterialTheme.colorScheme.onPrimary,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary
)
)
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(20.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Name
OutlinedTextField(
value = name,
onValueChange = {
name = it
nameError = false
},
label = { Text("Habit Name") },
placeholder = { Text("e.g. Drink 8 glasses of water") },
isError = nameError,
supportingText = if (nameError) {
{ Text("Name cannot be empty") }
} else null,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp)
)
// Category dropdown
var categoryExpanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = categoryExpanded,
onExpandedChange = { categoryExpanded = !categoryExpanded }
) {
OutlinedTextField(
value = selectedCategory.displayName,
onValueChange = {},
readOnly = true,
label = { Text("Category") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) },
modifier = Modifier
.fillMaxWidth()
.menuAnchor(MenuAnchorType.PrimaryNotEditable),
shape = RoundedCornerShape(12.dp)
)
ExposedDropdownMenu(
expanded = categoryExpanded,
onDismissRequest = { categoryExpanded = false }
) {
HabitCategory.entries.forEach { cat ->
DropdownMenuItem(
text = { Text(cat.displayName) },
onClick = {
selectedCategory = cat
categoryExpanded = false
}
)
}
}
}
// Target frequency
OutlinedTextField(
value = targetFrequency,
onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } },
label = { Text("Target (times per week)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp)
)
// Reminder toggle
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text("Daily Reminder", style = MaterialTheme.typography.bodyLarge)
Switch(
checked = reminderEnabled,
onCheckedChange = { reminderEnabled = it }
)
}
if (reminderEnabled) {
// Simple hour/minute pickers as text fields
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = reminderHour.toString().padStart(2, '0'),
onValueChange = {
val h = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0
reminderHour = h.coerceIn(0, 23)
},
label = { Text("Hour (0-23)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(12.dp)
)
OutlinedTextField(
value = reminderMinute.toString().padStart(2, '0'),
onValueChange = {
val m = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0
reminderMinute = m.coerceIn(0, 59)
},
label = { Text("Minute (0-59)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(12.dp)
)
}
}
Spacer(modifier = Modifier.height(8.dp))
// Save button
Button(
onClick = {
if (name.isBlank()) {
nameError = true
return@Button
}
val freq = targetFrequency.toIntOrNull() ?: 7
if (isEditing && existingHabit != null) {
viewModel.updateHabit(
existingHabit.copy(
name = name.trim(),
category = selectedCategory,
targetFrequency = freq,
reminderEnabled = reminderEnabled,
reminderHour = reminderHour,
reminderMinute = reminderMinute
)
)
} else {
viewModel.addHabit(
name = name.trim(),
category = selectedCategory,
targetFrequency = freq,
reminderEnabled = reminderEnabled,
reminderHour = reminderHour,
reminderMinute = reminderMinute
)
}
onNavigateBack()
},
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
shape = RoundedCornerShape(14.dp)
) {
Text(
if (isEditing) "Update Habit" else "Create Habit",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
}
}
}
}
@@ -0,0 +1,381 @@
package com.example.madwellbeingapp.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.HabitCategory
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HabitDetailScreen(
habitId: Int,
viewModel: HabitViewModel,
onNavigateBack: () -> Unit,
onEditHabit: (Int) -> Unit
) {
LaunchedEffect(habitId) { viewModel.selectHabit(habitId) }
val habit by viewModel.selectedHabit.collectAsState()
val logs by viewModel.selectedHabitLogs.collectAsState()
val currentStreak by viewModel.currentStreak.collectAsState()
val longestStreak by viewModel.longestStreak.collectAsState()
val weeklyProgress by viewModel.weeklyProgress(habitId).collectAsState(initial = 0f)
val todayLogs by viewModel.todayLogs.collectAsState()
val isCompletedToday = todayLogs.any { it.habitId == habitId && it.completed }
var showDeleteDialog by remember { mutableStateOf(false) }
if (showDeleteDialog && habit != null) {
AlertDialog(
onDismissRequest = { showDeleteDialog = false },
title = { Text("Delete Habit") },
text = { Text("Are you sure you want to delete \"${habit!!.name}\"? All associated data will be lost.") },
confirmButton = {
TextButton(onClick = {
viewModel.deleteHabit(habit!!)
showDeleteDialog = false
onNavigateBack()
}) {
Text("Delete", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { showDeleteDialog = false }) {
Text("Cancel")
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(habit?.name ?: "Habit Detail", fontWeight = FontWeight.Bold) },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { onEditHabit(habitId) }) {
Icon(Icons.Default.Edit, contentDescription = "Edit")
}
IconButton(onClick = { showDeleteDialog = true }) {
Icon(Icons.Default.Delete, contentDescription = "Delete")
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primary,
titleContentColor = MaterialTheme.colorScheme.onPrimary,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
actionIconContentColor = MaterialTheme.colorScheme.onPrimary
)
)
}
) { padding ->
if (habit == null) {
Box(
modifier = Modifier.fillMaxSize().padding(padding),
contentAlignment = Alignment.Center
) {
Text("Loading…")
}
return@Scaffold
}
val h = habit!!
val dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Info card
Card(
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(2.dp),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = categoryEmoji(h.category) + " " + h.category.displayName,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Started: ${dateFormat.format(Date(h.startDate))}",
style = MaterialTheme.typography.bodyMedium
)
Text(
text = "Target: ${h.targetFrequency}x per week",
style = MaterialTheme.typography.bodyMedium
)
if (h.reminderEnabled) {
Text(
text = "Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${
h.reminderMinute.toString().padStart(2, '0')
}",
style = MaterialTheme.typography.bodyMedium
)
}
}
}
// Mark today button
Button(
onClick = { viewModel.toggleTodayLog(habitId) },
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
shape = RoundedCornerShape(14.dp),
colors = if (isCompletedToday) ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
) else ButtonDefaults.buttonColors()
) {
Text(
if (isCompletedToday) "✅ Completed Today — Tap to Undo"
else "Mark Today as Done",
fontWeight = FontWeight.Bold
)
}
// Streak cards
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
StatCard(
title = "🔥 Current Streak",
value = "$currentStreak day${if (currentStreak != 1) "s" else ""}",
modifier = Modifier.weight(1f)
)
StatCard(
title = "🏆 Longest Streak",
value = "$longestStreak day${if (longestStreak != 1) "s" else ""}",
modifier = Modifier.weight(1f)
)
}
// Weekly progress
Card(
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(2.dp),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = "Weekly Progress",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(12.dp))
LinearProgressIndicator(
progress = { weeklyProgress },
modifier = Modifier
.fillMaxWidth()
.height(12.dp)
.clip(RoundedCornerShape(6.dp)),
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "${(weeklyProgress * 100).toInt()}% of weekly goal",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
// Last 14 days heatmap
Text(
text = "Last 14 Days",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold
)
val logDates = logs.filter { it.completed }.map { normaliseToDay(it.date) }.toSet()
val today = todayStartMillis()
val last14 = (0..13).map { today - it * 86_400_000L }.reversed()
LazyRow(
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
items(last14) { dayMillis ->
val completed = logDates.contains(dayMillis)
val dayFormat = SimpleDateFormat("dd", Locale.getDefault())
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(
modifier = Modifier
.size(36.dp)
.clip(CircleShape)
.background(
if (completed) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant
),
contentAlignment = Alignment.Center
) {
Text(
text = if (completed) "✓" else "",
color = if (completed) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelSmall
)
}
Spacer(modifier = Modifier.height(2.dp))
Text(
text = dayFormat.format(Date(dayMillis)),
style = MaterialTheme.typography.labelSmall,
textAlign = TextAlign.Center
)
}
}
}
// Total completions
val totalCompletions = logs.count { it.completed }
Card(
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(2.dp),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text("📊", style = MaterialTheme.typography.headlineMedium)
Spacer(modifier = Modifier.width(12.dp))
Column {
Text(
"Total Completions",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
Text(
"$totalCompletions time${if (totalCompletions != 1) "s" else ""}",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@Composable
private fun StatCard(title: String, value: String, modifier: Modifier = Modifier) {
Card(
modifier = modifier,
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(2.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
)
) {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = title,
style = MaterialTheme.typography.labelMedium,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = value,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
textAlign = TextAlign.Center
)
}
}
}
private fun categoryEmoji(category: HabitCategory): String = when (category) {
HabitCategory.HEALTH -> "❤️"
HabitCategory.STUDY -> "📚"
HabitCategory.FITNESS -> "💪"
HabitCategory.WELLBEING -> "🧘"
}
private fun normaliseToDay(millis: Long): Long {
val cal = Calendar.getInstance()
cal.timeInMillis = millis
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
private fun todayStartMillis(): Long {
val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
@@ -0,0 +1,264 @@
package com.example.madwellbeingapp.ui.screens
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitCategory
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
fun HomeScreen(
viewModel: HabitViewModel,
onAddHabit: () -> Unit,
onHabitClick: (Int) -> Unit
) {
val habits by viewModel.allHabits.collectAsState()
val todayLogs by viewModel.todayLogs.collectAsState()
val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = onAddHabit,
containerColor = MaterialTheme.colorScheme.primary
) {
Icon(Icons.Default.Add, contentDescription = "Add Habit")
}
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
// Header
Column(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 20.dp, vertical = 24.dp)
) {
Text(
text = "Smart Habit Companion",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(4.dp))
val dateFormat = SimpleDateFormat("EEEE, MMM d", Locale.getDefault())
Text(
text = dateFormat.format(Date()),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.8f)
)
Spacer(modifier = Modifier.height(12.dp))
// Quick summary
val completedToday = todayCompletedIds.size
val total = habits.size
Text(
text = "$completedToday / $total habits completed today",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Medium
)
if (total > 0) {
Spacer(modifier = Modifier.height(8.dp))
LinearProgressIndicator(
progress = { completedToday.toFloat() / total },
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.clip(RoundedCornerShape(4.dp)),
color = MaterialTheme.colorScheme.onPrimary,
trackColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.3f),
)
}
}
if (habits.isEmpty()) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(32.dp),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "No habits yet!",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Tap + to create your first habit",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
}
}
} else {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(habits, key = { it.id }) { habit ->
HabitCard(
habit = habit,
isCompletedToday = todayCompletedIds.contains(habit.id),
onToggle = { viewModel.toggleTodayLog(habit.id) },
onClick = { onHabitClick(habit.id) },
viewModel = viewModel
)
}
}
}
}
}
}
@Composable
private fun HabitCard(
habit: Habit,
isCompletedToday: Boolean,
onToggle: () -> Unit,
onClick: () -> Unit,
viewModel: HabitViewModel
) {
val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f)
Card(
modifier = Modifier
.fillMaxWidth()
.animateContentSize()
.clickable(onClick = onClick),
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
colors = CardDefaults.cardColors(
containerColor = if (isCompletedToday)
MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surface
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Check button
IconButton(
onClick = onToggle,
modifier = Modifier
.size(44.dp)
.clip(CircleShape)
.background(
if (isCompletedToday)
MaterialTheme.colorScheme.primary
else
MaterialTheme.colorScheme.surfaceVariant
)
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = if (isCompletedToday) "Completed" else "Mark complete",
tint = if (isCompletedToday)
MaterialTheme.colorScheme.onPrimary
else
MaterialTheme.colorScheme.onSurfaceVariant
)
}
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = habit.name,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(2.dp))
Text(
text = categoryEmoji(habit.category) + " " + habit.category.displayName +
" • ${habit.targetFrequency}x/week",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
// Weekly progress bar
LinearProgressIndicator(
progress = { weeklyProgress },
modifier = Modifier
.fillMaxWidth()
.height(6.dp)
.clip(RoundedCornerShape(3.dp)),
color = categoryColor(habit.category),
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
Spacer(modifier = Modifier.height(2.dp))
Text(
text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
}
}
}
}
private fun categoryEmoji(category: HabitCategory): String = when (category) {
HabitCategory.HEALTH -> "❤️"
HabitCategory.STUDY -> "📚"
HabitCategory.FITNESS -> "💪"
HabitCategory.WELLBEING -> "🧘"
}
@Composable
private fun categoryColor(category: HabitCategory) = when (category) {
HabitCategory.HEALTH -> MaterialTheme.colorScheme.error
HabitCategory.STUDY -> MaterialTheme.colorScheme.tertiary
HabitCategory.FITNESS -> MaterialTheme.colorScheme.primary
HabitCategory.WELLBEING -> MaterialTheme.colorScheme.secondary
}
@@ -0,0 +1,11 @@
package com.example.madwellbeingapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
@@ -0,0 +1,58 @@
package com.example.madwellbeingapp.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MadWellbeingAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -0,0 +1,34 @@
package com.example.madwellbeingapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
@@ -0,0 +1,248 @@
package com.example.madwellbeingapp.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.madwellbeingapp.HabitApp
import com.example.madwellbeingapp.R
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitCategory
import com.example.madwellbeingapp.data.model.HabitLog
import com.example.madwellbeingapp.data.repository.HabitRepository
import com.example.madwellbeingapp.notification.HabitNotificationScheduler
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.util.Calendar
class HabitViewModel(application: Application) : AndroidViewModel(application) {
private val repository: HabitRepository =
(application as HabitApp).repository
// ── All habits ──────────────────────────────────────────
val allHabits: StateFlow<List<Habit>> = repository.allHabits
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
// ── Today's logs ────────────────────────────────────────
private val todayStart: Long
get() {
val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
val todayLogs: StateFlow<List<HabitLog>> = repository.getLogsForDate(todayStart)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
// ── Selected habit detail ───────────────────────────────
private val _selectedHabitId = MutableStateFlow<Int?>(null)
val selectedHabitId = _selectedHabitId.asStateFlow()
@OptIn(ExperimentalCoroutinesApi::class)
val selectedHabit: StateFlow<Habit?> = _selectedHabitId
.flatMapLatest { id ->
if (id != null) repository.getHabitById(id) else flowOf(null)
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
@OptIn(ExperimentalCoroutinesApi::class)
val selectedHabitLogs: StateFlow<List<HabitLog>> = _selectedHabitId
.flatMapLatest { id ->
if (id != null) repository.getLogsForHabit(id) else flowOf(emptyList())
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
// ── Streak for selected habit ───────────────────────────
private val _currentStreak = MutableStateFlow(0)
val currentStreak: StateFlow<Int> = _currentStreak.asStateFlow()
private val _longestStreak = MutableStateFlow(0)
val longestStreak: StateFlow<Int> = _longestStreak.asStateFlow()
fun selectHabit(habitId: Int) {
_selectedHabitId.value = habitId
computeStreaks(habitId)
}
private fun computeStreaks(habitId: Int) {
viewModelScope.launch {
val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) {
_currentStreak.value = 0
_longestStreak.value = 0
return@launch
}
// Normalise dates to day-only & sort descending
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
// Current streak: consecutive days ending today or yesterday
var current = 0
val today = todayStart
val yesterday = today - 86_400_000L
if (days.first() == today || days.first() == yesterday) {
var expected = days.first()
for (day in days) {
if (day == expected) {
current++
expected -= 86_400_000L
} else break
}
}
// Longest streak
var longest = 1
var streak = 1
val sorted = days.sortedDescending()
for (i in 1 until sorted.size) {
if (sorted[i] == sorted[i - 1] - 86_400_000L) {
streak++
if (streak > longest) longest = streak
} else {
streak = 1
}
}
_currentStreak.value = current
_longestStreak.value = longest
}
}
// ── Weekly progress for a habit ─────────────────────────
fun weeklyProgress(habitId: Int): Flow<Float> {
return repository.getLogsForHabit(habitId).map { logs ->
val weekAgo = todayStart - 6 * 86_400_000L
val thisWeekCount = logs.count { it.completed && it.date >= weekAgo }
val habit = repository.getHabitByIdOnce(habitId)
val target = habit?.targetFrequency ?: 7
(thisWeekCount.toFloat() / target).coerceIn(0f, 1f)
}
}
// ── CRUD operations ─────────────────────────────────────
fun addHabit(
name: String,
category: HabitCategory,
targetFrequency: Int,
reminderEnabled: Boolean = true,
reminderHour: Int = 9,
reminderMinute: Int = 0
) {
viewModelScope.launch {
val habit = Habit(
name = name,
category = category,
startDate = System.currentTimeMillis(),
targetFrequency = targetFrequency,
reminderEnabled = reminderEnabled,
reminderHour = reminderHour,
reminderMinute = reminderMinute
)
val id = repository.insertHabit(habit).toInt()
if (reminderEnabled) {
HabitNotificationScheduler.schedule(
getApplication(), id, name, reminderHour, reminderMinute
)
}
}
}
fun updateHabit(habit: Habit) {
viewModelScope.launch {
repository.updateHabit(habit)
if (habit.reminderEnabled) {
HabitNotificationScheduler.schedule(
getApplication(), habit.id, habit.name,
habit.reminderHour, habit.reminderMinute
)
} else {
HabitNotificationScheduler.cancel(getApplication(), habit.id)
}
}
}
fun deleteHabit(habit: Habit) {
viewModelScope.launch {
HabitNotificationScheduler.cancel(getApplication(), habit.id)
repository.deleteHabit(habit)
}
}
// ── Daily logging ───────────────────────────────────────
fun toggleTodayLog(habitId: Int) {
viewModelScope.launch {
repository.toggleLog(habitId, todayStart)
// Refresh streaks if currently viewing this habit
if (_selectedHabitId.value == habitId) {
computeStreaks(habitId)
}
// Celebrate streak milestones
checkStreakCelebration(habitId)
}
}
private suspend fun checkStreakCelebration(habitId: Int) {
val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) return
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
val today = todayStart
if (days.first() != today) return
var streak = 0
var expected = today
for (day in days) {
if (day == expected) {
streak++
expected -= 86_400_000L
} else break
}
if (streak > 0 && streak % 7 == 0) {
// Send a celebration notification
sendCelebration(habitId, streak)
}
}
private suspend fun sendCelebration(habitId: Int, streak: Int) {
val habit = repository.getHabitByIdOnce(habitId) ?: return
val ctx = getApplication<HabitApp>()
val notification = androidx.core.app.NotificationCompat.Builder(ctx, HabitApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("🎉 Streak Milestone!")
.setContentText("Amazing! You've hit a $streak-day streak on \"${habit.name}\"!")
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build()
if (androidx.core.content.ContextCompat.checkSelfPermission(
ctx, android.Manifest.permission.POST_NOTIFICATIONS
) == android.content.pm.PackageManager.PERMISSION_GRANTED
) {
androidx.core.app.NotificationManagerCompat.from(ctx)
.notify(habitId + 10_000, notification)
}
}
// ── Helpers ──────────────────────────────────────────────
private fun normaliseToDay(millis: Long): Long {
val cal = Calendar.getInstance()
cal.timeInMillis = millis
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
}
+6
View File
@@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.ksp) apply false
}
+25
View File
@@ -0,0 +1,25 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
# Allow KSP-generated Kotlin source sets with AGP built-in Kotlin
android.disallowKotlinSourceSets=false
+26
View File
@@ -0,0 +1,26 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "Mad Wellbeing App"
include(":app")