content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.composequadrant import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/composequadrant/ExampleUnitTest.kt
3597841459
package com.example.diceroller.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Color.kt
2898381871
package com.example.diceroller.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.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat 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 DiceRollerTheme( 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Theme.kt
751687589
package com.example.diceroller.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 ) */ )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Type.kt
2881408862
package com.example.diceroller import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.diceroller.ui.theme.DiceRollerTheme import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DiceRollerTheme { DiceRollerApp() } } } } @Preview @Composable fun DiceRollerApp() { DiceWithButtonAndImage() } @Composable fun DiceWithButtonAndImage(modifier: Modifier = Modifier) { var result by remember { mutableStateOf(1) } val imageResource = when (result) { 1 -> R.drawable.dice_1 2 -> R.drawable.dice_2 3 -> R.drawable.dice_3 4 -> R.drawable.dice_4 5 -> R.drawable.dice_5 else -> R.drawable.dice_6 } Column( modifier = modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Image(painter = painterResource(imageResource), contentDescription = result.toString()) Button(onClick = { result = (1..6).random() }) { Text(stringResource(R.string.roll)) } } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/MainActivity.kt
3017748487
package com.example.taskcompleted.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Color.kt
2647091149
package com.example.taskcompleted.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.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 ) @Composable fun TaskCompletedTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = Color.Transparent.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Theme.kt
3512124051
package com.example.taskcompleted.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 ) )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Type.kt
2994149504
package com.example.taskcompleted import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.taskcompleted.ui.theme.TaskCompletedTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TaskCompletedTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { TaskCompletedScreen() } } } } } @Composable fun TaskCompletedScreen() { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { val image = painterResource(R.drawable.ic_task_completed) Image(painter = image, contentDescription = null) Text( text = stringResource(R.string.all_task_completed), modifier = Modifier.padding(top = 24.dp, bottom = 8.dp), fontWeight = FontWeight.Bold ) Text( text = stringResource(R.string.nice_work), fontSize = 16.sp ) } } @Preview(showBackground = true) @Composable fun TaskCompletedPreview() { TaskCompletedTheme { TaskCompletedScreen() } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/MainActivity.kt
1843820197
package com.example.happybirthday.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Color.kt
10902474
package com.example.happybirthday.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.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat 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 HappyBirthdayTheme( 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Theme.kt
3850951464
package com.example.happybirthday.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 ) */ )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Type.kt
4120706125
package com.example.happybirthday import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.happybirthday.ui.theme.HappyBirthdayTheme import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.ui.layout.ContentScale class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HappyBirthdayTheme { // A surface container using the 'background' color from the theme Surface(color = MaterialTheme.colorScheme.background) { GreetingImage("Happy Birthday Ainin!", "From Emma") } } } } } @Composable fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) { // Create a column so that texts don't overlap Column( verticalArrangement = Arrangement.Center, modifier = modifier ) { Text( text = message, fontSize = 100.sp, lineHeight = 116.sp, textAlign = TextAlign.Center ) Text( text = from, fontSize = 36.sp, modifier = Modifier .padding(16.dp) .align(alignment = Alignment.CenterHorizontally) ) } } @Composable fun GreetingImage(message: String, from: String, modifier: Modifier = Modifier) { val image = painterResource(R.drawable.androidparty) //Step 3 create a box to overlap image and texts Box { Image( painter = image, contentDescription = null, contentScale = ContentScale.Crop, alpha = 0.5F ) GreetingText( message = message, from = from, modifier = Modifier .fillMaxSize() .padding(8.dp) ) } } @Preview(showBackground = false) @Composable fun BirthdayCardPreview() { HappyBirthdayTheme { GreetingText(message = "Happy Birthday Ainin!", from = "From Emma") } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/MainActivity.kt
1007837701
package com.example.composearticle.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Color.kt
2161329073
package com.example.composearticle.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.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 ) @Composable fun ComposeArticleTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = Color.Transparent.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Theme.kt
2744330643
package com.example.composearticle.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 ) )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Type.kt
319593794
package com.example.composearticle import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.composearticle.ui.theme.ComposeArticleTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeArticleTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ComposeArticleApp() } } } } } @Composable fun ComposeArticleApp() { ArticleCard( title = stringResource(R.string.title_jetpack_compose_tutorial), shortDescription = stringResource(R.string.compose_short_desc), longDescription = stringResource(R.string.compose_long_desc), imagePainter = painterResource(R.drawable.bg_compose_background) ) } @Composable private fun ArticleCard( title: String, shortDescription: String, longDescription: String, imagePainter: Painter, modifier: Modifier = Modifier, ) { Column(modifier = modifier) { Image(painter = imagePainter, contentDescription = null) Text( text = title, modifier = Modifier.padding(16.dp), fontSize = 24.sp ) Text( text = shortDescription, modifier = Modifier.padding(start = 16.dp, end = 16.dp), textAlign = TextAlign.Justify ) Text( text = longDescription, modifier = Modifier.padding(16.dp), textAlign = TextAlign.Justify ) } } @Preview(showBackground = true) @Composable fun ComposeArticleAppPreview() { ComposeArticleTheme { ComposeArticleApp() } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/MainActivity.kt
767219649
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lemonade.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6A5F00) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFF9E44C) val md_theme_light_onPrimaryContainer = Color(0xFF201C00) val md_theme_light_secondary = Color(0xFF645F41) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFEBE3BD) val md_theme_light_onSecondaryContainer = Color(0xFF1F1C05) val md_theme_light_tertiary = Color(0xFF416651) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFC3ECD2) val md_theme_light_onTertiaryContainer = Color(0xFF002112) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF1D1C16) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF1D1C16) val md_theme_light_surfaceVariant = Color(0xFFE8E2D0) val md_theme_light_onSurfaceVariant = Color(0xFF4A4739) val md_theme_light_outline = Color(0xFF7B7768) val md_theme_light_inverseOnSurface = Color(0xFFF5F0E7) val md_theme_light_inverseSurface = Color(0xFF32302A) val md_theme_light_inversePrimary = Color(0xFFDCC830) val md_theme_light_surfaceTint = Color(0xFF6A5F00) val md_theme_light_outlineVariant = Color(0xFFCCC6B5) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFDCC830) val md_theme_dark_onPrimary = Color(0xFF373100) val md_theme_dark_primaryContainer = Color(0xFF504700) val md_theme_dark_onPrimaryContainer = Color(0xFFF9E44C) val md_theme_dark_secondary = Color(0xFFCFC7A2) val md_theme_dark_onSecondary = Color(0xFF353117) val md_theme_dark_secondaryContainer = Color(0xFF4C472B) val md_theme_dark_onSecondaryContainer = Color(0xFFEBE3BD) val md_theme_dark_tertiary = Color(0xFFA7D0B7) val md_theme_dark_onTertiary = Color(0xFF113725) val md_theme_dark_tertiaryContainer = Color(0xFF294E3B) val md_theme_dark_onTertiaryContainer = Color(0xFFC3ECD2) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1D1C16) val md_theme_dark_onBackground = Color(0xFFE7E2D9) val md_theme_dark_surface = Color(0xFF1D1C16) val md_theme_dark_onSurface = Color(0xFFE7E2D9) val md_theme_dark_surfaceVariant = Color(0xFF4A4739) val md_theme_dark_onSurfaceVariant = Color(0xFFCCC6B5) val md_theme_dark_outline = Color(0xFF959181) val md_theme_dark_inverseOnSurface = Color(0xFF1D1C16) val md_theme_dark_inverseSurface = Color(0xFFE7E2D9) val md_theme_dark_inversePrimary = Color(0xFF6A5F00) val md_theme_dark_surfaceTint = Color(0xFFDCC830) val md_theme_dark_outlineVariant = Color(0xFF4A4739) val md_theme_dark_scrim = Color(0xFF000000)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Color.kt
594178479
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lemonade.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.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun AppTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = false, 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Theme.kt
64699599
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lemonade.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 ) )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Type.kt
140986119
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lemonade import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image 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.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable 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.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.lemonade.ui.theme.AppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme() { LemonadeApp() } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun LemonadeApp() { var currentStep by remember { mutableStateOf(1) } var squeezeCount by remember { mutableStateOf(0) } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text( text = "Lemonade", fontWeight = FontWeight.Bold ) }, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer, navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer, actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) } ) { innerPadding -> Surface( modifier = Modifier .fillMaxSize() .padding(innerPadding) .background(MaterialTheme.colorScheme.tertiaryContainer), color = MaterialTheme.colorScheme.background ) { when (currentStep) { 1 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_select, drawableResourceId = R.drawable.lemon_tree, contentDescriptionResourceId = R.string.lemon_tree_content_description, onImageClick = { currentStep = 2 squeezeCount = (2..4).random() } ) } 2 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_squeeze, drawableResourceId = R.drawable.lemon_squeeze, contentDescriptionResourceId = R.string.lemon_content_description, onImageClick = { squeezeCount-- if (squeezeCount == 0) { currentStep = 3 } } ) } 3 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_drink, drawableResourceId = R.drawable.lemon_drink, contentDescriptionResourceId = R.string.lemonade_content_description, onImageClick = { currentStep = 4 } ) } 4 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_empty_glass, drawableResourceId = R.drawable.lemon_restart, contentDescriptionResourceId = R.string.empty_glass_content_description, onImageClick = { currentStep = 1 } ) } } } } } @Composable fun LemonTextAndImage( textLabelResourceId: Int, drawableResourceId: Int, contentDescriptionResourceId: Int, onImageClick: () -> Unit, modifier: Modifier = Modifier ) { Box( modifier = modifier ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Button( onClick = onImageClick, shape = RoundedCornerShape(dimensionResource(R.dimen.button_corner_radius)), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer) ) { Image( painter = painterResource(drawableResourceId), contentDescription = stringResource(contentDescriptionResourceId), modifier = Modifier .width(dimensionResource(R.dimen.button_image_width)) .height(dimensionResource(R.dimen.button_image_height)) .padding(dimensionResource(R.dimen.button_interior_padding)) ) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_vertical))) Text( text = stringResource(textLabelResourceId), style = MaterialTheme.typography.bodyLarge ) } } } @Preview @Composable fun LemonPreview() { AppTheme() { LemonadeApp() } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/MainActivity.kt
1276581266
package com.example.greetingcard.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Color.kt
2966474842
package com.example.greetingcard.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.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat 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 GreetingCardTheme( 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Theme.kt
2932088790
package com.example.greetingcard.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 ) */ )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Type.kt
2395137318
package com.example.greetingcard import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.foundation.layout.padding import com.example.greetingcard.ui.theme.GreetingCardTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GreetingCardTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Greeting("Ainin") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Surface(color = Color.Magenta) { Text( text = "Sawadee kha thukkhon my name is $name", modifier = modifier.padding(24.dp) ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { GreetingCardTheme { Greeting("Ainin") } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/MainActivity.kt
2410677849
package com.example.businesscard.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Color.kt
989791096
package com.example.businesscard.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.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat 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 BusinessCardTheme( 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Theme.kt
2982380513
package com.example.businesscard.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 ) */ )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Type.kt
555766880
package com.example.businesscard import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image 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.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Build import androidx.compose.material.icons.rounded.Email import androidx.compose.material.icons.rounded.Menu import androidx.compose.material.icons.rounded.Phone import androidx.compose.material.icons.rounded.Share import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.businesscard.ui.theme.BusinessCardTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BusinessCardTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ProfileBuilderApp() } } } } } @Composable fun ProfileBuilderApp() { Column( modifier = Modifier .fillMaxSize() .fillMaxWidth() .background(Color(0Xffd2e8d4)), verticalArrangement = Arrangement.Center ) { Row( modifier = Modifier .padding(16.dp) .weight(1f) .fillMaxHeight(), horizontalArrangement = Arrangement.Center ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Bottom, modifier = Modifier.fillMaxHeight() ) { Box( modifier = Modifier .size(100.dp) .background(Color(0xFF073042)) ) { Image( painter = painterResource(id = R.drawable.android_logo), contentDescription = null, modifier = Modifier.size(100.dp) ) } Text( text = stringResource(R.string.developer_name_text), Modifier.fillMaxWidth(), fontSize = 40.sp, textAlign = TextAlign.Center, ) Text( text = stringResource(R.string.developer_desc_text), Modifier.fillMaxWidth(), textAlign = TextAlign.Center, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xff006d3a) ) } } Row( modifier = Modifier .fillMaxWidth() .padding(16.dp) .weight(1f), horizontalArrangement = Arrangement.Center, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Bottom, modifier = Modifier.fillMaxSize() ) { Row ( horizontalArrangement = Arrangement.Start, modifier = Modifier.fillMaxWidth() ){ Icon( Icons.Rounded.Phone, contentDescription = null, Modifier.padding(start = 80.dp, end = 25.dp, bottom = 20.dp), tint = Color(0xff006d3a) ) Text(text = stringResource(R.string.phone_no_text)) } Row ( horizontalArrangement = Arrangement.Start, modifier = Modifier.fillMaxWidth() ) { Icon(Icons.Rounded.Share, contentDescription = null, Modifier.padding(start = 80.dp, end = 25.dp, bottom = 20.dp), tint = Color(0xff006d3a) ) Text(text = stringResource(R.string.domain_text)) } Row ( horizontalArrangement = Arrangement.Start, modifier = Modifier.fillMaxWidth() ){ Icon(Icons.Rounded.Email, contentDescription = null, Modifier.padding(start = 80.dp, end = 25.dp, bottom = 25.dp), tint = Color(0xff006d3a) ) Text(text = stringResource(R.string.email_text)) } } } } } @Composable private fun ComposableInfoCard( title: String, description: String, backgroundColor: Color, modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxSize() .background(backgroundColor) .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title, modifier = Modifier.padding(bottom = 16.dp), fontWeight = FontWeight.Bold ) Text( text = description, textAlign = TextAlign.Justify ) } } @Preview(showBackground = true, showSystemUi = true) @Composable private fun BusinessCard() { BusinessCardTheme { ProfileBuilderApp() } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/MainActivity.kt
3610715973
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.composequadrant.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)
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Color.kt
2319670969
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.composequadrant.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.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 ) @Composable fun ComposeQuadrantTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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 } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = Color.Transparent.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Theme.kt
2789334435
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.composequadrant.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 ) )
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Type.kt
87066807
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.composequadrant import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.composequadrant.ui.theme.ComposeQuadrantTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeQuadrantTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ComposeQuadrantApp() } } } } } @Composable fun ComposeQuadrantApp() { Column(Modifier.fillMaxWidth()) { Row(Modifier.weight(1f)) { ComposableInfoCard( title = stringResource(R.string.first_title), description = stringResource(R.string.first_description), backgroundColor = Color(0xFFEADDFF), modifier = Modifier.weight(1f) ) ComposableInfoCard( title = stringResource(R.string.second_title), description = stringResource(R.string.second_description), backgroundColor = Color(0xFFD0BCFF), modifier = Modifier.weight(1f) ) } Row(Modifier.weight(1f)) { ComposableInfoCard( title = stringResource(R.string.third_title), description = stringResource(R.string.third_description), backgroundColor = Color(0xFFB69DF8), modifier = Modifier.weight(1f) ) ComposableInfoCard( title = stringResource(R.string.fourth_title), description = stringResource(R.string.fourth_description), backgroundColor = Color(0xFFF6EDFF), modifier = Modifier.weight(1f) ) } } } @Composable private fun ComposableInfoCard( title: String, description: String, backgroundColor: Color, modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxSize() .background(backgroundColor) .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title, modifier = Modifier.padding(bottom = 16.dp), fontWeight = FontWeight.Bold ) Text( text = description, textAlign = TextAlign.Justify ) } } @Preview(showBackground = true) @Composable fun ComposeQuadrantAppPreview() { ComposeQuadrantTheme { ComposeQuadrantApp() } }
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/MainActivity.kt
3331289616
package com.example.hcltechenviride import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.hcltechenviride", appContext.packageName) } }
HCLTechEnviRide/app/src/androidTest/java/com/example/hcltechenviride/ExampleInstrumentedTest.kt
1775178159
package com.example.hcltechenviride import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
HCLTechEnviRide/app/src/test/java/com/example/hcltechenviride/ExampleUnitTest.kt
3316737500
package com.example.hcltechenviride import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.appcompat.app.AppCompatActivity import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.google.firebase.auth.FirebaseAuth // Function to retrieve data from encrypted SharedPreferences fun checkUserRoleAndOpenActivity(context: Context) { // Retrieve the user's role from SharedPreferences val userRole = EncryptedSharedPrefs.getUserRole(context) // Determine the appropriate activity based on the user's role val intent = when (userRole) { "Admin" -> Intent(context, AdminHomeActivity::class.java) "Employee" -> Intent(context, EmpHomeActivity::class.java) "Security" -> Intent(context, SecHomeActivity::class.java) else -> Intent(context, EmpLoginActivity::class.java) // Default activity for unknown role } // Start the selected activity context.startActivity(intent) } class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Set the status bar color to transparent window.statusBarColor = Color.TRANSPARENT // Delay execution to show a splash screen effect Handler(Looper.getMainLooper()).postDelayed({ // Check if the user is authenticated (logged in) if (FirebaseAuth.getInstance().currentUser == null) { // If not authenticated, start the login activity startActivity(Intent(this, EmpLoginActivity::class.java)) } else { // If authenticated, determine the user's role and open the appropriate activity checkUserRoleAndOpenActivity(this) finish() } finish() }, 3000) // Show splash screen for 3 seconds } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/MainActivity.kt
2141068499
package com.example.hcltechenviride.fragments import android.content.ContentValues.TAG import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import com.example.hcltechenviride.Models.CurrentCycle import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.R import com.example.hcltechenviride.adapters.CarouselAdapter import com.example.hcltechenviride.databinding.FragmentEmpHomeBinding import com.example.hcltechenviride.utils.CURRENT_CYCLE_FOLDER import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.example.hcltechenviride.utils.HISTORY_FOLDER import com.example.hcltechenviride.utils.RETURNED_CYCLE_FOLDER import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase import com.google.zxing.integration.android.IntentIntegrator private const val i = 0 class EmpHomeFragment : Fragment() { private lateinit var binding: FragmentEmpHomeBinding @RequiresApi(Build.VERSION_CODES.O) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentEmpHomeBinding.inflate(inflater, container, false) // Set up ViewPager2 with adapter val viewPager = binding.viewPager2 val adapter = CarouselAdapter(requireContext(), listOf(R.drawable.pic0, R.drawable.pic1, R.drawable.pic2)) viewPager.adapter = adapter // Set up click listeners for scan and return buttons binding.scan.setOnClickListener { if (EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) < 1) { startQrCodeScanner() EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 1) } else { Toast.makeText(requireActivity(), "Can only request one cycle at a time", Toast.LENGTH_SHORT).show() } } binding.returnBack.setOnClickListener { if (EncryptedSharedPrefs.getCurrentCycleId(requireActivity()) != null || EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) > 0 ) { returnCurrentCycle(EncryptedSharedPrefs.getCurrentCycleId(requireActivity())!!) EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) EncryptedSharedPrefs.clearCurrentCycleId(requireActivity()) binding.cycleID.text = "Cycle ID : ${EncryptedSharedPrefs.getCurrentCycleId(requireActivity())}" Toast.makeText(requireActivity(), "Returned successfully", Toast.LENGTH_SHORT).show() } else { Toast.makeText(requireActivity(), "Don't have a cycle to return", Toast.LENGTH_SHORT).show() } } return binding.root } @RequiresApi(Build.VERSION_CODES.O) private fun startQrCodeScanner() { val integrator = IntentIntegrator.forSupportFragment(this) integrator.setOrientationLocked(true) // Set orientation to portrait integrator.setPrompt("Scan QR code containing cycle ID") integrator.initiateScan() } @RequiresApi(Build.VERSION_CODES.O) override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result != null) { if (result.contents == null) { // Scan cancelled or failed EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Log.d(TAG, "Scan cancelled or failed") Toast.makeText(requireActivity(), "Scan cancelled or failed", Toast.LENGTH_SHORT).show() } else { // QR code scanned successfully val scannedCycleId = result.contents Log.d(TAG, "Scanned cycle ID: $scannedCycleId") val checker = DocumentChecker() checker.checkDocument(CYCLE_FOLDER, scannedCycleId) { documentExists, isAllotted, isDamaged -> if (documentExists) { if (isAllotted == "False" && isDamaged == "False") { allotCycle(scannedCycleId, EncryptedSharedPrefs.getCurrentEmployeeId(requireActivity())!!) EncryptedSharedPrefs.setCurrentCycleId(requireActivity(), scannedCycleId) } else { EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Toast.makeText(requireActivity(), "Cycle already in use or Damaged", Toast.LENGTH_SHORT).show() } } else { EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Toast.makeText(requireActivity(), "Invalid QR Code", Toast.LENGTH_SHORT).show() } } } } else { EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Log.e(TAG, "Failed to parse activity result") Toast.makeText(requireActivity(), "Failed to parse activity result", Toast.LENGTH_SHORT).show() } } @RequiresApi(Build.VERSION_CODES.O) private fun allotCycle(scannedCycleId: String, empId: String) { val currentCycle = CurrentCycle(scannedCycleId, empId) val db = FirebaseFirestore.getInstance() db.collection(CURRENT_CYCLE_FOLDER).document(scannedCycleId).set(currentCycle) .addOnSuccessListener { db.collection(CYCLE_FOLDER).document(scannedCycleId).update("allotted", "True") .addOnSuccessListener { binding.cycleID.text = "Cycle ID : ${EncryptedSharedPrefs.getCurrentCycleId(requireActivity())}" Toast.makeText(requireActivity(), "Cycle allocated successfully", Toast.LENGTH_SHORT).show() }.addOnFailureListener { Log.e(TAG, "Error adding history: ${it.localizedMessage}") EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Toast.makeText(requireActivity(), "Failed to allocate cycle: ${it.localizedMessage}", Toast.LENGTH_SHORT).show() } }.addOnFailureListener { Log.e(TAG, "Error adding history: ${it.localizedMessage}") EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0) Toast.makeText(requireActivity(), "Failed to allocate cycle: ${it.localizedMessage}", Toast.LENGTH_SHORT).show() } } @RequiresApi(Build.VERSION_CODES.O) fun returnCurrentCycle(currCyId: String) { val db = FirebaseFirestore.getInstance() db.collection(CYCLE_FOLDER).document(currCyId).update("allotted", "False") .addOnSuccessListener { db.collection(CURRENT_CYCLE_FOLDER).document(currCyId).get() .addOnSuccessListener { documentSnapshot -> val currCycle: CurrentCycle = documentSnapshot.toObject<CurrentCycle>()!! val history: History = History(currCycle.cycleID, currCycle.empID, currCycle.allottedTime) db.collection(HISTORY_FOLDER).document().set(history) db.collection(RETURNED_CYCLE_FOLDER).document(currCyId).set(history) db.collection(Firebase.auth.currentUser!!.uid).document().set(history) }.addOnSuccessListener { db.collection(CURRENT_CYCLE_FOLDER).document(currCyId).delete() } }.addOnSuccessListener { Log.d(TAG, "Cycle returned Successfully") } } companion object { } } class DocumentChecker { fun checkDocument( collectionPath: String, documentName: String, onComplete: (Boolean, Any?, Any?) -> Unit ) { val db = FirebaseFirestore.getInstance() val collectionRef = db.collection(collectionPath) collectionRef.document(documentName).get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { val allotted = documentSnapshot.data?.get("allotted") val damaged = documentSnapshot.data?.get("damaged") onComplete(true, allotted, damaged) } else { onComplete(false, null, null) } }.addOnFailureListener { exception -> onComplete(false, null, null) } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpHomeFragment.kt
3361131554
package com.example.hcltechenviride.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.adapters.EmpHistoryRvAdapter import com.example.hcltechenviride.databinding.FragmentEmpHistoryBinding import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class EmpHistoryFragment : Fragment() { private lateinit var binding: FragmentEmpHistoryBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentEmpHistoryBinding.inflate(inflater, container, false) val historyList = ArrayList<History>() val adapter = EmpHistoryRvAdapter(requireContext(), historyList) binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) binding.rv.adapter = adapter // Fetch user history from Firestore and populate RecyclerView Firebase.firestore.collection(Firebase.auth.currentUser!!.uid) .orderBy("duration", Query.Direction.DESCENDING) .get().addOnSuccessListener { querySnapshot -> val tempList = ArrayList<History>() for (document in querySnapshot.documents) { val history: History = document.toObject<History>()!! tempList.add(history) } historyList.addAll(tempList) adapter.notifyDataSetChanged() } return binding.root } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpHistoryFragment.kt
1265979179
package com.example.hcltechenviride.fragments import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.hcltechenviride.EmpLoginActivity import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.FragmentEmpProfileBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class EmpProfileFragment : Fragment() { private lateinit var binding: FragmentEmpProfileBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentEmpProfileBinding.inflate(inflater, container, false) // Set logout button click listener binding.logout.setOnClickListener { if (EncryptedSharedPrefs.getCurrentCycleId(requireActivity()) != null || EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) > 0 ) { // Show alert dialog if user has an active cycle val builder = AlertDialog.Builder(requireContext()) builder.setTitle("Can't Logout") builder.setMessage("Please Return the cycle Before Logout") builder.setPositiveButton("OK") { dialog, which -> dialog.dismiss() } val dialog = builder.create() dialog.show() } else { // Logout user if no active cycle FirebaseAuth.getInstance().signOut() EncryptedSharedPrefs.clearAllData(requireActivity()) startActivity(Intent(requireActivity(), EmpLoginActivity::class.java)) requireActivity().finish() } } return binding.root } override fun onStart() { super.onStart() // Fetch user data and populate UI Firebase.firestore.collection(EMP_USER_NODE).document(Firebase.auth.currentUser!!.uid).get() .addOnSuccessListener { val user: User = it.toObject<User>()!! binding.name.text = user.name binding.id.text = user.employeeId binding.email.text = user.email binding.role.text = user.role } } override fun onResume() { super.onResume() } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpProfileFragment.kt
3122838965
package com.example.hcltechenviride.utils import android.content.Context import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys object EncryptedSharedPrefs { private const val SHARED_PREFS_NAME = "encrypted_shared_prefs" fun setCurrentEmployeeId(context: Context, empId: String) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().putString(CURRENT_EMPLOYEE_ID, empId ).apply() } fun getCurrentEmployeeId(context: Context): String? { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) return sharedPreferences.getString(CURRENT_EMPLOYEE_ID, null) } fun getUserRole(context: Context): String? { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) return sharedPreferences.getString(USER_ROLE, null) } fun setUserRole(context: Context, role: String) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().putString(USER_ROLE, role).apply() } fun clearUserRole(context: Context) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().remove(USER_ROLE).apply() } fun getCurrentCycleCount(context: Context): Int { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) return sharedPreferences.getInt(CURRENT_CYCLE_COUNT, 0) } fun setCurrentCycleCount(context: Context, count: Int) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().putInt(CURRENT_CYCLE_COUNT, count).apply() } fun clearCurrentCycleId(context: Context) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().remove(CURRENT_CYCLE_ID).apply() } fun getCurrentCycleId(context: Context): String? { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) return sharedPreferences.getString(CURRENT_CYCLE_ID, null) } fun setCurrentCycleId(context: Context, cycleId: String) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().putString(CURRENT_CYCLE_ID, cycleId).apply() } fun clearAllData(context: Context) { val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) val sharedPreferences = EncryptedSharedPreferences.create( SHARED_PREFS_NAME, masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) sharedPreferences.edit().remove(USER_ROLE).apply() sharedPreferences.edit().remove(CURRENT_CYCLE_ID).apply() sharedPreferences.edit().remove(CURRENT_EMPLOYEE_ID).apply() sharedPreferences.edit().remove(CURRENT_CYCLE_COUNT).apply() sharedPreferences.edit().remove(USER_ROLE).apply() } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/utils/EncryptedSharedPrefs.kt
830214968
package com.example.hcltechenviride.utils const val EMP_USER_NODE = "User" const val HISTORY_FOLDER = "History" const val CURRENT_CYCLE_FOLDER = "CurrentCycles" const val CYCLE_FOLDER = "Cycles" const val RETURNED_CYCLE_FOLDER = "ReturnedCycles" const val COMPLAINTS_FOLDER = "Complaints" const val USER_ROLE = "user_role" const val CURRENT_CYCLE_COUNT = "current_cycle_count" const val CURRENT_CYCLE_ID = "current_cycle_id" const val CURRENT_EMPLOYEE_ID = "current_employee_id"
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/utils/Constants.kt
2141869546
package com.example.hcltechenviride.Models import android.os.Build import androidx.annotation.RequiresApi import java.time.LocalDateTime import java.time.format.DateTimeFormatter class History { // Current LocalDateTime @RequiresApi(Build.VERSION_CODES.O) private val now = LocalDateTime.now() // Employee ID var empID: String? = null // Cycle ID var cycleID: String? = null // Duration of cycle usage var duration: String? = null constructor() // Constructor to initialize history details @RequiresApi(Build.VERSION_CODES.O) constructor(cycleID: String?, empID: String?, allottedTime: String?) { this.duration = "$allottedTime to ${now.format(DateTimeFormatter.ofPattern("dd-MM-yy HH:mm"))}" this.empID = empID this.cycleID = cycleID } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/History.kt
806162583
package com.example.hcltechenviride.Models import android.os.Build import androidx.annotation.RequiresApi import java.time.LocalDateTime import java.time.format.DateTimeFormatter class CurrentCycle { // Current date and time @RequiresApi(Build.VERSION_CODES.O) private val now = LocalDateTime.now() // Allotted time for the cycle @RequiresApi(Build.VERSION_CODES.O) var allottedTime: String? = null // Cycle ID var cycleID: String? = null // Employee ID var empID: String? = null constructor() // Constructor to initialize current cycle details @RequiresApi(Build.VERSION_CODES.O) constructor(cycleID: String, empID: String) { this.allottedTime = now.format(DateTimeFormatter.ofPattern("dd-MM-yy HH:mm")) this.cycleID = cycleID this.empID = empID } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/CurrentCycle.kt
1640080092
package com.example.hcltechenviride.Models class Cycle { // Cycle ID var cycleID: String? = null // Color of the cycle var color: String? = null // Location of the cycle var location: String? = null // Whether the cycle is allotted or not var allotted: String? = null // Whether the cycle is damaged or not var damaged: String? = null constructor() // Constructor to initialize cycle details constructor( cycleID: String?, color: String?, location: String?, allotted: String = "False", damaged: String = "False" ) { this.cycleID = cycleID this.color = color this.location = location this.allotted = allotted this.damaged = damaged } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/Cycle.kt
4065815262
package com.example.hcltechenviride.Models class User { // User role var role: String? = null // User name var name: String? = null // User employee ID var employeeId: String? = null // User email var email: String? = null // User password var password: String? = null constructor() // Constructor used for login constructor(email: String?, password: String?) { this.email = email this.password = password } // Constructor used for registration constructor( role: String?, name: String?, employeeId: String?, email: String?, password: String? ) { this.role = role this.name = name this.employeeId = employeeId this.email = email this.password = password } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/User.kt
2133470762
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.UserListRvDesignBinding class UserListRvAdapter(var context: Context, var userList: ArrayList<User>) : RecyclerView.Adapter<UserListRvAdapter.ViewHolder>() { // Inner class to hold the views for each list item inner class ViewHolder(var binding: UserListRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Called when RecyclerView needs a new ViewHolder override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // Inflate the item layout and create a new ViewHolder val binding = UserListRvDesignBinding.inflate( LayoutInflater.from(context), parent, false ) return ViewHolder(binding) } // Returns the total number of items in the data set held by the adapter override fun getItemCount(): Int { return userList.size } // Called by RecyclerView to display the data at the specified position @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: ViewHolder, position: Int) { // Get the data model based on position val userItem = userList[position] // Set the data to the views in the ViewHolder holder.binding.employeeId.text = userItem.employeeId holder.binding.role.text = userItem.role } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/UserListRvAdapter.kt
2732598959
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.CurrentCycle import com.example.hcltechenviride.databinding.AdminCycleInUseRvDesignBinding class AdminCycleInUseRvAdapter(var context: Context, var cycleInUseList: ArrayList<CurrentCycle>) : RecyclerView.Adapter<AdminCycleInUseRvAdapter.ViewHolder>() { inner class ViewHolder(var binding: AdminCycleInUseRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Inflate the layout and create ViewHolder instances override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = AdminCycleInUseRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Return the size of the cycleInUseList override fun getItemCount(): Int { return cycleInUseList.size } // Bind data to views in the ViewHolder @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currCycle = cycleInUseList[position] holder.binding.cycleID.text = currCycle.cycleID holder.binding.employeeId.text = currCycle.empID holder.binding.allottedTime.text = currCycle.allottedTime } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/AdminCycleInUseRvAdapter.kt
894917444
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.databinding.DamagedCycleListRvDesignBinding import com.example.hcltechenviride.utils.COMPLAINTS_FOLDER import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class DamagedCycleAdapter(var context: Context, var damagedCycleList: ArrayList<History>) : RecyclerView.Adapter<DamagedCycleAdapter.ViewHolder>() { inner class ViewHolder(var binding: DamagedCycleListRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Create ViewHolder instances override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DamagedCycleAdapter.ViewHolder { val binding = DamagedCycleListRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Return the size of the damagedCycleList override fun getItemCount(): Int { return damagedCycleList.size } @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: DamagedCycleAdapter.ViewHolder, position: Int) { // Bind data to views in the ViewHolder holder.binding.cycleID.text = damagedCycleList[position].cycleID holder.binding.employeeId.text = damagedCycleList[position].empID // Set up action for the 'repaired' button holder.binding.repaired.setOnClickListener { // Update Firestore to mark the cycle as repaired and delete its complaint document Firebase.firestore.collection(CYCLE_FOLDER).document(damagedCycleList[position].cycleID!!) .update("damaged", "False") Firebase.firestore.collection(COMPLAINTS_FOLDER).document(damagedCycleList[position].cycleID!!) .delete() // Remove the repaired cycle from the list and notify the adapter removeAt(position) } } // Remove an item at the specified position from the damagedCycleList private fun removeAt(position: Int) { damagedCycleList.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, damagedCycleList.size) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/DamagedCycleAdapter.kt
3485054485
package com.example.hcltechenviride.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.databinding.ReturnRvBinding import com.example.hcltechenviride.utils.COMPLAINTS_FOLDER import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.example.hcltechenviride.utils.RETURNED_CYCLE_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class ReturnedCycleAdapter(var context: Context, var returnedCycleList: ArrayList<History>) : RecyclerView.Adapter<ReturnedCycleAdapter.ViewHolder>() { // Inner class to hold the views for each list item inner class ViewHolder(var binding: ReturnRvBinding) : RecyclerView.ViewHolder(binding.root) // Called when RecyclerView needs a new ViewHolder override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ReturnedCycleAdapter.ViewHolder { // Inflate the item layout and create a new ViewHolder val binding = ReturnRvBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Returns the total number of items in the data set held by the adapter override fun getItemCount(): Int { return returnedCycleList.size } // Called by RecyclerView to display the data at the specified position override fun onBindViewHolder(holder: ReturnedCycleAdapter.ViewHolder, position: Int) { // Get the data model based on position val historyItem = returnedCycleList[position] // Bind data to the views in the ViewHolder holder.binding.cycleID.text = historyItem.cycleID holder.binding.duration.text = historyItem.duration // Set click listeners for complaint and accept buttons holder.binding.complain.setOnClickListener { // Handle complaint by adding to complaints collection, marking cycle as damaged, // and removing from returned cycles collection Firebase.firestore.collection(COMPLAINTS_FOLDER) .document(historyItem.cycleID!!) .set(historyItem) Firebase.firestore.collection(CYCLE_FOLDER) .document(historyItem.cycleID!!).update("damaged", "True") Firebase.firestore.collection(RETURNED_CYCLE_FOLDER) .document(historyItem.cycleID!!).delete() removeAt(position) } holder.binding.accept.setOnClickListener { // Accept return by removing from returned cycles collection Firebase.firestore.collection(RETURNED_CYCLE_FOLDER) .document(historyItem.cycleID!!).delete() removeAt(position) } } // Removes an item from the list and notifies the adapter about the change private fun removeAt(position: Int) { returnedCycleList.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, returnedCycleList.size) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/ReturnedCycleAdapter.kt
1906696136
package com.example.hcltechenviride.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.databinding.CarouselRvDesignBinding class CarouselAdapter(var context: Context,private val images: List<Int>) : RecyclerView.Adapter<CarouselAdapter.ViewHolder>() { inner class ViewHolder(var binding: CarouselRvDesignBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { var binding = CarouselRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val imageRes = images[position % images.size] holder.binding.imageView.setImageResource(imageRes) } override fun getItemCount(): Int = Int.MAX_VALUE }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/CarouselAdapter.kt
2939841132
package com.example.hcltechenviride.adapters import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { // Lists to store fragments and their corresponding titles private val fragmentList = mutableListOf<Fragment>() // List to hold fragments private val titleList = mutableListOf<String>() // List to hold titles override fun getCount(): Int { // Return the total number of fragments return fragmentList.size } override fun getItem(position: Int): Fragment { // Return the fragment at the specified position return fragmentList[position] } override fun getPageTitle(position: Int): CharSequence? { // Return the title of the fragment at the specified position return titleList[position] } fun addFragments(fragment: Fragment, title: String) { // Add a fragment and its title to the lists fragmentList.add(fragment) titleList.add(title) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/ViewPagerAdapter.kt
2827535352
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.Cycle import com.example.hcltechenviride.databinding.CycleListRvDesignBinding import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class CycleListRvAdapter(var context: Context, var cycleList: ArrayList<Cycle>) : RecyclerView.Adapter<CycleListRvAdapter.ViewHolder>() { inner class ViewHolder(var binding: CycleListRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Inflate the layout and create ViewHolder instances override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = CycleListRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Return the size of the cycleList override fun getItemCount(): Int { return cycleList.size } // Bind data to views in the ViewHolder @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.binding.root val cycleItem = cycleList[position] holder.binding.cycleID.text = cycleItem.cycleID holder.binding.colorAndLocation.text = "${cycleItem.color} - ${cycleItem.location}" // Set up click listener for the delete button holder.binding.delete.setOnClickListener { // Check if the cycle is currently allotted if (cycleList[position].allotted == "True") { // Display a toast message if the cycle is in use Toast.makeText(context, "Can't Delete Cycle is in use", Toast.LENGTH_SHORT).show() } else { // If the cycle is not in use, prompt the user for confirmation val builder = android.app.AlertDialog.Builder(context) builder.setTitle("Confirm Delete!") .setMessage("Do you want to delete this Cycle") // If confirmed, delete the cycle document from Firestore and remove it from the list .setNegativeButton("Confirm") { dialog, which -> Firebase.firestore.collection(CYCLE_FOLDER) .document(cycleList[position].cycleID!!).delete() removeAt(position) dialog.dismiss() } // If canceled, dismiss the dialog .setPositiveButton("Cancel") { dialog, which -> dialog.dismiss() } val dialog = builder.create() dialog.show() } } } // Remove an item at the specified position from the cycleList private fun removeAt(position: Int) { cycleList.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, cycleList.size) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/CycleListRvAdapter.kt
3159025810
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.databinding.AdminHistoryRvDesignBinding class AdminCycleHistoryRvAdapter(var context: Context, var historyList: ArrayList<History>) : RecyclerView.Adapter<AdminCycleHistoryRvAdapter.ViewHolder>() { inner class ViewHolder(var binding: AdminHistoryRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Inflate the layout and create ViewHolder instances override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = AdminHistoryRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Return the size of the historyList override fun getItemCount(): Int { return historyList.size } // Bind data to views in the ViewHolder @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: ViewHolder, position: Int) { val historyItem = historyList[position] holder.binding.cycleID.text = historyItem.cycleID holder.binding.employeeId.text = historyItem.empID holder.binding.duration.text = historyItem.duration } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/AdminCycleHistoryRvAdapter.kt
2333396584
package com.example.hcltechenviride.adapters import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.databinding.EmpHistoryRvDesignBinding class EmpHistoryRvAdapter(var context: Context, var historyList: ArrayList<History>) : RecyclerView.Adapter<EmpHistoryRvAdapter.ViewHolder>() { inner class ViewHolder(var binding: EmpHistoryRvDesignBinding) : RecyclerView.ViewHolder(binding.root) // Called when RecyclerView needs a new ViewHolder override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // Inflate the item layout and create a new ViewHolder val binding = EmpHistoryRvDesignBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Returns the total number of items in the data set held by the adapter override fun getItemCount(): Int { return historyList.size } // Called by RecyclerView to display the data at the specified position @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: ViewHolder, position: Int) { // Get the data model based on position val historyItem = historyList[position] // Bind data to the views in the ViewHolder holder.binding.cycleID.text = historyItem.cycleID holder.binding.duration.text = historyItem.duration } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/EmpHistoryRvAdapter.kt
299318287
package com.example.hcltechenviride import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.example.hcltechenviride.databinding.ActivityAdminHomeBinding import com.google.android.material.bottomnavigation.BottomNavigationView class AdminHomeActivity : AppCompatActivity() { private lateinit var binding: ActivityAdminHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Inflating the layout using view binding binding = ActivityAdminHomeBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView // Finding the navigation controller associated with the NavHostFragment val navController = findNavController(R.id.nav_host_fragment_activity_admin_home) // Setting up the bottom navigation view with the navigation controller navView.setupWithNavController(navController) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/AdminHomeActivity.kt
1149091874
package com.example.hcltechenviride import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.example.hcltechenviride.databinding.ActivitySecHomeBinding import com.google.android.material.bottomnavigation.BottomNavigationView class SecHomeActivity : AppCompatActivity() { private lateinit var binding: ActivitySecHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySecHomeBinding.inflate(layoutInflater) setContentView(binding.root) // Set up the bottom navigation view val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_sec_home) navView.setupWithNavController(navController) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/SecHomeActivity.kt
1471119190
package com.example.hcltechenviride import android.content.Intent import android.os.Bundle import android.text.Html import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.ActivityEmpLoginBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class EmpLoginActivity : AppCompatActivity() { // Using view binding to access UI elements private val binding by lazy { ActivityEmpLoginBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Customize the "Don't have an account?" text val text = "<font color=#FF000000>Don't have an account?</font> <font color=#1E88E5>Register</font>" binding.toRegister.text = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY) binding.loginBtn.setOnClickListener { if (binding.email.editText?.text.toString().isEmpty() || binding.password.editText?.text.toString().isEmpty() ) { Toast.makeText( this@EmpLoginActivity, "Please fill all the fields", Toast.LENGTH_SHORT ).show() } else { val user = User( binding.email.editText?.text.toString(), binding.password.editText?.text.toString() ) Firebase.auth.signInWithEmailAndPassword(user.email!!, user.password!!) .addOnCompleteListener { it -> if (it.isSuccessful) { // Fetch user details from Firestore Firebase.firestore.collection(EMP_USER_NODE) .document(Firebase.auth.currentUser!!.uid) .get().addOnSuccessListener { document -> val user: User = document.toObject<User>()!! // Store user role and employee ID in shared preferences EncryptedSharedPrefs.setUserRole(this, user.role!!) EncryptedSharedPrefs.setCurrentEmployeeId(this, user.employeeId!!) Toast.makeText(this@EmpLoginActivity, "Login Success", Toast.LENGTH_SHORT).show() } // Navigate to main activity on successful login startActivity( Intent( this@EmpLoginActivity, MainActivity::class.java ) ) finish() } else { // Show error message if login fails Toast.makeText( this@EmpLoginActivity, it.exception?.localizedMessage, Toast.LENGTH_SHORT ).show() } } } } binding.toRegister.setOnClickListener { // Navigate to registration activity when "Register" is clicked startActivity(Intent(this@EmpLoginActivity, SignUpActivity::class.java)) finish() } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/EmpLoginActivity.kt
2746154888
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.Cycle import com.example.hcltechenviride.adapters.CycleListRvAdapter import com.example.hcltechenviride.databinding.ActivityCycleListBinding import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class CycleListActivity : AppCompatActivity() { // Binding variable using lazy initialization private val binding by lazy { ActivityCycleListBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Initialize cycle list and adapter var cycleList = ArrayList<Cycle>() var adapter = CycleListRvAdapter(this, cycleList) // Set layout manager and adapter to RecyclerView binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) binding.rv.adapter = adapter // Retrieve cycle data from Firestore and populate the list Firebase.firestore.collection(CYCLE_FOLDER) .orderBy("cycleID", Query.Direction.ASCENDING).get().addOnSuccessListener { var tempList = ArrayList<Cycle>() for (i in it.documents) { var cycle: Cycle = i.toObject<Cycle>()!! // Convert Firestore document to Cycle object tempList.add(cycle) } cycleList.addAll(tempList) // Add retrieved cycles to the list adapter.notifyDataSetChanged() // Notify adapter about data change } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/CycleListActivity.kt
3169373913
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.adapters.AdminCycleHistoryRvAdapter import com.example.hcltechenviride.databinding.FragmentCycleHistoryBinding import com.example.hcltechenviride.utils.HISTORY_FOLDER import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class CycleHistoryFragment : Fragment() { private lateinit var binding: FragmentCycleHistoryBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentCycleHistoryBinding.inflate(inflater, container, false) // Initialize history list and adapter var historyList = ArrayList<History>() var adapter = AdminCycleHistoryRvAdapter(requireContext(), historyList) // Set layout manager and adapter to RecyclerView binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) binding.rv.adapter = adapter // Retrieve cycle history data from Firestore and populate the list Firebase.firestore.collection(HISTORY_FOLDER) .orderBy("duration", Query.Direction.DESCENDING).get().addOnSuccessListener { var tempList = ArrayList<History>() for (i in it.documents) { var history: History = i.toObject<History>()!! // Convert Firestore document to History object tempList.add(history) } historyList.addAll(tempList) // Add retrieved history items to the list adapter.notifyDataSetChanged() // Notify adapter about data change } return binding.root } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/CycleHistoryFragment.kt
2457115901
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.CurrentCycle import com.example.hcltechenviride.adapters.AdminCycleInUseRvAdapter import com.example.hcltechenviride.databinding.FragmentCyclesInUseBinding import com.example.hcltechenviride.utils.CURRENT_CYCLE_FOLDER import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class CyclesInUseFragment : Fragment() { private lateinit var binding: FragmentCyclesInUseBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentCyclesInUseBinding.inflate(inflater, container, false) // Initialize variables val cycleInUseList = ArrayList<CurrentCycle>() val adapter = AdminCycleInUseRvAdapter(requireContext(), cycleInUseList) // Set up RecyclerView binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) binding.rv.adapter = adapter // Fetch current cycles in use from Firestore Firebase.firestore.collection(CURRENT_CYCLE_FOLDER) .orderBy("allottedTime", Query.Direction.DESCENDING).get().addOnSuccessListener { querySnapshot -> val tempList = ArrayList<CurrentCycle>() // Iterate through the documents for (document in querySnapshot.documents) { // Convert document to CurrentCycle object and add to temporary list val cycle: CurrentCycle = document.toObject<CurrentCycle>()!! tempList.add(cycle) } // Add all cycles to the list cycleInUseList.addAll(tempList) // Hide text view if there are cycles in use if (cycleInUseList.isNotEmpty()) { binding.textView.visibility = View.INVISIBLE } // Notify adapter of data changes adapter.notifyDataSetChanged() } return binding.root } companion object { // Any companion object members can be added here if needed } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/CyclesInUseFragment.kt
667359312
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.hcltechenviride.adapters.ViewPagerAdapter import com.example.hcltechenviride.databinding.FragmentAdminHomeBinding class AdminHomeFragment : Fragment() { // Binding instance for the fragment private var _binding: FragmentAdminHomeBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentAdminHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Setup view pager and tab layout setupViewPager() } private fun setupViewPager() { // Initialize the view pager adapter val viewPagerAdapter = ViewPagerAdapter(childFragmentManager) // Add fragments to the adapter with their titles viewPagerAdapter.addFragments(CyclesInUseFragment(), "Cycles In Use") viewPagerAdapter.addFragments(CycleHistoryFragment(), "History") // Set the adapter to the view pager binding.viewPager.adapter = viewPagerAdapter // Connect the tab layout with the view pager binding.tabLayout.setupWithViewPager(binding.viewPager) } override fun onDestroyView() { super.onDestroyView() // Set the binding instance to null to prevent memory leaks _binding = null } companion object { } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/AdminHomeFragment.kt
877861520
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.adapters.UserListRvAdapter import com.example.hcltechenviride.databinding.ActivityUserListBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class UserListActivity : AppCompatActivity() { // Lazily initialize the binding private val binding by lazy { ActivityUserListBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Initialize variables val userList = ArrayList<User>() val adapter = UserListRvAdapter(this, userList) // Set up RecyclerView binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) binding.rv.adapter = adapter // Fetch user data from Firestore Firebase.firestore.collection(EMP_USER_NODE) .orderBy("role", Query.Direction.ASCENDING).get().addOnSuccessListener { querySnapshot -> val tempList = ArrayList<User>() // Iterate through the documents for (document in querySnapshot.documents) { // Check if the document is not the current user's document if (!document.id.equals(Firebase.auth.currentUser!!.uid)) { // Convert document to User object and add to temporary list val user: User = document.toObject<User>()!! tempList.add(user) } } // Add all users to the list and notify adapter userList.addAll(tempList) adapter.notifyDataSetChanged() } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/UserListActivity.kt
2326231760
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.hcltechenviride.Models.Cycle import com.example.hcltechenviride.databinding.ActivityAddCyclesBinding import com.example.hcltechenviride.utils.CYCLE_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class AddCyclesActivity : AppCompatActivity() { private val binding by lazy { ActivityAddCyclesBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Set up spinner for cycle color val cycleColor = binding.cycleColor val colors = listOf("Red", "Black", "Blue", "Green") val colorAdapter = ArrayAdapter(this@AddCyclesActivity, android.R.layout.simple_spinner_item, colors) colorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) cycleColor.adapter = colorAdapter // Set up spinner for cycle location val location = binding.location val locations = listOf( "Hyderabad", "Madurai", "Nagpur", "Vijayawada", "Lucknow", "Noida", "Chennai", "Bangalore" ) val locationAdapter = ArrayAdapter(this@AddCyclesActivity, android.R.layout.simple_spinner_item, locations) locationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) location.adapter = locationAdapter // Add button click listener binding.addBtn.setOnClickListener { val selectedColor = cycleColor.selectedItem.toString() val selectedLocation = location.selectedItem.toString() // Check if cycle ID is empty if (binding.cycleID.editText?.text.toString().isEmpty()) { Toast.makeText(this@AddCyclesActivity, "Please fill all the fields", Toast.LENGTH_SHORT).show() } else { // Get cycle ID val cycleId = binding.cycleID.editText?.text.toString() // Create Cycle object val cycle = Cycle(cycleId, selectedColor, selectedLocation) // Add cycle to Firestore Firebase.firestore.collection(CYCLE_FOLDER).document(cycle.cycleID!!).set(cycle) .addOnSuccessListener { Toast.makeText(this@AddCyclesActivity, "Cycle added successfully", Toast.LENGTH_SHORT).show() }.addOnFailureListener { Toast.makeText(this@AddCyclesActivity, "Failed adding cycle $cycleId", Toast.LENGTH_SHORT).show() } } } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/AddCyclesActivity.kt
3672116609
package com.example.hcltechenviride.fragments_admin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.adapters.DamagedCycleAdapter import com.example.hcltechenviride.databinding.FragmentAdminComplaintsBinding import com.example.hcltechenviride.utils.COMPLAINTS_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class AdminComplaintsFragment : Fragment() { private lateinit var binding: FragmentAdminComplaintsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Initialize adapter and list for damaged cycles var adapter: DamagedCycleAdapter var damagedCycleList = ArrayList<History>() // Inflate the layout for this fragment binding = FragmentAdminComplaintsBinding.inflate(inflater, container, false) // Set up RecyclerView with StaggeredGridLayoutManager binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) adapter = DamagedCycleAdapter(requireContext(), damagedCycleList) binding.rv.adapter = adapter // Retrieve data from Firestore collection Firebase.firestore.collection(COMPLAINTS_FOLDER).get().addOnSuccessListener { querySnapshot -> val tempList = ArrayList<History>() for (document in querySnapshot.documents) { // Convert each document to History object and add to list val damagedCycle: History = document.toObject<History>()!! tempList.add(damagedCycle) } // Update list and UI with data damagedCycleList.addAll(tempList) binding.cyCount.text = "Damaged Cycles : ${damagedCycleList.size}" adapter.notifyDataSetChanged() } return binding.root } companion object { } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/AdminComplaintsFragment.kt
790598280
package com.example.hcltechenviride.fragments_admin import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.hcltechenviride.databinding.FragmentAdminManageBinding class AdminManageFragment : Fragment() { private lateinit var binding: FragmentAdminManageBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentAdminManageBinding.inflate(inflater, container, false) // Button click listeners to navigate to different activities binding.addCycleBtn.setOnClickListener { startActivity(Intent(requireActivity(), AddCyclesActivity::class.java)) } binding.cycleList.setOnClickListener { startActivity(Intent(requireActivity(), CycleListActivity::class.java)) } binding.userList.setOnClickListener { startActivity(Intent(requireActivity(), UserListActivity::class.java)) } return binding.root } companion object { } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/AdminManageFragment.kt
1330029834
package com.example.hcltechenviride.fragments_admin import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.hcltechenviride.EmpLoginActivity import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.FragmentAdminProfileBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class AdminProfileFragment : Fragment() { private lateinit var binding: FragmentAdminProfileBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentAdminProfileBinding.inflate(inflater, container,false) // Logout functionality binding.logout.setOnClickListener { FirebaseAuth.getInstance().signOut() EncryptedSharedPrefs.clearAllData(requireActivity()) startActivity(Intent(requireActivity(),EmpLoginActivity::class.java)) requireActivity().finish() } return binding.root } override fun onStart() { super.onStart() // Retrieve user data from Firestore and populate profile Firebase.firestore.collection(EMP_USER_NODE).document(Firebase.auth.currentUser!!.uid).get() .addOnSuccessListener { val user:User = it.toObject<User>()!! // Convert Firestore document to User object binding.name.text = user.name binding.id.text = user.employeeId binding.email.text = user.email binding.role.text = user.role } } override fun onResume() { super.onResume() } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_admin/AdminProfileFragment.kt
4073819514
package com.example.hcltechenviride import android.content.Intent import android.os.Bundle import android.text.Html import android.widget.ArrayAdapter import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.ActivitySignUpBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class SignUpActivity : AppCompatActivity() { // Using view binding to access UI elements private val binding by lazy { ActivitySignUpBinding.inflate(layoutInflater) } private lateinit var user: User override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Customize the "Already have an account?" text val text = "<font color=#FF000000>Already have an account?</font> <font color=#1E88E5>Login</font>" binding.toLogin.text = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY) user = User() // Initialize the Spinner with user roles val spinnerUserRole = binding.userRole val roles = listOf("Employee", "Security") val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, roles) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerUserRole.adapter = adapter binding.registerBtn.setOnClickListener { // Retrieve selected role from Spinner val selectedRole = spinnerUserRole.selectedItem.toString() // Check if all fields are filled if (binding.name.editText?.text.toString().isEmpty() || binding.id.editText?.text.toString().isEmpty() || binding.email.editText?.text.toString().isEmpty() || binding.password.editText?.text.toString().isEmpty()) { Toast.makeText( this@SignUpActivity, "Please fill all the fields", Toast.LENGTH_SHORT ).show() } else { // Create user in Firebase Authentication FirebaseAuth.getInstance().createUserWithEmailAndPassword( binding.email.editText?.text.toString(), binding.password.editText?.text.toString() ).addOnCompleteListener { result -> if (result.isSuccessful) { // Set user details user.name = binding.name.editText?.text.toString() user.employeeId = binding.id.editText?.text.toString() user.email = binding.email.editText?.text.toString() user.password = binding.password.editText?.text.toString() user.role = selectedRole // Store selected role // Insert user details into Firestore Firebase.firestore.collection(EMP_USER_NODE) .document(Firebase.auth.currentUser!!.uid).set(user) .addOnSuccessListener { // Navigate to login activity on successful registration startActivity( Intent( this@SignUpActivity, EmpLoginActivity::class.java ) ) finish() Toast.makeText( this@SignUpActivity, "Registration Success", Toast.LENGTH_SHORT ).show() } } else { // Show error message if registration fails Toast.makeText( this@SignUpActivity, result.exception?.localizedMessage, Toast.LENGTH_SHORT ).show() } } } } binding.toLogin.setOnClickListener { // Navigate to login activity when "Login" is clicked startActivity(Intent(this@SignUpActivity, EmpLoginActivity::class.java)) finish() } } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/SignUpActivity.kt
1009721775
package com.example.hcltechenviride import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.example.hcltechenviride.databinding.ActivityEmpHomeBinding import com.google.android.material.bottomnavigation.BottomNavigationView class EmpHomeActivity : AppCompatActivity() { private lateinit var binding: ActivityEmpHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Inflating the layout using view binding binding = ActivityEmpHomeBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView // Finding the navigation controller associated with the NavHostFragment val navController = findNavController(R.id.nav_host_fragment_activity_emp_home) // Setting up the bottom navigation view with the navigation controller navView.setupWithNavController(navController) } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/EmpHomeActivity.kt
4022238660
package com.example.hcltechenviride.fragments_security import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.hcltechenviride.Models.History import com.example.hcltechenviride.adapters.ReturnedCycleAdapter import com.example.hcltechenviride.databinding.FragmentSecHomeBinding import com.example.hcltechenviride.utils.RETURNED_CYCLE_FOLDER import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class SecHomeFragment : Fragment() { private lateinit var binding: FragmentSecHomeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Initialize variables var adapter: ReturnedCycleAdapter var returnedCycleList = ArrayList<History>() // Inflate the layout for this fragment binding = FragmentSecHomeBinding.inflate(inflater, container, false) binding.rv.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) adapter = ReturnedCycleAdapter(requireContext(), returnedCycleList) binding.rv.adapter = adapter // Fetch data from Firestore Firebase.firestore.collection(RETURNED_CYCLE_FOLDER).get().addOnSuccessListener { querySnapshot -> val tempList = ArrayList<History>() // Iterate through the documents for (document in querySnapshot.documents) { // Convert each document to a History object and add it to the list val returnedCycle: History = document.toObject<History>()!! tempList.add(returnedCycle) } returnedCycleList.addAll(tempList) // Update the UI with the count of pending cycles binding.cyCount.text = "Pending Cycles : ${returnedCycleList.size}" adapter.notifyDataSetChanged() } return binding.root } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_security/SecHomeFragment.kt
3284536534
package com.example.hcltechenviride.fragments_security import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.hcltechenviride.EmpLoginActivity import com.example.hcltechenviride.Models.User import com.example.hcltechenviride.databinding.FragmentSecProfileBinding import com.example.hcltechenviride.utils.EMP_USER_NODE import com.example.hcltechenviride.utils.EncryptedSharedPrefs import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase class SecProfileFragment : Fragment() { private lateinit var binding: FragmentSecProfileBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentSecProfileBinding.inflate(inflater, container, false) binding.logout.setOnClickListener { FirebaseAuth.getInstance().signOut() EncryptedSharedPrefs.clearAllData(requireActivity()) startActivity(Intent(requireActivity(), EmpLoginActivity::class.java)) requireActivity().finish() } return binding.root } override fun onStart() { super.onStart() Firebase.firestore.collection(EMP_USER_NODE).document(Firebase.auth.currentUser!!.uid).get() .addOnSuccessListener { documentSnapshot -> val user: User? = documentSnapshot.toObject<User>() user?.let { binding.name.text = user.name binding.id.text = user.employeeId binding.email.text = user.email binding.role.text = user.role } } } override fun onResume() { super.onResume() } }
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments_security/SecProfileFragment.kt
3832826143
package com.teamsparta.courseregistration2 import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class CourseRegistration2ApplicationTests { @Test fun contextLoads() { } }
Todolist2/src/test/kotlin/com/teamsparta/courseregistration2/CourseRegistration2ApplicationTests.kt
2219646726
package com.teamsparta.courseregistration2 import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class CourseRegistration2Application fun main(args: Array<String>) { runApplication<CourseRegistration2Application>(*args) }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/CourseRegistration2Application.kt
3277494322
package com.teamsparta.courseregistration2 import io.swagger.v3.oas.models.Components import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.oas.models.info.Info import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class SwaggerConfig { @Bean fun openAPI(): OpenAPI = OpenAPI() .components(Components()) .info( Info() .title("ํ• ์ผ") .description("Course API schema") .version("1.0.0") ) }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/SwaggerConfig.kt
2561773335
package com.teamsparta.courseregistration2.domain.dto import com.teamsparta.courseregistration2.domain.Comment import java.time.LocalDateTime data class CommentDto( val id: Long?, val content: String?, val author: String?, val createdDate: LocalDateTime? ) { constructor(comment: Comment) : this( id = comment.id, content = comment.content, author = comment.author, createdDate = comment.createdDate ?: LocalDateTime.now() ) } data class CreateCommentDto( val content: String, val author: String, val password: String ) data class UpdateCommentDto( val id: Long, val content: String, val password: String )
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/dto/CommentDto.kt
2322839414
package com.teamsparta.courseregistration2.domain.dto import com.teamsparta.courseregistration2.domain.Comment import java.time.LocalDateTime data class TaskDto( var id: Long? = null, var title: String, var content: String, var writer: String, var createdAt: LocalDateTime = LocalDateTime.now() ) data class TaskDetails( val id: Long?, val title: String, val content: String, val writer: String, val createdAt: LocalDateTime?, val comments: List<Comment> )
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/dto/TaskDto.kt
633538691
package com.teamsparta.courseregistration2.domain.repository import com.teamsparta.courseregistration2.domain.Comment import org.springframework.data.jpa.repository.JpaRepository interface CommentRepository : JpaRepository<Comment, Long> { fun findByTaskId(taskId: Long): List<Comment> }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/repository/CommentRepository.kt
1577263637
package com.teamsparta.courseregistration2.domain.repository import com.teamsparta.courseregistration2.domain.Task import org.springframework.data.jpa.repository.JpaRepository interface TaskRepository : JpaRepository<Task, Long>
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/repository/TaskRepository.kt
2004335391
package com.teamsparta.courseregistration2.domain data class CommentRequest( val content: String, val author: String, val password: String, val taskId: Long )
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/CommentRequest.kt
4107697426
package com.teamsparta.courseregistration2.domain.controller import com.fasterxml.jackson.annotation.JsonView import com.teamsparta.courseregistration2.domain.Task import com.teamsparta.courseregistration2.domain.Views import com.teamsparta.courseregistration2.domain.repository.CommentRepository import com.teamsparta.courseregistration2.domain.repository.TaskRepository import com.teamsparta.courseregistration2.domain.service.TaskService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.util.* @RestController @RequestMapping("/tasks") class TaskController( private val taskService: TaskService, private val taskRepository: TaskRepository, private val commentRepository: CommentRepository ) { @JsonView(Views.Summary::class) @GetMapping("") fun getTasks(): ResponseEntity<List<Task>> { val tasks = taskService.getAllTasks() return ResponseEntity(tasks, HttpStatus.OK) } @GetMapping("/{id}") fun getTask(@PathVariable id: Long): ResponseEntity<Task> { val task = taskService.getTaskById(id).orElseThrow { NoSuchElementException("Task with id $id not found") } return ResponseEntity(task, HttpStatus.OK) } @PostMapping("") fun createTask(@RequestBody task: Task): ResponseEntity<Task> { val newTask = taskService.createTask(task) return ResponseEntity(newTask, HttpStatus.CREATED) } @PutMapping("/{id}") fun updateTask(@PathVariable id: Long, @RequestBody task: Task): ResponseEntity<Optional<Task>> { val updatedTask = taskService.updateTask(id, task) return ResponseEntity(updatedTask, HttpStatus.OK) } @DeleteMapping("/{id}") fun deleteTask(@PathVariable id: Long): ResponseEntity<Void> { taskService.deleteTask(id) return ResponseEntity(HttpStatus.NO_CONTENT) } @PutMapping("/{id}/complete") fun completeTask(@PathVariable id: Long): ResponseEntity<Task> { val task = taskService.getTaskById(id).orElseThrow { NoSuchElementException("Task with id $id not found") } val completedTask = taskService.updateTask(id, task).orElseThrow { NoSuchElementException("Task with id $id not found after update") } return ResponseEntity(completedTask, HttpStatus.OK) } @DeleteMapping("") fun deleteAllTasks(): ResponseEntity<Void> { taskService.deleteAllTasks() return ResponseEntity(HttpStatus.NO_CONTENT) } }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/controller/TaskController.kt
1915964448
package com.teamsparta.courseregistration2.domain.controller import com.teamsparta.courseregistration2.domain.Comment import com.teamsparta.courseregistration2.domain.repository.CommentRepository import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/comments") class CommentController(private val commentRepository: CommentRepository) { @PostMapping fun createComment(@RequestBody comment: Comment): ResponseEntity<Comment> { val savedComment = commentRepository.save(comment) return ResponseEntity.ok(savedComment) } @GetMapping("/{commentId}") fun getComment(@PathVariable commentId: Long): ResponseEntity<Comment> { val comment = commentRepository.findById(commentId) .orElseThrow { IllegalArgumentException("Comment not found with id $commentId") } return ResponseEntity.ok(comment) } @PutMapping("/{commentId}") fun updateComment(@PathVariable commentId: Long, @RequestBody commentRequest: Comment): ResponseEntity<Comment> { val existingComment = commentRepository.findById(commentId) .orElseThrow { IllegalArgumentException("Comment not found with id $commentId") } existingComment.content = commentRequest.content val updatedComment = commentRepository.save(existingComment) return ResponseEntity.ok(updatedComment) } @DeleteMapping("/{commentId}") fun deleteComment(@PathVariable commentId: Long): ResponseEntity<Void> { val comment = commentRepository.findById(commentId) .orElseThrow { IllegalArgumentException("Comment not found with id $commentId") } commentRepository.delete(comment) return ResponseEntity.ok().build() } }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/controller/CommentController.kt
1674882582
package com.teamsparta.courseregistration2.domain import com.fasterxml.jackson.annotation.JsonIgnore import jakarta.persistence.* import java.time.LocalDateTime @Entity class Comment( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = true) var content: String? = null, @Column(nullable = true) var author: String? = null, @Column(nullable = true) var password: String? = null, @Column(nullable = false) var createdDate: LocalDateTime = LocalDateTime.now() ) { // Task ์ •๋ณด๋Š” JSON์œผ๋กœ ๋ณ€ํ™˜ ์‹œ ์ œ์™ธ @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "task_id") var task: Task? = null constructor(content: String, author: String, password: String): this(null, content, author, password, LocalDateTime.now()) }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/Comment.kt
1958231068
package com.teamsparta.courseregistration2.domain import com.fasterxml.jackson.annotation.JsonView import jakarta.persistence.* import java.time.LocalDateTime @Entity data class Task( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, var title: String = "", var content: String = "", var writer: String = "", var createdAt: LocalDateTime = LocalDateTime.now(), // ์™„๋ฃŒ ์—ฌ๋ถ€ ํ•„๋“œ ์ถ”๊ฐ€ var isCompleted: Boolean = false, @JsonView(Views.Detail::class) @OneToMany(mappedBy = "task", cascade = [CascadeType.ALL], orphanRemoval = true) var comments: List<Comment> = ArrayList() ) { constructor() : this(id = null) // ์™„๋ฃŒ ์ƒํƒœ ๋ณ€๊ฒฝ ๋ฉ”์†Œ๋“œ ์ถ”๊ฐ€ fun completeTask() { this.isCompleted = true } } interface Views { interface Summary interface Detail : Summary }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/Task.kt
3448582946
package com.teamsparta.courseregistration2.domain.service import com.teamsparta.courseregistration2.domain.Task import com.teamsparta.courseregistration2.domain.repository.TaskRepository import org.springframework.data.domain.Sort import org.springframework.stereotype.Service import java.util.* @Service class TaskService(private val taskRepository: TaskRepository) { fun getAllTasks(): List<Task> { val tasks = taskRepository.findAll(Sort.by(Sort.Direction.DESC, "createdAt")) return tasks } fun getTaskById(id: Long): Optional<Task> { return taskRepository.findById(id) } fun createTask(task: Task): Task { return taskRepository.save(task) } fun updateTask(id: Long, newTask: Task): Optional<Task> { return taskRepository.findById(id).map { existingTask -> updateTaskDetails(existingTask, newTask) taskRepository.save(existingTask) } } private fun updateTaskDetails(existingTask: Task, newTask: Task) { existingTask.title = newTask.title existingTask.content = newTask.content existingTask.writer = newTask.writer } fun deleteTask(id: Long) { return taskRepository.deleteById(id) } fun deleteAllTasks() { TODO("Not yet implemented") } }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/service/TaskService.kt
4008372404
package com.teamsparta.courseregistration2.domain.service import com.teamsparta.courseregistration2.domain.Comment import com.teamsparta.courseregistration2.domain.dto.CommentDto import com.teamsparta.courseregistration2.domain.dto.CreateCommentDto import com.teamsparta.courseregistration2.domain.dto.UpdateCommentDto import com.teamsparta.courseregistration2.domain.repository.CommentRepository import org.springframework.stereotype.Service import java.time.LocalDateTime @Service class CommentService( private val commentRepository: CommentRepository ) { fun createComment(dto: CreateCommentDto): CommentDto { val comment = Comment( content = dto.content, author = dto.author, password = dto.password, createdDate = LocalDateTime.now() ) commentRepository.save(comment) return CommentDto( id = comment.id, content = comment.content, author = comment.author, createdDate = comment.createdDate ) } fun getAllComments(): List<CommentDto> { return commentRepository.findAll().map { comment -> CommentDto( id = comment.id, content = comment.content, author = comment.author, createdDate = comment.createdDate ) } } fun updateComment(dto: UpdateCommentDto): CommentDto { val comment = commentRepository.findById(dto.id) .orElseThrow { NoSuchElementException("No comment found with id ${dto.id}") } if (comment.password != dto.password) { throw IllegalArgumentException("Invalid password") } comment.content = dto.content commentRepository.save(comment) return CommentDto( id = comment.id, content = comment.content, author = comment.author, createdDate = comment.createdDate ) } fun deleteComment(id: Long, password: String) { val comment = commentRepository.findById(id) .orElseThrow { NoSuchElementException("No comment found with id $id") } if (comment.password != password) { throw IllegalArgumentException("Invalid password") } commentRepository.delete(comment) } }
Todolist2/src/main/kotlin/com/teamsparta/courseregistration2/domain/service/CommentService.kt
280212361
package com.example.apiapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.apiapplication", appContext.packageName) } }
API_Android_Live/app/src/androidTest/java/com/example/apiapplication/ExampleInstrumentedTest.kt
584312765
package com.example.apiapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
API_Android_Live/app/src/test/java/com/example/apiapplication/ExampleUnitTest.kt
1533465154
package com.example.apiapplication.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.apiapplication.data.Repository import com.example.apiapplication.data.remote.CatAPI import kotlinx.coroutines.launch class CatViewModel : ViewModel() { private val repository = Repository(CatAPI) val facts = repository.facts init { loadData() } private fun loadData() { viewModelScope.launch { repository.getFacts() } } }
API_Android_Live/app/src/main/java/com/example/apiapplication/ui/CatViewModel.kt
857684902
package com.example.apiapplication.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import com.example.apiapplication.R import com.example.apiapplication.adapter.ItemAdapter import com.example.apiapplication.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private lateinit var binding : FragmentHomeBinding private val viewModel: CatViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentHomeBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val adapter = ItemAdapter() binding.homeRecylcer.adapter = adapter viewModel.facts.observe(viewLifecycleOwner) { adapter.submitList(it) } } }
API_Android_Live/app/src/main/java/com/example/apiapplication/ui/HomeFragment.kt
2934583466
package com.example.apiapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
API_Android_Live/app/src/main/java/com/example/apiapplication/MainActivity.kt
2728822886
package com.example.apiapplication.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.apiapplication.data.CatFact import com.example.apiapplication.databinding.ListItemBinding class ItemAdapter() : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() { private var dataset = listOf<CatFact>() inner class ItemViewHolder(val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) @SuppressLint("NotifyDataSetChanged") fun submitList(newList: List<CatFact>) { dataset = newList notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val binding = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ItemViewHolder(binding) } override fun getItemCount(): Int { return dataset.size } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val fact = dataset[position] holder.binding.itemTV.text = fact.text } }
API_Android_Live/app/src/main/java/com/example/apiapplication/adapter/ItemAdapter.kt
2672596654
package com.example.apiapplication.data import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.apiapplication.data.remote.CatAPI import java.lang.Exception class Repository(private val api: CatAPI) { private val _facts = MutableLiveData<List<CatFact>>() val facts: LiveData<List<CatFact>> get() = _facts suspend fun getFacts() { try { _facts.value = api.retrofitService.getFacts() } catch (e : Exception) { Log.d("Repo", "$e") } } }
API_Android_Live/app/src/main/java/com/example/apiapplication/data/Repository.kt
2455205507
package com.example.apiapplication.data class CatFact( val text : String )
API_Android_Live/app/src/main/java/com/example/apiapplication/data/CatFact.kt
1796524743
package com.example.apiapplication.data.remote import com.example.apiapplication.data.CatFact import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET const val BASE_URL = "https://cat-fact.herokuapp.com/" private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .baseUrl(BASE_URL) .build() interface CatApiService { @GET("facts") suspend fun getFacts(): List<CatFact> } object CatAPI { val retrofitService: CatApiService by lazy { retrofit.create(CatApiService::class.java) } }
API_Android_Live/app/src/main/java/com/example/apiapplication/data/remote/CatApiService.kt
3539427029
package cloud.csonic.labgradle import cloud.csonic.labgradle.api.CustomersApi import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.assertj.core.api.Assertions.assertThat @SpringBootTest class LabgradleApplicationTests(@Autowired val customersApi: CustomersApi){ @Test fun contextLoads() { assertThat(customersApi).isNotNull } }
galaxy-jenkins-lab-gradle/src/test/kotlin/cloud/csonic/labgradle/LabgradleApplicationTests.kt
3716404411
package cloud.csonic.labgradle.api import cloud.csonic.labgradle.excepions.CustomerNotFound import cloud.csonic.labgradle.model.Customer import cloud.csonic.labgradle.service.CustomerService import com.ninjasquad.springmockk.MockkBean import io.mockk.clearMocks import io.mockk.confirmVerified import io.mockk.every import io.mockk.verify import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.hamcrest.Matchers.hasSize import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.http.MediaType import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* @WebMvcTest(CustomersApi::class) internal class CustomersApiTest(@Autowired val mockMvc: MockMvc) { @MockkBean lateinit var customerService: CustomerService @BeforeEach fun setUp() { } @AfterEach fun tearDown() { clearMocks(customerService) } @Test fun `check mocks & objects`() { assertThat(mockMvc).isNotNull assertThat(customerService).isNotNull } @Test fun getAll() { // Preparing data val list = listOf(Customer(1,"lastName1","name1"),Customer(2,"lastName2","name2")) // Mocks & Stubs configuration every { customerService.findAll() } returns list // Business logic execution mockMvc.perform(get("/customers")) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("\$.customers", hasSize<Any>(2))) .andExpect(jsonPath("\$.customers[0].id").value(1)) .andExpect(jsonPath("\$.customers[0].lastName").value("lastName1")) .andExpect(jsonPath("\$.customers[0].name").value("name1")) .andExpect(jsonPath("\$.customers[1].id").value(2)) .andExpect(jsonPath("\$.customers[1].lastName").value("lastName2")) .andExpect(jsonPath("\$.customers[1].name").value("name2")) // Validating results // Validating mocks behaviour verify(exactly = 1) { customerService.findAll()} confirmVerified(customerService) } @Test fun getById() { // Preparing data val customer1 = Customer(1,"lastName1","name1") // Mocks & Stubs configuration every { customerService.findById(1) } returns customer1 // Business logic execution mockMvc.perform(get("/customers/1")) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) // Validating results // Validating mocks behaviour verify(exactly = 1) { customerService.findById(1) } confirmVerified(customerService) } @Test fun `customer didn't find`() { // Preparing data // Mocks & Stubs configuration every { customerService.findById(1) } throws CustomerNotFound("Cliente no encontrado") // Business logic execution mockMvc.perform(get("/customers/1")) .andExpect(status().isNotFound) // Validating results // Validating mocks behaviour verify(exactly = 1) { customerService.findById(1) } confirmVerified(customerService) } }
galaxy-jenkins-lab-gradle/src/test/kotlin/cloud/csonic/labgradle/api/CustomersApiTest.kt
1950389644
package cloud.csonic.labgradle.model data class Customer ( val id: Long, val lastName: String, val name: String )
galaxy-jenkins-lab-gradle/src/main/kotlin/cloud/csonic/labgradle/model/Customer.kt
3167000082
package cloud.csonic.labgradle.excepions class CustomerNotFound(message:String) : Exception(message)
galaxy-jenkins-lab-gradle/src/main/kotlin/cloud/csonic/labgradle/excepions/CustomerNotFound.kt
2178253254
package cloud.csonic.labgradle.api.dto import cloud.csonic.labgradle.model.Customer data class CustomersDto (var customers: List<Customer>) data class CustomerDto (var customer: Customer)
galaxy-jenkins-lab-gradle/src/main/kotlin/cloud/csonic/labgradle/api/dto/CustomersDto.kt
1952241893
package cloud.csonic.labgradle.api import cloud.csonic.labgradle.api.dto.CustomerDto import cloud.csonic.labgradle.api.dto.CustomersDto import cloud.csonic.labgradle.excepions.CustomerNotFound import cloud.csonic.labgradle.service.CustomerService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.net.http.HttpResponse @RestController @RequestMapping(value = ["/customers"]) class CustomersApi(val customerService: CustomerService){ @GetMapping fun getAll() = CustomersDto(customerService.findAll()) @GetMapping("{id}") fun getById(@PathVariable("id") id:Long): ResponseEntity<CustomerDto> { return try { ResponseEntity.ok(CustomerDto(customerService.findById(id))) }catch (e:CustomerNotFound){ ResponseEntity(HttpStatus.NOT_FOUND); } } }
galaxy-jenkins-lab-gradle/src/main/kotlin/cloud/csonic/labgradle/api/CustomersApi.kt
4291121772
package cloud.csonic.labgradle.service import cloud.csonic.labgradle.excepions.CustomerNotFound import cloud.csonic.labgradle.model.Customer import org.springframework.stereotype.Service interface CustomerService { fun findAll(): List<Customer> fun findById(id:Long): Customer } @Service class CustomerServiceImpl: CustomerService{ var list = listOf( Customer(1,"lastName01","name01"), Customer(2,"lastName02","name02") ) override fun findAll() = list override fun findById(id:Long) = list.find { it.id==id } ?: throw CustomerNotFound("Cliente $id no encontrado") }
galaxy-jenkins-lab-gradle/src/main/kotlin/cloud/csonic/labgradle/service/CustomerService.kt
4068103528