content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.project8_classc.ui.home.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.repository.KontakRepository
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.io.IOException
sealed class KontakUIState{
data class Success(val kontak: List<Kontak>) : KontakUIState()
object Error : KontakUIState()
object Loading : KontakUIState()
}
class HomeViewModel(private val kontakRepository: KontakRepository) : ViewModel(){
var kontakUIState: KontakUIState by mutableStateOf(KontakUIState.Loading)
private set
init {
getKontak()
}
fun getKontak(){
viewModelScope.launch {
kontakUIState = KontakUIState.Loading
kontakUIState = try {
KontakUIState.Success(kontakRepository.getKontak())
}catch (e: IOException){
KontakUIState.Error
}catch (e : HttpException){
KontakUIState.Error
}
}
}
fun deleteKontak(id: Int){
viewModelScope.launch {
try {
kontakRepository.deleteKontak(id)
}catch (e: IOException){
KontakUIState.Error
}catch (e: HttpException){
KontakUIState.Error
}
}
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/home/viewmodel/HomeViewModel.kt | 3416876544 |
package com.example.project8_classc.ui.home.screen
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
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.project8_classc.R
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.navigation.DestinasiNavigasi
import com.example.project8_classc.ui.home.viewmodel.HomeViewModel
import com.example.project8_classc.ui.home.viewmodel.KontakUIState
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.project8_classc.ui.PenyediaViewModel
import com.example.project8_classc.ui.TopAppBarKontak
import com.example.project8_classc.ui.theme.Project8_ClassCTheme
object DestinasiHome : DestinasiNavigasi{
override val route = "home"
override val titleRes = "Kontak"
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
navigateToItemEntry: () -> Unit,
modifier: Modifier = Modifier,
onDetailClick: (Int) -> Unit = {},
viewModel: HomeViewModel = viewModel(factory = PenyediaViewModel.Factory)
){
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBarKontak(
title = DestinasiHome.titleRes ,
canNavigasiBack = false,
scrollBehavior = scrollBehavior
)
},
floatingActionButton = {
FloatingActionButton(
onClick = navigateToItemEntry,
shape = MaterialTheme.shapes.medium,
modifier = Modifier.padding(18.dp)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add Kontak"
)
}
},
) { innerPadding ->
HomeStatus(
kontakUIState = viewModel.kontakUIState ,
retryAction = {
viewModel.getKontak()
},
modifier = Modifier.padding(innerPadding),
onDetailClick = onDetailClick,
onDeleteClick = {
viewModel.deleteKontak(it.id)
viewModel.getKontak()
}
)
}
}
@Composable
fun HomeStatus(
kontakUIState: KontakUIState,
retryAction: () -> Unit,
modifier: Modifier = Modifier,
onDeleteClick: (Kontak) -> Unit = {},
onDetailClick: (Int) -> Unit
){
when (kontakUIState){
is KontakUIState.Loading -> OnLoading(modifier.fillMaxSize())
is KontakUIState.Success -> KontakLayout(
kontak = kontakUIState.kontak,
modifier = modifier.fillMaxWidth(),
onDetailClick = {
onDetailClick(it.id)
}
) {
onDeleteClick(it)
}
is KontakUIState.Error -> OnError(retryAction, modifier.fillMaxSize())
}
}
//The homescreen displaying the loading message
@Composable
fun OnLoading(modifier: Modifier = Modifier){
Image(
modifier = modifier.size(200.dp),
painter = painterResource(id = R.drawable.loading_img),
contentDescription = stringResource(R. string.loading)
)
}
//The home screen displaying error message
@Composable
fun OnError(
retryAction: () -> Unit,
modifier: Modifier = Modifier
){
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.ic_connection_error) ,
contentDescription = ""
)
Text(stringResource(R.string.retry))
}
}
@Composable
fun KontakLayout(
kontak: Kontak,
modifier: Modifier = Modifier,
onDetailClick: (Kontak) -> Unit,
onDeleteClick: (Kontak) -> Unit = {}
){
LazyColumn(
modifier = modifier,
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
){
items(kontak){kontak ->
KontakCard(kontak = kontak, modifier = Modifier
.fillMaxWidth()
.clickable { onDetailClick(kontak) },
onDeleteClick = {
onDeleteClick(kontak)
}
)
}
}
}
@Composable
fun KontakCard(
kontak: Kontak,
onDeleteClick: (Kontak) -> Unit = {},
modifier: Modifier = Modifier
){
Card(
modifier = modifier,
shape = MaterialTheme.shapes.medium,
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
){
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Person,
contentDescription = null
)
Spacer(Modifier.padding(10.dp))
Text(
text = kontak.nama,
style = MaterialTheme.typography.titleLarge
)
}
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
){
Icon(
imageVector = Icons.Default.Phone,
contentDescription = null
)
Spacer(Modifier.padding(10.dp))
Text(
text = kontak.telpon,
style = MaterialTheme.typography.titleMedium
)
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Email,
contentDescription = null
)
Spacer(Modifier.padding(10.dp))
Text(
text = kontak.alamat,
style = MaterialTheme.typography.titleMedium
)
}
}
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
){
Spacer(Modifier.weight(1f))
IconButton(onClick = {onDeleteClick(kontak)}) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = null
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun previewHomeScreen(){
Project8_ClassCTheme {
HomeScreen(navigateToItemEntry = {})
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/home/screen/HomeScreen.kt | 3843956696 |
package com.example.project8_classc.ui
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.project8_classc.KontakApplication
import com.example.project8_classc.ui.home.viewmodel.HomeViewModel
import com.example.project8_classc.ui.kontak.viewmodel.DetailsViewModel
import com.example.project8_classc.ui.kontak.viewmodel.EditViewModel
import com.example.project8_classc.ui.kontak.viewmodel.InsertViewModel
object PenyediaViewModel{
val Factory = viewModelFactory {
initializer {
HomeViewModel(aplikasiKontak().container.kontakRepository)
}
initializer {
InsertViewModel(aplikasiKontak().container.kontakRepository)
}
initializer {
DetailsViewModel(
createSavedStateHandle(),
kontakRepository = aplikasiKontak().container.kontakRepository
)
}
initializer {
EditViewModel(
createSavedStateHandle(),
kontakRepository = aplikasiKontak().container.kontakRepository
)
}
}
}
fun CreationExtras.aplikasiKontak(): KontakApplication =
(this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as KontakApplication) | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/PenyediaViewModel.kt | 2689688759 |
package com.example.project8_classc.ui
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.project8_classc.R
import com.example.project8_classc.navigation.PengelolaHalaman
import com.example.project8_classc.ui.home.screen.HomeScreen
import com.example.project8_classc.ui.home.viewmodel.HomeViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun KontakApp(
homeViewModel: HomeViewModel = viewModel(factory = PenyediaViewModel.Factory)
){
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = { TopAppBar(scrollBehavior = scrollBehavior)}
){
Surface (
modifier = Modifier
.fillMaxSize()
.padding(it)
){
PengelolaHalaman()
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopAppBarKontak(
title: String,
canNavigasiBack: Boolean,
modifier: Modifier = Modifier,
scrollBehavior: TopAppBarScrollBehavior? = null,
navigateUp: () -> Unit = {}
){
CenterAlignedTopAppBar(title = { Text(title) },
modifier = modifier,
scrollBehavior = scrollBehavior,
navigationIcon = {
if (canNavigasiBack){
IconButton(onClick = navigateUp) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = ""
)
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopAppBar(
scrollBehavior: TopAppBarScrollBehavior,
modifier: Modifier = Modifier
){
CenterAlignedTopAppBar(
scrollBehavior = scrollBehavior,
title = {
Text(
text = stringResource(R.string.app_name),
style = MaterialTheme.typography.headlineSmall
)
},
modifier = modifier
)
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/KontakApp.kt | 2539957429 |
package com.example.project8_classc.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) | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/theme/Color.kt | 2894303581 |
package com.example.project8_classc.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 Project8_ClassCTheme(
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
)
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/theme/Theme.kt | 1926112911 |
package com.example.project8_classc.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
)
*/
) | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/theme/Type.kt | 3369396388 |
package com.example.project8_classc.ui.kontak.viewmodel
import android.provider.ContactsContract.CommonDataKinds.Email
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.repository.KontakRepository
import kotlinx.coroutines.launch
class InsertViewModel (private val kontakRepository: KontakRepository) : ViewModel(){
var insertKontakState by mutableStateOf(InsertUiState())
private set
fun updateInsertKontakState(insertUiEvent: InsertUiEvent){
insertKontakState = InsertUiState(insertUiEvent = insertUiEvent)
}
suspend fun insertKontak(){
viewModelScope.launch {
try{
kontakRepository.insertKontak(insertKontakState.insertUiEvent.toKontak())
}catch (e: Exception){
e.printStackTrace()
}
}
}
}
data class InsertUiState(
val insertUiEvent: InsertUiEvent = InsertUiEvent(),
)
data class InsertUiEvent(
val id: Int = 0,
val nama: String = "",
val alamat: String = "",
val telpon: String = "",
)
fun InsertUiEvent.toKontak(): Kontak = Kontak(
id = id,
nama = nama,
alamat = alamat,
telpon = telpon,
)
fun Kontak.toUiStateKontak(): InsertUiState = InsertUiState(
insertUiEvent = toInsertUiEvent(),
)
fun Kontak.toInsertUiEvent(): InsertUiEvent = InsertUiEvent(
id = id,
nama = nama,
alamat = alamat,
telpon = telpon,
) | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/viewmodel/InsertViewModel.kt | 1859275426 |
package com.example.project8_classc.ui.kontak.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.repository.KontakRepository
import com.example.project8_classc.ui.kontak.screen.DetailsDestination
import kotlinx.coroutines.launch
sealed class DetailsKontakUiState{
data class Success(
val kontak: Kontak
) : DetailsKontakUiState()
object Error : DetailsKontakUiState()
object Loading : DetailsKontakUiState()
}
class DetailsViewModel (
savedStateHandle: SavedStateHandle,
private val kontakRepository: KontakRepository
): ViewModel(){
private val kontakId: Int = checkNotNull(savedStateHandle[DetailsDestination.kontakId])
var detailsKontakUiState: DetailsKontakUiState by mutableStateOf(DetailsKontakUiState.Loading)
private set
init {
getKontakById()
}
fun getKontakById(){
viewModelScope.launch {
detailsKontakUiState = DetailsKontakUiState.Loading
detailsKontakUiState = try {
DetailsKontakUiState.Success(
kontak = kontakRepository.getKontakById(kontakId)
)
}catch (e: Exception){
DetailsKontakUiState.Error
}
}
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/viewmodel/DetailsViewModel.kt | 1730767505 |
package com.example.project8_classc.ui.kontak.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.project8_classc.repository.KontakRepository
import com.example.project8_classc.ui.kontak.screen.EditDestination
import kotlinx.coroutines.launch
class EditViewModel(
savedStateHandle: SavedStateHandle,
private val kontakRepository: KontakRepository
) : ViewModel(){
var editKontakState by mutableStateOf(InsertUiState())
private set
val kontakId: Int = checkNotNull(savedStateHandle[EditDestination.kontakId])
init {
viewModelScope.launch {
editKontakState = kontakRepository.getKontakById(kontakId).toUiStateKontak()
}
}
fun updateInsertKontakState(insertUiEvent: InsertUiEvent){
editKontakState = InsertUiState(insertUiEvent = insertUiEvent)
}
suspend fun updateKontak(){
viewModelScope.launch {
try {
kontakRepository.updateKontak(kontakId, editKontakState.insertUiEvent.toKontak())
}catch (e : Exception){
e.printStackTrace()
}
}
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/viewmodel/EditViewModel.kt | 684621302 |
package com.example.project8_classc.ui.kontak.screen
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp
import com.example.project8_classc.navigation.DestinasiNavigasi
import com.example.project8_classc.ui.PenyediaViewModel
import com.example.project8_classc.ui.TopAppBarKontak
import com.example.project8_classc.ui.kontak.viewmodel.InsertUiEvent
import com.example.project8_classc.ui.kontak.viewmodel.InsertUiState
import com.example.project8_classc.ui.kontak.viewmodel.InsertViewModel
import kotlinx.coroutines.launch
object DestinasiEntry: DestinasiNavigasi{
override val route = "item_entry"
override val titleRes = "Entry Siswa"
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EntryKontakScreen(
navigateBack: () -> Unit,
modifier: Modifier = Modifier,
viewModel: InsertViewModel = viewModel(factory = PenyediaViewModel.Factory),
){
val coroutineScope = rememberCoroutineScope()
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold (
modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBarKontak(
title = DestinasiEntry.titleRes ,
canNavigasiBack = true,
scrollBehavior = scrollBehavior,
navigateUp = navigateBack
)
}
){ innerPadding ->
EntryKontakBody(
insertUiState = viewModel.insertKontakState,
onSiswaValueChange = viewModel::updateInsertKontakState,
onSaveClick = {
coroutineScope.launch {
viewModel.insertKontak()
navigateBack()
}
},
modifier = Modifier
.padding(innerPadding)
.verticalScroll(rememberScrollState())
.fillMaxWidth()
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FormInputSiswa(
insertUiEvent: InsertUiEvent,
modifier: Modifier = Modifier,
onValueChange: (InsertUiEvent) -> Unit = {},
enabled: Boolean = true
){
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = insertUiEvent.nama,
onValueChange = {onValueChange(insertUiEvent.copy(nama = it))},
label = { Text("Nama")},
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true
)
OutlinedTextField(
value = insertUiEvent.alamat,
onValueChange = {onValueChange(insertUiEvent.copy(alamat = it))},
label = { Text("Email")},
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true
)
OutlinedTextField(
value = insertUiEvent.telpon,
onValueChange = {onValueChange(insertUiEvent.copy(telpon = it))},
label = { Text("No Hp")},
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true
)
if (enabled){
Text(
text = "Isi semua data",
modifier = Modifier.padding(start = 12.dp)
)
}
Divider(
thickness = 8.dp,
modifier = Modifier.padding(12.dp)
)
}
}
@Composable
fun EntryKontakBody(
insertUiState: InsertUiState,
onSiswaValueChange: (InsertUiEvent) -> Unit,
onSaveClick: () -> Unit,
modifier: Modifier = Modifier
){
Column(
verticalArrangement = Arrangement.spacedBy(18.dp),
modifier = modifier.padding(12.dp)
) {
FormInputSiswa(
insertUiEvent = insertUiState.insertUiEvent,
onValueChange = onSiswaValueChange,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = onSaveClick,
shape = MaterialTheme.shapes.small,
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Simpan")
}
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/screen/InsertScreen.kt | 2550263073 |
package com.example.project8_classc.ui.kontak.screen
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.navigation.DestinasiNavigasi
import com.example.project8_classc.ui.PenyediaViewModel
import com.example.project8_classc.ui.TopAppBarKontak
import com.example.project8_classc.ui.home.screen.DestinasiHome
import com.example.project8_classc.ui.home.screen.KontakLayout
import com.example.project8_classc.ui.home.screen.OnError
import com.example.project8_classc.ui.home.screen.OnLoading
import com.example.project8_classc.ui.kontak.viewmodel.DetailsKontakUiState
import com.example.project8_classc.ui.kontak.viewmodel.DetailsViewModel
object DetailsDestination : DestinasiNavigasi{
override val route = "item_details"
override val titleRes = "Detail Kontak"
const val kontakId = "itemId"
val routeWithArgs = "$route/{$kontakId}"
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailsScreen(
onEditClick: (Int) -> Unit,
modifier: Modifier = Modifier,
navigateBack: () -> Unit,
detailsViewModel: DetailsViewModel = viewModel(factory = PenyediaViewModel.Factory)
){
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBarKontak(
title = DestinasiHome.titleRes ,
canNavigasiBack = true,
scrollBehavior = scrollBehavior,
navigateUp = navigateBack
)
},
) { innerPadding ->
DetailStatus(
kontakUiState = detailsViewModel.detailsKontakUiState,
retryAction = {
detailsViewModel.getKontakById()
},
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
onEditClick = onEditClick
)
}
}
@Composable
fun DetailStatus(
kontakUiState: DetailsKontakUiState,
retryAction: () -> Unit,
modifier: Modifier = Modifier,
onEditClick: (Int) -> Unit
){
when(kontakUiState){
is DetailsKontakUiState.Success -> {
KontakLayout(
kontak = kontakUiState.kontak,
modifier = modifier.padding(16.dp),
onEditClick = {
onEditClick(it)
}
)
}
is DetailsKontakUiState.Loading ->{
OnLoading(modifier = modifier)
}
is DetailsKontakUiState.Error -> {
OnError(
retryAction = retryAction,
modifier = modifier
)
}
}
}
@Composable
fun KontakLayout(
kontak: Kontak,
modifier: Modifier = Modifier,
onEditClick: (Int) -> Unit = {},
){
Column (
modifier = modifier,
){
KontakCard(
kontak = kontak,
modifier = Modifier
.fillMaxWidth(),
)
Spacer(modifier = Modifier.padding(16.dp))
Button(
onClick = {
onEditClick(kontak.id)
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "Edit")
}
}
}
@Composable
fun KontakCard(
kontak: Kontak,
modifier: Modifier = Modifier
){
Card (
modifier = modifier,
shape = MaterialTheme.shapes.medium,
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row (
modifier = Modifier.fillMaxWidth(),
){
Text(
text = kontak.nama,
style = MaterialTheme.typography.titleLarge
)
Spacer(Modifier.weight(1f))
Icon(
imageVector = Icons.Default.Phone,
contentDescription = null
)
Text(
text = kontak.telpon,
style = MaterialTheme.typography.titleMedium
)
}
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
){
Text(
text = kontak.alamat,
style = MaterialTheme.typography.titleMedium
)
Spacer(Modifier.weight(1f))
}
}
}
}
| 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/screen/DetailsScreen.kt | 198524638 |
package com.example.project8_classc.ui.kontak.screen
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import com.example.project8_classc.navigation.DestinasiNavigasi
import com.example.project8_classc.ui.kontak.viewmodel.EditViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.project8_classc.ui.PenyediaViewModel
import com.example.project8_classc.ui.TopAppBarKontak
import com.example.project8_classc.ui.home.screen.DestinasiHome
import kotlinx.coroutines.launch
object EditDestination : DestinasiNavigasi {
override val route = "edit"
override val titleRes = "Edit Kontak"
const val kontakId = "itemId"
val routeWithArgs = "$route/{$kontakId}"
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemEditScreen(
navigateBack: () -> Unit,
onNavigateUp: () -> Unit,
modifier: Modifier = Modifier,
viewModel: EditViewModel = viewModel(factory = PenyediaViewModel.Factory)
){
val coroutineScope = rememberCoroutineScope()
Scaffold(
topBar = {
TopAppBarKontak(
title = DestinasiHome.titleRes,
canNavigasiBack = true,
navigateUp = navigateBack
)
},
modifier = modifier
) {innerPadding ->
EntryKontakBody(
insertUiState = viewModel.editKontakState,
onSiswaValueChange = viewModel::updateInsertKontakState,
onSaveClick = {
coroutineScope.launch {
viewModel.updateKontak()
onNavigateUp()
}
},
modifier = Modifier.padding(innerPadding)
)
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/ui/kontak/screen/EditScreen.kt | 752514701 |
package com.example.project8_classc.repository
import com.example.project8_classc.service_api.KontakService
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.create
interface AppContainer{
val kontakRepository: KontakRepository
}
class KontakContainer: AppContainer{
private val baseurl = "http://10.0.2.2:8080/"
private val json = Json { ignoreUnknownKeys = true }
private val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseurl)
.build()
private val kontakService: KontakService by lazy {
retrofit.create(KontakService::class.java)
}
override val kontakRepository: KontakRepository by lazy {
NetworkKontakRepository(kontakService)
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/repository/KontakContainer.kt | 1744303390 |
package com.example.project8_classc.repository
import com.example.project8_classc.model.Kontak
import com.example.project8_classc.service_api.KontakService
import java.io.IOException
interface KontakRepository{
suspend fun getKontak(): List<Kontak>
suspend fun insertKontak(kontak: Kontak)
suspend fun updateKontak(id: Int, kontak: Kontak)
suspend fun deleteKontak(id: Int)
suspend fun getKontakById(id: Int): Kontak
}
class NetworkKontakRepository(
private val kontakApiService: KontakService
): KontakRepository{
override suspend fun getKontak(): List<Kontak> = kontakApiService.getKontak()
override suspend fun insertKontak(kontak: Kontak) {
kontakApiService.insertKontak(kontak)
}
override suspend fun updateKontak(id: Int, kontak: Kontak) {
kontakApiService.updateKontak(id, kontak)
}
override suspend fun deleteKontak(id: Int) {
try {
val response = kontakApiService.deleteKontak(id)
if (!response.isSuccessful){
throw IOException("Failed to delete kontak. HTTP status code" +
"${response.code()}")
}
else{
response.message()
println(response.message())
}
}
catch (e:Exception){
throw e
}
}
override suspend fun getKontakById(id: Int): Kontak {
return kontakApiService.getKontakById(id)
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/repository/KontakRepository.kt | 834772617 |
package com.example.project8_classc
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.tooling.preview.Preview
import com.example.project8_classc.ui.KontakApp
import com.example.project8_classc.ui.theme.Project8_ClassCTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Project8_ClassCTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
KontakApp()
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Project8_ClassCTheme {
Greeting("Android")
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/MainActivity.kt | 461002883 |
package com.example.project8_classc.navigation
interface DestinasiNavigasi{
val route: String
val titleRes: String
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/navigation/DestinasiNavigasi.kt | 2358947128 |
package com.example.project8_classc.navigation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.project8_classc.ui.home.screen.DestinasiHome
import com.example.project8_classc.ui.home.screen.HomeScreen
import com.example.project8_classc.ui.kontak.screen.DestinasiEntry
import com.example.project8_classc.ui.kontak.screen.DetailsDestination
import com.example.project8_classc.ui.kontak.screen.DetailsScreen
import com.example.project8_classc.ui.kontak.screen.EditDestination
import com.example.project8_classc.ui.kontak.screen.EntryKontakScreen
import com.example.project8_classc.ui.kontak.screen.ItemEditScreen
@Composable
fun PengelolaHalaman(navController: NavHostController = rememberNavController()){
NavHost(
navController = navController,
startDestination = DestinasiHome.route,
modifier = Modifier,
){
composable(DestinasiHome.route){
HomeScreen(navigateToItemEntry = {
navController.navigate(DestinasiEntry.route)
},
onDetailClick = {itemId ->
navController.navigate("${DetailsDestination.route}/$itemId")
println(itemId)
}
)
}
composable(
DestinasiEntry.route
){
EntryKontakScreen(navigateBack = {
navController.navigate(
DestinasiHome.route
){
popUpTo(DestinasiHome.route){
inclusive = true
}
}
})
}
composable(
EditDestination.routeWithArgs,
arguments = listOf(navArgument(EditDestination.kontakId){
type = NavType.IntType
})
){
ItemEditScreen(
navigateBack = { navController.popBackStack() },
onNavigateUp = {
navController.navigate(DestinasiHome.route) {
popUpTo(DestinasiHome.route) {
inclusive = true
}
}
},
modifier = Modifier
)
}
composable(
DetailsDestination.routeWithArgs,
arguments = listOf(navArgument(DetailsDestination.kontakId) {
type = NavType.IntType
})
){backStackEntry ->
val itemId = backStackEntry.arguments?.getInt(DetailsDestination.kontakId)
itemId?.let {
DetailsScreen(
navigateBack = {
navController.navigateUp()
},
onEditClick = { itemId ->
navController.navigate("${EditDestination.route}/$itemId")
println(itemId)
}
)
}
}
composable(EditDestination.routeWithArgs,
arguments = listOf(navArgument(EditDestination.kontakId){
type = NavType.IntType
})
){
ItemEditScreen(
navigateBack = { navController.popBackStack() },
onNavigateUp = {
navController.navigate(DestinasiHome.route){
popUpTo(DestinasiHome.route){
inclusive = true
}
}
},
modifier = Modifier
)
}
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/navigation/PengelolaHalaman.kt | 706710282 |
package com.example.project8_classc
import android.app.Application
import com.example.project8_classc.repository.AppContainer
import com.example.project8_classc.repository.KontakContainer
class KontakApplication : Application(){
lateinit var container: AppContainer
override fun onCreate(){
super.onCreate()
container = KontakContainer()
}
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/KontakApplication.kt | 3481598037 |
package com.example.project8_classc.service_api
import com.example.project8_classc.model.Kontak
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query
interface KontakService {
@Headers(
"Accept: application/json"
)
@GET("/kontak")
suspend fun getKontak():List<Kontak>
@GET("kontak/{id}")
suspend fun getKontakById(@Query("id")id:Int): Kontak
@POST("kontak")
suspend fun insertKontak(@Body kontak: Kontak)
@PUT("kontak/{id}")
suspend fun updateKontak(@Query("id") Id: Int, @Body kontak: Kontak)
@DELETE("kontak/{id}")
suspend fun deleteKontak(@Query("id") id:Int): Response<Void>
} | 061_RestAPI/app/src/main/java/com/example/project8_classc/service_api/KontakService.kt | 3174791103 |
package com.example.project8_classc.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Kontak(
val id: Int,
val nama: String,
@SerialName("nohp")
val telpon: String,
@SerialName("email")
val alamat: String,
)
| 061_RestAPI/app/src/main/java/com/example/project8_classc/model/Kontak.kt | 1550293065 |
package com.example.getiskin
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.getiskin", appContext.packageName)
}
} | Team_Project_GETISKIN_CV_spaghetti/app/src/androidTest/java/com/example/getiskin/ExampleInstrumentedTest.kt | 296536670 |
package com.example.getiskin
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)
}
} | Team_Project_GETISKIN_CV_spaghetti/app/src/test/java/com/example/getiskin/ExampleUnitTest.kt | 1209641049 |
package com.example.getiskin
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
data class SkinAnalysisData(
val userID: String,
var timestamp: String,
val finalSkinType: String,
val skinType1: String,
val skinType2: String,
val skinType3: String,
val facePart1: String,
val facePart2: String,
val facePart3: String,
val imageUrl1: String,
val imageUrl2: String,
val imageUrl3: String,
) {
// 매개변수가 없는 기본 생성자
// firestore가 기본 생성자가 없으면 값을 못읽음... 생성필수라함
constructor() : this("", "", "", "", "", "", "", "", "", "", "", "")
}
fun saveSkinAnalysisData(skinAnalysisData: SkinAnalysisData) {
val db = FirebaseFirestore.getInstance()
// Add a new document with a generated ID
db.collection("skinAnalysis")
.add(skinAnalysisData)
.addOnSuccessListener { documentReference ->
println("DocumentSnapshot added with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
println("Error adding document: $e")
}
}
@Composable
fun HomeReturnButton2(
navController: NavController,
auth: FirebaseAuth,
uri1: Uri,
uri2: Uri,
uri3: Uri,
skinType1: String,
skinType2: String,
skinType3: String,
facePart1: String?,
facePart2: String?,
facePart3: String?,
finalSkinType: String?
) {
val user = auth.currentUser
val uid = user?.uid ?: "" //유저
var imageUrl1 by remember { mutableStateOf("") }
var imageUrl2 by remember { mutableStateOf("") }
var imageUrl3 by remember { mutableStateOf("") }
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
uploadRawDataToFirestorage(uri1, skinType1, facePart1,
onImageUploaded = {
Log.d("성공", "이미지 업로드 URL : $it")
})
uploadRawDataToFirestorage(uri2, skinType2, facePart2,
onImageUploaded = {
Log.d("성공", "이미지 업로드 URL : $it")
})
uploadRawDataToFirestorage(uri3, skinType3, facePart3,
onImageUploaded = {
Log.d("성공", "이미지 업로드 URL : $it")
})
uploadImageToFirestorage(uri1) { url1 ->
imageUrl1 = url1
Log.d("URL", "이미지 업로드 URL : $url1")
uploadImageToFirestorage(uri2) { url2 ->
imageUrl2 = url2
uploadImageToFirestorage(uri3) { url3 ->
imageUrl3 = url3
val skinAnalysis = SkinAnalysisData(
uid,
timestamp,
finalSkinType!!,
skinType1,
skinType2,
skinType3,
facePart1!!,
facePart2!!,
facePart3!!,
imageUrl1,
imageUrl2,
imageUrl3
)
saveSkinAnalysisData(skinAnalysis)
navController.navigate("home")
}
}
}
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.home),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "결과 저장 및 홈으로",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
fun uploadImageToFirestorage(imageUri: Uri, onImageUploaded: (String) -> Unit) {
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
val imageRef = storageRef.child("images/${imageUri.lastPathSegment}")
imageRef.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata?.reference?.downloadUrl?.addOnSuccessListener { downloadUri ->
val imageUrl = downloadUri.toString()
onImageUploaded(imageUrl)
}
}
.addOnFailureListener {
// 이미지 업로드 실패 시 처리
Log.d("망함", "망함")
}
}
@Composable
fun ResultsScreen(
navController: NavController,
auth: FirebaseAuth,
predictOilHead: Int?,
predictOilNose: Int?,
predictOilCheek: Int?,
predictHead: Int?,
predictNose: Int?,
predictCheek: Int?,
headUriString: String?,
noseUriString: String?,
cheekUriString: String?
) {
val complexAd = "https://www.coupang.com/np/search?component=&q=%EB%B3%B5%ED%95%A9%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
val oilyAd = "https://www.coupang.com/np/search?component=&q=%EC%A7%80%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
val dryAd = "https://www.coupang.com/np/search?component=&q=%EA%B1%B4%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
val uri1 = Uri.parse(headUriString)
val uri2 = Uri.parse(noseUriString)
val uri3 = Uri.parse(cheekUriString)
val skinType1 = if (predictOilHead == 0) "건성" else "지성"
val skinType2 = if (predictOilNose == 0) "건성" else "지성"
val skinType3 = if (predictOilCheek == 0) "건성" else "지성"
val facePart1 = when (predictHead) {
0 -> "볼"
1 -> "이마"
2 -> "코"
else -> null // 또는 원하는 다른 처리를 수행할 수 있음
}
val facePart2 = when (predictNose) {
0 -> "볼"
1 -> "이마"
2 -> "코"
else -> null
}
val facePart3 = when (predictCheek) {
0 -> "볼"
1 -> "이마"
2 -> "코"
else -> null
}
val finalSkinType: String = when {
skinType1 == "건성" && skinType2 == "건성" && skinType3 == "건성" -> "건성"
skinType1 == "지성" && skinType2 == "지성" && skinType3 == "지성" -> "지성"
else -> "복합성"
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(android.graphics.Color.parseColor("#ffffff")))
) {
// 상단 이미지
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(80.dp))
// Text
Text(
text = "측 정 결 과",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
Spacer(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5"))) // 원하는 배경 색상으로 설정
.padding(16.dp)
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
StyledSkinType(finalSkinType)
Spacer(modifier = Modifier.height(15.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromUri(uri1)
StyledText(facePart1!!, skinType1)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromUri(uri2)
StyledText(facePart2!!, skinType2)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromUri(uri3)
StyledText(facePart3!!, skinType3)
}
}
HomeReturnButton2(
navController,
auth,
uri1,
uri2,
uri3,
skinType1,
skinType2,
skinType3,
facePart1,
facePart2,
facePart3,
finalSkinType
)
AdPlaces("지성 화장품 광고", oilyAd)
AdPlaces("건성 화장품 광고", dryAd)
AdPlaces("복합성 화장품 광고", complexAd)
}
}
}
}
}
fun uploadRawDataToFirestorage(
imageUri: Uri,
skinType: String,
facePart: String?,
onImageUploaded: (String) -> Unit
) {
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
// 이미지를 저장할 경로 및 이름 설정
val imageRef = storageRef.child("raw/${facePart}/${skinType}/${UUID.randomUUID()}.jpg")
imageRef.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata?.reference?.downloadUrl?.addOnSuccessListener { downloadUri ->
val imageUrl = downloadUri.toString()
onImageUploaded(imageUrl)
}
}
.addOnFailureListener {
Log.e("실패", "망함")
// 이미지 업로드 실패 시 처리
}
}
@Composable
fun LoadImageFromUri(uri: Uri) {
// Coil을 사용하여 이미지 로드
Image(
painter = rememberImagePainter(
data = uri,
builder = {
crossfade(true) // crossfade 효과 사용
transformations(CircleCropTransformation()) // 원형으로 자르기
}
),
contentDescription = null,
modifier = Modifier
.size(100.dp)
)
}
@Composable
fun StyledText(first: String, second: String) {
val boldFacePart1 = AnnotatedString.Builder().apply {
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append(first)
}
append(" : $second")
}.toAnnotatedString()
Text(text = boldFacePart1)
}
@Composable
fun StyledSkinType(finalSkinType: String, name: String = "당신") {
val color = when (finalSkinType) {
"건성" -> Color.Red
"지성" -> Color.Blue
"복합성" -> Color.Magenta
else -> LocalContentColor.current // 기본 색상
}
val styledText = AnnotatedString.Builder().apply {
withStyle(style = SpanStyle(color = color, fontWeight = FontWeight.Bold)) {
append("${name}의 피부는 \"$finalSkinType\" 입니다.")
}
}.toAnnotatedString()
Text(
text = styledText,
fontSize = 24.sp,
)
}
| Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ResultsScreen.kt | 3108069125 |
package com.example.getiskin.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)
val Orange = Color(0xFFED7D31) | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ui/theme/Color.kt | 2417261522 |
package com.example.getiskin.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 GetiSkinTheme(
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
)
} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ui/theme/Theme.kt | 875715004 |
package com.example.getiskin.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
)
*/
) | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ui/theme/Type.kt | 491411481 |
package com.example.getiskin
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults.buttonColors
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.graphics.Color
import androidx.compose.ui.res.painterResource
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 androidx.navigation.compose.rememberNavController
// Product 데이터 클래스 정의
data class Product(
val imageResourceId: Int,
val manufacturer: String,
val name: String,
val price: String,
val additionalInfo: String
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProductScreen() {
// 현재 선택된 피부 유형을 추적하는 변수
var selectedSkinType by remember { mutableStateOf("지성") }
// 피부 유형에 따른 상품 리스트
var productList by remember { mutableStateOf<List<Product>>(emptyList()) }
DisposableEffect(selectedSkinType) {
productList = generateProductList(selectedSkinType)
onDispose { /* Clean up if needed */ }
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
// Text
Text(
text = "제 품 추 천",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
Spacer(modifier = Modifier.height(8.dp))
TopAppBar(
title = {
Text(
text = selectedSkinType, // 선택된 피부 유형에 따라 타이틀 변경
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
.padding(10.dp),
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368"))
)
},
modifier = Modifier
.height(56.dp)
.border(2.dp, Color(0xFFE39368), shape = RoundedCornerShape(16.dp))
)
// Divider(color = Color.Black, thickness = 1.dp)
// 피부 유형을 선택하는 버튼 행
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
// 각 피부 유형 버튼
SkinTypeButton("지성", selectedSkinType, onSelectSkinType = { selectedSkinType = it })
SkinTypeButton("건성", selectedSkinType, onSelectSkinType = { selectedSkinType = it })
SkinTypeButton("복합성", selectedSkinType, onSelectSkinType = { selectedSkinType = it })
}
// 상품 리스트를 보여주는 LazyColumn
LazyColumn {
items(productList) { product ->
ProductCard(
imageResourceId = product.imageResourceId,
manufacturer = product.manufacturer,
name = product.name,
price = product.price,
additionalInfo = product.additionalInfo
)
}
}
}
}
// 피부 유형을 선택하는 버튼 Composable
@Composable
fun SkinTypeButton(skinType: String, selectedSkinType: String, onSelectSkinType: (String) -> Unit) {
// 피부 유형을 나타내는 버튼
Button(
onClick = { onSelectSkinType(skinType) },
colors = buttonColors(
containerColor = if (skinType == selectedSkinType) Color.Black else Color(0xFFE39368)
)
) {
Text(text = skinType, fontWeight = FontWeight.Bold)
}
}
@Composable
fun ProductCard(
imageResourceId: Int,
manufacturer: String,
name: String,
price: String,
additionalInfo: String
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.border(2.dp, Color(0xFFE39368), shape = RoundedCornerShape(16.dp))
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
Row(modifier = Modifier.padding(8.dp)) {
Image(
painter = painterResource(id = imageResourceId),
contentDescription = "image",
modifier = Modifier
.size(110.dp)
.fillMaxHeight()
)
Column(modifier = Modifier.padding(8.dp)) {
Text(
text = manufacturer,
color = Color.Gray,
fontWeight = FontWeight.Normal,
modifier = Modifier.align(Alignment.Start)
)
Text(
text = name,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Text(
text = price,
fontWeight = FontWeight.Bold
)
Text(
text = additionalInfo,
color = Color.Gray,
fontWeight = FontWeight.Normal
)
}
}
}
}
}
fun generateProductList(skinType: String): List<Product> {
// 각 피부 유형에 따른 상품 리스트를 생성하는 로직
// (이 부분은 실제 서버에서 데이터를 가져오는 로직 등으로 변경할 수 있음)
return when (skinType) {
"지성" -> listOf(
Product(R.drawable.dokdo, "라운드랩", "1025 독도 토너", "19,900원", "300ml"),
Product(R.drawable.beplain, "비플레인", "녹두 약산성 클렌징폼", "18,900원", "120ml"),
Product(R.drawable.blemish, "닥터지", "레드 블레미쉬 클리어 수딩 크림", "26,600원", "50ml"),
Product(R.drawable.jajak, "라운드랩", "자작나무 수분 선크림", "19,900원", "80ml"),
Product(R.drawable.power, "잇츠스킨", "파워 10 감초줄렌 젤리패드", "27,500원", "120ml"),
Product(R.drawable.oil, "마녀공장", "퓨어 클렌징 오일", "24,500원", "400ml"),
// ...
)
"건성" -> listOf(
Product(R.drawable.toner, "이즈앤트리", "초저분자 히아루론산 토너", "14,900원", "300ml"),
Product(R.drawable.dalba_w, "달바", "화이트 트러플 더블 세럼 앤 크림", "78,000원", "70g"),
Product(R.drawable.dalba_s, "달바", "워터풀 선크림", "34,000원", "50ml"),
Product(R.drawable.snature, "에스네이처", "아쿠아 스쿠알란 수분크림", "29,900원", "160ml"),
Product(R.drawable.seramaid, "아이레시피", "세라마이드 유자 힐링 클렌징 밤", "48,000원", "120g"),
Product(R.drawable.carrot, "스킨푸드", "캐롯 카로틴 카밍워터 패드", "20,800원", "260g"),
)
"복합성" -> listOf(
Product(R.drawable.aqua, "에스네이처", "아쿠아 오아시스 토너", "19,900원", "300ml"),
Product(R.drawable.madagascar, "스킨1004", "마다가스카르 센텔라 히알루-시카 워터핏 선세럼", "14,000원", "50ml"),
Product(R.drawable.beplain, "비플레인", "녹두 약산성 클렌징폼", "18,900원", "120ml"),
Product(R.drawable.dokdo, "라운드랩", "1025 독도 토너", "19,900원", "300ml"),
Product(R.drawable.torriden, "토리든", "다이브인 저분자 히알루론산 수딩 크림", "14,500원", "100ml"),
Product(R.drawable.atoberrier, "에스트라", "아토베리어365크림", "23,250원", "80ml"),
// ...
)
else -> emptyList()
}
}
@Preview(showBackground = true)
@Composable
fun ProductScreenPreview() {
val navController = rememberNavController()
MaterialTheme {
ProductScreen()
}
}
| Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ProductScreen.kt | 1892398895 |
package com.example.getiskin
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.libraries.places.api.Places
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.delay
class MainActivity : ComponentActivity() {
private lateinit var mAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var firestore: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
Places.initialize(applicationContext, "AIzaSyBBi36Pj-bYMFFMQ9mAS-vwvOvusUqnglo")
super.onCreate(savedInstanceState)
mAuth = FirebaseAuth.getInstance()
firestore = FirebaseFirestore.getInstance()
// 구글 로그인 구현
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) // default_web_client_id 에러 시 rebuild
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
setContent {
val navController = rememberNavController()
val signInIntent = googleSignInClient.signInIntent
val launcher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
// result returned from launching the intent from GoogleSignInApi.getSignInIntent()
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val exception = task.exception
if (task.isSuccessful) {
try {
// Google SignIn was successful, authenticate with firebase
val account = task.getResult(ApiException::class.java)!!
firebaseAuthWithGoogle(account.idToken!!)
navController.popBackStack()
navController.navigate("home")
} catch (e: Exception) {
// Google SignIn failed
Log.d("SignIn", "로그인 실패")
}
} else {
Log.d("SignIn", exception.toString())
}
}
MaterialTheme {
Surface {
// NavHost를 사용하여 네비게이션 구조를 설정합니다.
NavHost(navController = navController, startDestination = "splash") {
composable("login") { LoginScreen(signInClicked = { launcher.launch(signInIntent) }) }
composable("home") { HomeScreen(navController, onClicked = { signOut(navController)}) }
composable("skin_analysis") { SkinAnalysisScreen(navController) }
composable("diary") { DiaryScreen(mAuth) }
composable("product") { ProductScreen() }
composable("clinic") { ClinicScreen(navController) }
composable("splash") { SplashContent(navController) }
composable("results/{headOil}/{noseOil}/{cheekOil}/{head}/{nose}/{cheek}/{headUri}/{noseUri}/{cheekUri}") {
val predictOily1 = it.arguments?.getString("headOil")?.toInt()
val predictOily2 = it.arguments?.getString("noseOil")?.toInt()
val predictOily3 = it.arguments?.getString("cheekOil")?.toInt()
val predictFace1 = it.arguments?.getString("head")?.toInt()
val predictFace2 = it.arguments?.getString("nose")?.toInt()
val predictFace3 = it.arguments?.getString("cheek")?.toInt()
val uri1 = it.arguments?.getString("headUri")
val uri2 = it.arguments?.getString("noseUri")
val uri3 = it.arguments?.getString("cheekUri")
ResultsScreen(
navController,
mAuth,
predictOily1,
predictOily2,
predictOily3,
predictFace1,
predictFace2,
predictFace3,
uri1,
uri2,
uri3
)
}
// 여기에 다른 화면들을 네비게이션 구조에 추가합니다.
}
}
}
}
}
@Composable
fun SplashContent(navController: NavController) {
var scale by remember { mutableStateOf(1f) }
var alpha by remember { mutableStateOf(1f) }
val user: FirebaseUser? = mAuth.currentUser
val startDestination = remember {
if (user == null) {
"login"
} else {
"home"
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.primary),
contentAlignment = Alignment.Center
) {
// 스플래시 화면에 표시할 내용 (이미지, 로고 등)
Image(
painter =
painterResource(id = R.drawable.logo),
contentDescription = null,
modifier = Modifier
.graphicsLayer(
scaleX = animateFloatAsState(targetValue = scale, animationSpec = tween(durationMillis = 1000)).value,
scaleY = animateFloatAsState(targetValue = scale, animationSpec = tween(durationMillis = 1000)).value,
alpha = alpha
)
)
// 스플래시 화면에서 HomeScreen으로 Navigation
LaunchedEffect(true) {
delay(1000) // 초기 딜레이
scale = 1.5f
alpha = 0f
delay(1000) // 스케일 및 투명도 변경 후 딜레이
navController.navigate(startDestination)
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// SignIn Successful
Toast.makeText(this, "로그인 성공", Toast.LENGTH_SHORT).show()
} else {
// SignIn Failed
Toast.makeText(this, "로그인 실패", Toast.LENGTH_SHORT).show()
}
}
}
private fun signOut(navController: NavController) {
// get the google account
val googleSignInClient: GoogleSignInClient
// configure Google SignIn
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
// Sign Out of all accounts
mAuth.signOut()
googleSignInClient.signOut().addOnSuccessListener {
Toast.makeText(this, "로그아웃 성공", Toast.LENGTH_SHORT).show()
navController.navigate("login")
}.addOnFailureListener {
Toast.makeText(this, "로그아웃 실패", Toast.LENGTH_SHORT).show()
}
}
} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/MainActivity.kt | 3897370662 |
package com.example.getiskin
// 필요한 추가 import 문
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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 androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.File
import java.io.IOException
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*
@Composable
fun SkinAnalysisScreen(navController: NavController) {
val context = LocalContext.current
var imageUri by remember { mutableStateOf<Uri?>(null) }
var selectUris by remember { mutableStateOf<MutableList<Uri?>?>(mutableListOf()) }
val predictOliyList by remember { mutableStateOf<MutableList<Int>>(mutableListOf()) }
val predictFaceList by remember { mutableStateOf<MutableList<Int>>(mutableListOf()) }
val scope = rememberCoroutineScope()
val maxUrisSize = 3
//카메라 퍼미션 확인
var hasCameraPermission by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
)
}
//카메라 퍼미션 확인 런쳐
val cameraPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
hasCameraPermission = true
} else {
Toast.makeText(
context,
"Camera permission is required to take photos",
Toast.LENGTH_LONG
).show()
}
}
//카메라로 찍은 파일 Uri로 바꿔줌
fun createImageUri(): Uri {
val timestamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
File.createTempFile("JPEG_${timestamp}_", ".jpg", storageDir)
).also { uri ->
imageUri = uri
}
}
//카메라 런쳐
val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture()
) { success: Boolean ->
if (success) {
// 사진 촬영 성공, imageUri에 이미지가 저장됨
scope.launch {
imageUri?.let { uri ->
//이미지 uri들을 selectUris에 하나씩 저장
selectUris?.let { uris ->
val newList = uris.toMutableList()
newList.add(uri)
selectUris = if (newList.size > maxUrisSize) {
newList.takeLast(maxUrisSize).toMutableList()
} else {
newList
}
}
//파일로 변경후 서버 모델에서 예측값 받아오기
val inputStream = context.contentResolver.openInputStream(uri)
val file = File(context.cacheDir, "image.png")
inputStream?.use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
val (predictedClassOliy, predictedClassFace) = uploadImage(file)
predictOliyList.add(predictedClassOliy)
predictFaceList.add(predictedClassFace)
while (predictOliyList.size > 3) {
predictOliyList.removeAt(0)
}
while (predictFaceList.size > 3) {
predictFaceList.removeAt(0)
}
}
}
} else {
Log.e("사진 촬영 실패", "실패실패실패실패실패실패")
}
}
//포토피커로 사진 여러장 가져오기
val multiPhotoLoader = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickMultipleVisualMedia(),
onResult = { uris ->
val selectedUris = uris.take(3)
// 현재의 selectUris 크기가 3을 초과하는 경우, 앞에서부터 제거
while (selectUris!!.size + selectedUris.size > 3) {
selectUris!!.removeAt(0)
}
selectUris!!.addAll(selectedUris)
scope.launch {
selectUris.let {
if (it != null) {
for (uri in it) {
if (uri != null) {
val inputStream = context.contentResolver.openInputStream(uri)
val file = File(context.cacheDir, "image.png")
inputStream?.use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
try {
val (predictedClassOliy, predictedClassFace) = uploadImage(file)
predictOliyList.add(predictedClassOliy)
predictFaceList.add(predictedClassFace)
while (predictOliyList.size > 3) {
predictOliyList.removeAt(0)
}
while (predictFaceList.size > 3) {
predictFaceList.removeAt(0)
}
Log.d("성공함", "예측값 추가됨: $predictedClassOliy, $predictedClassFace")
} catch (e: Exception) {
Log.e("예외 발생", e.toString())
}
}
}
}
}
}
}
)
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(android.graphics.Color.parseColor("#ffffff")))
) {
// 상단 이미지
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
) {
Spacer(modifier = Modifier.height(80.dp))
// Text
Text(
text = "피 부 측 정",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
Spacer(modifier = Modifier.height(16.dp))
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
// 사진 보여주는곳
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
for (uri in selectUris.orEmpty()) {
if (uri != null) {
val headBitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val decodeBitmap = ImageDecoder.decodeBitmap(
ImageDecoder.createSource(
context.contentResolver, uri
)
)
decodeBitmap
} else {
MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
}
Image(
bitmap = headBitmap.asImageBitmap(), contentDescription = "", modifier = Modifier
.size(120.dp)
.clickable {
selectUris?.let { currentUris ->
// 클릭한 이미지의 uri를 제거
val updatedUris = currentUris
.filter { it != uri }
.toMutableList()
selectUris = updatedUris
}
}
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
if (hasCameraPermission) {
val uri = createImageUri()
cameraLauncher.launch(uri)
} else {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
},
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(10.dp)
.border(
1.dp,
Color(android.graphics.Color.parseColor("#e39368")),
shape = RoundedCornerShape(10)
),
colors = ButtonDefaults.buttonColors(
Color(0xFFE39368), // 버튼 배경색상 설정
contentColor = White // 버튼 내부 텍스트 색상 설정
),
shape = RoundedCornerShape(10)
) {
Text(
text = "카메라로 촬영하기",
textAlign = TextAlign.Center,
color = White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(20.dp))
Button(
onClick = {
// 앨범 런처를 실행합니다.
multiPhotoLoader.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))
},
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(10.dp)
.border(
1.dp,
Color(android.graphics.Color.parseColor("#e39368")),
shape = RoundedCornerShape(10)
),
colors = ButtonDefaults.buttonColors(
Color(0xFFE39368), // 버튼 배경색상 설정
contentColor = White // 버튼 내부 텍스트 색상 설정
),
shape = RoundedCornerShape(10)
) {
Text(
text = "앨범에서 사진 선택하기",
textAlign = TextAlign.Center,
color = White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(16.dp))
/*TODO 버튼 색변경 및 글씨 스타일링, list로 값 보내기*/
Button(
onClick = {
val headEncodedUri = URLEncoder.encode(selectUris?.get(0).toString(), "UTF-8")
val noseEncodedUri = URLEncoder.encode(selectUris?.get(1).toString(), "UTF-8")
val cheekEncodedUri = URLEncoder.encode(selectUris?.get(2).toString(), "UTF-8")
if (selectUris != null) {
navController.navigate(
"results/${predictOliyList[0]}/${predictOliyList[1]}/${predictOliyList[2]}/${predictFaceList[0]}/${predictFaceList[1]}/${predictFaceList[2]}/${headEncodedUri}/${noseEncodedUri}/${cheekEncodedUri}"
)
}
},
enabled = (selectUris?.size ?: 0) >= 3,
colors = ButtonDefaults.buttonColors(
Color(0xFFE39368), // 버튼 배경색상 설정
contentColor = White // 버튼 내부 텍스트 색상 설정
),
) {
Text(
text = "진단하기",
color = White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
}
Spacer(modifier = Modifier.height(10.dp)) // 간격 조절
TextButton(
onClick = {
navController.navigate("home")
},
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
) {
Text(
text = "홈으로",
color = Gray,
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxSize()
)
}
}
}
}
}
//서버와 통신하는 함수
//비동기 환경에서 처리
suspend fun uploadImage(file: File): Pair<Int, Int> = withContext(Dispatchers.IO) {
//서버가 열린 주소
val url = "http://192.168.1.111:5000/predict"
//ok3http 사용
val client = OkHttpClient()
//request(요청)보낼 파일(이미지)생성
val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
//이름은 image, 파일이름은 image.png로 보냄
.addFormDataPart(
"image",
"image.png",
RequestBody.create(MediaType.parse("image/*"), file)
)
.build()
//request post
val request = Request.Builder()
//해당 서버주소
.url(url)
//파일 전송
.post(requestBody)
.build()
//오류 캐치를 위해
try {
//응답을 받아옴(요청에 대한값)
val response = client.newCall(request).execute()
if (response.isSuccessful) {
//응답이 온다면 string으로 만듦
val responseBody = response.body()?.string()
//json파일 pasing을 위한 함수 사용
val gson = Gson()
//응답을 PredictResponse에 값을 참조해옴
val predictResponse = gson.fromJson(responseBody, PredictResponse::class.java)
val intValue = Pair(predictResponse.predictedClassOliy, predictResponse.predictedClassFace)
Log.d("성공함", "이미지가 올라갔다? Respones : ${responseBody ?: "no data"}")
return@withContext intValue
} else {
Log.e("망함", "망함")
}
} catch (e: IOException) {
e.printStackTrace()
// Handle exception
} as Pair<Int, Int>
}
//서버에서 보낸 json에서 값을 추출
data class PredictResponse(
//이 이름을 찾음 @SeriallizedName
@SerializedName("predicted_class_oliy")
val predictedClassOliy: Int,
@SerializedName("predicted_class_face")
val predictedClassFace: Int,
)
@Preview
@Composable
fun SkinAnalysisScreenPreview() {
// You can create a preview of the HomeScreen here
// For example, you can use a NavController with a LocalCompositionLocalProvider
// to simulate the navigation.
// Note: This is a simplified example; you may need to adjust it based on your actual navigation setup.
val navController = rememberNavController()
SkinAnalysisScreen(navController = navController)
}
| Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/SkinAnalysisScreen.kt | 1048277111 |
package com.example.getiskin
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
@Composable
fun DiaryScreen(auth: FirebaseAuth) {
var skinAnalysisList by remember { mutableStateOf<List<SkinAnalysisData>>(emptyList()) }
LaunchedEffect(Unit) {
// 코루틴을 사용하여 데이터를 비동기적으로 가져옴
skinAnalysisList = fetchDataFromFirestore(auth.currentUser?.uid ?: "")
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
Text(
text = "나 의 일 지",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
// Journal Entries
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(skinAnalysisList) { entry ->
JournalEntryCard(entry = entry, auth)
}
}
}
}
@Composable
fun JournalEntryCard(entry: SkinAnalysisData, auth: FirebaseAuth) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.border(2.dp, Color(0xFFE39368), shape = RoundedCornerShape(16.dp))
) {
// Box(
// modifier = Modifier
// .fillMaxSize()
// .background(Color(android.graphics.Color.parseColor("#F7F1E5")))
// ) {
val user = auth.currentUser
Column(
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(16.dp)
) {
Text(
text = entry.timestamp,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
.align(Alignment.CenterHorizontally)
)
Divider(color = Color.Black, thickness = 1.dp)
// 세로 구분선
Spacer(modifier = Modifier.height(8.dp))
Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
// 내 피부상태
// Text(
// text = "피부상태: ${entry.finalSkinType}",
// style = MaterialTheme.typography.titleSmall
// )
user?.displayName?.let { StyledSkinType(entry.finalSkinType, "${it}님") }
// 세로 구분선
Spacer(modifier = Modifier.height(8.dp))
// 사진
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromFirebase(entry.imageUrl1)
Spacer(modifier = Modifier.height(8.dp))
StyledText(entry.facePart1, entry.skinType1)
}
// 사진
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromFirebase(entry.imageUrl2)
Spacer(modifier = Modifier.height(8.dp))
StyledText(entry.facePart2, entry.skinType2)
}
// 사진
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LoadImageFromFirebase(entry.imageUrl3)
Spacer(modifier = Modifier.height(8.dp))
StyledText(entry.facePart3, entry.skinType3)
}
}
}
}
}
private suspend fun fetchDataFromFirestore(userId: String): List<SkinAnalysisData> = suspendCoroutine { continuation ->
val db = FirebaseFirestore.getInstance()
val result = mutableListOf<SkinAnalysisData>()
// "skinAnalysis" 컬렉션에서 데이터 가져오기
db.collection("skinAnalysis")
.orderBy("timestamp", Query.Direction.DESCENDING) // timestamp 기준으로 최신순으로 정렬
.get().addOnSuccessListener { querySnapshot ->
for (document in querySnapshot) {
val skinAnalysisData = document.toObject(SkinAnalysisData::class.java)
if (skinAnalysisData.userID == userId) {
result.add(skinAnalysisData)
}
}
continuation.resume(result)
}.addOnFailureListener { exception ->
println("Error getting documents: $exception")
continuation.resumeWithException(exception)
}
}
@Composable
fun LoadImageFromFirebase(imageUrl: String) {
val painter = rememberImagePainter(data = imageUrl, builder = {
crossfade(true)
transformations(CircleCropTransformation()) // 원형으로 자르기
})
Image(
painter = painter, contentDescription = null, modifier = Modifier
.fillMaxWidth()
.height(150.dp)
.clip(MaterialTheme.shapes.medium)
)
}
//@Preview(showBackground = true)
//@Composable
//fun DiaryScreenPreview() {
// val navController = rememberNavController()
// MaterialTheme {
// DiaryScreen(navController)
// }
//} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/DiaryScreen.kt | 2221702569 |
package com.example.getiskin
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
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.unit.dp
@Composable
fun LoginScreen(signInClicked: () -> Unit) {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.primary),
contentAlignment = Alignment.Center
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(painter = painterResource(id = R.drawable.logo), contentDescription = null)
GoogleSignInButton(signInClicked)
}
}
}
@Composable
fun GoogleSignInButton(
signInClicked: () -> Unit
) {
Image(
painter = painterResource(id = R.drawable.google_login),
contentDescription = "구글로그인",
modifier = Modifier.size(250.dp, 100.dp).clickable { signInClicked() }
)
} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/LoginScreen.kt | 1349731392 |
package com.example.getiskin
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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 androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
@Composable
fun HomeReturnButton(navController: NavController) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
navController.navigate("home")
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.home),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "홈 화면으로",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun ClinicSearchButton() {
val searchText = "피부관리"
val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(LocalContext.current)
val context = LocalContext.current
var isLocationPermissionGranted by remember { mutableStateOf(false) }
val requestLocationPermissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
isLocationPermissionGranted = isGranted
}
var isClicked by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
isClicked = true
}
) {
if (isClicked) {
// 클릭되었을 때의 UI
// 예를 들어, 광고 클릭 후에 할 작업을 여기에 추가
if (ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
// 이미 권한이 있는 경우
isLocationPermissionGranted = true
if (isLocationPermissionGranted) {
// 위치 권한이 허용된 경우 위치 정보 가져오기 시도
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
// 위치 정보 가져오기 성공
val currentLatLng =
LatLng(location.latitude, location.longitude)
// 검색어와 현재 위치 기반으로 Google Maps 열기
openGoogleMaps(context, currentLatLng, searchText)
} else {
// 위치 정보 없음
}
}.addOnFailureListener { exception ->
// 위치 정보 가져오기 실패
}
} else {
// 위치 권한이 거부된 경우 처리
// 여기에 권한이 거부되었을 때의 동작을 추가할 수 있습니다.
}
} else {
// 권한이 없는 경우
requestLocationPermissionLauncher.launch(android.Manifest.permission.ACCESS_FINE_LOCATION)
}
}
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.clinics),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "피부관리샵 찾기",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun ClinicScreen(navController: NavController) {
val complexAd = "https://www.coupang.com/np/search?component=&q=%EB%B3%B5%ED%95%A9%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
val hwahaeAd = "https://www.hwahae.co.kr/"
val searchText = "피부관리"
val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(LocalContext.current)
val context = LocalContext.current
var isLocationPermissionGranted by remember { mutableStateOf(false) }
// 위치 권한 요청을 위한 런처
val requestLocationPermissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
isLocationPermissionGranted = isGranted
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(android.graphics.Color.parseColor("#ffffff")))
) {
// 상단 이미지
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(80.dp))
// Text
Text(
text = "C L I N I C",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
// 중앙 컨텐츠
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
AdPlaces("복합성 화장품 광고", complexAd)
Spacer(modifier = Modifier.height(80.dp))
// Button
ClinicSearchButton()
Spacer(modifier = Modifier.height(20.dp))
HomeReturnButton(navController)
Spacer(modifier = Modifier.height(70.dp))
AdPlaces("화해 광고", hwahaeAd)
}
}
}
}
// Google Maps 열기 함수
private fun openGoogleMaps(context: Context, destinationLatLng: LatLng, searchText: String) {
val mapIntent = Intent(
Intent.ACTION_VIEW,
Uri.parse("geo:${destinationLatLng.latitude},${destinationLatLng.longitude}?q=$searchText")
)
// Google Maps 앱이 설치되어 있는 경우 Google Maps 앱에서 지도를 엽니다.
// 설치되어 있지 않은 경우 웹 브라우저에서 지도를 엽니다.
mapIntent.setPackage("com.google.android.apps.maps")
context.startActivity(mapIntent)
}
@Composable
fun PreviewClinicScreen() {
// 여기서는 NavController를 mock으로 사용하거나, 필요에 따라 빈 NavController를 생성할 수 있습니다.
val navController = rememberNavController() // 빈 NavController 생성
// 미리보기에서 사용할 가상의 데이터 등을 여기에 추가할 수 있습니다.
ClinicScreen(navController = navController)
}
@Preview
@Composable
fun ClinicScreenPreview() {
PreviewClinicScreen()
} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/ClinicScreen.kt | 1436780175 |
package com.example.getiskin
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
@Composable
fun ShowToasts(message: String) {
val context = LocalContext.current
val toast = remember { Toast.makeText(context, message, Toast.LENGTH_SHORT) }
toast.show()
}
@Composable
fun SkinButton(navController: NavController) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
navController.navigate("skin_analysis")
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.skin),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "피부 진단",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun DiaryButton(navController: NavController) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
navController.navigate("diary")
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.newdiary),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "나의 일지",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun ShopButton(navController: NavController) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
navController.navigate("product")
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.cosmetics),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "상품 추천",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun ClinicButton(navController: NavController) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
navController.navigate("clinic")
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.clinics),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "피부관리샵 찾기",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun AdPlaces(adName: String, uriString: String) {
var isClicked by remember { mutableStateOf(false) }
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(10.dp)
.border(
1.dp,
Color(android.graphics.Color.parseColor("#e39368")),
shape = RoundedCornerShape(10)
)
.clickable {
// 광고를 클릭할 때 수행할 작업 추가
isClicked = true
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
context.startActivity(intent)
}
) {
if (isClicked) {
// 클릭되었을 때의 UI
// 예를 들어, 광고 클릭 후에 할 작업을 여기에 추가
ShowToasts("업체 웹페이지로 이동합니다")
}
Image(
painter = painterResource(id = R.drawable.analysis), // 가상 이미지 리소스 ID로 변경
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxSize()
.border(
1.dp,
Color(android.graphics.Color.parseColor("#e39368")),
shape = RoundedCornerShape(10)
)
)
// 광고 텍스트
Text(
text = adName,
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
@Composable
fun HomeScreen(navController: NavController, onClicked: () -> Unit) {
val oilyAd = "https://www.coupang.com/np/search?component=&q=%EC%A7%80%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
val dryAd = "https://www.coupang.com/np/search?component=&q=%EA%B1%B4%EC%84%B1+%ED%99%94%EC%9E%A5%ED%92%88&channel=user"
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(android.graphics.Color.parseColor("#ffffff")))
) {
// 상단 이미지
Image(
painter = painterResource(id = R.drawable.logo), // 이미지 리소스 ID로 변경
contentDescription = null, // contentDescription은 필요에 따라 추가
modifier = Modifier
.fillMaxWidth()
.height(100.dp) // 이미지 높이 조절
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(80.dp))
// Text
Text(
text = "H O M E",
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5")))
.padding(20.dp)
.height(30.dp), // 여백 추가
textAlign = TextAlign.Center,
fontSize = 24.sp, // 원하는 크기로 조절
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#e39368")) // 원하는 색상으로 조절
)
Spacer(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.background(Color(android.graphics.Color.parseColor("#F7F1E5"))) // 원하는 배경 색상으로 설정
.padding(16.dp)
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
SkinButton(
navController
)
Spacer(modifier = Modifier.width(15.dp))
DiaryButton(
navController
)
ShopButton(
navController
)
ClinicButton(
navController
)
LogoutButton(onClicked)
AdPlaces("지성 화장품 광고", oilyAd)
AdPlaces("건성 화장품 광고", dryAd)
}
}
}
}
}
@Composable
fun LogoutButton(onClicked: () -> Unit) {
Box(
modifier = Modifier
.height(150.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10))
.clickable {
onClicked()
}
) {
// Image 등의 내용을 넣어줌
Image(
painter = painterResource(id = R.drawable.logout),
contentDescription = null,
contentScale = ContentScale.Crop, // 이미지가 잘릴 수 있도록 설정
modifier = Modifier
.fillMaxSize() // 이미지를 꽉 채우도록 설정
.aspectRatio(1f)
.clip(RoundedCornerShape(10))
)
Text(
text = "로그아웃",
textAlign = TextAlign.Center,
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(16.dp)
.background(Color.Transparent) // 텍스트 배경을 투명하게 설정
)
}
}
//@Preview
//@Composable
//fun HomeScreenPreview() {
// // You can create a preview of the HomeScreen here
// // For example, you can use a NavController with a LocalCompositionLocalProvider
// // to simulate the navigation.
// // Note: This is a simplified example; you may need to adjust it based on your actual navigation setup.
// val navController = rememberNavController()
// HomeScreen(navController = navController)
//} | Team_Project_GETISKIN_CV_spaghetti/app/src/main/java/com/example/getiskin/HomeScreen.kt | 84876724 |
package com.example.kotlintouch
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.kotlintouch", appContext.packageName)
}
} | development-android/KotlinTouch/app/src/androidTest/java/com/example/kotlintouch/ExampleInstrumentedTest.kt | 2790145276 |
package com.example.kotlintouch
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)
}
} | development-android/KotlinTouch/app/src/test/java/com/example/kotlintouch/ExampleUnitTest.kt | 562460317 |
package com.example.kotlintouch
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)
}
} | development-android/KotlinTouch/app/src/main/java/com/example/kotlintouch/MainActivity.kt | 801340519 |
package com.example.hospel
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.hospel", appContext.packageName)
}
} | Hospel/app/src/androidTest/java/com/example/hospel/ExampleInstrumentedTest.kt | 337941962 |
package com.example.hospel
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)
}
} | Hospel/app/src/test/java/com/example/hospel/ExampleUnitTest.kt | 4013971528 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hospel.databinding.ActivityAkunBinding
class Akun : AppCompatActivity() {
private lateinit var binding: ActivityAkunBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAkunBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backAkun.setOnClickListener {
onBackPressed()
}
binding.ubahPassword.setOnClickListener {
val intent = Intent(this@Akun, UbahPassword::class.java)
startActivity(intent)
}
binding.ubahEmail.setOnClickListener {
val intent = Intent(this@Akun, UbahEmail::class.java)
startActivity(intent)
}
}
} | Hospel/app/src/main/java/com/example/hospel/Akun.kt | 2406438528 |
package com.example.hospel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.example.hospel.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
val fragHome : Fragment = HomeFragment()
val fragProfil : Fragment = ProfilFragment()
val fragPesan : Fragment = PesanFragment()
var hideHomeFragment : Fragment = fragHome
var hideProfilFragment : Fragment = fragProfil
var hidePesanFragment : Fragment = fragPesan
val fm : FragmentManager = supportFragmentManager
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
fm.beginTransaction().add(R.id.fragmentContainerView, fragHome).show(fragHome).commit()
fm.beginTransaction().add(R.id.fragmentContainerView, fragProfil).hide(fragProfil).commit()
fm.beginTransaction().add(R.id.fragmentContainerView, fragPesan).hide(fragPesan).commit()
binding.bottomNavigationView.setOnItemSelectedListener {
when(it.itemId){
R.id.homeFragment -> replaceFragment(HomeFragment())
R.id.settingsFragment -> replaceFragment(ProfilFragment())
R.id.pesanFragment -> replaceFragment(PesanFragment())
else ->{
}
}
true
}
}
private fun replaceFragment(fragment : Fragment){
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragmentContainerView, fragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
} | Hospel/app/src/main/java/com/example/hospel/MainActivity.kt | 1907887446 |
package com.example.hospel
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.hospel.databinding.FragmentPesanBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class PesanFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var pesanList: ArrayList<DataListPesan?> // Tetapkan tipe data pesanList menjadi ArrayList<DataListPesan?>
private lateinit var binding: FragmentPesanBinding
private val firestore = FirebaseFirestore.getInstance()
private val auth = FirebaseAuth.getInstance()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentPesanBinding.inflate(layoutInflater, container, false)
recyclerView = binding.recyclerViewPesan
pesanList = ArrayList<DataListPesan?>()
// Ambil data dari Firestore
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
firestore.collection("users")
.document(uid)
.get()
.addOnSuccessListener { userDocument ->
val nama = userDocument.getString("nama") ?: ""
val email = userDocument.getString("email") ?: ""
val alamat = userDocument.getString("alamat") ?: ""
val nomor = userDocument.getString("nomor") ?: ""
// Tambahkan data dari koleksi "users" ke pesanList
pesanList.add(DataListPesan(nama, email, alamat, nomor, "", "", "", "", ""))
// Ambil data dari subkoleksi "nota" yang berada di dalam koleksi "users"
firestore.collection("users")
.document(uid)
.collection("nota")
.get()
.addOnSuccessListener { notaQuerySnapshot ->
for (notaDocument in notaQuerySnapshot) {
val kelas_nota = notaDocument.getString("kelas_hotel") ?: ""
val kamar_nota = notaDocument.getString("kamar_hotel") ?: ""
val jumlah_hari_nota = notaDocument.getString("jumlah_hari") ?: ""
val total_nota = notaDocument.getString("total") ?: ""
val status_nota = notaDocument.getString("status") ?: ""
// Tambahkan data dari subkoleksi "nota" ke pesanList
pesanList.add(DataListPesan(nama, email,alamat,nomor, kelas_nota, kamar_nota,jumlah_hari_nota, total_nota, status_nota))
if (isAdded && activity != null) {
populateData()
}
}
}
.addOnFailureListener { notaException ->
// Handle kesalahan jika terjadi saat mengambil data dari subkoleksi "nota"
Log.e("PesanFragment", "Gagal menampilkan nota pembayaran", notaException)
}
}
.addOnFailureListener { userException ->
// Handle kesalahan jika terjadi saat mengambil data dari koleksi "users"
Log.e("PesanFragment", "Gagal menampilkan data pengguna", userException)
}
}
return binding.root
}
private fun populateData() {
val linearLayout = LinearLayoutManager(activity)
linearLayout.stackFromEnd = true
linearLayout.reverseLayout = true
recyclerView.layoutManager = linearLayout
// Gunakan pesanList untuk inisialisasi adapter
val adp = AdapterListPesan(requireActivity(), pesanList)
recyclerView.adapter = adp
}
}
| Hospel/app/src/main/java/com/example/hospel/PesanFragment.kt | 3561067102 |
package com.example.hospel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hospel.databinding.ActivityEditProfilBinding
import com.example.hospel.databinding.ActivityTentangKamiBinding
class TentangKami : AppCompatActivity() {
private lateinit var binding: ActivityTentangKamiBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityTentangKamiBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backTentangKami.setOnClickListener {
onBackPressed()
}
}
} | Hospel/app/src/main/java/com/example/hospel/TentangKami.kt | 3859760316 |
package com.example.hospel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.hospel.databinding.ActivityUbahEmailBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
class UbahEmail : AppCompatActivity() {
private lateinit var binding: ActivityUbahEmailBinding
private val auth = FirebaseAuth.getInstance()
private val firestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityUbahEmailBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.backUbahEmail.setOnClickListener {
onBackPressed()
}
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
firestore.collection("users")
.document(uid)
.get()
.addOnSuccessListener { document ->
if (document.exists()) {
val email = if (isGoogleSignIn()) {
currentUser.email
} else {
document.getString("email") // Gunakan email dari Firestore
}
binding.etUbahEmail.setText(email)
}
}
}
binding.buttonSimpanUbahEmail.setOnClickListener {
val updatedEmail = if (isGoogleSignIn()) {
auth.currentUser?.email // Gunakan email dari Google
} else {
binding.etUbahEmail.text.toString() // Gunakan email dari formulir jika bukan Google SignIn
}
// Simpan perubahan ke Firestore
val user = auth.currentUser
if (user != null) {
val uid = user.uid
if (user.providerData.any { it.providerId == GoogleAuthProvider.PROVIDER_ID }) {
// Pengguna login menggunakan Google, buat data baru di Firestore
val userMap = hashMapOf(
"email" to user.email // Gunakan email dari Google
)
firestore.collection("users")
.document(uid)
.set(userMap as Map<String, Any>, SetOptions.merge())
.addOnSuccessListener {
Toast.makeText(this, "Data berhasil disimpan.", Toast.LENGTH_SHORT).show()
onBackPressed()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Data gagal disimpan, silakan coba lagi.", Toast.LENGTH_SHORT).show()
}
} else {
val userMap = hashMapOf(
"email" to updatedEmail
)
firestore.collection("users")
.document(uid)
.update(userMap as Map<String, Any>)
.addOnSuccessListener {
Toast.makeText(this, "Data berhasil disimpan.", Toast.LENGTH_SHORT).show()
onBackPressed()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Data gagal disimpan, silakan coba lagi.", Toast.LENGTH_SHORT).show()
}
}
}
}
}
private fun isGoogleSignIn(): Boolean {
val currentUser = auth.currentUser
return currentUser != null && currentUser.providerData.any { it.providerId == GoogleAuthProvider.PROVIDER_ID }
}
} | Hospel/app/src/main/java/com/example/hospel/UbahEmail.kt | 2762206459 |
package com.example.hospel
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.hospel.databinding.FragmentProfilBinding
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.squareup.picasso.Picasso
class ProfilFragment : Fragment() {
private lateinit var binding: FragmentProfilBinding
private var auth = FirebaseAuth.getInstance()
private val firestore = FirebaseFirestore.getInstance()
private val storage = FirebaseStorage.getInstance()
private val storageReference: StorageReference = storage.reference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentProfilBinding.inflate(layoutInflater, container, false)
auth = FirebaseAuth.getInstance()
binding.gantiProfil.setOnClickListener {
selectImage()
}
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
val userDocRef = firestore.collection("users").document(uid)
userDocRef.addSnapshotListener { document, error ->
if (error != null) {
return@addSnapshotListener
}
if (document != null && document.exists()) {
val displayName = document.getString("nama")
val email = document.getString("email")
val profileImageURL = document.getString("profile_image")
if (profileImageURL != null) {
Picasso.get()
.load(profileImageURL)
.into(binding.gambarProfilPengaturan)
}
binding.usernamePengaturan.text = displayName
binding.emailPengaturan.text = email
}
}
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.editProfil.setOnClickListener {
val intent = Intent(requireContext(), EditProfil::class.java)
startActivity(intent)
}
binding.tentangKami.setOnClickListener {
val intent = Intent(requireContext(), TentangKami::class.java)
startActivity(intent)
}
binding.dukungan.setOnClickListener {
val intent = Intent(requireContext(), Dukungan::class.java)
startActivity(intent)
}
binding.setting.setOnClickListener {
val intent = Intent(requireContext(), Akun::class.java)
startActivity(intent)
}
binding.exit.setOnClickListener {
showLogoutConfirmationDialog()
}
}
// Metode untuk memilih gambar dari penyimpanan perangkat
private fun selectImage() {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, 1)
}
// Metode untuk menangani hasil pemilihan gambar
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
val imageUri = data.data
// Upload gambar ke Firebase Storage
if (imageUri != null) {
uploadImage(imageUri)
}
}
}
// Metode untuk mengunggah gambar ke Firebase Storage
private fun uploadImage(imageUri: Uri) {
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
// Hapus foto profil lama dari Firebase Storage
deleteOldProfileImage(uid)
// Upload gambar ke Firebase Storage
val profileImageRef = storageReference.child("profile_images/$uid.jpg")
profileImageRef.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
profileImageRef.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
// Simpan URL gambar baru di Firestore
firestore.collection("users")
.document(uid)
.update("profile_image", imageUrl)
.addOnSuccessListener {
// Berhasil mengunggah dan menyimpan URL baru
}
.addOnFailureListener {
// Gagal menyimpan URL baru
}
}
}
.addOnFailureListener { exception ->
// Gagal mengunggah gambar baru
}
}
}
// Metode untuk menghapus foto profil lama dari Firebase Storage
private fun deleteOldProfileImage(uid: String) {
val oldProfileImageRef = storageReference.child("profile_images/$uid.jpg")
oldProfileImageRef.delete()
.addOnSuccessListener {
// Foto profil lama berhasil dihapus
Log.d("StorageDelete", "Foto profil lama berhasil dihapus")
}
.addOnFailureListener { exception ->
// Gagal menghapus foto profil lama
Log.e("StorageDelete", "Gagal menghapus foto profil lama: ${exception.message}")
}
}
private fun showLogoutConfirmationDialog() {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Konfirmasi Keluar")
builder.setMessage("Apakah Anda ingin keluar dari aplikasi?")
builder.setPositiveButton("Ya") { _, _ ->
logoutUser()
}
builder.setNegativeButton("Tidak", null)
builder.show()
}
private fun logoutUser() {
if (auth.currentUser != null) {
// Sign out from Firebase
auth.signOut()
// Sign out from Google
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build()
val googleSignInClient = GoogleSignIn.getClient(requireContext(), gso)
googleSignInClient.signOut()
// Redirect to Login activity
val intent = Intent(requireContext(), Login::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
requireActivity().finish()
}
}
} | Hospel/app/src/main/java/com/example/hospel/ProfilFragment.kt | 267524918 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
class SyaratDanKetentuanActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.syarat_dan_ketentuan)
val back = findViewById<ImageView>(R.id.back_sdk)
back.setOnClickListener {
val intent = Intent(this@SyaratDanKetentuanActivity, Daftar::class.java)
startActivity(intent)
}
val buttonSyarat = findViewById<Button>(R.id.button_syarat)
buttonSyarat.setOnClickListener {
val intent = Intent(this@SyaratDanKetentuanActivity, Daftar::class.java)
intent.putExtra("CHECKBOX_STATUS", true)
startActivity(intent)
}
}
} | Hospel/app/src/main/java/com/example/hospel/SyaratDanKetentuanActivity.kt | 2576249205 |
package com.example.hospel
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.Patterns
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.hospel.databinding.ActivityLoginBinding
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class Login : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var auth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private var loadingProgressBar: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("LoginActivity", "onCreate called")
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
loadingProgressBar = findViewById(R.id.loadingProgressBar)
auth = Firebase.auth
binding.emailLogin.background = null
binding.passwordLogin.background = null
binding.daftarLogin.setOnClickListener {
val intent = Intent(this@Login, Daftar::class.java)
startActivity(intent)
}
if (auth.currentUser != null) {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
if (auth.currentUser != null) {
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
val webClientId = getString(R.string.default_web_client_id)
if (webClientId.isNotEmpty()) {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(webClientId)
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
} else {
Toast.makeText(this, "Web client ID is empty or null", Toast.LENGTH_SHORT).show()
loadingProgressBar?.visibility = View.VISIBLE
}
binding.buttonLogin.setOnClickListener {
signInUser()
}
binding.loginGoogle.setOnClickListener {
signInWithGoogle()
}
}
}
override fun onResume() {
super.onResume()
if (auth.currentUser != null && !isTaskRoot) {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
private var loginAttempts = 0
private fun signInUser() {
val email = binding.emailLogin.text.toString()
val password = binding.passwordLogin.text.toString()
clearErrors()
if (validateForm(email, password)) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
loginAttempts = 0
startActivity(Intent(this, MainActivity::class.java))
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
finish()
} else {
loginAttempts++
if (loginAttempts >= 6) {
Toast.makeText(
this,
"Percobaan login gagal terlalu banyak. Akun diblokir.",
Toast.LENGTH_SHORT
).show()
loadingProgressBar?.visibility = View.VISIBLE
} else {
Toast.makeText(this, "Login gagal. Silakan coba lagi.", Toast.LENGTH_SHORT)
.show()
loadingProgressBar?.visibility = View.VISIBLE
}
}
}
}
}
private fun signInWithGoogle() {
val signInIntent = googleSignInClient.signInIntent
launcher.launch(signInIntent)
}
private val launcher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
handleResult(task)
}
}
private fun handleResult(task: Task<GoogleSignInAccount>) {
if (task.isSuccessful) {
val account: GoogleSignInAccount? = task.result
account?.let {
Log.d("GoogleSignIn", "Google Sign-In Successful. Account: ${it.displayName}")
updateUI(it)
loadingProgressBar?.visibility = View.VISIBLE
}
} else {
Log.e("GoogleSignIn", "Google Sign-In Failed", task.exception)
Toast.makeText(this, "Login gagal, silakan coba lagi", Toast.LENGTH_SHORT).show()
loadingProgressBar?.visibility = View.VISIBLE
}
}
private fun updateUI(account: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(account.idToken, null)
auth.signInWithCredential(credential).addOnCompleteListener {
if (it.isSuccessful) {
Log.d("GoogleSignIn", "Firebase Sign-In Successful")
startActivity(Intent(this, MainActivity::class.java))
finish()
loadingProgressBar?.visibility = View.VISIBLE
} else {
Log.e("GoogleSignIn", "Firebase Sign-In Failed", it.exception)
Toast.makeText(this, "Login Gagal!", Toast.LENGTH_SHORT).show()
loadingProgressBar?.visibility = View.VISIBLE
}
}
}
private fun validateForm(email: String, password: String): Boolean {
var isValid = true
if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.pkEmailLogin.visibility = View.VISIBLE
isValid = false
} else {
binding.pkEmailLogin.visibility = View.INVISIBLE
}
if (TextUtils.isEmpty(password) || password.length < 8) {
binding.pkPasswordLogin.visibility = View.VISIBLE
isValid = false
} else {
binding.pkPasswordLogin.visibility = View.INVISIBLE
}
return isValid
}
private fun clearErrors() {
binding.pkEmailLogin.visibility = View.INVISIBLE
binding.pkPasswordLogin.visibility = View.INVISIBLE
}
}
| Hospel/app/src/main/java/com/example/hospel/Login.kt | 1000283253 |
package com.example.hospel
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.hospel.databinding.ActivityBookingKamarBinding
import com.google.firebase.firestore.FirebaseFirestore
class BookingKamar : AppCompatActivity() {
private lateinit var binding: ActivityBookingKamarBinding
private val firestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBookingKamarBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backBookingKamar.setOnClickListener {
onBackPressed()
}
binding.btnBookingKamar.setOnClickListener {
val documentId = intent.getStringExtra("documentId")
if (documentId != null) {
load(documentId)
}
}
val documentId = intent.getStringExtra("documentId")
if (documentId != null) {
loadNomorKamar(documentId)
}
}
private fun loadNomorKamar(documentId: String) {
firestore.collection("kamar_hotel")
.document(documentId)
.collection("nomer_kamar")
.addSnapshotListener { snapshot, error ->
if (error != null) {
Toast.makeText(this, "Terjadi kesalahan saat memuat nomor kamar", Toast.LENGTH_SHORT).show()
return@addSnapshotListener
}
if (snapshot != null && !snapshot.isEmpty) {
for (document in snapshot.documents) {
val statusKamar1 = document.getString("status_kamar1") ?: ""
val statusKamar2 = document.getString("status_kamar2") ?: ""
val statusKamar3 = document.getString("status_kamar3") ?: ""
val statusKamar4 = document.getString("status_kamar4") ?: ""
val statusKamar5 = document.getString("status_kamar5") ?: ""
val statusKamar6 = document.getString("status_kamar6") ?: ""
val statusKamar7 = document.getString("status_kamar7") ?: ""
val statusKamar8 = document.getString("status_kamar8") ?: ""
val statusKamar9 = document.getString("status_kamar9") ?: ""
val statusKamar10 = document.getString("status_kamar10") ?: ""
setBackgroundCompat(binding.btnNo1, statusKamar1)
setBackgroundCompat(binding.btnNo2, statusKamar2)
setBackgroundCompat(binding.btnNo3, statusKamar3)
setBackgroundCompat(binding.btnNo4, statusKamar4)
setBackgroundCompat(binding.btnNo5, statusKamar5)
setBackgroundCompat(binding.btnNo6, statusKamar6)
setBackgroundCompat(binding.btnNo7, statusKamar7)
setBackgroundCompat(binding.btnNo8, statusKamar8)
setBackgroundCompat(binding.btnNo9, statusKamar9)
setBackgroundCompat(binding.btnNo10, statusKamar10)
}
}
}
}
private fun setBackgroundCompat(textView: TextView, status: String) {
val colorResource = when (status) {
"Kosong" -> R.color.bg_rounded_green
"Penuh" -> R.color.bg_rounded_red
else -> {
R.color.bg_rounded_white // Default color for unexpected status
}
}
val color = ContextCompat.getColor(this, colorResource)
textView.setBackgroundColor(color)
}
private fun load(documentId: String) {
val intent = Intent(this@BookingKamar, Reservasi::class.java)
intent.putExtra("documentId", documentId)
startActivity(intent)
}
}
| Hospel/app/src/main/java/com/example/hospel/BookingKamar.kt | 2760926316 |
package com.example.hospel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hospel.databinding.ActivityInformasiHotelBinding
class InformasiHotel : AppCompatActivity() {
private lateinit var binding : ActivityInformasiHotelBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInformasiHotelBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backInformasiHotel.setOnClickListener {
onBackPressed()
}
}
} | Hospel/app/src/main/java/com/example/hospel/InformasiHotel.kt | 3031837319 |
package com.example.hospel
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hospel.databinding.ActivityDukunganBinding
class Dukungan : AppCompatActivity() {
private lateinit var binding: ActivityDukunganBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDukunganBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backDukungan.setOnClickListener {
onBackPressed()
}
binding.buttonDukungan.setOnClickListener {
val url = "https://docs.google.com/forms/d/e/1FAIpQLSfTrclf5wxcU9EbAtAswVp_VFPyiYwP6K1W3NCQcMpK13eIVg/viewform?vc=0&c=0&w=1&flr=0"
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
}
}
} | Hospel/app/src/main/java/com/example/hospel/Dukungan.kt | 1038547112 |
package com.example.hospel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.hospel.databinding.ActivityUbahPasswordBinding
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
class UbahPassword : AppCompatActivity() {
private lateinit var binding: ActivityUbahPasswordBinding
private val auth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUbahPasswordBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backUbahPassword.setOnClickListener {
onBackPressed()
}
binding.buttonSimpanUbahPassword.setOnClickListener {
ubahPassword()
}
}
private fun ubahPassword() {
val passwordSaatIni = binding.etPasswordSaatIni.text.toString()
val passwordBaru = binding.etPasswordBaru.text.toString()
val konfirmasiPasswordBaru = binding.etKonfirmasiPasswordBaru.text.toString()
val user: FirebaseUser? = auth.currentUser
if (user != null && user.email != null) {
// Memeriksa apakah password saat ini sesuai
val credential = EmailAuthProvider.getCredential(user.email!!, passwordSaatIni)
user.reauthenticate(credential)
.addOnSuccessListener {
// Password saat ini sesuai, lanjutkan dengan memeriksa kondisi lainnya
if (passwordBaru == passwordSaatIni) {
// Password baru tidak boleh sama dengan password saat ini
Toast.makeText(this, "Password baru tidak boleh sama dengan password saat ini", Toast.LENGTH_SHORT).show()
} else if (passwordBaru != konfirmasiPasswordBaru) {
// Konfirmasi password harus sama dengan password baru
Toast.makeText(this, "Konfirmasi password harus sama dengan password baru", Toast.LENGTH_SHORT).show()
} else {
// Lakukan perubahan password
user.updatePassword(passwordBaru)
.addOnSuccessListener {
Toast.makeText(this, "Password berhasil diubah", Toast.LENGTH_SHORT).show()
onBackPressed()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Gagal mengubah password: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
}
.addOnFailureListener { e ->
// Password saat ini tidak sesuai
Toast.makeText(this, "Password saat ini salah", Toast.LENGTH_SHORT).show()
}
}
}
} | Hospel/app/src/main/java/com/example/hospel/UbahPassword.kt | 860761243 |
package com.example.hospel
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
class AdapterListPesan (val context: Context, val homeList: ArrayList<DataListPesan?>): RecyclerView.Adapter<AdapterListPesan.MyViewHolder>() {
private val auth = FirebaseAuth.getInstance()
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val nama_nota = view.findViewById<TextView>(R.id.nama_nota)
val email_nota = view.findViewById<TextView>(R.id.email_nota)
val alamat_nota = view.findViewById<TextView>(R.id.alamat_nota)
val nomor_nota = view.findViewById<TextView>(R.id.nomor_nota)
val kelas_nota = view.findViewById<TextView>(R.id.kelas_nota)
val kamar_nota = view.findViewById<TextView>(R.id.kamar_nota)
val jumlah_hari_nota = view.findViewById<TextView>(R.id.jumlah_hari_nota)
val total_nota = view.findViewById<TextView>(R.id.total_nota)
val status_nota = view.findViewById<TextView>(R.id.status_nota)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.fetch_list_pesan, parent, false)
return AdapterListPesan.MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = homeList[position]
val userId = auth.currentUser?.uid
if (userId != null) {
holder.nama_nota.text = currentItem?.nama_nota
holder.email_nota.text = currentItem?.email_nota
holder.alamat_nota.text = currentItem?.alamat_nota
holder.nomor_nota.text = currentItem?.nomor_nota
holder.kelas_nota.text = currentItem?.kelas_nota
holder.kamar_nota.text = currentItem?.kamar_nota
holder.jumlah_hari_nota.text = currentItem?.jumlah_hari_nota
holder.total_nota.text = currentItem?.total_nota
holder.status_nota.text = currentItem?.status_nota
// Set warna teks berdasarkan status
when (currentItem?.status_nota) {
"Sudah dibayar" -> holder.status_nota.setTextColor(ContextCompat.getColor(context, R.color.green)) // Sesuaikan dengan ID warna hijau
"Menunggu pembayaran" -> holder.status_nota.setTextColor(ContextCompat.getColor(context, R.color.red)) // Sesuaikan dengan ID warna merah
}
}
}
override fun getItemCount(): Int {
return homeList.size
}
} | Hospel/app/src/main/java/com/example/hospel/AdapterListPesan.kt | 2455620154 |
package com.example.hospel
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.hospel.databinding.ActivityReservasiBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
class Reservasi : AppCompatActivity() {
private lateinit var binding: ActivityReservasiBinding
private val firestore = FirebaseFirestore.getInstance()
private val auth = FirebaseAuth.getInstance()
private var total: String = ""
private var kelasKamar: String = ""
private var isProcessing = false // Variable untuk memastikan tidak ada proses ganda
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityReservasiBinding.inflate(layoutInflater)
setContentView(binding.root)
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
firestore.collection("users")
.document(uid)
.get()
.addOnSuccessListener { document ->
if (document.exists()) {
val fullname = document.getString("nama")
val email = document.getString("email")
val nomor = document.getString("nomor")
val alamat = document.getString("alamat")
// Isi formulir dengan data saat ini
binding.namaReservasi.setText(fullname)
binding.emailReservasi.setText(email)
binding.etNomorReservasi.setText(nomor)
binding.etAlamatReservasi.setText(alamat)
}
}
}
binding.btnSimpanReservasi.setOnClickListener {
if (isProcessing) {
// Jika sedang dalam proses, keluar dari fungsi
return@setOnClickListener
}
// Menampilkan kotak dialog konfirmasi
showConfirmationDialog()
}
}
private fun showConfirmationDialog() {
val builder = AlertDialog.Builder(this)
val title =
"Transfer ke BCA no rek : 1234567890 Atas Nama : Aditya Yuda Pamungkas. Transfer sesuai total yang harus dibayarkan yang tampil di menu Pesan"
val message = "Apakah anda ingin melanjutkan pembayaran?"
builder.setTitle("Perhatian")
builder.setMessage("$title\n\n$message")
builder.setPositiveButton("Lanjutkan") { dialog, which ->
// Eksekusi prosesnya
executeReservationProcess()
executeReservationProcess2()
}
builder.setNegativeButton("Tidak") { dialog, which ->
// Tindakan jika memilih "Tidak"
// Di sini Anda dapat menambahkan tindakan yang sesuai, jika diperlukan
Toast.makeText(this, "Pemesanan dibatalkan", Toast.LENGTH_SHORT).show()
}
builder.show()
}
private fun executeReservationProcess() {
// Mengunci proses
isProcessing = true
val jumlahHari = binding.teksJumlahHari.text.toString()
val nomorKamar = binding.etNomorKamarReservasi.text.toString()
// Memastikan tidak ada nilai yang kosong
if (jumlahHari.isEmpty() || nomorKamar.isEmpty()) {
Toast.makeText(this, "Harap isi semua kolom!", Toast.LENGTH_SHORT).show()
// Membuka kunci setelah proses selesai
isProcessing = false
return
}
// Simpan perubahan ke Firestore
val user = auth.currentUser
if (user != null) {
val uid = user.uid
val userMap = hashMapOf(
"jumlah_hari" to jumlahHari,
"kamar_hotel" to nomorKamar,
"status" to "Menunggu pembayaran"
)
// Update data in the "users" collection
firestore.collection("users")
.document(uid)
.set(userMap as Map<String, Any>, SetOptions.merge())
.addOnSuccessListener {
// Continue to save data to the "nota" subcollection
firestore.collection("users")
.document(uid)
.collection("nota")
.add(userMap)
.addOnSuccessListener {
// Jika sukses, pindah ke MainActivity
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
Toast.makeText(
this,
"Pemesanan berhasil! Lakukan pembayaran, dan mohon tunggu sedang diverifikasi oleh admin",
Toast.LENGTH_SHORT
).show()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Pemesanan gagal!", Toast.LENGTH_SHORT).show()
}
.addOnCompleteListener {
// Membuka kunci setelah proses selesai
isProcessing = false
}
}
.addOnFailureListener { e ->
Toast.makeText(this, "Pemesanan gagal!", Toast.LENGTH_SHORT).show()
// Membuka kunci setelah proses selesai (termasuk jika ada kegagalan)
isProcessing = false
}
}
}
private fun executeReservationProcess2() {
// Mengunci proses
isProcessing = true
val documentId = intent.getStringExtra("documentId")
if (documentId != null) {
loadKamar(documentId)
}
// Ambil nilai dari binding dan simpan di dalam variabel
total = binding.total.text.toString()
kelasKamar = binding.kelasKamar.text.toString()
// Simpan perubahan ke Firestore
val user = auth.currentUser
if (user != null) {
val uid = user.uid
val userMap = hashMapOf(
"kelas_hotel" to total,
"total" to kelasKamar
)
// Update data in the "users" collection
firestore.collection("users")
.document(uid)
.set(userMap as Map<String, Any>, SetOptions.merge())
.addOnSuccessListener {
// Continue to save data to the "nota" subcollection
firestore.collection("users")
.document(uid)
.collection("nota")
.add(userMap)
.addOnSuccessListener {
// Jika sukses, pindah ke MainActivity
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
Toast.makeText(
this,
"Pemesanan berhasil! Lakukan pembayaran, dan mohon tunggu sedang diverifikasi oleh admin",
Toast.LENGTH_SHORT
).show()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Pemesanan gagal!", Toast.LENGTH_SHORT).show()
}
.addOnCompleteListener {
// Membuka kunci setelah proses selesai
isProcessing = false
}
}
.addOnFailureListener { e ->
Toast.makeText(this, "Pemesanan gagal!", Toast.LENGTH_SHORT).show()
// Membuka kunci setelah proses selesai (termasuk jika ada kegagalan)
isProcessing = false
}
}
}
private fun loadKamar(documentId: String) {
firestore.collection("kamar_hotel")
.document(documentId)
.addSnapshotListener { snapshot, error ->
if (error != null) {
Toast.makeText(
this,
"Terjadi kesalahan saat memuat nomor kamar",
Toast.LENGTH_SHORT
).show()
return@addSnapshotListener
}
if (snapshot != null && snapshot.exists()) {
total = snapshot.getString("harga_kamar") ?: ""
kelasKamar = snapshot.getString("nama_kamar") ?: ""
binding.total.setText(total)
binding.kelasKamar.setText(kelasKamar)
}
}
}
}
| Hospel/app/src/main/java/com/example/hospel/Reservasi.kt | 920612144 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
class SplashScreen : AppCompatActivity() {
private val splashTimeOut : Long = 2000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
Handler().postDelayed({
startActivity(Intent(this, Login::class.java))
finish()
}, splashTimeOut)
}
} | Hospel/app/src/main/java/com/example/hospel/SplashScreen.kt | 202410141 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import com.example.hospel.databinding.ActivityKelasHotelBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.squareup.picasso.Picasso
class KelasHotel : AppCompatActivity() {
private lateinit var binding: ActivityKelasHotelBinding
private var auth = FirebaseAuth.getInstance()
private var loadingProgressBar: ProgressBar? = null
private val firestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityKelasHotelBinding.inflate(layoutInflater)
loadingProgressBar = findViewById(R.id.loadingProgressBar)
auth = FirebaseAuth.getInstance()
setContentView(binding.root)
binding.backKelasHotel.setOnClickListener {
onBackPressed()
}
binding.kelasEkonomi.setOnClickListener {
loadDetailKamar("LSdCMTBu4paaSG7iM1kd")
}
binding.kelasMenengah.setOnClickListener {
loadDetailKamar("s8aHBMm2duKrtxWTcSBo")
}
binding.kelasPremium.setOnClickListener {
loadDetailKamar("3y4YsQAaSS1YARn94Ugp")
}
binding.kelasEksklusif.setOnClickListener {
loadDetailKamar("jTev6AGwKLzTmS8cZ6uj")
}
firestore.collection("kamar_hotel")
.document("LSdCMTBu4paaSG7iM1kd") // Ganti dengan ID dokumen yang sesuai
.addSnapshotListener { dokumen, error ->
if (error != null) {
return@addSnapshotListener
}
if (dokumen != null && dokumen.exists()) {
val namaHotel = dokumen.getString("nama_kamar")
val hargaHotel = dokumen.getString("harga_kamar")
val gambarHotel = dokumen.getString("hotel_image")
binding.teksKelasEkonomi.text = namaHotel
binding.hargaEkonomi.text = hargaHotel
// Gunakan Picasso atau library pemuatan gambar lainnya untuk memuat gambar ke dalam ImageView
if (gambarHotel != null && gambarHotel.isNotEmpty()) {
Picasso.get().load(gambarHotel).into(binding.gambarEkonomi)
}
loadingProgressBar?.visibility = View.VISIBLE
}
}
firestore.collection("kamar_hotel")
.document("s8aHBMm2duKrtxWTcSBo") // Ganti dengan ID dokumen yang sesuai
.addSnapshotListener { dokumen, error ->
if (error != null) {
return@addSnapshotListener
}
if (dokumen != null && dokumen.exists()) {
val namaHotel = dokumen.getString("nama_kamar")
val hargaHotel = dokumen.getString("harga_kamar")
val gambarHotel = dokumen.getString("hotel_image")
binding.teksKelasMenengah.text = namaHotel
binding.hargaMenengah.text = hargaHotel
// Gunakan Picasso atau library pemuatan gambar lainnya untuk memuat gambar ke dalam ImageView
if (gambarHotel != null && gambarHotel.isNotEmpty()) {
Picasso.get().load(gambarHotel).into(binding.gambarMenengah)
}
loadingProgressBar?.visibility = View.VISIBLE
}
}
firestore.collection("kamar_hotel")
.document("3y4YsQAaSS1YARn94Ugp") // Ganti dengan ID dokumen yang sesuai
.addSnapshotListener { dokumen, error ->
if (error != null) {
return@addSnapshotListener
}
if (dokumen != null && dokumen.exists()) {
val namaHotel = dokumen.getString("nama_kamar")
val hargaHotel = dokumen.getString("harga_kamar")
val gambarHotel = dokumen.getString("hotel_image")
binding.teksKelasPremium.text = namaHotel
binding.hargaPremium.text = hargaHotel
// Gunakan Picasso atau library pemuatan gambar lainnya untuk memuat gambar ke dalam ImageView
if (gambarHotel != null && gambarHotel.isNotEmpty()) {
Picasso.get().load(gambarHotel).into(binding.gambarPremium)
loadingProgressBar?.visibility = View.VISIBLE
}
}
}
firestore.collection("kamar_hotel")
.document("jTev6AGwKLzTmS8cZ6uj") // Ganti dengan ID dokumen yang sesuai
.addSnapshotListener { dokumen, error ->
if (error != null) {
return@addSnapshotListener
}
if (dokumen != null && dokumen.exists()) {
val namaHotel = dokumen.getString("nama_kamar")
val hargaHotel = dokumen.getString("harga_kamar")
val gambarHotel = dokumen.getString("hotel_image")
binding.teksKelasEksklusif.text = namaHotel
binding.hargaEksklusif.text = hargaHotel
// Gunakan Picasso atau library pemuatan gambar lainnya untuk memuat gambar ke dalam ImageView
if (gambarHotel != null && gambarHotel.isNotEmpty()) {
Picasso.get().load(gambarHotel).into(binding.gambarEksklusif)
loadingProgressBar?.visibility = View.VISIBLE
}
}
}
}
private fun loadDetailKamar(documentId: String) {
val intent = Intent(this@KelasHotel, DetailKamarEkonomi::class.java)
intent.putExtra("documentId", documentId)
startActivity(intent)
}
} | Hospel/app/src/main/java/com/example/hospel/KelasHotel.kt | 1898794359 |
package com.example.hospel
data class DataListPesan(
val nama_nota: String,
val email_nota: String,
val alamat_nota: String,
var nomor_nota: String?,
var kelas_nota: String?,
var kamar_nota: String?,
var jumlah_hari_nota: String?,
var total_nota: String?,
var status_nota: String?
)
| Hospel/app/src/main/java/com/example/hospel/DataListPesan.kt | 3060571669 |
package com.example.hospel
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.hospel.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding : FragmentHomeBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.reservasiHotel.setOnClickListener{
val intent = Intent(requireContext(), KelasHotel::class.java)
startActivity(intent)
}
binding.informasiHotel.setOnClickListener {
val intent = Intent(requireContext(), InformasiHotel::class.java)
startActivity(intent)
}
}
} | Hospel/app/src/main/java/com/example/hospel/HomeFragment.kt | 3452276305 |
package com.example.hospel
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.example.hospel.databinding.ActivityEditProfilBinding
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
class EditProfil : AppCompatActivity() {
private lateinit var binding: ActivityEditProfilBinding
private val firestore = FirebaseFirestore.getInstance()
private val auth = FirebaseAuth.getInstance()
private var currentProfileImageUrl: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditProfilBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backEditProfil.setOnClickListener {
onBackPressed()
}
binding.buttonSimpan.setOnClickListener {
}
val currentUser = auth.currentUser
if (currentUser != null) {
val uid = currentUser.uid
firestore.collection("users")
.document(uid)
.get()
.addOnSuccessListener { document ->
if (document.exists()) {
val fullname = document.getString("nama")
val nomor = document.getString("nomor")
val alamat = document.getString("alamat")
// Tambahkan ini untuk menyimpan URL gambar profil saat ini
currentProfileImageUrl = document.getString("profile_image").toString()
// Isi formulir dengan data saat ini
binding.etNama.setText(fullname)
binding.etNomor.setText(nomor)
binding.etAlamat.setText(alamat)
}
}
}
binding.buttonSimpan.setOnClickListener {
val updatedFullname = binding.etNama.text.toString()
val updatedNomor = binding.etNomor.text.toString()
val updatedAlamat = binding.etAlamat.text.toString()
// Simpan perubahan ke Firestore
val user = auth.currentUser
if (user != null) {
val uid = user.uid
if (user.providerData.any { it.providerId == GoogleAuthProvider.PROVIDER_ID }) {
// Pengguna login menggunakan Google, buat data baru di Firestore
val userMap = hashMapOf(
"nama" to updatedFullname,
"nomor" to updatedNomor,
"alamat" to updatedAlamat
)
firestore.collection("users")
.document(uid)
.set(userMap as Map<String, Any>, SetOptions.merge())
.addOnSuccessListener {
Toast.makeText(this, "Data berhasil disimpan.", Toast.LENGTH_SHORT).show()
onBackPressed()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Data gagal disimpan, silakan coba lagi.", Toast.LENGTH_SHORT).show()
}
} else {
val userMap = hashMapOf(
"nama" to updatedFullname,
"nomor" to updatedNomor,
"alamat" to updatedAlamat
)
firestore.collection("users")
.document(uid)
.update(userMap as Map<String, Any>)
.addOnSuccessListener {
Toast.makeText(this, "Data berhasil disimpan.", Toast.LENGTH_SHORT).show()
onBackPressed()
finish()
}
.addOnFailureListener { e ->
Toast.makeText(this, "Data gagal disimpan, silakan coba lagi.", Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
| Hospel/app/src/main/java/com/example/hospel/EditProfil.kt | 2424899131 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hospel.databinding.ActivityDetailKamarEkonomiBinding
import com.google.firebase.firestore.FirebaseFirestore
import com.squareup.picasso.Picasso
class DetailKamarEkonomi : AppCompatActivity() {
private lateinit var binding : ActivityDetailKamarEkonomiBinding
private val firestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailKamarEkonomiBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backDetailKamar.setOnClickListener {
onBackPressed()
}
binding.buttonDetail.setOnClickListener {
val documentId = intent.getStringExtra("documentId")
if (documentId != null) {
loadBookingKamar(documentId)
}
}
val documentId = intent.getStringExtra("documentId")
if (documentId != null) {
loadKamarDetail(documentId)
}
}
private fun loadKamarDetail(documentId: String) {
firestore.collection("kamar_hotel")
.document(documentId)
.addSnapshotListener { dokumen, error ->
if (error != null) {
// Handle error, misalnya tampilkan pesan kesalahan
return@addSnapshotListener
}
if (dokumen != null && dokumen.exists()) {
val namaHotel = dokumen.getString("nama_kamar")
val gambarHotel = dokumen.getString("hotel_image")
val deskripsi = dokumen.getString("deskripsi")
val fasilitas = dokumen.getString("fasilitas")
binding.teksKelasDetailKamar.text = namaHotel
binding.teksDeskripsiDetail.text = deskripsi
binding.fasilitas.text = fasilitas
// Gunakan Picasso atau library pemuatan gambar lainnya untuk memuat gambar ke dalam ImageView
if (gambarHotel != null && gambarHotel.isNotEmpty()) {
Picasso.get().load(gambarHotel).into(binding.gambarDetailKamar)
}
}
}
}
private fun loadBookingKamar(documentId: String) {
val intent = Intent(this@DetailKamarEkonomi, BookingKamar::class.java)
intent.putExtra("documentId", documentId)
startActivity(intent)
}
} | Hospel/app/src/main/java/com/example/hospel/DetailKamarEkonomi.kt | 1147577998 |
package com.example.hospel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Patterns
import android.view.View
import android.widget.Toast
import com.example.hospel.databinding.ActivityDaftarBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
class Daftar : AppCompatActivity() {
private lateinit var binding : ActivityDaftarBinding
private lateinit var auth: FirebaseAuth
private val firestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDaftarBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = Firebase.auth
binding.namaDaftar.background = null
binding.emailDaftar.background = null
binding.passwordDaftar.background = null
binding.syaratDanKetentuan.setOnClickListener {
val intent = Intent(this@Daftar, SyaratDanKetentuanActivity::class.java)
startActivity(intent)
}
binding.login.setOnClickListener {
val intent = Intent(this@Daftar, Login::class.java)
startActivity(intent)
}
val checkboxStatus = intent.getBooleanExtra("CHECKBOX_STATUS", false)
binding.cbDaftar.isChecked = checkboxStatus
binding.buttonDaftar.setOnClickListener {
val nama = binding.namaDaftar.text.toString()
val email = binding.emailDaftar.text.toString()
val password = binding.passwordDaftar.text.toString()
val checkBoxChecked: Boolean = binding.cbDaftar.isChecked
clearErrors()
if (validateForm(nama, email, password, checkBoxChecked)) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = auth.currentUser
if (user != null) {
val uid = user.uid
val userMap = HashMap<String, Any>()
userMap["nama"] = nama
userMap["email"] = email
firestore.collection("users")
.document(uid)
.set(userMap)
.addOnSuccessListener {
Toast.makeText(this, "Selamat Daftar Berhasil!", Toast.LENGTH_SHORT).show()
startActivity(Intent(this@Daftar, Login::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
})
finish()
}
.addOnFailureListener {
Toast.makeText(this, "Gagal menyimpan email ke Firestore", Toast.LENGTH_SHORT).show() }
}
} else {
Toast.makeText(this, "Registrasi Gagal! ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
}
private fun validateForm(fullname: String, email: String, password: String, checkBoxChecked: Boolean): Boolean {
var isValid = true
if (TextUtils.isEmpty(fullname)) {
binding.pkNama?.visibility = View.VISIBLE
isValid = false
} else {
binding.pkNama?.visibility = View.INVISIBLE
}
if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.pkEmail?.visibility = View.VISIBLE
isValid = false
} else {
binding.pkEmail?.visibility = View.INVISIBLE
}
if (TextUtils.isEmpty(password) || password.length < 8) {
binding.pkPassword?.visibility = View.VISIBLE
isValid = false
} else {
binding.pkPassword?.visibility = View.INVISIBLE
}
if (!checkBoxChecked) {
Toast.makeText(applicationContext, "Baca Syarat dan Ketentuan jika setuju centang checkbox untuk mendaftar!", Toast.LENGTH_SHORT).show()
isValid = false
}
return isValid
}
private fun clearErrors() {
binding.pkNama?.visibility = View.INVISIBLE
binding.pkEmail?.visibility = View.INVISIBLE
binding.pkPassword?.visibility = View.INVISIBLE
}
} | Hospel/app/src/main/java/com/example/hospel/Daftar.kt | 431625676 |
package com.example.lego
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.lego", appContext.packageName)
}
} | proyectoConvergentes/app/src/androidTest/java/com/example/lego/ExampleInstrumentedTest.kt | 1501488071 |
package com.example.lego
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)
}
} | proyectoConvergentes/app/src/test/java/com/example/lego/ExampleUnitTest.kt | 1007996569 |
package com.example.lego
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.auth
import com.google.firebase.Firebase
class EmailPasswordActivity: Activity() {
private lateinit var auth: FirebaseAuth
} | proyectoConvergentes/app/src/main/java/com/example/lego/EmailPasswordActivity.kt | 3632912074 |
package com.example.lego
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class HomeActivity : AppCompatActivity(){
// lateinit var usernameIN: EditText
// lateinit var cerrar_btn:Button
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
//usernameIN = findViewById(R.id.usernameIN)
super.onCreate(savedInstanceState, persistentState)
setContentView(R.layout.activity_home)
//val bundle = intent.extras
//val username = bundle?.getString("username")
//setup(username?: "Yipi")
}
private fun iniciarForm(){
val FormIntent = Intent(this, FormularioOrigen::class.java)
startActivity(FormIntent)
}
// private fun setup(username:String){
// title = "Inicio"
// usernameIN.setText(username)
//
// cerrar_btn.setOnClickListener {
// FirebaseAuth.getInstance().signOut()
// onBackPressed()
// }
//}
}
| proyectoConvergentes/app/src/main/java/com/example/lego/HomeActivity.kt | 2189727132 |
package com.example.lego
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.Firebase
class AuthActivity : AppCompatActivity() {
lateinit var username:EditText
lateinit var password:EditText
lateinit var login_btn:Button
lateinit var reallogin_btn:Button
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
auth = Firebase.auth
username = findViewById(R.id.username)
password = findViewById(R.id.password)
login_btn = findViewById(R.id.login_btn)
reallogin_btn = findViewById(R.id.reallogin_btn)
//setup
setup()
}
private fun setup() {
title = "Authentication"
reallogin_btn.setOnClickListener {
if(username.text.isNotEmpty() && password.text.isNotEmpty()) {
val usernameIn = username.text.toString()
val passwordIn = password.text.toString()
FirebaseAuth.getInstance().createUserWithEmailAndPassword(usernameIn, passwordIn).addOnCompleteListener{
if(it.isSuccessful){
//showHome(it.result?.user?.email ?: "Nobrother")
showHome()
} else {
showAlertCreate()
}
}
Log.i("Credenciales revisadas", "Username : $usernameIn and Password: $passwordIn")
}
}
login_btn.setOnClickListener {
if(username.text.isNotEmpty() && password.text.isNotEmpty()) {
val usernameIn = username.text.toString()
val passwordIn = password.text.toString()
FirebaseAuth.getInstance().signInWithEmailAndPassword(usernameIn, passwordIn).addOnCompleteListener{
if(it.isSuccessful){
//showHome(it.result?.user?.email ?: "Nobrother")
showHome()
} else {
showAlert()
}
}
Log.i("Credenciales revisadas", "Username : $usernameIn and Password: $passwordIn")
}
}
}
private fun showAlert() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Se produjo un error de autenticar / contraseña o correo invalidos")
builder.setPositiveButton("Aceptar",null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlertCreate() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Se produjo un error al crear la cuenta")
builder.setPositiveButton("Aceptar",null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showHome(){
// val homeIntent = Intent(this, HomeActivity::class.java).apply {
//putExtra("usuario",usuario)
//}
val homeIntent = Intent(this, HomeActivity::class.java)
startActivity(homeIntent)
}
}
| proyectoConvergentes/app/src/main/java/com/example/lego/AuthActivity.kt | 288034967 |
package com.epoxy.playground
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.epoxy.playground", appContext.packageName)
}
} | EpoxyPlayGround/app/src/androidTest/java/com/epoxy/playground/ExampleInstrumentedTest.kt | 2237655165 |
package com.epoxy.playground
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)
}
} | EpoxyPlayGround/app/src/test/java/com/epoxy/playground/ExampleUnitTest.kt | 2281813992 |
package com.epoxy.playground
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)
}
} | EpoxyPlayGround/app/src/main/java/com/epoxy/playground/MainActivity.kt | 1261712592 |
package com.jakubisz.obd2ai
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.jakubisz.obd2ai", appContext.packageName)
}
} | OBD2AI/Src/app/src/androidTest/java/com/jakubisz/obd2ai/ExampleInstrumentedTest.kt | 3332743511 |
package com.jakubisz.obd2ai
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)
}
} | OBD2AI/Src/app/src/test/java/com/jakubisz/obd2ai/ExampleUnitTest.kt | 770880507 |
package com.jakubisz.obd2ai.ui.viewmodels
import android.app.Activity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.jakubisz.obd2ai.model.BluetoothDeviceDTO
import com.jakubisz.obd2ai.model.DtpCodeDTO
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
interface IConnectorViewModel {
val isBluetoothPermissionGranted: LiveData<Boolean>
var dtp: MutableList<String>
var pendingDtp: MutableList<String>
var permanentDtp: MutableList<String>
val allDtp: List<String>
val dtpResults: MutableLiveData<List<DtpCodeDTO>>
fun requestBluetoothPermissions(activity: Activity)
fun enableBluetooth(activity: Activity)
fun getAvailableDevices(): List<BluetoothDeviceDTO>
fun connectToDevice(deviceAddress: String, onSuccess: (Pair<InputStream, OutputStream>) -> Unit, onFailure: (IOException) -> Unit)
fun disconnectFromDevice()
fun setupOBDConnection(deviceAddress: String)
suspend fun gatherDtpCodes()
fun assesDtpCodes()
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/viewmodels/IConnectorViewModel.kt | 493360028 |
package com.jakubisz.obd2ai.ui.viewmodels
import android.app.Activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jakubisz.obd2ai.helpers.BluetoothHelper
import com.jakubisz.obd2ai.helpers.ObdHelper
import com.jakubisz.obd2ai.helpers.OpenAIService
import com.jakubisz.obd2ai.model.BluetoothDeviceDTO
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class TestViewModel(private val bluetoothHelper: BluetoothHelper, private val obdHelper: ObdHelper, private val openAI: OpenAIService) : ViewModel() {
// Function to request Bluetooth permissions
fun requestBluetoothPermissions(activity: Activity) {
bluetoothHelper.requestPermissions(activity)
}
// Function to enable Bluetooth
fun enableBluetooth(activity: Activity) {
viewModelScope.launch {
try {
bluetoothHelper.enableBluetooth()
} catch (e: SecurityException) {
// Handle if permissions are not granted
bluetoothHelper.requestPermissions(activity)
}
}
}
// Function to get available devices
fun getAvailableDevices(): List<BluetoothDeviceDTO> {
return bluetoothHelper.getAvailableDevices()
}
// Function to connect to a device
fun connectToDevice(deviceAddress: String, onSuccess: (Pair<InputStream, OutputStream>) -> Unit, onFailure: (IOException) -> Unit) {
viewModelScope.launch {
try {
val connection = bluetoothHelper.connectToDevice(deviceAddress)
onSuccess(connection)
} catch (e: IOException) {
onFailure(e)
}
}
}
suspend fun getDtpErrorExplanation() : String
{
//Example of function
obdHelper.setupObd("00:1D:A5:68:98:8B")
var connection = obdHelper.getObdDeviceConnection()
var dtp = obdHelper.getDtpCodes()
var pendDtp = obdHelper.getPendingDtpCodes()
var permDtp = obdHelper.getPermanentDtpCodes()
var query = "Assess these DTP codes for Renault Clio 2001: Classic error codes: {$dtp}, Pending error codes: {$pendDtp}, Permanent(deleted) error codes: {$permDtp}"
var response = openAI.getResponse(query)
return response
}
suspend fun getDtpErrorExplanationExample() : String
{
//Example of function
//obdHelper.setupObd("00:1D:A5:68:98:8B")
//var connection = obdHelper.getObdDeviceConnection()
var dtp = "P504, P500"
var pendDtp = "P0532, P0331"
var permDtp = "P0136, P3404"
var query = "Assess these DTP codes for Renault Clio 2001: Classic error codes: {$dtp}, Pending error codes: {$pendDtp}, Permanent(deleted) error codes: {$permDtp}"
var response = openAI.getResponse(query)
return response
}
suspend fun testApi(): String {
return openAI.getResponse("This is test say something smart.")
}
// Function to disconnect from a device
fun disconnectFromDevice() {
bluetoothHelper.disconnectFromDevice()
}
// Additional functions as needed
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/viewmodels/TestViewModel.kt | 3947353081 |
package com.jakubisz.obd2ai.ui.viewmodels
import android.app.Activity
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jakubisz.obd2ai.helpers.BluetoothHelper
import com.jakubisz.obd2ai.helpers.ObdHelper
import com.jakubisz.obd2ai.helpers.OpenAIService
import com.jakubisz.obd2ai.model.BluetoothDeviceDTO
import com.jakubisz.obd2ai.model.DtpCodeDTO
import com.jakubisz.obd2ai.model.ErrorSeverity
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class ConnectorViewModel(
private val bluetoothHelper: BluetoothHelper,
private val obdHelper: ObdHelper,
private val openAI: OpenAIService
) : ViewModel() {
// Function to request Bluetooth permissions
val isBluetoothPermissionGranted: LiveData<Boolean> = bluetoothHelper.isBluetoothPermissionGranted
var dtp : MutableList<String> = mutableListOf()
var pendingDtp : MutableList<String> = mutableListOf()
var permanentDtp : MutableList<String> = mutableListOf()
val allDtp = dtp + pendingDtp + permanentDtp
val dtpResults = MutableLiveData<List<DtpCodeDTO>>()
//---------------------------------Bluetooth---------------------------------
// Function to request Bluetooth permissions
fun requestBluetoothPermissions(activity: Activity) {
bluetoothHelper.requestPermissions(activity)
}
// Function to enable Bluetooth
fun enableBluetooth(activity: Activity) {
viewModelScope.launch {
try {
bluetoothHelper.enableBluetooth()
} catch (e: SecurityException) {
// Handle if permissions are not granted
bluetoothHelper.requestPermissions(activity)
}
}
}
// Function to get available devices
fun getAvailableDevices(): List<BluetoothDeviceDTO> {
val dummyDevices = mutableListOf<BluetoothDeviceDTO>()
//Real data
dummyDevices.addAll(bluetoothHelper.getAvailableDevices())
// Dummy data
for (i in 1..15) {
dummyDevices.add(
BluetoothDeviceDTO(
name = "Dummy Device $i",
address = "00:00:00:00:00:${i.toString().padStart(2, '0')}"
)
)
}
return dummyDevices
// return bluetoothHelper.getAvailableDevices()
}
// Function to connect to a device
fun connectToDevice(deviceAddress: String, onSuccess: (Pair<InputStream, OutputStream>) -> Unit, onFailure: (IOException) -> Unit) {
viewModelScope.launch {
try {
val connection = bluetoothHelper.connectToDevice(deviceAddress)
onSuccess(connection)
} catch (e: IOException) {
onFailure(e)
}
}
}
// Function to disconnect from a device
fun disconnectFromDevice() {
bluetoothHelper.disconnectFromDevice()
}
//---------------------------------OBD---------------------------------
// Function to setup OBD connection
fun setupOBDConnection(deviceAddress: String) {
viewModelScope.launch { obdHelper.setupObd(deviceAddress) }
}
// Function to get DTP codes from OBD sensor
suspend fun gatherDtpCodes()
{
dtp = obdHelper.getDtpCodes().toMutableList()
pendingDtp = obdHelper.getPendingDtpCodes().toMutableList()
permanentDtp = obdHelper.getPermanentDtpCodes().toMutableList()
}
//---------------------------------OpenAI---------------------------------
// Function to get DTP codes
fun assesDtpCodes() {
viewModelScope.launch {
try {
//val results = listOf(openAI.getDtpCodeAssessment("P0300"))
val results = dtp.map { openAI.getDtpCodeAssessment(it) }
dtpResults.postValue(results)
} catch (e: SecurityException) {
Log.e("ConnectorViewModel", "Error in assesDtpCodes: ${e.message}")
dtpResults.postValue(emptyList())
}
}
}
//---------------------------------Tests---------------------------------
fun assesDtpCodesTest() {
val results = mutableListOf<DtpCodeDTO>()
results.add( DtpCodeDTO( errorCode = "P0300", severity = ErrorSeverity.HIGH, title = "Random/Multiple Cylinder Misfire Detected", detail = "This code indicates that one or more engine cylinders are misfiring, causing the engine to run unevenly. This could be due to several factors such as faulty spark plugs, ignition coil, fuel injectors, camshaft/crankshaft position sensors, or issues with the air-fuel mixture.", implications = "If left unresolved, this problem could lead to significant reduction in engine performance, fuel economy, and an increase in harmful emissions. In severe cases, it may cause damage to the catalytic converter, a major and expensive component of the vehicle's emission control system.", suggestedActions = listOf("Check and replace spark plugs and wires if necessary", "Test ignition coils and replace if necessary", "Inspect fuel injectors and replace if necessary", "Test camshaft and crankshaft position sensors", "Check for vacuum leaks and repair if detected") ) )
results.add( DtpCodeDTO( errorCode = "P0420", severity = ErrorSeverity.HIGH, title = "Catalyst System Efficiency Below Threshold", detail = "This code suggests that the efficiency of the catalytic converter is below the manufacturer-defined threshold. This condition may be caused by a malfunctioning catalytic converter, oxygen sensor, air leaks in the exhaust system, or issues with the fuel injection system.", implications = "Failure to resolve this issue promptly may result in increased tailpipe emissions, failed emission test, decreased fuel economy, and potential engine damage in the long run.", suggestedActions = listOf("Check and replace the catalytic converter if necessary", "Test oxygen sensor and replace if necessary", "Inspect for air leaks in the exhaust system and repair", "Check the fuel injection system for any faults") ) )
results.add( DtpCodeDTO( errorCode = "P0171", severity = ErrorSeverity.HIGH, title = "System Too Lean", detail = "This error code means the engine's air-fuel mixture has too much air (oxygen) and not enough fuel. This could happen due to a vacuum leak, a faulty Mass Air Flow (MAF) sensor, fuel pressure problems, or a defective oxygen sensor.", implications = "If left unresolved, it could lead to poor vehicle performance, higher emissions, and potential engine damage. Thus, it requires immediate attention.", suggestedActions = listOf("Inspect for vacuum leaks and repair if detected", "Check the MAF sensor and clean or replace if necessary", "Test fuel pressure and rectify any issues", "Check the oxygen sensor and replace if necessary") ) )
results.add( DtpCodeDTO( errorCode = "P0136", severity = ErrorSeverity.HIGH, title = "Oxygen Sensor Circuit Malfunction", detail = "The code indicates a malfunction within the circuit of oxygen sensor no.2, usually located in the exhaust system. Issues could result from a faulty sensor, damaged wires, or loose electrical connections.", implications = "If unresolved, this fault could lead to reduced fuel efficiency, sub-optimal engine performance, and an increase in harmful exhaust emissions. It's crucial to fix it to prevent possible engine damage.", suggestedActions = listOf("Check and replace the oxygen sensor if needed", "Inspect wiring and connections to the sensor", "If the check engine light persists, consider diagnosing the engine control unit (ECU)") ) )
results.add( DtpCodeDTO( errorCode = "P0340", severity = ErrorSeverity.HIGH, title = "Camshaft Position Sensor Circuit Malfunction", detail = "The code signals an issue within the 'A' circuit of the camshaft position sensor, which monitors the rotational position of the camshaft. Causes could be a faulty sensor, wiring issues, or a broken timing belt/chain.", implications = "Engine performance could be significantly compromised, potentially leading to engine stalling, hard starting, or engine damage in severe cases. Prompt attention is needed.", suggestedActions = listOf("Check and replace the camshaft position sensor if necessary", "Inspect and repair wiring issues", "Check the timing belt/chain and replace if necessary") ) )
results.add( DtpCodeDTO( errorCode = "P1523", severity = ErrorSeverity.MEDIUM, title = "Intake Manifold Runner Control Circuit Malfunction", detail = "This code denotes an error in the Intake Manifold Runner Control (IMRC) circuit. The issue could be a result of a faulty IMRC solenoid or actuator, or a problem in the relevant wiring harness or connectors.", implications = "Vehicle performance could be negatively affected, including power loss, stalled engine, or increased fuel emissions. To prevent further damage to the engine, repairs should be done promptly.", suggestedActions = listOf("Inspect and replace the IMRC solenoid if necessary", "Check the IMRC actuator", "Inspect the wiring harness and the connectors", "Check for related trouble codes that could suggest more specific issues") ) )
results.add( DtpCodeDTO( errorCode = "P0128", severity = ErrorSeverity.MEDIUM, title = "Coolant Thermostat Malfunction", detail = "This error code indicates a potential defect with the coolant thermostat, which regulates the engine's operating temperature. It could mean that the thermostat is stuck in the open position, or the engine coolant temperature sensor is faulty.", implications = "Ignoring this problem could lead to increased fuel consumption, poor engine performance, and potential engine damage due to overcooling or overheating.", suggestedActions = listOf("Inspect and replace the thermostat if necessary", "Check the engine coolant temperature sensor and replace if needed", "Check the coolant level and top off if low") ) )
results.add( DtpCodeDTO( errorCode = "P0504", severity = ErrorSeverity.MEDIUM, title = "Brake Switch 'A'/'B' Correlation", detail = "This error code means there is a discrepancy between the 'A' and 'B' brake switches signals. Possible causes include a faulty brake switch, a blown fuse, or wiring issues.", implications = "Failure to address this issue could influence several vehicle systems such as cruise control or anti-lock braking system (ABS), affecting driving safety. Therefore, timely action is recommended.", suggestedActions = listOf("Check the brake switch and replace if necessary", "Inspect the brake system's fuses and replace any that are blown", "Check for wiring issues in the brake system and fix if detected") ) )
results.add( DtpCodeDTO( errorCode = "P0532", severity = ErrorSeverity.MEDIUM, title = "Air Conditioning Refrigerant Pressure Sensor Low Input", detail = "This code indicates that the input from the air conditioning refrigerant pressure sensor is abnormally low. It's most likely due to low refrigerant levels in the AC system caused by leaks or a faulty sensor.", implications = "Your car’s air conditioning may work inefficiently, reducing riding comfort. Prolonged disregard to this issue could lead to the failure of the air conditioning system.", suggestedActions = listOf("Refill AC refrigerant levels", "Check the refrigerant pressure sensor", "Inspect for leaks in the AC system and repair") ) )
dtpResults.postValue(results)
}
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/viewmodels/ConnectorViewModel.kt | 3630246784 |
package com.jakubisz.obd2ai.ui.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.jakubisz.obd2ai.helpers.BluetoothHelper
import com.jakubisz.obd2ai.helpers.ObdHelper
import com.jakubisz.obd2ai.helpers.OpenAIService
class ConnectorViewModelFactory(
private val bluetoothHelper: BluetoothHelper,
private val obdHelper: ObdHelper,
private val openAI: OpenAIService
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ConnectorViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return ConnectorViewModel(bluetoothHelper, obdHelper, openAI) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/viewmodels/ConnectorViewModelFactory.kt | 4020192382 |
package com.jakubisz.obd2ai.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.jakubisz.obd2ai.R
class InitialFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_welcome_info, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val buttonNext: Button = view.findViewById(R.id.button_grant)
buttonNext.setOnClickListener {
findNavController().navigate(R.id.action_welcome_info_to_permissions)
}
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/InitialFragment.kt | 2109030975 |
package com.jakubisz.obd2ai.ui.fragments
import android.app.AlertDialog
import android.app.Dialog
import android.content.ContentResolver
import android.os.Bundle
import android.provider.Settings.Global.putString
import androidx.fragment.app.DialogFragment
class ErrorDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireContext())
.setTitle("Error")
.setMessage(arguments?.getString("errorMessage"))
.setPositiveButton("OK") { dialog, _ -> dialog.dismiss() }
.create()
}
companion object {
fun newInstance(errorMessage: String) = ErrorDialogFragment().apply {
arguments = Bundle().apply {
putString("errorMessage", errorMessage)
}
}
}
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/ErrorDialogFragment.kt | 3660694653 |
package com.jakubisz.obd2ai.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModel
import com.jakubisz.obd2ai.ui.activities.MainActivity
import com.jakubisz.obd2ai.R
class PermissionsFragment : Fragment() {
private val connectorViewModel: ConnectorViewModel by activityViewModels {
(activity as MainActivity).defaultViewModelProviderFactory
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_permissions, container, false)
//val bluetoothViewModel = TestViewModel(bluetoothHelper, obdHelper, OpenAIService())
val btnRequestPermission = view.findViewById<Button>(R.id.button_grant)
connectorViewModel.isBluetoothPermissionGranted.observe(viewLifecycleOwner, Observer { data ->
if (data)
{
findNavController().navigate(R.id.action_permissions_to_connectFragment)
}
else
{
val errorDialog = ErrorDialogFragment.newInstance("Required Bluetooth permissions were not granted")
errorDialog.show(parentFragmentManager, "errorDialog")
}
})
btnRequestPermission.setOnClickListener {
activity?.let { activity ->
connectorViewModel.requestBluetoothPermissions(activity)
}
}
return view
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
findNavController().navigate(R.id.action_permissions_to_connectFragment)
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/PermissionsFragment.kt | 336101093 |
package com.jakubisz.obd2ai.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModel
import com.jakubisz.obd2ai.ui.adapters.ErrorOverviewRecyclerViewAdapter
import com.jakubisz.obd2ai.ui.activities.MainActivity
import com.jakubisz.obd2ai.R
import com.jakubisz.obd2ai.model.DtpCodeDTO
import com.jakubisz.obd2ai.model.ErrorSeverity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class ErrorOverviewFragment : Fragment() {
private lateinit var errorViewAdapter: ErrorOverviewRecyclerViewAdapter
private lateinit var progressBar: ProgressBar
private lateinit var recyclerView: RecyclerView
private lateinit var statsTextView: TextView
private var isDemo = false
private val connectorViewModel: ConnectorViewModel by activityViewModels {
(activity as MainActivity).defaultViewModelProviderFactory
}
private var errorCodes: List<DtpCodeDTO> = listOf()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_error_overview, container, false)
isDemo = ErrorOverviewFragmentArgs.fromBundle(requireArguments()).isDemo
statsTextView = view.findViewById(R.id.textView_stats)
//RecyclerView setup
recyclerView = view.findViewById(R.id.view_error_overview)
progressBar = view.findViewById(R.id.progressBar)
setupRecyclerView()
observeErrorCodes()
showLoading(false)
val btnRequestPermission = view.findViewById<Button>(R.id.button_analyze)
btnRequestPermission.setOnClickListener {
activity?.let { activity ->
loadErrorCodes()
}
}
return view
}
private fun loadErrorCodes() {
showLoading(true)
lifecycleScope.launch {
if (isDemo) {
delay(3000)
//connectorViewModel.dtp.addAll(listOf("P0300", "P0420", "P0171", "P0128"))
//connectorViewModel.assesDtpCodes()
connectorViewModel.assesDtpCodesTest()
}
else{
connectorViewModel.gatherDtpCodes()
connectorViewModel.assesDtpCodes()
}
}
}
private fun observeErrorCodes() {
connectorViewModel.dtpResults.observe(viewLifecycleOwner, Observer { dtpCodes ->
val codes = dtpCodes.sortedBy { it.severity } ?: listOf()
updateUI(codes)
})
}
private fun updateUI(errorCodes: List<DtpCodeDTO>) {
showLoading(errorCodes.isEmpty())
if (errorCodes.isEmpty()) {
return
}
var stats = "Low: ${errorCodes.count { it.severity == ErrorSeverity.LOW }} " +
"Medium: ${errorCodes.count { it.severity == ErrorSeverity.MEDIUM }} " +
"High: ${errorCodes.count { it.severity == ErrorSeverity.HIGH }}"
statsTextView.text = stats
errorViewAdapter.errorCodes = errorCodes
errorViewAdapter.notifyDataSetChanged()
}
private fun setupRecyclerView() {
errorViewAdapter = ErrorOverviewRecyclerViewAdapter(errorCodes) { errorItem ->
val action =
ErrorOverviewFragmentDirections.actionErrorOverviewFragmentToErrorDetailFragment(
errorItem.errorCode
)
findNavController().navigate(action)
recyclerView.adapter = errorViewAdapter
showLoading(false)
}
recyclerView.adapter = errorViewAdapter
recyclerView.layoutManager = LinearLayoutManager(context)
}
private fun showLoading(show: Boolean) {
progressBar.visibility = if (show) View.VISIBLE else View.GONE
}
fun showErrorDialog(text: String) {
val errorDialog = ErrorDialogFragment.newInstance(text)
errorDialog.show(parentFragmentManager, "errorDialog")
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/ErrorOverviewFragment.kt | 3843674410 |
package com.jakubisz.obd2ai.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModel
import com.jakubisz.obd2ai.ui.activities.MainActivity
import com.jakubisz.obd2ai.R
import com.jakubisz.obd2ai.ui.adapters.SuggestionsRecycleViewAdapter
import com.jakubisz.obd2ai.model.DtpCodeDTO
import com.jakubisz.obd2ai.model.ErrorSeverity
class ErrorDetailFragment : Fragment() {
private val connectorViewModel: ConnectorViewModel by activityViewModels {
(activity as MainActivity).defaultViewModelProviderFactory
}
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: SuggestionsRecycleViewAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_error_detail, container, false)
recyclerView = view.findViewById(R.id.suggestedActionRecyclerView)
// Inflate the layout for this fragment
val errorCode = ErrorDetailFragmentArgs.fromBundle(requireArguments()).errorCode
connectorViewModel.dtpResults.value?.find { it.errorCode == errorCode }?.let {
renderErrorDetail(it, view)
}
return view
}
fun renderErrorDetail(dtpCodeDTO: DtpCodeDTO, view: View) {
view.findViewById<TextView>(R.id.textViewErrorTitle).text = dtpCodeDTO.title
view.findViewById<TextView>(R.id.textViewErrorCode).text = dtpCodeDTO.errorCode
view.findViewById<TextView>(R.id.textViewErrorSeverity).text = "Severity: ${dtpCodeDTO.severity}"
view.findViewById<TextView>(R.id.textViewErrorDetail).text = dtpCodeDTO.detail
view.findViewById<TextView>(R.id.textViewErrorImplications).text = dtpCodeDTO.implications
val color = ErrorSeverity.getColor(dtpCodeDTO.severity)
view.findViewById<ImageView>(R.id.imageView_icon).setColorFilter(color)
setupSuggestedActionsRecyclerView(view, dtpCodeDTO.suggestedActions)
}
private fun setupSuggestedActionsRecyclerView(view: View, suggestedActions: List<String>) {
val recyclerView = view.findViewById<RecyclerView>(R.id.suggestedActionRecyclerView)
adapter = SuggestionsRecycleViewAdapter(suggestedActions)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
}
fun setRecyclerViewHeightBasedOnChildren(recyclerView: RecyclerView) {
val adapter = recyclerView.adapter ?: return
var height = 0
val childCount = adapter.itemCount
for (i in 0 until childCount) {
val child = recyclerView.getChildAt(i) ?: continue
recyclerView.measure(
View.MeasureSpec.makeMeasureSpec(recyclerView.width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
height += child.measuredHeight
}
val layoutParams = recyclerView.layoutParams
layoutParams.height = height
recyclerView.layoutParams = layoutParams
recyclerView.requestLayout()
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/ErrorDetailFragment.kt | 1345181274 |
package com.jakubisz.obd2ai.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.ui.adapters.BluetoothRecyclerViewAdapter
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModel
import com.jakubisz.obd2ai.ui.activities.MainActivity
import com.jakubisz.obd2ai.R
class ConnectFragment : Fragment() {
private lateinit var bluetoothAdapter: BluetoothRecyclerViewAdapter
private var deviceAdress: String = ""
private val connectorViewModel: ConnectorViewModel by activityViewModels {
(activity as MainActivity).defaultViewModelProviderFactory
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_connect, container, false)
val btnConnect = view.findViewById<Button>(R.id.button_connect)
val btnDemo = view.findViewById<Button>(R.id.button_demo)
val textSelected = view.findViewById<TextView>(R.id.textViewSelectedDev)
val devices = connectorViewModel.getAvailableDevices()
val recyclerView = view.findViewById<RecyclerView>(R.id.devicesView)
val
bluetoothAdapter = BluetoothRecyclerViewAdapter(devices) { device ->
// Handle click
deviceAdress = device.address // Get the device ID (address)
textSelected.text = device.name
btnConnect.visibility = View.VISIBLE
}
recyclerView.adapter = bluetoothAdapter
recyclerView.layoutManager = LinearLayoutManager(context)
btnConnect.setOnClickListener {
connectorViewModel.setupOBDConnection(deviceAdress)
val action =
ConnectFragmentDirections.actionConnectFragmentToErrorOverviewFragment(isDemo = false)
findNavController().navigate(action)
}
btnDemo.setOnClickListener {
val action =
ConnectFragmentDirections.actionConnectFragmentToErrorOverviewFragment(isDemo = true)
findNavController().navigate(action)
}
return view
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/fragments/ConnectFragment.kt | 3041788503 |
package com.jakubisz.obd2ai.ui.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.R
import com.jakubisz.obd2ai.model.DtpCodeDTO
import com.jakubisz.obd2ai.model.ErrorSeverity
class ErrorOverviewRecyclerViewAdapter(
items: List<DtpCodeDTO>,
private val onItemClick: (DtpCodeDTO) -> Unit
) : RecyclerView.Adapter<ErrorOverviewRecyclerViewAdapter.ErrorCodeViewHolder>() {
var errorCodes = items
class ErrorCodeViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val iconImageView: ImageView = view.findViewById(R.id.imageView_icon)
private val titleTextView: TextView = view.findViewById(R.id.title)
private val detailTextView: TextView = view.findViewById(R.id.detail)
fun bind(item: DtpCodeDTO, onItemClick: (DtpCodeDTO) -> Unit) {
titleTextView.text = item.title
detailTextView.text = item.detail
// Set color based on severity
val color = ErrorSeverity.getColor(item.severity)
iconImageView.setColorFilter(color)
itemView.setOnClickListener { onItemClick(item) }
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ErrorCodeViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_error_overview_layout, parent, false)
return ErrorCodeViewHolder(view)
}
override fun onBindViewHolder(holder: ErrorCodeViewHolder, position: Int) {
holder.bind(errorCodes[position], onItemClick)
}
override fun getItemCount(): Int = errorCodes.size
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/adapters/ErrorOverviewRecyclerViewAdapter.kt | 573686363 |
package com.jakubisz.obd2ai.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.R
class SuggestionsRecycleViewAdapter(private val actions: List<String>) :
RecyclerView.Adapter<SuggestionsRecycleViewAdapter.ActionViewHolder>() {
class ActionViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
RecyclerView.ViewHolder(inflater.inflate(R.layout.item_error_detail_suggestions_layout, parent, false)) {
private var textView: TextView = itemView.findViewById(R.id.textViewSuggestedAction)
fun bind(action: String) {
textView.text = action
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ActionViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ActionViewHolder(inflater, parent)
}
override fun onBindViewHolder(holder: ActionViewHolder, position: Int) {
val action = actions[position]
holder.bind(action)
}
override fun getItemCount() = actions.size
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/adapters/SuggestionsRecycleViewAdapter.kt | 927663652 |
package com.jakubisz.obd2ai.ui.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.jakubisz.obd2ai.R
import com.jakubisz.obd2ai.model.BluetoothDeviceDTO
class BluetoothRecyclerViewAdapter (
private val devices: List<BluetoothDeviceDTO>,
private val onItemClick: (BluetoothDeviceDTO) -> Unit
) : RecyclerView.Adapter<BluetoothRecyclerViewAdapter.DeviceViewHolder>() {
class DeviceViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val deviceNameTextView: TextView = view.findViewById(R.id.deviceNameTextView)
fun bind(device: BluetoothDeviceDTO, onItemClick: (BluetoothDeviceDTO) -> Unit) {
deviceNameTextView.text = device.name ?: "Unknown Device"
itemView.setOnClickListener { onItemClick(device) }
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_bluetooth_device, parent, false)
return DeviceViewHolder(view)
}
override fun onBindViewHolder(holder: DeviceViewHolder, position: Int) {
holder.bind(devices[position], onItemClick)
}
override fun getItemCount(): Int = devices.size
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/adapters/BluetoothRecyclerViewAdapter.kt | 1774073340 |
package com.jakubisz.obd2ai.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) | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/theme/Color.kt | 402627243 |
package com.jakubisz.obd2ai.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 OBD2AITheme(
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
)
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/theme/Theme.kt | 1809722460 |
package com.jakubisz.obd2ai.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
)
*/
) | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/theme/Type.kt | 348993833 |
package com.jakubisz.obd2ai.ui.activities
import android.os.Bundle
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.jakubisz.obd2ai.ui.theme.OBD2AITheme
import android.annotation.SuppressLint
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.AlertDialog
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import com.github.eltonvs.obd.command.ObdResponse
import com.github.eltonvs.obd.command.control.PendingTroubleCodesCommand
import com.github.eltonvs.obd.command.control.PermanentTroubleCodesCommand
import com.github.eltonvs.obd.command.control.TroubleCodesCommand
import com.github.eltonvs.obd.connection.ObdDeviceConnection
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*
import androidx.compose.foundation.layout.*
import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import com.jakubisz.obd2ai.helpers.BluetoothHelper
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModel
import com.jakubisz.obd2ai.ui.viewmodels.ConnectorViewModelFactory
import com.jakubisz.obd2ai.helpers.ObdHelper
import com.jakubisz.obd2ai.helpers.OpenAIService
import com.jakubisz.obd2ai.R
import com.jakubisz.obd2ai.ui.viewmodels.TestViewModel
class MainActivity : AppCompatActivity() { // ComponentActivity() {
private lateinit var bluetoothHelper: BluetoothHelper
private lateinit var obdHelper: ObdHelper
private lateinit var connector: ConnectorViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initHelpers()
connector = ViewModelProvider(this,
ConnectorViewModelFactory(
bluetoothHelper,
obdHelper,
OpenAIService()
))[ConnectorViewModel::class.java]
setContentView(R.layout.activity_main)
}
private fun initHelpers() {
bluetoothHelper = BluetoothHelper(this)
obdHelper = ObdHelper(bluetoothHelper)
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (bluetoothHelper.resolvePermissionsResult(requestCode, grantResults)) {
// Permissions granted. You can proceed with your Bluetooth operations.
//setupObd()
} else {
// Permissions denied. Handle the feature's unavailability.
//showPermissionsDeniedDialog()
}
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/ui/activities/MainActivity.kt | 1234004233 |
package com.jakubisz.obd2ai.model
data class DtpCodeDTO(
val errorCode: String,
val severity: ErrorSeverity,
val title: String,
val detail: String,
val implications: String,
val suggestedActions: List<String>
)
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/model/DtpCodeDTO.kt | 1996937944 |
package com.jakubisz.obd2ai.model
data class BluetoothDeviceDTO(
val name: String,
val address: String
)
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/model/BluetoothDeviceDTO.kt | 3380500863 |
package com.jakubisz.obd2ai.model
import android.graphics.Color
enum class ErrorSeverity {
LOW,
MEDIUM,
HIGH;
companion object {
fun fromInt(value: Int) = when (value) {
0 -> LOW
1 -> MEDIUM
2 -> HIGH
else -> throw IllegalArgumentException("Invalid severity level: $value")
}
fun getColor(severity: ErrorSeverity) = when (severity) {
MEDIUM -> Color.rgb(255, 165, 0) // Orange color
HIGH -> Color.RED
else -> Color.GRAY
}
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/model/ErrorSeverity.kt | 3800813200 |
package com.jakubisz.obd2ai.helpers
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.jakubisz.obd2ai.model.BluetoothDeviceDTO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*
class BluetoothHelper(private val context: Context) {
private val bluetoothAdapter: BluetoothAdapter?
private var bluetoothSocket: BluetoothSocket? = null
private val sppUuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // Standard SPP UUID
private val _isBluetoothPermissionGranted = MutableLiveData<Boolean>()
val isBluetoothPermissionGranted: LiveData<Boolean> = _isBluetoothPermissionGranted
init {
val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
}
companion object {
private const val REQUEST_CODE_PERMISSIONS = 101
private val REQUIRED_PERMISSIONS = arrayOf(
android.Manifest.permission.BLUETOOTH,
android.Manifest.permission.BLUETOOTH_ADMIN,
android.Manifest.permission.ACCESS_FINE_LOCATION
)
}
fun checkBluetoothPermissions(): Boolean {
return REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
@Throws(SecurityException::class)
fun throwIfPermissionsNotGranted() {
if (!checkBluetoothPermissions()) {
throw SecurityException("Required Bluetooth permissions are not granted")
}
}
fun requestPermissions(activity: Activity) {
ActivityCompat.requestPermissions(activity, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
fun setupBluetooth() {
if(checkBluetoothPermissions()) {
enableBluetooth()
} else {
//TODO:Pottencional issue when user denies permissions
requestPermissions(context as Activity)
enableBluetooth()
}
//val devices = getAvailableDevices()
//connectToDevice("00:1D:A5:68:98:8B")
}
@Throws(SecurityException::class)
fun enableBluetooth() {
throwIfPermissionsNotGranted()
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
context.startActivity(enableBtIntent)
}
}
@Throws(SecurityException::class, IOException::class)
fun getAvailableDevices(): List<BluetoothDeviceDTO> {
throwIfPermissionsNotGranted()
val bluetoothAdapter = bluetoothAdapter ?: throw IOException("Bluetooth adapter is null")
val deviceDTOs = bluetoothAdapter.bondedDevices.map { convertToDeviceDTO(it) }
return deviceDTOs
}
@Throws(IOException::class, SecurityException::class)
suspend fun connectToDevice(deviceAddress: String): Pair<InputStream, OutputStream> = withContext(Dispatchers.IO) {
// Check for permissions before proceeding
throwIfPermissionsNotGranted()
val device = bluetoothAdapter?.getRemoteDevice(deviceAddress)
?: throw IOException("Device not found")
bluetoothSocket = device.createRfcommSocketToServiceRecord(sppUuid).apply {
try {
// Cancel discovery as it may slow down the connection
bluetoothAdapter.cancelDiscovery()
// Connect to the remote device
connect()
} catch (e: SecurityException) {
throw IOException("Failed to connect to device due to security restrictions", e)
} catch (e: IOException) {
throw IOException("Failed to connect to device", e)
}
}
// Verify that the socket streams are not null
val bluetoothSocket = bluetoothSocket ?: throw IOException("Bluetooth socket is null")
Pair(bluetoothSocket.inputStream, bluetoothSocket.outputStream)
}
fun disconnectFromDevice() {
bluetoothSocket?.close()
bluetoothSocket = null
}
// Method to handle permission results
//Returns true if the result was granted, false otherwise
fun resolvePermissionsResult(requestCode: Int, grantResults: IntArray): Boolean {
var allPermissionsGranted = true
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (grantResults.isNotEmpty()) {
for (i in grantResults.indices) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
allPermissionsGranted = false
break
}
}
} else {
allPermissionsGranted = false
}
}
_isBluetoothPermissionGranted.postValue(allPermissionsGranted)
return allPermissionsGranted
}
@SuppressLint("MissingPermission")
fun convertToDeviceDTO(bluetoothDevice: BluetoothDevice): BluetoothDeviceDTO {
return BluetoothDeviceDTO(
name = bluetoothDevice.name,
address = bluetoothDevice.address
// Map other fields if needed
)
}
/*
suspend fun runAutomatedBluetoothSetup(): Pair<InputStream, OutputStream> = withContext(Dispatchers.IO) {
if(checkBluetoothPermissions()) {
enableBluetooth()
} else {
//TODO:Pottencional issue when user denies permissions
requestPermissions(context as Activity)
}
val devices = getAvailableDevices()
connectToDevice("00:1D:A5:68:98:8B")
//connectToObdDevice("00:1D:A5:68:98:8B")
}*/
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/helpers/BluetoothHelper.kt | 2435875409 |
package com.jakubisz.obd2ai.helpers
import com.aallam.openai.api.chat.ChatCompletion
import com.aallam.openai.api.chat.ChatCompletionRequest
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.chat.ChatRole
import com.aallam.openai.api.http.Timeout
import com.aallam.openai.api.model.ModelId
import com.aallam.openai.client.OpenAI
import com.jakubisz.obd2ai.BuildConfig
import com.jakubisz.obd2ai.model.DtpCodeDTO
import com.jakubisz.obd2ai.model.ErrorSeverity
import org.json.JSONObject
import kotlin.time.Duration.Companion.seconds
class OpenAIService {
private lateinit var openAI: OpenAI
init {
openAI = OpenAI(
token = BuildConfig.OPENAI_API_KEY,
timeout = Timeout(socket = 60.seconds)
)
}
suspend fun getDtpCodeAssessment(dtpCode: String): DtpCodeDTO {
val response = getResponse(dtpCode)
return parseErrorInfo(response)
}
suspend fun getResponse(query: String): String {
//TODO: Issue #2 - implement assistant https://github.com/JaKuBisz/OBD2AI/issues/2 - https://github.com/aallam/openai-kotlin/blob/main/guides/Assistants.md
val chatCompletionRequest = ChatCompletionRequest(
model = ModelId("gpt-3.5-turbo"),
messages = listOf(
ChatMessage(
role = ChatRole.System,
content = "\"Given a plain error code as input, provide a resolution in a structured JSON format. The JSON should include the following fields:\n" +
"\n" +
"1. errorCode: The provided error code.\n" +
"2. severity: The severity level of the error (0 for Low, 1 for Medium, 2 for High) - defines how big implication this has on the driving and safety of vehicle.\n" +
"3. title: A short, descriptive title of the error, try limit length to 32chars max is 60 chars.\n" +
"4. detail: A detailed explanation of what the error is. - ideal length around 300 chars\n" +
"5. implications: Information on the implications of the error, including any potential safety concerns, urgency for repair or usage complications/limitations. - ideal length around 300 chars\n" +
"6. suggestedActions: Recommended actions or steps to resolve or investigate the error further. - ideally 5 or more suggestions\n" +
"\n" +
"Example Input:\n" +
"'P0420'\n" +
"\n" +
"Expected JSON Output:\n" +
"{\n" +
" \"errorCode\": \"P0420\",\n" +
" \"severity\": 2,\n" +
" \"title\": \"Catalyst System Efficiency Below Threshold\",\n" +
" \"detail\": \"Indicates that the oxygen levels in the exhaust are not as expected, suggesting inefficiency in the catalyst system, possibly due to a malfunctioning catalytic converter or faulty sensors.\",\n" +
" \"implications\": \"A compromised catalyst system can increase harmful emissions, reduce fuel efficiency, and potentially lead to more significant engine problems if not addressed promptly.\",\n" +
" \"suggestedActions\": [\n" +
" \"Inspect and, if necessary, replace the catalytic converter\",\n" +
" \"Check and replace faulty oxygen sensors\",\n" +
" \"Examine the exhaust system for leaks or damage\",\n" +
" \"Verify the operation of the engine management system\",\n" +
" \"Check for software updates for the engine control unit (ECU)\",\n" +
" \"Ensure proper fuel quality and engine tuning\"\n" +
" ]\n" +
"}\"\n" +
"Additional instructions:\n" +
"\"You are an expert mechanic. Your goal is to provide an assessment of the following OBD2 error codes. Explain what they mean and where the problem is. \""
),
ChatMessage(
role = ChatRole.User,
content = query
)
)
)
val completion: ChatCompletion = openAI.chatCompletion(chatCompletionRequest)
val result = completion.choices.first().message.content ?: "No result"
return result
}
fun parseErrorInfo(jsonString: String): DtpCodeDTO {
try {
val jsonObject = JSONObject(jsonString)
val errorCode = jsonObject.getString("errorCode")
val severity = ErrorSeverity.fromInt(jsonObject.getInt("severity"))
val title = jsonObject.getString("title")
val detail = jsonObject.getString("detail")
val implications = jsonObject.getString("implications")
val actionsArray = jsonObject.getJSONArray("suggestedActions")
val suggestedActions = mutableListOf<String>()
for (i in 0 until actionsArray.length()) {
suggestedActions.add(actionsArray.getString(i))
}
return DtpCodeDTO(errorCode, severity, title, detail, implications, suggestedActions)
} catch (e: Exception) {
return DtpCodeDTO("Error", ErrorSeverity.LOW, "Error", "Error", "Error", listOf("Error"))
}
}
} | OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/helpers/OpenAIService.kt | 1245052141 |
package com.jakubisz.obd2ai.helpers
import com.github.eltonvs.obd.command.control.PendingTroubleCodesCommand
import com.github.eltonvs.obd.command.control.PermanentTroubleCodesCommand
import com.github.eltonvs.obd.command.control.TroubleCodesCommand
import com.github.eltonvs.obd.connection.ObdDeviceConnection
import java.io.IOException
class ObdHelper(private val bluetoothHelper: BluetoothHelper) {
private var obdConnection: ObdDeviceConnection? = null
suspend fun setupObd(deviceAddress: String) {
val (inputStream, outputStream) = bluetoothHelper.connectToDevice(deviceAddress)
obdConnection = ObdDeviceConnection(inputStream, outputStream)
}
fun getObdDeviceConnection(): ObdDeviceConnection? {
return obdConnection
}
suspend fun getDtpCodes() : List<String>
{
val obdDeviceConnection = obdConnection ?: throw IOException("ObdDeviceConnection is null")
val result = obdDeviceConnection.run(TroubleCodesCommand()).formattedValue
return splitErrors(result)
}
suspend fun getPendingDtpCodes() : List<String>
{
val obdDeviceConnection = obdConnection ?: throw IOException("ObdDeviceConnection is null")
val result = obdDeviceConnection.run(PendingTroubleCodesCommand()).formattedValue
return splitErrors(result)
}
suspend fun getPermanentDtpCodes() : List<String>
{
val obdDeviceConnection = obdConnection ?: throw IOException("ObdDeviceConnection is null")
val result = obdDeviceConnection.run(PermanentTroubleCodesCommand()).formattedValue
return splitErrors(result)
}
suspend fun getAllDtpCodes() : List<String>
{
val responses = mutableListOf<String>()
responses.addAll(getDtpCodes())
responses.addAll(getPendingDtpCodes())
responses.addAll(getPermanentDtpCodes())
return responses
}
fun disconnectFromObdDevice() {
bluetoothHelper.disconnectFromDevice()
}
fun splitErrors(errors: String) : List<String>
{
return errors.split(",").map { it.trim() }
}
}
| OBD2AI/Src/app/src/main/java/com/jakubisz/obd2ai/helpers/ObdHelper.kt | 4209665801 |
// required for Gatling core structure DSL
// required for Gatling HTTP DSL
// can be omitted if you don't use jdbcFeeder
// used for specifying durations with a unit, eg Duration.ofMinutes(5)
import io.gatling.javaapi.core.CoreDsl.*
import io.gatling.javaapi.core.Simulation
import io.gatling.javaapi.http.HttpDsl.*
import java.time.Duration
class ApiSimulation : Simulation() {
val httpProtocol = http
.baseUrl("http://localhost:8080/v1")
.acceptHeader("application/json")
val createAndGetUsers = scenario("Create and Get Users")
.feed(tsv("create-users.tsv").circular())
.exec(
http("Create")
.post("/users")
.body(StringBody("#{payload}"))
.header("Content-Type", "application/json")
.check(status().`in`(201))
.check(status().saveAs("httpStatus"))
.checkIf { session -> session.getString("httpStatus") == "201" }
.then(header("Location").saveAs("location"))
).pause(Duration.ofMillis(1), Duration.ofMillis(30))
.doIf { session -> session.getString("httpStatus") == "201" }.then(
exec(
http("Get")
.get("#{location}")
.header("Content-Type", "application/json")
.check(status().`in`(200))
)
)
init {
this.setUp(
createAndGetUsers.injectOpen(
constantUsersPerSec(2.0).during(Duration.ofSeconds(10)),
constantUsersPerSec(5.0).during(Duration.ofSeconds(15)).randomized(),
rampUsersPerSec(6.0).to(600.0).during(Duration.ofMinutes(3))
)
).protocols(httpProtocol)
}
} | crud-users-kotlin/stress-test/src/gatling/kotlin/ApiSimulation.kt | 1467823928 |
package com.crud.usersweb.controller
import com.crud.usersweb.AbstractIntegrationTest
import com.crud.usersweb.handlers.ErrorsResponse
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.client.getForEntity
import org.springframework.boot.test.web.client.postForObject
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.RequestEntity
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.test.jdbc.JdbcTestUtils
import java.net.URI
import java.time.LocalDateTime
import java.util.UUID
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserControllerTest : AbstractIntegrationTest() {
@LocalServerPort
private var port: Int = 0
@Autowired
lateinit var testRestTemplate: TestRestTemplate
private var baseUrl: String = "http://localhost"
@BeforeEach
fun setUp() {
baseUrl = "$baseUrl:$port/v1/users"
}
@AfterEach
fun setDown(@Autowired jdbcTemplate: JdbcTemplate) {
JdbcTestUtils.deleteFromTables(jdbcTemplate, "users")
}
@Nested
inner class GetUser {
@Test
fun `Get user by id`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.of(2024, 1, 17, 1, 1),
stack = listOf("NodeJS")
)
val createUserResponse = testRestTemplate.postForObject<UserResponse>(baseUrl, userRequest)
val userResponse = testRestTemplate.getForEntity<UserResponse>("$baseUrl/${createUserResponse?.id}")
assertNotNull(userResponse)
assertEquals(HttpStatus.OK, userResponse.statusCode)
val user = userResponse.body
assertNotNull(user?.id)
assertEquals(userRequest.nick, user?.nick)
assertEquals(userRequest.name, user?.name)
assertEquals(userRequest.birthDate, user?.birthDate)
assertEquals(userRequest.stack, user?.stack)
}
@Test
fun `Get user that not exists`() {
val userResponse = testRestTemplate.getForEntity<UserResponse>("$baseUrl/${UUID.randomUUID()}")
assertNotNull(userResponse)
assertEquals(HttpStatus.NOT_FOUND, userResponse.statusCode)
}
}
@Nested
inner class ListUser {
@Test
fun `List users when not have users`() {
val response = testRestTemplate.getForEntity<List<UserResponse>>(baseUrl)
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.OK)
val users = response.body as ArrayList<UserResponse>
assertTrue(users.isEmpty())
}
@Test
fun `List users when have one user`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.of(2024, 1, 17, 1, 1),
stack = listOf("NodeJS")
)
val userCreated = testRestTemplate.postForObject(baseUrl, userRequest, UserResponse::class.java)
val response = testRestTemplate.exchange(
RequestEntity.get(URI(baseUrl)).build(),
object : ParameterizedTypeReference<List<UserResponse>>() {})
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.OK)
val users: List<UserResponse>? = response.body
assertThat(users)
.isNotNull()
.hasSize(1)
.first()
.usingRecursiveComparison()
.isEqualTo(
UserResponse(
id = userCreated.id,
name = userRequest.name,
nick = userRequest.nick,
birthDate = userRequest.birthDate,
stack = userRequest.stack,
)
)
}
}
@Nested
inner class CreateUser {
@Test
fun `Create User`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.now(),
stack = listOf("NodeJS")
)
val response =
testRestTemplate.postForEntity(baseUrl, userRequest, UserResponse::class.java)
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.CREATED)
val user = response.body as UserResponse
assertNotNull(user)
assertNotNull(user.id)
assertEquals(response.headers.location.toString(), "/users/${user.id}")
assertEquals(user.nick, userRequest.nick)
assertEquals(user.name, userRequest.name)
assertEquals(user.birthDate, userRequest.birthDate)
assertEquals(user.stack, userRequest.stack)
}
@ParameterizedTest()
@ValueSource(
strings = [
"",
"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" +
"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" +
"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" +
"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"
]
)
fun `Not create user when name is invalid value`(name: String) {
val userRequest = CreateUserRequest(
name = name,
nick = "nick",
birthDate = LocalDateTime.now(),
stack = listOf("NodeJS")
)
val response =
testRestTemplate.postForEntity(baseUrl, userRequest, ErrorsResponse::class.java)
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.BAD_REQUEST)
val errors = response.body?.errors
assertNotNull(errors)
assertThat(errors)
.allMatch { it == "O campo nome é obrigatório e deve estar entre 1 e 255" }
}
@Test
fun `Not create user when have empty value on stack`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.now(),
stack = listOf("", "")
)
val response =
testRestTemplate.postForEntity(baseUrl, userRequest, ErrorsResponse::class.java)
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.BAD_REQUEST)
val errors = response.body?.errors
assertNotNull(errors)
assertThat(errors)
.allMatch { it == "Os elementos da lista devem estar entre 1 e 32" }
}
@Test
fun `Should create user when not have stack`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.now(),
)
val response =
testRestTemplate.postForEntity(baseUrl, userRequest, UserResponse::class.java)
assertNotNull(response)
assertEquals(response.statusCode, HttpStatus.CREATED)
val user = response.body as UserResponse
assertNotNull(user)
assertNotNull(user.id)
assertEquals(response.headers.location.toString(), "/users/${user.id}")
assertEquals(user.nick, userRequest.nick)
assertEquals(user.name, userRequest.name)
assertEquals(user.birthDate, userRequest.birthDate)
assertNull(user.stack)
}
}
@Nested
inner class DeleteUser {
@Test
fun `Delete user by id`() {
val userRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.now(),
stack = listOf("NodeJS")
)
val userCreatedResponse = testRestTemplate.postForObject<UserResponse>(baseUrl, userRequest)
val userDeletedResponse = testRestTemplate.exchange(
RequestEntity.delete(URI("$baseUrl/${userCreatedResponse?.id}")).build(),
Nothing::class.java
)
assertNotNull(userDeletedResponse)
assertEquals(HttpStatus.NO_CONTENT, userDeletedResponse.statusCode)
}
@Test
fun `Delete user that not exists`() {
val userId = UUID.randomUUID()
val userDeletedResponse = testRestTemplate.exchange(
RequestEntity.delete(URI("$baseUrl/$userId")).build(),
Nothing::class.java
)
assertNotNull(userDeletedResponse)
assertEquals(HttpStatus.NOT_FOUND, userDeletedResponse.statusCode)
}
}
@Nested
inner class UpdateUser {
@Test
fun `Update User`() {
val createUserRequest = CreateUserRequest(
name = "Name",
nick = "nick",
birthDate = LocalDateTime.now(),
stack = listOf("NodeJS")
)
val createUserResponse =
testRestTemplate.postForEntity(baseUrl, createUserRequest, UserResponse::class.java)
val userCreated = createUserResponse.body as UserResponse
val updateUserRequest = UpdateUserRequest(
name = "Name 2",
nick = "nick 2",
birthDate = LocalDateTime.of(2023, 12, 1, 1, 1),
stack = null
)
val userId = userCreated.id
val updateUserResponse = testRestTemplate.exchange(
RequestEntity<UpdateUserRequest>(
updateUserRequest,
HttpMethod.PUT,
URI("$baseUrl/$userId")
), UserResponse::class.java
)
assertNotNull(updateUserResponse)
assertEquals(updateUserResponse.statusCode, HttpStatus.OK)
val user = updateUserResponse.body as UserResponse
assertNotNull(user)
assertEquals(user.id, userId)
assertEquals(user.nick, updateUserRequest.nick)
assertEquals(user.name, updateUserRequest.name)
assertEquals(user.birthDate, updateUserRequest.birthDate)
assertEquals(user.stack, updateUserRequest.stack)
}
}
} | crud-users-kotlin/users-web/src/test/kotlin/com/crud/usersweb/controller/UserControllerTest.kt | 2543694982 |
package com.crud.usersweb
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class UsersWebApplicationTests : AbstractIntegrationTest() {
@Test
fun contextLoads() {
}
}
| crud-users-kotlin/users-web/src/test/kotlin/com/crud/usersweb/UsersWebApplicationTests.kt | 391032139 |
package com.crud.usersweb
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.test.context.ContextConfiguration
import org.testcontainers.containers.OracleContainer
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.utility.DockerImageName
@SpringBootTest
@ContextConfiguration(initializers = [AbstractIntegrationTest.Initializer::class])
abstract class AbstractIntegrationTest {
companion object {
private val postgreSQLContainer = PostgreSQLContainer<Nothing>("postgres:latest")
private val oracleContainer = OracleContainer(
DockerImageName
.parse("container-registry.oracle.com/database/express:21.3.0-xe")
.asCompatibleSubstituteFor("gvenzl/oracle-xe")
).apply {
withEnv("ORACLE_PWD", "123456")
}
}
internal class Initializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
override fun initialize(configurableApplicationContext: ConfigurableApplicationContext) {
if (configurableApplicationContext.environment.activeProfiles.any { it == "oracle" }) {
oracleContainer.start()
TestPropertyValues.of(
"spring.datasource.url=${oracleContainer.jdbcUrl}",
).applyTo(configurableApplicationContext.environment)
} else {
postgreSQLContainer.start()
TestPropertyValues.of(
"spring.datasource.url=${postgreSQLContainer.jdbcUrl}",
"spring.datasource.username=${postgreSQLContainer.username}",
"spring.datasource.password=${postgreSQLContainer.password}"
).applyTo(configurableApplicationContext.environment)
}
}
}
}
| crud-users-kotlin/users-web/src/test/kotlin/com/crud/usersweb/AbstractIntegrationTest.kt | 4047725857 |
package com.crud.usersweb
import jakarta.validation.Constraint
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import jakarta.validation.Payload
import kotlin.reflect.KClass
@Target(AnnotationTarget.FIELD)
@MustBeDocumented
@Constraint(validatedBy = [SizeElementsOfListValidator::class])
annotation class SizeElementsOfList(
val message: String = "Os elementos da lista devem estar entre 1 e {size}",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
val size: Int = 32
)
class SizeElementsOfListValidator : ConstraintValidator<SizeElementsOfList, List<String>> {
private var size: Int = 32
override fun initialize(constraintAnnotation: SizeElementsOfList?) {
if (constraintAnnotation != null) {
size = constraintAnnotation.size
}
}
override fun isValid(value: List<String>?, context: ConstraintValidatorContext?): Boolean =
value == null || value.all { it.isNotBlank() && it.length in 0..size }
} | crud-users-kotlin/users-web/src/main/kotlin/com/crud/usersweb/CustomValidator.kt | 1645312084 |
package com.crud.usersweb.repository
import com.crud.usersweb.entity.User
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import java.util.UUID
@Repository
interface UserRepository: CrudRepository<User, UUID> | crud-users-kotlin/users-web/src/main/kotlin/com/crud/usersweb/repository/UserRepository.kt | 360648589 |
package com.crud.usersweb.entity
import jakarta.persistence.AttributeConverter
import jakarta.persistence.Converter
@Converter
class StringListConverter : AttributeConverter<List<String>, String> {
override fun convertToDatabaseColumn(attribute: List<String>?): String = attribute?.joinToString(";") ?: ""
override fun convertToEntityAttribute(dbData: String?): List<String> = if (dbData?.isNotBlank() == true) dbData.split(";") else listOf()
} | crud-users-kotlin/users-web/src/main/kotlin/com/crud/usersweb/entity/StringListConverter.kt | 4070343444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.