content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.valbac.calendarinertia.feature_calendar.data.remote.dto
data class NextPublicHolidaysDto(
val counties: List<String>,
val countryCode: String,
val date: String,
val fixed: Boolean,
val global: Boolean,
val launchYear: Int?,
val localName: String,
val name: String,
val types: List<String>
) | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/remote/dto/NextPublicHolidaysDto.kt | 770352394 |
package com.valbac.calendarinertia.feature_calendar.data.remote
import com.valbac.calendarinertia.feature_calendar.data.remote.dto.NextPublicHolidaysDto
import retrofit2.http.GET
import retrofit2.http.Path
interface PublicHolidayApi {
@GET("/api/v3/NextPublicHolidays/{countryCode}")
suspend fun getPublicHolidaysInfo(
@Path("countryCode") countryCode: String,
):List<NextPublicHolidaysDto>
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/remote/PublicHolidayApi.kt | 1164704663 |
package com.valbac.calendarinertia.feature_calendar.domain.repository
import com.valbac.calendarinertia.feature_calendar.data.remote.dto.NextPublicHolidaysDto
interface PublicHolidaysRepository {
suspend fun getPublicHolidaysInfo(countryCode: String): List<NextPublicHolidaysDto>
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/domain/repository/PublicHolidaysRepository.kt | 94092747 |
package com.valbac.calendarinertia.feature_calendar.domain.repository
import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity
import kotlinx.coroutines.flow.Flow
interface TaskRepository {
suspend fun upsertTask(taskEntity: TaskEntity)
suspend fun deleteTask(taskEntity: TaskEntity)
fun getTasks(): Flow<List<TaskEntity>>
suspend fun getTaskById(id: Int): TaskEntity?
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/domain/repository/TaskRepository.kt | 2114675098 |
package com.valbac.calendarinertia.feature_calendar.domain.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class TaskEntity(
val title: String,
val description: String,
val isDone: Boolean,
val checked: Boolean,
val color: Int,
val dateDay: Int,
val dateMonth: Int,
val dateYear: Int,
val hour: Int,
val minute: Int,
val second: Int,
@PrimaryKey(autoGenerate = true)
val id: Int = 0
)
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/domain/model/TaskEntity.kt | 3450285667 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import com.kizitonwose.calendar.compose.CalendarState
import com.kizitonwose.calendar.compose.ContentHeightMode
import com.kizitonwose.calendar.compose.HorizontalCalendar
import com.kizitonwose.calendar.compose.rememberCalendarState
import com.kizitonwose.calendar.core.CalendarMonth
import com.kizitonwose.calendar.core.DayPosition
import com.kizitonwose.calendar.core.OutDateStyle
import com.kizitonwose.calendar.core.daysOfWeek
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.flow.filter
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.YearMonth
@SuppressLint("RememberReturnType")
@Destination
@Composable
fun CalendarMonthScreen(
navigator: DestinationsNavigator,
) {
Column(
modifier = Modifier
.fillMaxSize()
) {
val today = remember { LocalDate.now() }
val currentMonth = remember { YearMonth.now() }
val startMonth = remember { currentMonth.minusMonths(100) } // Adjust as needed
val endMonth = remember { currentMonth.plusMonths(100) } // Adjust as needed
val daysOfWeek = remember { daysOfWeek(firstDayOfWeek = DayOfWeek.MONDAY) }
val state = rememberCalendarState(
startMonth = startMonth,
endMonth = endMonth,
firstVisibleMonth = currentMonth,
firstDayOfWeek = daysOfWeek.first(),
outDateStyle = OutDateStyle.EndOfGrid
)
val visibleMonth = rememberFirstVisibleMonthAfterScroll(state)
HorizontalCalendar(
state = state,
dayContent = { day ->
Day(
day = day,
isToday = day.position == DayPosition.MonthDate && day.date == today,
navigator = navigator
)
},
monthHeader = {
MonthHeader(
daysOfWeek = daysOfWeek,
)
},
monthFooter = {
val currentMonth: YearMonth = visibleMonth.yearMonth
MonthFooter(
currentMonth = currentMonth
)
},
contentHeightMode = ContentHeightMode.Fill
)
}
}
@Composable
fun rememberFirstVisibleMonthAfterScroll(state: CalendarState): CalendarMonth {
val visibleMonth = remember(state) { mutableStateOf(state.firstVisibleMonth) }
LaunchedEffect(state) {
snapshotFlow { state.isScrollInProgress }
.filter { scrolling -> !scrolling }
.collect { visibleMonth.value = state.firstVisibleMonth }
}
return visibleMonth.value
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/CalendarMonthScreen.kt | 1885336769 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
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.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.kizitonwose.calendar.core.CalendarDay
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.valbac.calendarinertia.feature_calendar.presentation.destinations.AddEditTaskScreenDestination
import com.valbac.calendarinertia.feature_calendar.presentation.task.TaskEvent
import com.valbac.calendarinertia.feature_calendar.presentation.task.TaskItem
import com.valbac.calendarinertia.feature_calendar.presentation.task.TaskViewModel
import kotlinx.coroutines.launch
import java.time.LocalDate
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Destination
@Composable
fun DayInfoScreen(
viewModel: TaskViewModel = hiltViewModel(),
viewModelCalendar: CalendarViewModel = hiltViewModel(),
day: CalendarDay,
navigator: DestinationsNavigator
) {
val tasks = viewModel.tasks.collectAsState(initial = emptyList())
val publicHolidaysDE by viewModelCalendar.getPublicHolidaysDEFlow().collectAsState(initial = emptyList())
val sortedTaskList =
tasks.value.sortedWith(compareBy({ it.hour }, { it.minute }, { it.second }))
val publicHolidaysDESorted = publicHolidaysDE.sortedBy { it.date }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
topBar = {
TopAppBar(navigationIcon = {
IconButton(onClick = {
navigator.popBackStack()
}) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Menu"
)
}
},
title = {
Text(
modifier = Modifier
.fillMaxWidth(),
text = "${day.date.dayOfMonth} - ${day.date.month.toString().lowercase()}",
fontSize = 20.sp
)
},
colors = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
titleContentColor = MaterialTheme.colorScheme.onBackground
)
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
navigator.navigate(AddEditTaskScreenDestination(0))
}
)
{
Icon(Icons.Filled.Add, "Floating action button.")
}
},
snackbarHost = { SnackbarHost(snackbarHostState) }
)
{ innerPadding ->
Column(
modifier = Modifier.padding(innerPadding),
) {
for (publicHoliday in publicHolidaysDESorted) {
val composedDate = LocalDate.of(day.date.year, day.date.month, day.date.dayOfMonth)
if (composedDate == LocalDate.parse(publicHoliday.date)) {
Column(
modifier = Modifier.background(MaterialTheme.colorScheme.errorContainer)
) {
Row(
modifier = Modifier.height(40.dp)
) {
Column(
modifier = Modifier
.weight(1f)
.padding(vertical = 5.dp)
.padding(start = 6.dp)
) {
Text(
text = publicHoliday.localName,
style = MaterialTheme.typography.titleLarge.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
if (publicHoliday.counties != null || publicHoliday.launchYear != null) {
Row(
modifier = Modifier
.padding(horizontal = 6.dp)
.padding(bottom = 6.dp)
) {
val textValue = listOfNotNull(
publicHoliday.counties?.let { "Only for Landkreis: $it" },
publicHoliday.launchYear?.let { "Launch year: $it" }
).joinToString("\n")
Text(
text = textValue,
style = MaterialTheme.typography.bodyMedium.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
}
Spacer(modifier = Modifier.padding(8.dp))
}
}
LazyColumn(
) {
items(sortedTaskList) { task ->
if (day.date.dayOfMonth == task.dateDay && day.date.month.value == task.dateMonth && day.date.year == task.dateYear) {
TaskItem(
task = task,
modifier = Modifier.clickable {
navigator.navigate(AddEditTaskScreenDestination(task.id))
}
)
{
viewModel.onEvent(TaskEvent.DeleteTask(task))
scope.launch {
val result = snackbarHostState.showSnackbar(
message = "Note deleted",
actionLabel = "Undo",
duration = SnackbarDuration.Long
)
if (result == SnackbarResult.ActionPerformed) {
viewModel.onEvent(TaskEvent.RestoreNote)
}
}
}
}
}
}
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/DayInfoScreen.kt | 2255390350 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
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.fillMaxHeight
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.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.kizitonwose.calendar.core.CalendarDay
import com.kizitonwose.calendar.core.DayPosition
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.valbac.calendarinertia.feature_calendar.presentation.destinations.DayInfoScreenDestination
import com.valbac.calendarinertia.feature_calendar.presentation.task.TaskViewModel
import com.valbac.calendarinertia.ui.theme.GreenGrey60
import com.valbac.calendarinertia.ui.theme.Red40
import java.time.LocalDate
@Composable
fun Day(
viewModelTask: TaskViewModel = hiltViewModel(),
viewModelCalendar: CalendarViewModel = hiltViewModel(),
navigator: DestinationsNavigator,
day: CalendarDay,
isToday: Boolean,
) {
val tasks = viewModelTask.tasks.collectAsState(initial = emptyList())
val publicHolidaysDE by viewModelCalendar.getPublicHolidaysDEFlow().collectAsState(initial = emptyList())
val scrollState = rememberScrollState()
val publicHolidaysDESorted = publicHolidaysDE.sortedBy { it.date }
val sortedTaskList =
tasks.value.sortedWith(compareBy({ it.hour }, { it.minute }, { it.second }))
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.border(
width = 0.dp,
color = Color.Transparent,
)
.padding(1.dp)
.background(
color = when {
isToday -> MaterialTheme.colorScheme.inversePrimary
day.position == DayPosition.MonthDate -> MaterialTheme.colorScheme.primaryContainer
else -> MaterialTheme.colorScheme.secondaryContainer
}
)
.clickable(
onClick = { navigator.navigate(DayInfoScreenDestination(day = day)) }
),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier
.align(Alignment.TopCenter)
.padding(top = 3.dp),
text = day.date.dayOfMonth.toString(),
color = if (day.position == DayPosition.MonthDate) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSecondaryContainer,
fontSize = 12.sp,
)
Column(
modifier = Modifier
.align(Alignment.TopCenter)
.fillMaxWidth()
.verticalScroll(scrollState)
.padding(top = 20.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
for (publicHoliday in publicHolidaysDESorted) {
val composedDate = LocalDate.of(day.date.year, day.date.month, day.date.dayOfMonth)
if (composedDate == LocalDate.parse(publicHoliday.date)) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(15.dp)
.background(MaterialTheme.colorScheme.errorContainer),
) {
Text(
modifier = Modifier.padding(horizontal = 2.dp),
style = MaterialTheme.typography.labelSmall.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
text = publicHoliday.localName,
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
}
for (task in sortedTaskList) {
if (day.date.dayOfMonth == task.dateDay && day.date.month.value == task.dateMonth && day.date.year == task.dateYear) {
Box(
modifier = Modifier
.alpha(
if (task.isDone) 0.25f else 1.0f
)
.fillMaxWidth()
.height(15.dp)
.padding(horizontal = 2.dp)
.clip(RoundedCornerShape(4.dp))
.background(Color(task.color)),
) {
Text(
modifier = Modifier.padding(horizontal = 2.dp),
style = MaterialTheme.typography.labelSmall.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
text = task.title,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
}
}
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/Day.kt | 2441884576 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import java.time.DayOfWeek
import java.time.format.TextStyle
import java.util.Locale
@Composable
fun MonthHeader(daysOfWeek: List<DayOfWeek>) {
Row(
modifier = Modifier
.fillMaxWidth()
.testTag("MonthHeader")
.background(color = MaterialTheme.colorScheme.background)
) {
for (dayOfWeek in daysOfWeek) {
Text(
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center,
fontSize = 15.sp,
text = dayOfWeek.displayText(),
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onBackground
)
}
}
}
fun DayOfWeek.displayText(uppercase: Boolean = false): String {
return getDisplayName(TextStyle.SHORT, Locale.ENGLISH).let { value ->
if (uppercase) value.uppercase(Locale.ENGLISH) else value
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/MonthHeader.kt | 1251041346 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
import androidx.lifecycle.ViewModel
import com.valbac.calendarinertia.feature_calendar.domain.repository.PublicHolidaysRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class CalendarViewModel @Inject constructor(
private val repository: PublicHolidaysRepository
) : ViewModel() {
fun getPublicHolidaysDEFlow() = flow {
var retryCount = 0
while (true) {
try {
val holidays = withContext(Dispatchers.IO) {
repository.getPublicHolidaysInfo("DE")
}
emit(holidays)
break
} catch (e: Exception) {
retryCount++
if (retryCount >= MAX_RETRIES) {
break
}
}
}
}
companion object {
const val MAX_RETRIES = 3
}
}
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/CalendarViewModel.kt | 235772650 |
package com.valbac.calendarinertia.feature_calendar.presentation.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import java.time.YearMonth
@Composable
fun MonthFooter(currentMonth: YearMonth) {
Box(
Modifier
.fillMaxWidth()
.testTag("MonthFooter")
.background(color = MaterialTheme.colorScheme.background)
.padding(vertical = 10.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = "${currentMonth.month} - ${currentMonth.year}",
color = MaterialTheme.colorScheme.onBackground
)
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/calendar/MonthFooter.kt | 3099503983 |
package com.valbac.calendarinertia.feature_calendar.presentation
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.FreeCancellation
import androidx.compose.material.icons.filled.Task
import androidx.compose.material.icons.outlined.DateRange
import androidx.compose.material.icons.outlined.FreeCancellation
import androidx.compose.material.icons.outlined.Task
import androidx.compose.ui.graphics.vector.ImageVector
data class NavigationItem(
val title: String,
val selectedIcon: ImageVector,
val unselectedIcon: ImageVector,
val badgeCount: Int? = null
)
val items = listOf(
NavigationItem(
title = "Calendar",
selectedIcon = Icons.Filled.DateRange,
unselectedIcon = Icons.Outlined.DateRange
),
NavigationItem(
title = "Tasks",
selectedIcon = Icons.Filled.Task,
unselectedIcon = Icons.Outlined.Task
),
NavigationItem(
title = "Public Holidays",
selectedIcon = Icons.Filled.FreeCancellation,
unselectedIcon = Icons.Outlined.FreeCancellation
)
)
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/NavigationItem.kt | 629329499 |
package com.valbac.calendarinertia.feature_calendar.presentation.public_holidays
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.valbac.calendarinertia.feature_calendar.presentation.calendar.CalendarViewModel
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun PublicHolidaysInfoScreen(
viewModelCalendar: CalendarViewModel = hiltViewModel()
) {
val publicHolidaysDE by viewModelCalendar.getPublicHolidaysDEFlow().collectAsState(initial = emptyList())
val publicHolidaysDESorted = publicHolidaysDE.sortedBy { it.date }
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.verticalScroll(scrollState)
) {
for (publicHoliday in publicHolidaysDESorted) {
Column(
modifier = Modifier
.padding(start = 12.dp, end = 12.dp)
.clip(RoundedCornerShape(8.dp))
.background(color = MaterialTheme.colorScheme.errorContainer)
) {
Row(
modifier = Modifier.height(40.dp)
) {
Column(
modifier = Modifier
.weight(1f)
.padding(vertical = 5.dp)
.padding(start = 6.dp)
) {
Text(
text = "${publicHoliday.date.split("-").reversed().toTypedArray().joinToString ("-")} - ${publicHoliday.localName}",
style = MaterialTheme.typography.titleLarge.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
if (publicHoliday.counties != null || publicHoliday.launchYear != null) {
Row(
modifier = Modifier
.padding(horizontal = 6.dp)
.padding(bottom = 6.dp)
) {
val textValue = listOfNotNull(
publicHoliday.counties?.let { "Only for Landkreis: $it" },
publicHoliday.launchYear?.let { "Launch year: $it" }
).joinToString("\n")
Text(
text = textValue,
style = MaterialTheme.typography.bodyMedium.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
color = MaterialTheme.colorScheme.onErrorContainer,
)
}
}
}
Spacer(modifier = Modifier.padding(8.dp))
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/public_holidays/PublicHolidaysInfoScreen.kt | 817781582 |
package com.valbac.calendarinertia.feature_calendar.presentation.task
import android.annotation.SuppressLint
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.valbac.calendarinertia.feature_calendar.presentation.destinations.AddEditTaskScreenDestination
import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Destination
@Composable
fun TaskInfoScreen(
navigator: DestinationsNavigator,
viewModel: TaskViewModel = hiltViewModel()
) {
val tasks = viewModel.tasks.collectAsState(initial = emptyList())
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = {
navigator.navigate(AddEditTaskScreenDestination(0)){
}
}
)
{
Icon(Icons.Filled.Add, "Floating action button.")
}
},
snackbarHost = { SnackbarHost(snackbarHostState) }
) {
Column {
LazyColumn(
) {
items(tasks.value) { task ->
TaskItem(
task = task,
modifier = Modifier.clickable {
navigator.navigate(AddEditTaskScreenDestination(task.id))
}
)
{
viewModel.onEvent(TaskEvent.DeleteTask(task))
scope.launch {
val result = snackbarHostState.showSnackbar(
message = "Note deleted",
actionLabel = "Undo",
duration = SnackbarDuration.Long
)
if (result == SnackbarResult.ActionPerformed) {
viewModel.onEvent(TaskEvent.RestoreNote)
}
}
}
}
}
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/task/TaskInfoScreen.kt | 1071019371 |
package com.valbac.calendarinertia.feature_calendar.presentation.task
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity
import com.valbac.calendarinertia.feature_calendar.domain.repository.TaskRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class TaskViewModel @Inject constructor(
private val repository: TaskRepository
) : ViewModel() {
val tasks = repository.getTasks()
private var recentlyDeletedTask: TaskEntity? = null
fun onEvent(event: TaskEvent) {
when (event) {
is TaskEvent.DeleteTask -> {
viewModelScope.launch {
repository.deleteTask(event.task)
recentlyDeletedTask = event.task
}
}
is TaskEvent.RestoreNote -> {
viewModelScope.launch {
repository.upsertTask(recentlyDeletedTask ?: return@launch)
recentlyDeletedTask = null
}
}
is TaskEvent.OnDoneChange -> {
viewModelScope.launch {
repository.upsertTask(
event.task.copy(
isDone = event.isDone
)
)
}
}
}
}
}
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/task/TaskViewModel.kt | 1527856788 |
package com.valbac.calendarinertia.feature_calendar.presentation.task
import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity
sealed interface TaskEvent {
data class DeleteTask(val task: TaskEntity): TaskEvent
object RestoreNote: TaskEvent
data class OnDoneChange(val task: TaskEntity, val isDone: Boolean): TaskEvent
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/task/TaskEvent.kt | 3893046549 |
package com.valbac.calendarinertia.feature_calendar.presentation.task
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity
@Composable
fun TaskItem(
task: TaskEntity,
modifier: Modifier = Modifier,
viewModel: TaskViewModel = hiltViewModel(),
onDeleteClick: () -> Unit
) {
Column(
modifier = modifier
.alpha(
if (task.isDone) 0.25f else 1.0f
)
.padding(start = 12.dp, end = 12.dp, bottom = 6.dp)
.clip(RoundedCornerShape(8.dp))
.background(color = Color(task.color))
) {
Row(
modifier = modifier.height(50.dp)
) {
Column(
modifier = Modifier
.weight(1f)
.padding(vertical = 10.dp)
.padding(start = 12.dp)
) {
Text(
text = task.title,
style = MaterialTheme.typography.titleLarge.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurface
)
}
Checkbox(
modifier = Modifier.padding(vertical = 12.dp),
checked = task.isDone,
colors = CheckboxDefaults.colors(
uncheckedColor = Color.Black,
checkedColor = Color.White,
checkmarkColor = Color.Black
),
onCheckedChange = { isChecked ->
viewModel.onEvent(TaskEvent.OnDoneChange(task, isChecked))
}
)
Column(
modifier = Modifier.padding(vertical = 6.dp)
) {
Text(
text = "${task.dateDay}.${task.dateMonth}.${task.dateYear}",
fontSize = 14.sp,
style = MaterialTheme.typography.titleMedium.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
)
)
Text(
text = "${task.hour}:${task.minute}:${task.second}",
fontSize = 14.sp,
style = MaterialTheme.typography.titleMedium.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
)
)
}
IconButton(
modifier = Modifier.padding(vertical = 12.dp),
onClick = onDeleteClick,
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Delete note",
tint = Color.Black
)
}
}
if (task.description.isNotBlank()) {
Row(
modifier = Modifier
.padding(horizontal = 12.dp)
.padding(bottom = 12.dp)
) {
Text(
text = "${task.description}",
style = MaterialTheme.typography.bodyMedium.copy(
shadow = Shadow(
color = Color.DarkGray,
offset = Offset(x = 2f, y = 4f),
blurRadius = 0.5f
)
),
color = MaterialTheme.colorScheme.onSurface,
)
}
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/task/TaskItem.kt | 1401996305 |
package com.valbac.calendarinertia.feature_calendar.presentation.add_edit_task
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity
import com.valbac.calendarinertia.feature_calendar.domain.repository.TaskRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AddEditTaskViewModel @Inject constructor(
private val repository: TaskRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _state = mutableStateOf(AddEditTaskState())
val state: State<AddEditTaskState> = _state
private val _showDialog = MutableStateFlow(false)
val showDialog: StateFlow<Boolean> = _showDialog
init {
savedStateHandle.get<Int>("id")?.let {
val id = it
viewModelScope.launch {
repository.getTaskById(id)?.let {task ->
_state.value = state.value.copy(
title = task.title,
description = task.description,
isDone = task.isDone,
color = task.color,
dateDay = task.dateDay,
dateMonth = task.dateMonth,
dateYear = task.dateYear,
hour = task.hour,
minute = task.minute,
second = task.second,
id = task.id,
checked = task.checked
)
}
}
}
}
fun validateInputs(title: String, color: Int, dateDay: Int, hour: Int): Boolean {
var isValid = true
if (title.isBlank() || color >= 0 || dateDay <= 0 || hour < 0) {
_showDialog.value = true
isValid = false
} else {
_showDialog.value = false
}
return isValid
}
fun closeDialog() {
_showDialog.value = false
}
fun onEvent(event: AddEditTaskEvent) {
when (event) {
is AddEditTaskEvent.SaveTask -> {
val title = state.value.title
val description = state.value.description
val isDone = state.value.isDone
val color = state.value.color
val dateDay = state.value.dateDay
val dateMonth = state.value.dateMonth
val dateYear = state.value.dateYear
val hour = state.value.hour
val minute = state.value.minute
val second = state.value.second
val id = state.value.id
val checked = state.value.checked
val task = TaskEntity(
title = title,
description = description,
isDone = isDone,
color = color,
dateDay = dateDay,
dateMonth = dateMonth,
dateYear = dateYear,
hour = hour,
minute = minute,
second = second,
id = id,
checked = checked
)
viewModelScope.launch {
repository.upsertTask(task)
}
_state.value = state.value.copy(
title = "",
description = "",
isDone = false,
color = 0,
dateDay = 0,
dateMonth = 0,
dateYear = 0,
hour = -1,
minute = -1,
second = -1,
id = 0,
checked = false
)
}
is AddEditTaskEvent.SetDescription -> {
_state.value = state.value.copy(
description = event.description
)
}
is AddEditTaskEvent.SetTitle -> {
_state.value = state.value.copy(
title = event.title
)
}
is AddEditTaskEvent.SetTime -> {
_state.value = state.value.copy(
hour = event.hour,
minute = event.minute,
second = event.second
)
}
is AddEditTaskEvent.SetDate -> {
_state.value = state.value.copy(
dateDay = event.dateDay,
dateMonth = event.dateMonth,
dateYear = event.dateYear
)
}
is AddEditTaskEvent.SetColor -> {
_state.value = state.value.copy(
color = event.color
)
}
is AddEditTaskEvent.SetReminder -> {
_state.value = state.value.copy(
checked = event.checked
)
}
}
}
}
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/add_edit_task/AddEditTaskViewModel.kt | 2980462946 |
package com.valbac.calendarinertia.feature_calendar.presentation.add_edit_task
data class AddEditTaskState(
val title: String = "",
val description: String = "",
val color: Int = 0,
val dateDay: Int = 0,
val dateMonth: Int = 0,
val dateYear: Int = 0,
val hour: Int = -1,
val minute: Int = -1,
val second: Int = -1,
val isDone: Boolean = false,
val checked: Boolean = false,
val id: Int = 0,
)
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/add_edit_task/AddEditTaskState.kt | 2063134215 |
package com.valbac.calendarinertia.feature_calendar.presentation.add_edit_task
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@Composable
fun ErrorDialog(
showDialog: Boolean,
onDismiss: () -> Unit
) {
if (showDialog) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(text = "Error") },
text = { Text("Please enter a title, a date, a time and choose a color.") },
confirmButton = {
Button(onClick = onDismiss) {
Text("OK")
}
}
)
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/add_edit_task/ErrorDialog.kt | 1902409611 |
package com.valbac.calendarinertia.feature_calendar.presentation.add_edit_task
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Done
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import com.maxkeppeker.sheets.core.models.base.rememberUseCaseState
import com.maxkeppeler.sheets.calendar.CalendarDialog
import com.maxkeppeler.sheets.calendar.models.CalendarConfig
import com.maxkeppeler.sheets.calendar.models.CalendarSelection
import com.maxkeppeler.sheets.clock.ClockDialog
import com.maxkeppeler.sheets.clock.models.ClockConfig
import com.maxkeppeler.sheets.clock.models.ClockSelection
import com.maxkeppeler.sheets.color.ColorDialog
import com.maxkeppeler.sheets.color.models.ColorConfig
import com.maxkeppeler.sheets.color.models.ColorSelection
import com.maxkeppeler.sheets.color.models.ColorSelectionMode
import com.maxkeppeler.sheets.color.models.MultipleColors
import com.maxkeppeler.sheets.color.models.SingleColor
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.valbac.calendarinertia.core.AlarmItem
import com.valbac.calendarinertia.feature_calendar.data.AlarmSchedulerImpl
import com.valbac.calendarinertia.ui.theme.templateColorBlue
import com.valbac.calendarinertia.ui.theme.templateColorGreen
import com.valbac.calendarinertia.ui.theme.templateColorGreenBlue
import com.valbac.calendarinertia.ui.theme.templateColorOrange
import com.valbac.calendarinertia.ui.theme.templateColorPink
import com.valbac.calendarinertia.ui.theme.templateColorPurple
import com.valbac.calendarinertia.ui.theme.templateColorRed
import com.valbac.calendarinertia.ui.theme.templateColorTurquoise
import com.valbac.calendarinertia.ui.theme.templateColorYellow
import java.time.LocalDateTime
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Destination
@Composable
fun AddEditTaskScreen(
navigator: DestinationsNavigator,
id: Int?,
viewModel: AddEditTaskViewModel = hiltViewModel()
) {
val state = viewModel.state
val calendarState = rememberUseCaseState()
val clockState = rememberUseCaseState()
val colorState = rememberUseCaseState()
val pickedColor = remember { mutableStateOf(Color.Red.toArgb()) }
val templateColors = MultipleColors.ColorsInt(
templateColorRed.toArgb(),
templateColorOrange.toArgb(),
templateColorYellow.toArgb(),
templateColorGreen.toArgb(),
templateColorGreenBlue.toArgb(),
templateColorTurquoise.toArgb(),
templateColorBlue.toArgb(),
templateColorPurple.toArgb(),
templateColorPink.toArgb(),
)
var checked by remember { mutableStateOf(false) }
val context = LocalContext.current
val showDialog by viewModel.showDialog.collectAsState()
ErrorDialog(showDialog = showDialog, onDismiss = viewModel::closeDialog)
var hasNotificationPermission by remember {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
)
} else mutableStateOf(true)
}
val scheduler = AlarmSchedulerImpl(context = context)
var alarmItem: AlarmItem? = null
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
onResult = { isGranted ->
hasNotificationPermission = isGranted
}
)
CalendarDialog(
state = calendarState,
config = CalendarConfig(
monthSelection = true,
yearSelection = true
),
selection = CalendarSelection.Date { date ->
viewModel.onEvent(AddEditTaskEvent.SetDate(date.dayOfMonth, date.monthValue, date.year))
}
)
ClockDialog(
state = clockState,
config = ClockConfig(
is24HourFormat = true
),
selection = ClockSelection.HoursMinutesSeconds { hour, minute, second ->
viewModel.onEvent(AddEditTaskEvent.SetTime(hour, minute, second))
}
)
ColorDialog(
state = colorState,
selection = ColorSelection(
selectedColor = SingleColor(pickedColor.value),
onSelectColor = { color ->
viewModel.onEvent(AddEditTaskEvent.SetColor(color))
},
),
config = ColorConfig(
templateColors = templateColors,
displayMode = ColorSelectionMode.TEMPLATE
),
)
Scaffold(
topBar = {
TopAppBar(navigationIcon = {
IconButton(onClick = {
navigator.popBackStack()
}) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Menu"
)
}
},
title = {
Text(
text = "Task",
color = MaterialTheme.colorScheme.onSurface
)
},
colors = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
titleContentColor = MaterialTheme.colorScheme.onBackground
),
actions = {
Text(
text = "Reminder?",
color = MaterialTheme.colorScheme.onBackground
)
Switch(
checked = state.value.checked,
onCheckedChange = {
if (!checked && !hasNotificationPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
checked = it
viewModel.onEvent(AddEditTaskEvent.SetReminder(checked))
},
thumbContent = if (checked) {
{
Icon(
imageVector = Icons.Filled.Check,
contentDescription = null,
modifier = Modifier.size(SwitchDefaults.IconSize),
)
}
} else {
null
},
enabled = state.value.hour in 0..23 && state.value.title != "" && state.value.dateYear != 0
)
}
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
val isValid = viewModel.validateInputs(
state.value.title,
state.value.color,
state.value.dateDay,
state.value.hour
)
if (isValid) {
if (checked) {
alarmItem = AlarmItem(
time = LocalDateTime.of(
state.value.dateYear,
state.value.dateMonth,
state.value.dateDay,
state.value.hour,
state.value.minute,
state.value.second
),
message = state.value.title
)
alarmItem?.let(scheduler::schedule)
}
viewModel.onEvent(AddEditTaskEvent.SaveTask)
navigator.popBackStack()
}
},
containerColor = MaterialTheme.colorScheme.primaryContainer
) {
Icon(
imageVector = Icons.Default.Done,
contentDescription = "Save note",
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
}
}
) { innerPadding ->
Column(
modifier = Modifier.padding(innerPadding)
) {
OutlinedTextField(
value = state.value.title,
onValueChange = { viewModel.onEvent(AddEditTaskEvent.SetTitle(it)) },
label = { Text("Title") },
placeholder = { Text("...") },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textStyle = MaterialTheme.typography.titleLarge
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Button(
modifier = Modifier
.padding(4.dp),
onClick = {
calendarState.show()
},
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Text(text = "Date Picker")
}
Button(
modifier = Modifier
.padding(4.dp),
onClick = {
clockState.show()
},
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Text(text = "Time Picker")
}
Button(
modifier = Modifier
.padding(4.dp),
onClick = {
colorState.show()
},
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Text(text = "Color Picker")
}
}
OutlinedTextField(
value = state.value.description,
onValueChange = { viewModel.onEvent(AddEditTaskEvent.SetDescription(it)) },
label = { Text("Description") },
placeholder = { Text("...") },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textStyle = MaterialTheme.typography.bodyMedium
)
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/add_edit_task/AddEditTaskScreen.kt | 1510902331 |
package com.valbac.calendarinertia.feature_calendar.presentation.add_edit_task
sealed interface AddEditTaskEvent {
object SaveTask: AddEditTaskEvent
data class SetTitle(val title: String): AddEditTaskEvent
data class SetDescription(val description: String): AddEditTaskEvent
data class SetReminder(val checked: Boolean): AddEditTaskEvent
data class SetColor(val color: Int): AddEditTaskEvent
data class SetTime(val hour: Int, val minute: Int, val second: Int): AddEditTaskEvent
data class SetDate(val dateDay: Int, val dateMonth: Int, val dateYear: Int,): AddEditTaskEvent
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/add_edit_task/AddEditTaskEvent.kt | 746411078 |
package com.valbac.calendarinertia.feature_calendar.presentation
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
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.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.valbac.calendarinertia.feature_calendar.presentation.calendar.CalendarMonthScreen
import com.valbac.calendarinertia.feature_calendar.presentation.public_holidays.PublicHolidaysInfoScreen
import com.valbac.calendarinertia.feature_calendar.presentation.task.TaskInfoScreen
import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@RootNavGraph(start = true)
@Destination
@Composable
fun MainScreen(
navigator: DestinationsNavigator
) {
Surface(
modifier = Modifier.fillMaxSize()
) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
var selectedItemIndex by rememberSaveable {
mutableStateOf(0)
}
ModalNavigationDrawer(
drawerContent = {
ModalDrawerSheet(
drawerContainerColor = MaterialTheme.colorScheme.background,
) {
Spacer(modifier = Modifier.height(16.dp))
items.forEachIndexed { index, item ->
NavigationDrawerItem(
label = {
Text(text = item.title)
},
selected = index == selectedItemIndex,
onClick = {
selectedItemIndex = index
scope.launch {
drawerState.close()
}
},
icon = {
Icon(
imageVector = if (index == selectedItemIndex) {
item.selectedIcon
} else item.unselectedIcon,
contentDescription = item.title
)
},
badge = {
item.badgeCount?.let {
Text(text = item.badgeCount.toString())
}
},
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
colors = NavigationDrawerItemDefaults.colors(
unselectedContainerColor = MaterialTheme.colorScheme.background
)
)
}
}
},
drawerState = drawerState
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text =
when (selectedItemIndex) {
1 -> "Tasks"
2 -> "Public Holidays"
else -> "Calendar Inertia"
}
)
},
navigationIcon = {
IconButton(onClick = {
scope.launch {
drawerState.open()
}
}) {
Icon(
imageVector = Icons.Default.Menu,
contentDescription = "Menu"
)
}
},
colors = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
titleContentColor = MaterialTheme.colorScheme.onBackground
)
)
}
)
{ innerPadding ->
Column(modifier = Modifier.padding(innerPadding)) {
AnimatedContent (
targetState = selectedItemIndex, label = "NavigationDrawerAnimation"
) {
targetState ->
when (targetState) {
0 -> CalendarMonthScreen(navigator = navigator)
1 -> TaskInfoScreen(navigator = navigator)
2 -> PublicHolidaysInfoScreen()
}
}
}
}
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/presentation/MainScreen.kt | 2823134865 |
package com.valbac.calendarinertia.ui.theme
import androidx.compose.ui.graphics.Color
val Green10 = Color(0xff003314)
val Green20 = Color(0xff006627)
val Green30 = Color(0xff00993b)
val Green40 = Color(0xff00cc4e)
val Green80 = Color(0xff99ffc0)
val Green90 = Color(0xffccffe0)
val DarkGreen10 = Color(0xff0d260d)
val DarkGreen20 = Color(0xff194d19)
val DarkGreen30 = Color(0xff267326)
val DarkGreen40 = Color(0xff339933)
val DarkGreen80 = Color(0xffb3e6b3)
val DarkGreen90 = Color(0xffd9f2d9)
val Violet10 = Color(0xff330033)
val Violet20 = Color(0xff660066)
val Violet30 = Color(0xff990099)
val Violet40 = Color(0xffcc00cc)
val Violet80 = Color(0xffff99ff)
val Violet90 = Color(0xffffccff)
val Red10 = Color(0xFF410001)
val Red20 = Color(0xFF680003)
val Red30 = Color(0xFF930006)
val Red40 = Color(0xFFBA1B1B)
val Red80 = Color(0xFFFFB4A9)
val Red90 = Color(0xFFFFDAD4)
val Grey10 = Color(0xFF191C1D)
val Grey20 = Color(0xFF2D3132)
val Grey90 = Color(0xFFE0E3E3)
val Grey95 = Color(0xFFEFF1F1)
val Grey99 = Color(0xFFFBFDFD)
val GreenGrey30 = Color(0xFF316847)
val GreenGrey50 = Color(0xFF52ad76)
val GreenGrey60 = Color(0xFF74be92)
val GreenGrey80 = Color(0xFFbadec8)
val GreenGrey90 = Color(0xFFdcefe4)
val templateColorRed = Color(0xFFff0000)
val templateColorOrange = Color(0xFFff8000)
val templateColorYellow = Color(0xFFcccc00)
val templateColorGreen = Color(0xFF00cc00)
val templateColorGreenBlue = Color(0xFF20c573)
val templateColorTurquoise = Color(0xFF20c5c5)
val templateColorBlue = Color(0xFF0066ff)
val templateColorPurple = Color(0xFFcc33ff)
val templateColorPink = Color(0xFFff0080)
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/ui/theme/Color.kt | 2238685269 |
package com.valbac.calendarinertia.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Green80,
onPrimary = Green20,
primaryContainer = Green30,
onPrimaryContainer = Green90,
inversePrimary = Green40,
secondary = DarkGreen80,
onSecondary = DarkGreen20,
secondaryContainer = DarkGreen30,
onSecondaryContainer = DarkGreen90,
tertiary = Violet80,
onTertiary = Violet20,
tertiaryContainer = Violet30,
onTertiaryContainer = Violet90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = Grey10,
onBackground = Grey90,
surface = GreenGrey30,
onSurface = GreenGrey80,
inverseSurface = Grey90,
inverseOnSurface = Grey10,
surfaceVariant = GreenGrey30,
onSurfaceVariant = GreenGrey80,
outline = GreenGrey80
)
private val LightColorScheme = lightColorScheme(
primary = Green40,
onPrimary = Color.White,
primaryContainer = Green90,
onPrimaryContainer = Green10,
inversePrimary = Green80,
secondary = DarkGreen40,
onSecondary = Color.White,
secondaryContainer = DarkGreen90,
onSecondaryContainer = DarkGreen10,
tertiary = Violet40,
onTertiary = Color.White,
tertiaryContainer = Violet90,
onTertiaryContainer = Violet10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = Grey99,
onBackground = Grey10,
surface = GreenGrey90,
onSurface = GreenGrey30,
inverseSurface = Grey20,
inverseOnSurface = Grey95,
surfaceVariant = GreenGrey90,
onSurfaceVariant = GreenGrey30,
outline = GreenGrey50
)
@Composable
fun CalendarInertiaTheme(
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.background.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/ui/theme/Theme.kt | 839260155 |
package com.valbac.calendarinertia.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
)
*/
) | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/ui/theme/Type.kt | 2510539518 |
package com.valbac.calendarinertia
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class CalendarInertiaApplication: Application() {
override fun onCreate() {
super.onCreate()
val channel = NotificationChannel(
"reminder",
"Reminder Channel",
NotificationManager.IMPORTANCE_HIGH
)
channel.description = "A notification channel for reminder"
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/CalendarInertiaApplication.kt | 1800992891 |
package com.valbac.calendarinertia
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.ramcosta.composedestinations.DestinationsNavHost
import com.valbac.calendarinertia.feature_calendar.presentation.NavGraphs
import com.valbac.calendarinertia.ui.theme.CalendarInertiaTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CalendarInertiaTheme {
DestinationsNavHost(navGraph = NavGraphs.root)
}
}
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/MainActivity.kt | 372974623 |
package com.valbac.calendarinertia.di
import android.app.Application
import androidx.room.Room
import com.valbac.calendarinertia.feature_calendar.data.local.TheDatabase
import com.valbac.calendarinertia.feature_calendar.data.remote.PublicHolidayApi
import com.valbac.calendarinertia.feature_calendar.data.repository.PublicHolidaysRepositoryImpl
import com.valbac.calendarinertia.feature_calendar.data.repository.TaskRepositoryImpl
import com.valbac.calendarinertia.feature_calendar.domain.repository.PublicHolidaysRepository
import com.valbac.calendarinertia.feature_calendar.domain.repository.TaskRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideDatabase(app: Application): TheDatabase {
return Room.databaseBuilder(
app,
TheDatabase::class.java,
TheDatabase.DATABASE_NAME
).build()
}
@Provides
@Singleton
fun provideTaskRepository(db: TheDatabase): TaskRepository {
return TaskRepositoryImpl(db.taskDao)
}
@Provides
@Singleton
fun providePublicHolidayApi(): PublicHolidayApi{
return Retrofit.Builder()
.baseUrl("https://date.nager.at/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(PublicHolidayApi::class.java)
}
@Provides
@Singleton
fun providePublicHolidaysRepository(api: PublicHolidayApi): PublicHolidaysRepository {
return PublicHolidaysRepositoryImpl(api)
}
}
| CalendarInertia/app/src/main/java/com/valbac/calendarinertia/di/AppModule.kt | 1682146866 |
package com.valbac.calendarinertia.core
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import com.valbac.calendarinertia.MainActivity
import com.valbac.calendarinertia.R
import kotlin.random.Random
class AlarmReceiver : BroadcastReceiver () {
private fun showNotification(context: Context?, message: String) {
val notification = context?.let {
NotificationCompat.Builder(it, "reminder")
.setContentText(message)
.setContentTitle("Task Reminder")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(
PendingIntent.getActivity(
it,
0,
Intent(it, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
},
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
.setAutoCancel(true)
.build()
}
context?.getSystemService(NotificationManager::class.java)?.notify(
Random.nextInt(),
notification
)
}
override fun onReceive(context: Context?, intent: Intent?) {
val message = intent?.getStringExtra("EXTRA_MESSAGE") ?: return
showNotification(context, message)
}
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/core/AlarmReceiver.kt | 365211499 |
package com.valbac.calendarinertia.core
import java.time.LocalDateTime
class AlarmItem(
val time: LocalDateTime,
val message: String
) {
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/core/AlarmItem.kt | 3593338143 |
package com.valbac.calendarinertia.core
interface AlarmScheduler {
fun schedule(item: AlarmItem)
fun cancel(item: AlarmItem)
} | CalendarInertia/app/src/main/java/com/valbac/calendarinertia/core/AlarmScheduler.kt | 3889679083 |
package dev.jadnb.nimgameserver
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.entities.GameState
import dev.jadnb.nimgameserver.logic.computerstrategy.ComputerPlayerStrategy
import dev.jadnb.nimgameserver.logic.computerstrategy.ComputerStrategyFactory
import dev.jadnb.nimgameserver.logic.computerstrategy.DPStrategy
import dev.jadnb.nimgameserver.logic.computerstrategy.RandomComputerStrategy
import org.assertj.core.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import java.util.*
import java.util.function.Predicate
@SpringBootTest
class StrategyTest @Autowired constructor(
private val computerStrategyFactory: ComputerStrategyFactory
) {
val randomStrat = computerStrategyFactory.createStrategy("RANDOM")
val dpStrat = computerStrategyFactory.createStrategy("DP")
private fun createTestGame(nMatches: Int, allowedMoves: MutableList<Int>): Game {
val newGame = Game(UUID.randomUUID(), null, mutableListOf(), allowedMoves)
val gameState = GameState(UUID.randomUUID(), nMatches, newGame, 0, true)
newGame.currentState = gameState
return newGame
}
@Test
fun `factory should return correct instances`()
{
assertThat(computerStrategyFactory.createStrategy("RANDOM")).isInstanceOf(RandomComputerStrategy::class.java)
assertThat(computerStrategyFactory.createStrategy("DP")).isInstanceOf(DPStrategy::class.java)
assertThat(computerStrategyFactory.isValidStrategy("RANDOM")).isTrue()
assertThat(computerStrategyFactory.isValidStrategy("DP")).isTrue()
}
@Test
fun `factory for invalid name should fail`()
{
val exception = assertThrows<RuntimeException> { computerStrategyFactory.createStrategy("INVALID") }
assertThat(exception.message).isEqualTo("No Strategy named INVALID")
assertThat(computerStrategyFactory.isValidStrategy("INVALID")).isFalse()
}
fun testForMoves(strategy: ComputerPlayerStrategy, game: Game, predicate: Predicate<Int>) {
for (i in 1..1000)
{
assertThat(strategy.calculateMove(game)).matches { predicate.test(it) }
}
}
@Test
fun `random strategy does not violate allowed moves`()
{
val allowedMoves = mutableListOf(1,2,3,4)
val game = createTestGame(10, allowedMoves)
testForMoves(randomStrat, game) { it in allowedMoves}
}
@Test
fun `random strategy does not exceed current number of matches`()
{
val allowedMoves = mutableListOf(1,2,3,4)
val game = createTestGame(2, allowedMoves)
testForMoves(randomStrat, game) { it <= 2}
}
@Test
fun `dp strategy does not violate allowed moves`()
{
val allowedMoves = mutableListOf(1,2,3,4)
val game = createTestGame(10, allowedMoves)
testForMoves(dpStrat, game) { it in allowedMoves}
}
@Test
fun `dp strategy does not exceed current number of matches`()
{
val allowedMoves = mutableListOf(1,2,3,4)
val game = createTestGame(2, allowedMoves)
testForMoves(dpStrat, game) { it <= 2}
}
} | holisticon-nim-server/src/test/kotlin/dev/jadnb/nimgameserver/StrategyTest.kt | 2153421465 |
package dev.jadnb.nimgameserver
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class NimGameServerApplicationTests {
@Test
fun contextLoads() {
}
}
| holisticon-nim-server/src/test/kotlin/dev/jadnb/nimgameserver/NimGameServerApplicationTests.kt | 1196215597 |
package dev.jadnb.nimgameserver
import com.fasterxml.jackson.databind.ObjectMapper
import dev.jadnb.nimgameserver.controller.GameController
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.entities.GameState
import dev.jadnb.nimgameserver.exceptions.IllegalTurn
import dev.jadnb.nimgameserver.exceptions.NotFoundException
import dev.jadnb.nimgameserver.logic.GameService
import org.hamcrest.Matchers.`is`
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.Mockito.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import java.util.*
@WebMvcTest(GameController::class)
class GameWebTest @Autowired constructor(
private val mockMvc: MockMvc,
private val objectMapper: ObjectMapper
){
@MockBean
lateinit var gameService: GameService
@Test
fun `New Game endpoint should work with default parameters`()
{
val game = Game(null, null, mutableListOf(), mutableListOf())
`when`(gameService.create()).thenReturn(game)
mockMvc.post("/game/new") {
content = mapOf<String, Any>()
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
}
}
@Test
fun `New Game endpoint should accept additional game parameters`()
{
val game = Game(null, null, mutableListOf(), mutableListOf())
`when`(gameService.create(anyInt(), anyList(), anyString())).thenReturn(game)
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf<String, Any>("matches" to 14))
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
}
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf<String, Any>("allowedMoves" to listOf("1,2,3,4")))
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
}
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf("matches" to 14, "allowedMoves" to listOf("1,2,3,4")))
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
}
}
@Test
fun `New Game with arguments should call GameService with parameters`()
{
val game = Game(null, null, mutableListOf(), mutableListOf())
`when`(gameService.create(eq(14), anyList(), anyString())).thenReturn(game)
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf("matches" to 14, "allowedMoves" to listOf("1,2,3,4")))
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content {
contentType(MediaType.APPLICATION_JSON)
}
}
}
@Test
fun `New Game should accept Strategy argument`()
{
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf("computerStrategy" to "RANDOM"))
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
}
}
@Test
fun `Check if fields are present`()
{
val game = Game(null, null, mutableListOf(), mutableListOf(1,2,3))
val gameState = GameState(null, 13, game, 0, true)
game.currentState = gameState
`when`(gameService.create(anyInt(), anyList(), anyString())).thenReturn(game)
mockMvc.post("/game/new") {
content = objectMapper.writeValueAsString(mapOf<String, Any>())
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
content {
contentType(MediaType.APPLICATION_JSON)
}
jsonPath("\$.id").exists()
jsonPath("\$.allowedMoves", `is`(listOf(1,2,3)))
jsonPath("\$.winner", `is`("none"))
jsonPath("\$.currentState").exists()
jsonPath("\$.currentState.numMatches", `is`(13))
jsonPath("\$.currentState.turn", `is`(0))
jsonPath("\$.currentState.playersTurn", `is`(true))
}
}
@Test
fun `Empty request should fail`()
{
mockMvc.post("/game/new")
.andExpectAll {
status { isBadRequest() }
}
}
@Test
fun `Make move should work if supplied with correct arguments`()
{
val arguments = mapOf("nMatches" to 3, "id" to UUID.randomUUID())
mockMvc.post("/game/makeMove") {
content = objectMapper.writeValueAsString(arguments)
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status { isOk() }
}
}
@Test
fun `Make move with missing arguments should fail`()
{
val arg1 = mapOf("nMatches" to 3)
val arg2 = mapOf("id" to "abc")
mockMvc.post("/game/makeMove") {
content = objectMapper.writeValueAsString(arg1)
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status {
isUnprocessableEntity()
}
}
mockMvc.post("/game/makeMove") {
content = objectMapper.writeValueAsString(arg2)
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status {
isUnprocessableEntity()
}
}
}
private fun <T> anyObject(): T {
return Mockito.any<T>()
}
@Test
fun `Illegal move should throw forbidden`()
{
val errorMessage = "Illegal turn"
`when`(gameService.makeMove(anyObject(), anyInt())).thenThrow(IllegalTurn(errorMessage))
val arguments = mapOf("nMatches" to 3, "id" to UUID.randomUUID())
mockMvc.post("/game/makeMove") {
content = objectMapper.writeValueAsString(arguments)
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status {
isForbidden()
}
}
}
@Test
fun `Invalid ID should return not found`()
{
val errorMessage = "Not Found"
`when`(gameService.makeMove(anyObject(), anyInt())).thenThrow(NotFoundException(errorMessage))
val arguments = mapOf("nMatches" to 3, "id" to UUID.randomUUID())
mockMvc.post("/game/makeMove") {
content = objectMapper.writeValueAsString(arguments)
contentType = MediaType.APPLICATION_JSON
}.andExpectAll {
status {
isNotFound()
}
}
}
} | holisticon-nim-server/src/test/kotlin/dev/jadnb/nimgameserver/GameWebTest.kt | 2892449136 |
package dev.jadnb.nimgameserver
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.entities.GameRepository
import dev.jadnb.nimgameserver.entities.GameState
import dev.jadnb.nimgameserver.entities.GameStateRepository
import dev.jadnb.nimgameserver.exceptions.IllegalTurn
import dev.jadnb.nimgameserver.exceptions.InvalidInputException
import dev.jadnb.nimgameserver.logic.GameService
import jakarta.transaction.Transactional
import org.assertj.core.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@Transactional
@SpringBootTest
class GameServiceTest @Autowired constructor(
val gameRepository: GameRepository,
val gameStateRepository: GameStateRepository,
val gameService: GameService,
){
/**
* Will set up and persist a game and a gamestate according to the parameters to this function
* @param nMatches Number of matches left
* @param allowedMoves Moves allowed to make
*/
private fun setupTestGame(nMatches: Int, allowedMoves: MutableList<Int>): Pair<Game, GameState> {
val game = Game(null, null, mutableListOf(), allowedMoves)
gameRepository.save(game)
val gameState = GameState(null, nMatches, game, 0, true)
gameStateRepository.save(gameState)
game.currentState = gameState
gameRepository.save(game)
return Pair(game, gameState)
}
@Test
fun `creating a new game should be persisted`()
{
val game = gameService.create()
assertThat(game.id).isNotNull
assertThat(gameRepository.findGameById(game.id!!)).isNotNull
}
@Test
fun `Custom parameter should be persisted`()
{
val game = gameService.create(14, listOf(1,2,3,4))
assertThat(game.id).isNotNull()
val repoGame = gameRepository.findGameById(game.id!!)!!
assertThat(repoGame.allowedMoves.size).isEqualTo(4)
assertThat(repoGame.currentState).isNotNull
assertThat(repoGame.currentState!!.numMatches).isEqualTo(14)
}
@Test
fun `Invalid strategy should throw exception`()
{
assertThrows<InvalidInputException> { gameService.create(13, listOf(1,2,3), "Invalid") }
}
@Test
fun `Valid strategy should be set in object`()
{
val game = gameService.create(13, listOf(1,2,3), "RANDOM")
assertThat(game.id).isNotNull()
assertThat(game.computerPlayerStrategy).isEqualTo("RANDOM")
}
@Test
fun `A finished game should not accept a new move`()
{
lateinit var game: Game
// Set up finished game
setupTestGame(0, mutableListOf()).let {
game = it.first
}
// Check that game actually got persisted
assertThat(game.id).isNotNull()
// Test
assertThrows<IllegalTurn> {
gameService.makeMove(game.id!!, 1)
}
}
@Test
fun `should not allow to take illegal number of matches`()
{
lateinit var game: Game
// Setup game with 10 matches and [1,2,3,11] as allowed moves
setupTestGame(10, mutableListOf(1,2,3,11)).let {
game = it.first
}
// Check that game got persisted
assertThat(game.id).isNotNull()
// Test that we cannot take 4 matches
val exception4Matches = assertThrows<IllegalTurn> {
gameService.makeMove(game.id!!, 4)
}
assertThat(exception4Matches.message).isEqualTo("Invalid Turn, Taking 4 is not allowed")
// Test that we cannot take more matches than available
val exceptionNotEnoughMatches = assertThrows<IllegalTurn> {
gameService.makeMove(game.id!!, 11)
}
assertThat(exceptionNotEnoughMatches.message).isEqualTo("Invalid Turn, trying to take more matches than left on the heap")
}
@Test
fun `should modify game and make computer turn`()
{
lateinit var game: Game
// Set up game with 10 matches and allow only taking one match per turn
setupTestGame(10, mutableListOf(1)).let {
game = it.first
}
// Do a move
gameService.makeMove(game.id!!, 1)
game = gameRepository.findGameById(game.id!!)!!
assertThat(game.currentState).isNotNull
assertThat(game.currentState!!.numMatches).isEqualTo(8)
}
@Test
fun `should set winner correctly when computer wins`()
{
lateinit var game: Game
setupTestGame(1, mutableListOf(1)).let {
game = it.first
}
// Before the move it should be none
assertThat(game.winner).isEqualTo("none")
gameService.makeMove(game.id!!, 1)
// Check if field is updated
game = gameRepository.findGameById(game.id!!)!!
assertThat(game.winner).isEqualTo("Computer")
}
@Test
fun `should set winner correctly when player wins`()
{
lateinit var game: Game
setupTestGame(2, mutableListOf(1)).let {
game = it.first
}
assertThat(game.winner).isEqualTo("none")
gameService.makeMove(game.id!!, 1)
// Check if field is updated correctly
game = gameRepository.findGameById(game.id!!)!!
assertThat(game.winner).isEqualTo("Player")
}
} | holisticon-nim-server/src/test/kotlin/dev/jadnb/nimgameserver/GameServiceTest.kt | 138779164 |
package dev.jadnb.nimgameserver
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class NimGameServerApplication
fun main(args: Array<String>) {
runApplication<NimGameServerApplication>(*args)
}
| holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/NimGameServerApplication.kt | 3703152629 |
package dev.jadnb.nimgameserver.logic.computerstrategy
import dev.jadnb.nimgameserver.entities.Game
/**
* Simple strategy that just selects a random number of matches. Adheres to the
* rules of the game by filtering for illegal options
*/
class RandomComputerStrategy : ComputerPlayerStrategy {
override fun calculateMove(game: Game): Int {
val currentState = game.currentState ?:
throw IllegalStateException("Computer Strategy should not be called when there is no current State")
return game.allowedMoves.filter { it <= currentState.numMatches }.random()
}
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/computerstrategy/RandomComputerStrategy.kt | 487651372 |
package dev.jadnb.nimgameserver.logic.computerstrategy
import dev.jadnb.nimgameserver.entities.Game
/**
* An interface to be used in a strategy pattern to allow for multiple
* strategies for the computer player.
*/
interface ComputerPlayerStrategy {
/**
* Given a game, this function returns how many matches should be taken
* by the computer. It is the responsibility of this function to adhere to the
* game rules such as allowed number of matches to take or to not take
* more matches than left in the heap.
*/
fun calculateMove(game: Game): Int
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/computerstrategy/ComputerPlayerStrategy.kt | 2520902254 |
package dev.jadnb.nimgameserver.logic.computerstrategy
import org.springframework.stereotype.Component
/**
* Straightforward implementation of the ComputerStrategyFactory interface. However,
* this factory acts more as a Flyweight instancing the strategies and returning the
* same objects upon request. This has the advantage that we can store information that is only
* related to the strategy directly in the Strategy object across multiple invocations
*/
@Component
class ComputerStrategyFactoryImpl : ComputerStrategyFactory
{
private val randomPlayer = RandomComputerStrategy()
private val dpPlayer = DPStrategy()
private val strategies = mapOf(
"RANDOM" to randomPlayer,
"DP" to dpPlayer,
)
/*
Returns one of the strategy objects based on the descriptor. If no of the
strategies matches the descriptors, the method throws a RuntimeException
*/
override fun createStrategy(descriptor: String): ComputerPlayerStrategy {
return strategies[descriptor] ?: throw RuntimeException("No Strategy named $descriptor")
}
/*
Checks if the descriptor is a valid strategy for this factory. In this case, check
if the descriptor is in the static list of supported strategies
*/
override fun isValidStrategy(descriptor: String): Boolean {
return descriptor in listOf("RANDOM", "DP")
}
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/computerstrategy/ComputerStrategyFactoryImpl.kt | 733862733 |
package dev.jadnb.nimgameserver.logic.computerstrategy
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.exceptions.NotFoundException
import java.util.*
/**
* DPStrategy implements a more winning-oriented strategy by abusing the simplicity of the game.
* The Strategy computes all possible moves in a Dynamic Programming (DP) way and keeps
* track of the best move at all times. This might not always be a 100% win, but
* the algorithm always chooses the situation with the most favorable outcome for the
* computer. It can adapt to different game rules such as different number of matches
* or different number of allowed moves.
*/
class DPStrategy : ComputerPlayerStrategy {
/*
We use that we only create one instance of this strategy and keep a cache that stores
all already computed solutions such that we only have to run the computation on the first query
*/
private val cache: MutableMap<UUID, Solution> = mutableMapOf()
/*
Returns the best possible number of matches to take
*/
override fun calculateMove(game: Game): Int {
// Check if game state is valid
val gameId = game.id ?: throw NotFoundException("Id of game is missing")
val gameState = game.currentState ?: throw IllegalStateException("Game State cannot be null")
// Get the precomputed solution or if not present, recompute
val sol: Solution = cache.getOrPut(gameId) {
Solution(gameState.numMatches, game.allowedMoves)
}
return sol.getNextMove(gameState.numMatches)
}
/**
* Helper class that stores all information related to the Solution and can be kept in our cache Map
*/
class Solution (problemSize: Int, allowedMoves: List<Int>)
{
// The win probability for the computer from 0 to problemSize inclusive
private val winProbability: MutableList<Double> = MutableList(problemSize+1) { -1.0 }
// The win probability for the player
private val playerWinProbability: MutableList<Double> = MutableList(problemSize+1) { -1.0 }
// the best move at each point in the game for the computer
private val bestMove: MutableList<Int> = MutableList(problemSize+1) { -1 }
/**
* Returns the best number of matches to take, according to this Solution
*/
fun getNextMove(matchesLeft: Int): Int {
return bestMove[matchesLeft]
}
/*
On initialization, we have all information needed to compute the Solution for the whole game
*/
init {
// Initialize the base case, if zero matches left, the game is over
winProbability[0] = 0.0
playerWinProbability[0] = 0.0
bestMove[0] = 0
// Build DP tables from bottom up
for (i in 1..problemSize) {
// Calculate all the moves possible for the computer if i matches are left
val allMoves: List<Pair<Double, Int>> = allowedMoves.fold(listOf()) { acc, j ->
if (j > i)
// Taking j matches is not allowed
acc
else if (j == i)
// Taking j matches will lose us the game
acc + Pair(0.0, j)
else
// Break down to game where i-j matches are left and player is in turn
acc + Pair(1.0-playerWinProbability[i-j], j)
}
// Its computers turn, so we want to select the best possible move
val currentBestMove = allMoves.maxBy { it.first }
winProbability[i] = currentBestMove.first
bestMove[i] = currentBestMove.second
/*
The player might not always make the best decisions. To account for that,
we have a look at all possible moves and average the possibility that the
player wins
*/
playerWinProbability[i] = allowedMoves.fold(listOf<Double>()) { acc, j ->
if (j > i)
acc
else if (j == i)
acc + 0.0
else
acc + (1-winProbability[i-j])
}.average()
}
}
}
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/computerstrategy/DPStrategy.kt | 3885452221 |
package dev.jadnb.nimgameserver.logic.computerstrategy
/**
* Interface for a strategy factory that allows to get a corresponding ComputerPlayerStrategy object
* given a string identifier.
*/
interface ComputerStrategyFactory {
/**
* Returns ComputerPlayerStrategy object dependent on the descriptor
* passed to this function
* @param descriptor The descriptor of the strategy
* @return An ComputerPlayerStrategy object
* @throws RuntimeException if the descriptor is not understood
*/
fun createStrategy(descriptor: String): ComputerPlayerStrategy
/**
* Allows checking if this factory understands the descriptor,
* a more graceful way to check if a descriptor is valid than the exception in
* the createStrategy function
* @param descriptor The descriptor of the strategy
* @return true if createStrategy does not fail when called with descriptor
*/
fun isValidStrategy(descriptor: String): Boolean
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/computerstrategy/ComputerStrategyFactory.kt | 3496772437 |
package dev.jadnb.nimgameserver.logic
import dev.jadnb.nimgameserver.logic.computerstrategy.ComputerStrategyFactory
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.entities.GameRepository
import dev.jadnb.nimgameserver.entities.GameState
import dev.jadnb.nimgameserver.entities.GameStateRepository
import dev.jadnb.nimgameserver.exceptions.IllegalTurn
import dev.jadnb.nimgameserver.exceptions.InvalidInputException
import dev.jadnb.nimgameserver.exceptions.NotFoundException
import jakarta.transaction.Transactional
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
/**
* Implementation of the Game Service interface. Using the repositories to persist
* created Games and GameStates
*/
@Service
class GameServiceImpl @Autowired constructor(
private val gameRepository: GameRepository,
private val gameStateRepository: GameStateRepository,
private val computerStrategyFactory: ComputerStrategyFactory
) : GameService {
/*
Checks if the strategy is valid and then creates a game in an initial state
according to the arguments passed to the function
*/
override fun create(matches: Int, legalMoves: List<Int>, strategy: String): Game {
// Check if passed strategy is valid
if (!computerStrategyFactory.isValidStrategy(strategy)) {
throw InvalidInputException("Strategy $strategy is not a valid strategy")
}
// Check if matches and moves are legal
if (matches < 0) {
throw InvalidInputException("Number of matches at the beginning of the game should be at least 0")
}
if (legalMoves.any { it < 0 } || legalMoves.isEmpty()) {
throw InvalidInputException("allowedMoves is not valid")
}
// Create Game and initial GameState
val game = createInitGame(legalMoves, strategy)
val initialGameState = createInitGameState(matches, game)
// Link initial GameState to Game
game.currentState = initialGameState
gameRepository.save(game)
return game
}
/*
This function handles the logic of actually playing the game. First checks if the
move is actually legal. Afterward, it applies the move of the player and then
performs the move of the computer. Returns the Game after the Computer made its move.
*/
override fun makeMove(id: UUID, nMatches: Int): Game {
// Look up game in repository
val game = gameRepository.findGameById(id) ?: throw NotFoundException("No game with ID $id")
val gameState = game.currentState ?: throw NotFoundException("Game State was null")
// If illegal, will throw an exception to be handled by Spring
isMoveLegal(gameState, nMatches)
// Make players move and update the game
val playerGameState = takeMatches(gameState, nMatches)
setNewGameState(game, playerGameState)
if (isGameOver(playerGameState)) {
// The Game is finished, player looses
setWinner(game, false)
return game
}
// Computer Turn
val strategy = computerStrategyFactory.createStrategy(game.computerPlayerStrategy)
val computerMatches = strategy.calculateMove(game)
// Perform the Computer Move
val computerGameState = takeMatches(playerGameState, computerMatches)
setNewGameState(game, computerGameState)
if (isGameOver(computerGameState))
{
// The Game is finished, the computer looses
setWinner(game, true)
}
gameRepository.save(game)
return game
}
override fun getGame(id: UUID): Game? =
gameRepository.findGameById(id)
/*
Private helper functions
*/
/**
* Creates the initial Game object and persist it
* @param legalMoves Number of matches that can be taken each turn in this game
* @param strategy The strategy the computer player is supposed to use
* @return A new game object with the id field populated
*/
private fun createInitGame(legalMoves: List<Int>, strategy: String): Game {
val game = Game(null, null, mutableListOf(), legalMoves.toMutableList(), strategy)
gameRepository.save(game)
return game
}
/**
* Creates the first game state and persists it
* @param matches Number of matches to start the game with
* @param game the Game object this state belongs to
* @return A new GameState with the id field populated
*/
private fun createInitGameState(matches: Int, game: Game): GameState {
val initialGameState = GameState(null, matches, game, 0, true)
gameStateRepository.save(initialGameState)
return initialGameState
}
/**
* Checks if taking nMatches in the current games state is allowed
* @param gameState The current game state
* @param nMatches the number of matches intended to be taken.
* @throws IllegalTurn if a condition is violated
*/
private fun isMoveLegal(gameState: GameState, nMatches: Int): Unit {
if (gameState.numMatches == 0)
throw IllegalTurn("Invalid Turn, this game is already finished")
if (gameState.numMatches < nMatches)
throw IllegalTurn("Invalid Turn, trying to take more matches than left on the heap")
if (nMatches !in gameState.game.allowedMoves)
throw IllegalTurn("Invalid Turn, Taking $nMatches is not allowed")
}
/**
* Creates the new game state that results if we take nMatches
* in the currentGameState
* @param currentGameState the actual game state in which we want to take nMatches
* @param nMatches the number of matches to be taken
* @return the new GameState
*/
private fun takeMatches(currentGameState: GameState, nMatches: Int): GameState {
val game = currentGameState.game
// Create a new GameState object by subtracting the matches, add one turn and change the player who is next
val newGameState = GameState(null,
currentGameState.numMatches - nMatches,
game,
currentGameState.turn + 1,
!currentGameState.playersTurn)
gameStateRepository.save(newGameState)
return newGameState
}
/**
* Update the Game to use the game state provided as argument
* @param game The game that is supposed to be updated
* @param gameState the new game state
*/
private fun setNewGameState(game: Game, gameState: GameState): Unit {
game.currentState = gameState
game.allTurns.add(gameState)
}
/**
* Checks if the GameState is a finished game.
* @param gameState The game State
* @return true if the game is over
*/
private fun isGameOver(gameState: GameState): Boolean {
return gameState.numMatches == 0
}
/**
* Sets the winner field of Game
* @param game The game where the winner field should be updated
* @param playerHasWon Pass true if the player won, false otherwise
*/
private fun setWinner(game: Game, playerHasWon: Boolean): Unit {
game.winner = if (playerHasWon) "Player" else "Computer"
gameRepository.save(game)
}
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/GameServiceImpl.kt | 4139766204 |
package dev.jadnb.nimgameserver.logic
import dev.jadnb.nimgameserver.entities.Game
import java.util.UUID
/**
* The GameService provides the logic of the game through a simple interface.
* Furthermore, the GameService takes care of persisting the data of a game
* and makes handles validation of inputs to ensure that the input adheres to the rules
* of the game
*
*/
interface GameService {
/**
* Creates a new game. The parameters can be adjusted to play the game with different
* parameters, the default values for those parameters correspond to the default rules of the game
* @param matches number of matches at the beginning of the game
* @param legalMoves the possible number of matches that can be taken each turn
* @param strategy the strategy that the computer player should use
* @return A new game object
*/
fun create(matches: Int = 13, legalMoves: List<Int> = listOf(1, 2, 3), strategy: String = "DP"): Game
/**
* Takes a UUID and then takes nMatches from the game which corresponds to the UUID. Checks if it
* is allowed to take nMatches and fails if nMatches is not a valid input
* @param id The uuid of the game as returned by the create function
* @param nMatches The number of matches that shall be taken of the heap of the game
*/
fun makeMove(id: UUID, nMatches: Int): Game
/**
* Loads a game given the id.
* @param id The uuid of the game
* @return a game instance or null if no instance with this id is found
*/
fun getGame(id: UUID): Game?
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/logic/GameService.kt | 3721453232 |
package dev.jadnb.nimgameserver.exceptions
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
/**
* Exception class for invalid inputs. If thrown in a Spring Context will cause
* * the web server to response with UNPROCESSABLE_ENTITY (422)
*/
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
class InvalidInputException : RuntimeException {
constructor(message: String): super(message)
constructor(message: String, cause: Throwable): super(message, cause)
constructor(cause: Throwable): super(cause)
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/exceptions/InvalidInputException.kt | 113786166 |
package dev.jadnb.nimgameserver.exceptions
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
/**
* Exception class for all not found resources. If thrown in a Spring Context will cause
* the web server to response with NOT FOUND (404)
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
class NotFoundException(msg: String) : RuntimeException(msg) | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/exceptions/NotFoundException.kt | 2356765235 |
package dev.jadnb.nimgameserver.exceptions
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
/**
* Exception class for all illegal moves. If thrown in a Spring Context will cause
* the web server to response with FORBIDDEN (403)
*/
@ResponseStatus(HttpStatus.FORBIDDEN)
class IllegalTurn : RuntimeException {
constructor(message: String) : super(message) {
}
constructor(message: String, throwable: Throwable) : super(message, throwable)
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/exceptions/IllegalTurn.kt | 762425215 |
package dev.jadnb.nimgameserver.controller
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.contains
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.exceptions.*
import dev.jadnb.nimgameserver.logic.GameService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.*
/**
* Spring Controller for the Nim Game Application, handles
* http requests to the API and forwards them to the GameService.
*/
@RestController
@RequestMapping("/game")
class GameController @Autowired constructor(
private val gameService: GameService
)
{
/*
* Endpoints
*/
/**
* Endpoint for creating a new game. The JSON request could be an
* empty object or might specify the number of matches, allowedMoves, and
* the strategy the computer player should use.
* @param payload Additional rules for the game
* @return A new game
* @throws InvalidInputException if the payload specifies invalid values
*/
@PostMapping("/new")
fun createGame(@RequestBody payload: JsonNode): Game {
// Will throw an exception if input is invalid
validateNewGameInput(payload)
return gameService.create(
getNumberOfMatches(payload),
getLegalMoves(payload),
getStrategy(payload)
)
}
/**
* Endpoint for playing the game. Will validate the input and then
* hand over the information to the GameService.
* @param payload Information about the move the player makes
* @return The updated game
* @throws InvalidInputException can be thrown if any input is missing
* or not in the correct format.
* @throws IllegalTurn is thrown when the action taken by the user is not allowed.
* @throws NotFoundException is thrown if the game id does not exist
*/
@PostMapping("/makeMove")
fun makeMove(@RequestBody payload: JsonNode): Game {
// Will throw an exception if input is incorrect
validateMoveInput(payload)
// UUID.fromString might fail, if so, throw InvalidInputException
val id = try { UUID.fromString(payload["id"].asText()) }
catch (e: Exception) { throw InvalidInputException(e.message ?: "")}
val nMatches = payload["nMatches"].toString().toInt()
return gameService.makeMove(id, nMatches)
}
/**
* Endpoint for getting a game without any state change
* @param id given as query parameter
*/
@GetMapping("/get")
fun getGame(@RequestParam("id") id: String): Game {
val uuid = try { UUID.fromString(id) }
catch (e: Exception) { throw InvalidInputException(e.message ?: "")}
return gameService.getGame(uuid) ?: throw NotFoundException("No game with $uuid was found")
}
/*
* Helper Functions
*/
/**
* Validates the JSON request and checks if its eligible as request
* for a move. If validation succeeds, the function returns.
* @throws InvalidInputException is thrown if the validation does not succeed.
*/
private fun validateMoveInput(payload: JsonNode) {
if (!payload.isObject)
throw InvalidInputException("Expected JSON object")
if (!payload.contains("nMatches"))
throw InvalidInputException("Expected field nMatches")
if (!payload.contains("id"))
throw InvalidInputException("Expected field id")
}
/**
* Validates the JSON request for a new game. If validation succeeds, the function
* returns.
* @throws InvalidInputException is thrown if the validation does not succeed.
*/
private fun validateNewGameInput(payload: JsonNode) {
if (!payload.isObject)
throw InvalidInputException("Expected JSON object")
}
/**
* Reads the "matches" field from a JSON request and parses it as int
* @return the value of the "matches" field or a default value
*/
private fun getNumberOfMatches(payload: JsonNode): Int {
return if (payload.has("matches") && payload["matches"].isInt)
payload["matches"].asInt()
else 13
}
/**
* Reads the "allowedMoves" field from a JSON request and parses the items
* to ints.
* @return the array in the "allowedMoves" field or a default value
*/
private fun getLegalMoves(payload: JsonNode): List<Int> {
return if (payload.has("allowedMoves")
&& payload["allowedMoves"].isArray
&& payload["allowedMoves"].all { it.isInt })
payload["allowedMoves"].fold(listOf()) {acc, v ->
acc + v.asInt()
}
else listOf(1,2,3)
}
/**
* Reads the "computerStrategy" field which indicates which strategy the computer player should use.
* @return the strategy specified in the "computerStrategy" field or a default value
*/
private fun getStrategy(payload: JsonNode): String {
return if (payload.has("computerStrategy") && payload["computerStrategy"].isTextual)
payload["computerStrategy"].asText()
else
"DP"
}
} | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/controller/GameController.kt | 1581174133 |
package dev.jadnb.nimgameserver.entities
import dev.jadnb.nimgameserver.entities.Game
import dev.jadnb.nimgameserver.entities.GameState
import org.springframework.data.repository.CrudRepository
import java.util.UUID
/**
* Repository to queue and save Game objects
*/
interface GameRepository : CrudRepository<Game, UUID> {
fun findGameById(id: UUID): Game?
}
/**
* Repository to queue and save GameState objects
*/
interface GameStateRepository : CrudRepository<GameState, UUID>
| holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/entities/Repositories.kt | 3328136684 |
package dev.jadnb.nimgameserver.entities
import jakarta.persistence.*
import java.util.*
/**
* JPA Entity that represents the current game state. Note that this object designed as an immutable
* object is replaced by a new object when a player makes a move.
* @param id A unique identifier that is generated by the JPA backend
* @param numMatches the number of matches that are left in the game.
* @param game the parent game object, each GameState only belongs to one game
* @param turn The number of turns already done
* @param playersTurn Indicates if the next turn is the players turn (or not)
*/
@Entity
class GameState(
@Id
@GeneratedValue
val id: UUID? = null,
val numMatches: Int,
@ManyToOne
val game: Game,
val turn: Int,
val playersTurn: Boolean,
) | holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/entities/GameState.kt | 1648586270 |
package dev.jadnb.nimgameserver.entities
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import jakarta.persistence.*
import org.hibernate.annotations.Immutable
import java.util.UUID
/**
* JPA entity that represents a single game and stores accompanying information.
*
* @param id Contains a unique UUID generated by the JPA backend
* @param currentState the actual game state is stored in a separate entity, the game object
* only keeps a reference to it.
* @param allTurns Contains a list of all gameStates that were associated with this game.
* @param allowedMoves A list that specifies how many matches can be taken per turn in this
* specific instantiation of the game
* @param computerPlayerStrategy The strategy the computer player should employ in this game
* @param winner is either "none" until no winner is decided, "Player" if the player won or
* "Computer" if the computer won.
*/
@Entity
class Game(
@Id
@GeneratedValue
val id: UUID? = null,
@OneToOne
@JsonIgnoreProperties("game", "id")
var currentState: GameState?,
@OneToMany
@JsonIgnore
val allTurns: MutableList<GameState>,
@ElementCollection
@Immutable
val allowedMoves: MutableList<Int>,
val computerPlayerStrategy: String = "DP",
var winner: String = "none",
)
| holisticon-nim-server/src/main/kotlin/dev/jadnb/nimgameserver/entities/Game.kt | 124645542 |
package com.canodevs.charlapp
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.canodevs.charlapp", appContext.packageName)
}
} | CharlApp/app/src/androidTest/java/com/canodevs/charlapp/ExampleInstrumentedTest.kt | 2040633766 |
package com.canodevs.charlapp
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)
}
} | CharlApp/app/src/test/java/com/canodevs/charlapp/ExampleUnitTest.kt | 3653583129 |
package com.canodevs.charlapp
import android.app.ProgressDialog
import android.content.ContentProviderClient
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
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.material.button.MaterialButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.database.FirebaseDatabase
class Inicio : AppCompatActivity() {
// Instanciamos 2 botones, uno para registro y otro para logeo
private lateinit var Btn_ir_logeo: MaterialButton
private lateinit var Btn_login_google : MaterialButton
var firebaseUser: FirebaseUser? = null
private lateinit var auth : FirebaseAuth
private lateinit var progressDialog: ProgressDialog
private lateinit var mGoogleSignInClient: GoogleSignInClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_inicio)
// Asociamos cada botón por ID a su elemento del layout
Btn_ir_logeo = findViewById(R.id.Btn_ir_logeo)
Btn_login_google = findViewById(R.id.Btn_login_google)
progressDialog = ProgressDialog(this)
progressDialog.setTitle("Por favor, espere")
progressDialog.setCanceledOnTouchOutside(false)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
// Establecemos un Listener para que nos lleve a la pantalla de login
Btn_ir_logeo.setOnClickListener() {
val intent = Intent(this@Inicio, LoginActivity::class.java)
Toast.makeText(applicationContext, "Inicio de sesión", Toast.LENGTH_SHORT).show()
startActivity(intent)
}
Btn_login_google.setOnClickListener {
empezarInicioSesionGoogle()
}
}
private fun empezarInicioSesionGoogle() {
val googleSignIntent = mGoogleSignInClient.signInIntent
googleSignInARL.launch(googleSignIntent)
}
private val googleSignInARL = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()){resultado ->
if (resultado.resultCode == RESULT_OK) {
val data = resultado.data
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
autenticarGoogleFirebase(account.idToken)
} catch (e: Exception) {
Toast.makeText(applicationContext, "Ha ocurrido la siguiente excepción: ${e.message}", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(applicationContext, "Cancelado", Toast.LENGTH_SHORT).show()
}
}
private fun autenticarGoogleFirebase(idToken: String?) {
val credencial = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credencial)
.addOnSuccessListener {authResult ->
// Si el usuario es nuevo
if (authResult.additionalUserInfo!!.isNewUser) {
guardarInfoBBDD()
// Si el usuario ya existe
} else {
startActivity(Intent(this, MainActivity::class.java))
finishAffinity()
}
}.addOnFailureListener {e ->
Toast.makeText(applicationContext, "${e.message}", Toast.LENGTH_SHORT).show()
}
}
private fun guardarInfoBBDD() {
progressDialog.setMessage("Guardando su información...")
progressDialog.show()
// Obtener información de una cuenta de Google
val uidGoogle = auth.uid
val correoGoogle = auth.currentUser?.email
val n_Google = auth.currentUser?.displayName
val nombre_usuario_G : String = n_Google.toString()
val hashMap = HashMap<String, Any?>()
hashMap["uid"] = uidGoogle
hashMap["n_usuario"] = nombre_usuario_G
hashMap["email"] = correoGoogle
hashMap["imagen"] = ""
hashMap["buscar"] = nombre_usuario_G.lowercase()
/*Nuevos datos de usuario*/
hashMap["nombres"] = ""
hashMap["apellidos"] = ""
hashMap["edad"] = ""
hashMap["profesion"] = ""
hashMap["domicilio"] = ""
hashMap["telefono"] = ""
hashMap["estado"] = "offline"
hashMap["proveedor"] = "Google"
// Referencia a la BBDD
val reference = FirebaseDatabase.getInstance().getReference("Usuarios")
reference.child(uidGoogle!!)
.setValue(hashMap)
.addOnSuccessListener {
progressDialog.dismiss()
startActivity(Intent(applicationContext, MainActivity::class.java))
Toast.makeText(applicationContext, "¡Registro exitoso!", Toast.LENGTH_SHORT).show()
finishAffinity()
}
.addOnFailureListener { e->
progressDialog.dismiss()
Toast.makeText(applicationContext, "${e.message}", Toast.LENGTH_SHORT).show()
}
}
private fun comprobarSesion() {
firebaseUser = FirebaseAuth.getInstance().currentUser
if (firebaseUser != null) {
val intent = Intent(this@Inicio, MainActivity::class.java)
Toast.makeText(applicationContext, "Sesión de usuario activa", Toast.LENGTH_SHORT).show()
startActivity(intent)
finish()
}
}
override fun onStart() {
comprobarSesion()
super.onStart()
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Inicio.kt | 2419959014 |
package com.canodevs.charlapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.canodevs.charlapp.Fragmentos.FragmentoUsuarios
import com.canodevs.charlapp.Modelo.Usuario
import com.canodevs.charlapp.Perfil.PerfilActivity
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class MainActivity : AppCompatActivity() {
var reference: DatabaseReference? = null
var firebaseUser: FirebaseUser? = null
private lateinit var nombre_usuario: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
inicializarComponentes()
ObtenerDato()
}
fun inicializarComponentes() {
val appBarLayout: AppBarLayout = findViewById(R.id.toolbarMain)
val toolbar: Toolbar = appBarLayout.findViewById(R.id.toolbarInsideAppBar)
if (supportActionBar == null) {
setSupportActionBar(toolbar)
}
supportActionBar!!.title = ""
firebaseUser = FirebaseAuth.getInstance().currentUser
reference =
FirebaseDatabase.getInstance().reference.child("Usuarios").child(firebaseUser!!.uid)
nombre_usuario = findViewById(R.id.Nombre_usuario)
val tabLayout: TabLayout = findViewById(R.id.TabLayoutMain)
val viewPager: ViewPager = findViewById(R.id.ViewPagerMain)
val viewpagerAdapter = ViewPagerAdapter(supportFragmentManager)
viewpagerAdapter.addItem(FragmentoUsuarios(), "Usuarios")
viewpagerAdapter.addItem(FragmentoUsuarios(), "Chats")
viewPager.adapter = viewpagerAdapter
tabLayout.setupWithViewPager(viewPager)
}
fun ObtenerDato() {
reference!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val usuario: Usuario? = snapshot.getValue(Usuario::class.java)
nombre_usuario.text = usuario!!.getN_Usuario()
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
class ViewPagerAdapter(fragmentManager: FragmentManager) :
FragmentPagerAdapter(fragmentManager) {
private val listaFragmentos: MutableList<Fragment> = ArrayList()
private val listaTitulos: MutableList<String> = ArrayList()
override fun getCount(): Int {
return listaFragmentos.size
}
override fun getItem(position: Int): Fragment {
return listaFragmentos[position]
}
override fun getPageTitle(position: Int): CharSequence? {
return listaTitulos[position]
}
fun addItem(fragment: Fragment, titulo: String) {
listaFragmentos.add(fragment)
listaTitulos.add(titulo)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.menu_principal, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_perfil -> {
val intent = Intent(applicationContext, PerfilActivity::class.java)
startActivity(intent)
return true
}
R.id.menu_acerca_de -> {
Toast.makeText(
applicationContext,
"Desarrollado por Nicolás Cano",
Toast.LENGTH_SHORT
).show()
return true
}
R.id.menu_salir -> {
// Sign out of Firebase
FirebaseAuth.getInstance().signOut()
// Navigate to the login activity
val intent = Intent(this@MainActivity, Inicio::class.java)
Toast.makeText(applicationContext, "Has cerrado sesión", Toast.LENGTH_SHORT).show()
startActivity(intent)
return true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| CharlApp/app/src/main/java/com/canodevs/charlapp/MainActivity.kt | 2894116630 |
package com.canodevs.charlapp.Chat
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.net.UrlQuerySanitizer.ValueSanitizer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.canodevs.charlapp.Adaptador.AdaptadorChat
import com.canodevs.charlapp.Modelo.Chat
import com.canodevs.charlapp.Modelo.Usuario
import com.canodevs.charlapp.R
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageTask
import com.google.firebase.storage.UploadTask
class MensajesActivity : AppCompatActivity() {
private lateinit var imagen_perfil_chat: ImageView
private lateinit var N_usuario_chat: TextView
private lateinit var Et_mensaje: EditText
private lateinit var IB_Adjuntar: ImageButton
private lateinit var IB_Enviar: ImageButton
var uid_usuario_seleccionado: String = ""
var firebaseUser: FirebaseUser? = null
private var imagenUri: Uri? = null
lateinit var RV_chats: RecyclerView
var chatAdapter: AdaptadorChat? = null
var chatList: List<Chat>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mensajes)
inicializarVistas()
obtenerUid()
leerInfoUsuarioSeleccionado()
IB_Enviar.setOnClickListener {
val mensaje = Et_mensaje.text.toString()
if (mensaje.isEmpty()) {
Toast.makeText(applicationContext, "Escribe un mensaje", Toast.LENGTH_SHORT).show()
} else {
enviarMensaje(firebaseUser!!.uid, uid_usuario_seleccionado, mensaje)
Et_mensaje.setText("")
}
}
IB_Adjuntar.setOnClickListener {
abrirGaleria()
}
}
private fun obtenerUid() {
intent = intent
uid_usuario_seleccionado = intent.getStringExtra("uid_usuario").toString()
}
private fun enviarMensaje(uid_emisor: String, uid_receptor: String, mensaje: String) {
val reference = FirebaseDatabase.getInstance().reference
val mensajeKey = reference.push().key
val infoMensaje = HashMap<String, Any?>()
infoMensaje["id_mensaje"] = mensajeKey
infoMensaje["emisor"] = uid_emisor
infoMensaje["receptor"] = uid_receptor
infoMensaje["mensaje"] = mensaje
infoMensaje["url"] = ""
infoMensaje["visto"] = false
reference.child("Chats").child(mensajeKey!!).setValue(infoMensaje)
.addOnCompleteListener { tarea ->
if (tarea.isSuccessful) {
val listaMensajesEmisor =
FirebaseDatabase.getInstance().reference.child("ListaMensajes")
.child(firebaseUser!!.uid)
.child(uid_usuario_seleccionado)
listaMensajesEmisor.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (!snapshot.exists()) {
listaMensajesEmisor.child("uid").setValue(uid_usuario_seleccionado)
}
val listaMensajesReceptor =
FirebaseDatabase.getInstance().reference.child("ListaMensajes")
.child(uid_usuario_seleccionado)
.child(firebaseUser!!.uid)
listaMensajesReceptor.child("uid").setValue(firebaseUser!!.uid)
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
}
private fun inicializarVistas() {
imagen_perfil_chat = findViewById(R.id.imagen_perfil_chat)
N_usuario_chat = findViewById(R.id.N_usuario_chat)
Et_mensaje = findViewById(R.id.Et_mensaje)
IB_Adjuntar = findViewById(R.id.IB_Adjuntar)
IB_Enviar = findViewById(R.id.IB_Enviar)
firebaseUser = FirebaseAuth.getInstance().currentUser
RV_chats = findViewById(R.id.RV_chats)
RV_chats.setHasFixedSize(true)
var linearLayoutManager = LinearLayoutManager(applicationContext)
linearLayoutManager.stackFromEnd = true
RV_chats.layoutManager = linearLayoutManager
}
private fun leerInfoUsuarioSeleccionado() {
val reference = FirebaseDatabase.getInstance().reference.child("Usuarios")
.child(uid_usuario_seleccionado)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val usuario: Usuario? = snapshot.getValue(Usuario::class.java)
// Obtener nombre de usuario
N_usuario_chat.text = usuario!!.getN_Usuario()
// Obtener imagen de perfil
Glide.with(applicationContext).load(usuario.getImagen())
.placeholder(R.drawable.ic_item_usuario)
.into(imagen_perfil_chat)
recuperarMensajes(firebaseUser!!.uid, uid_usuario_seleccionado, usuario.getImagen())
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
private fun recuperarMensajes(EmisorUid: String, ReceptorUid: String, ReceptorImagen: String?) {
chatList = ArrayList()
val reference = FirebaseDatabase.getInstance().reference.child("Chats")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(chatList as ArrayList<Chat>).clear()
for (sn in snapshot.children) {
val chat = sn.getValue(Chat::class.java)
if (chat!!.getReceptor().equals(EmisorUid) && chat.getEmisor()
.equals(ReceptorUid)
|| chat.getReceptor().equals(ReceptorUid) && chat.getEmisor()
.equals(EmisorUid)
) {
(chatList as ArrayList<Chat>).add(chat)
}
chatAdapter = AdaptadorChat(this@MensajesActivity, (chatList as ArrayList<Chat>), ReceptorImagen!!)
RV_chats.adapter = chatAdapter
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
private fun abrirGaleria() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
galeriaARL.launch(intent)
}
private val galeriaARL = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback<ActivityResult> { resultado ->
if (resultado.resultCode == RESULT_OK) {
val data = resultado.data
imagenUri = data!!.data
val cargandoImagen = ProgressDialog(this@MensajesActivity)
cargandoImagen.setMessage("Enviando imagen...")
cargandoImagen.setCanceledOnTouchOutside(false)
cargandoImagen.show()
val carpetaImagenes =
FirebaseStorage.getInstance().reference.child("Imágenes de mensajes")
val reference = FirebaseDatabase.getInstance().reference
val idMensaje = reference.push().key
val nombreImagen = carpetaImagenes.child("$idMensaje.jpg")
val uploadTask: StorageTask<*>
uploadTask = nombreImagen.putFile(imagenUri!!)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return@Continuation nombreImagen.downloadUrl
}).addOnCompleteListener { task ->
if (task.isSuccessful) {
cargandoImagen.dismiss()
val downloadUrl = task.result
val url = downloadUrl.toString()
val infoMensajeImagen = HashMap<String, Any?>()
infoMensajeImagen["id_mensaje"] = idMensaje
infoMensajeImagen["emisor"] = firebaseUser!!.uid
infoMensajeImagen["receptor"] = uid_usuario_seleccionado
infoMensajeImagen["mensaje"] = "Imagen enviada"
infoMensajeImagen["url"] = url
infoMensajeImagen["visto"] = false
reference.child("Chats").child(idMensaje!!).setValue(infoMensajeImagen)
.addOnCompleteListener { tarea ->
if (tarea.isSuccessful) {
val listaMensajesEmisor =
FirebaseDatabase.getInstance().reference.child("ListaMensajes")
.child(firebaseUser!!.uid)
.child(uid_usuario_seleccionado)
listaMensajesEmisor.addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (!snapshot.exists()) {
listaMensajesEmisor.child("uid")
.setValue(uid_usuario_seleccionado)
}
val listaMensajesReceptor =
FirebaseDatabase.getInstance().reference.child("ListaMensajes")
.child(uid_usuario_seleccionado)
.child(firebaseUser!!.uid)
listaMensajesReceptor.child("uid")
.setValue(firebaseUser!!.uid)
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
Toast.makeText(
applicationContext,
"Imagen enviada correctamente",
Toast.LENGTH_SHORT
).show()
}
}
} else {
Toast.makeText(
applicationContext,
"Envío cancelado por el usuario",
Toast.LENGTH_SHORT
).show()
}
}
)
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Chat/MensajesActivity.kt | 483370979 |
package com.canodevs.charlapp.Perfil
import android.app.Dialog
import android.app.ProgressDialog
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import com.canodevs.charlapp.R
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
class EditarImagenPerfil : AppCompatActivity() {
private lateinit var ImagenPerfilActualizar: ImageView
private lateinit var BtnElegirImagenDe: Button
private lateinit var BtnActualizarImagen: Button
private var imageUri: Uri? = null
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var progressDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editar_imagen_perfil)
ImagenPerfilActualizar = findViewById(R.id.ImagenPerfilActualizar)
BtnElegirImagenDe = findViewById(R.id.BtnElegirImagenDe)
BtnActualizarImagen = findViewById(R.id.BtnActualizarImagen)
progressDialog = ProgressDialog(this@EditarImagenPerfil)
progressDialog.setTitle("Espere por favor")
progressDialog.setCanceledOnTouchOutside(false)
firebaseAuth = FirebaseAuth.getInstance()
BtnElegirImagenDe.setOnClickListener {
// Toast.makeText(applicationContext, "Seleccionar imagen de", Toast.LENGTH_SHORT).show()
mostrarDialog()
}
BtnActualizarImagen.setOnClickListener {
// Toast.makeText(applicationContext, "Actualizar imagen", Toast.LENGTH_SHORT).show()
validarImagen()
}
}
private fun validarImagen() {
if (imageUri == null) {
Toast.makeText(applicationContext, "Es necesario una imagen", Toast.LENGTH_SHORT).show()
} else {
subirImagen()
}
}
private fun subirImagen() {
progressDialog.setMessage("Actualizando imagen ...")
progressDialog.show()
val rutaImagen = "Perfil_usuario/" + firebaseAuth.uid
val referenceStorage = FirebaseStorage.getInstance().getReference(rutaImagen)
referenceStorage.putFile(imageUri!!).addOnSuccessListener { tarea ->
val uriTarea: Task<Uri> = tarea.storage.downloadUrl
while (!uriTarea.isSuccessful);
val urlImagen = "${uriTarea.result}"
actualizarImagenBD(urlImagen)
}.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"No se pudo subir la imagen debido a: ${e.message}",
Toast.LENGTH_SHORT
).show()
}
}
private fun actualizarImagenBD(urlImagen: String) {
progressDialog.setMessage("Actualizando imagen de perfil...")
val hashmap: HashMap<String, Any> = HashMap()
if (imageUri != null) {
hashmap["imagen"] = urlImagen
}
val reference = FirebaseDatabase.getInstance().getReference("Usuarios")
reference.child(firebaseAuth.uid!!).updateChildren(hashmap).addOnSuccessListener {
progressDialog.dismiss()
Toast.makeText(
applicationContext,
"¡Imagen actualizada correctamente!",
Toast.LENGTH_SHORT
).show()
}.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"No se pudo actualizar su imagen debido a: ${e.message}",
Toast.LENGTH_SHORT
).show()
}
}
private fun abrirGaleria() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
galeriaActivityResultLauncher.launch(intent)
}
private val galeriaActivityResultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback<ActivityResult> { resultado ->
if (resultado.resultCode == RESULT_OK) {
val data = resultado.data
imageUri = data!!.data
ImagenPerfilActualizar.setImageURI(imageUri)
} else {
Toast.makeText(applicationContext, "Cancelado por el usuario", Toast.LENGTH_SHORT)
.show()
}
}
)
private fun abrirCamara() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "Título")
values.put(MediaStore.Images.Media.DESCRIPTION, "Descripción")
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
camaraActivityResultLauncher.launch(intent)
}
private val camaraActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { resultado_camara ->
if (resultado_camara.resultCode == RESULT_OK) {
ImagenPerfilActualizar.setImageURI(imageUri)
} else {
Toast.makeText(applicationContext, "Cancelado por el usuario", Toast.LENGTH_SHORT)
.show()
}
}
private fun mostrarDialog() {
val Btn_abrir_galeria: Button
val Btn_abrir_camara: Button
val dialog = Dialog(this@EditarImagenPerfil)
dialog.setContentView(R.layout.cuadro_d_seleccionar)
Btn_abrir_galeria = dialog.findViewById(R.id.Btn_abrir_galeria)
Btn_abrir_camara = dialog.findViewById(R.id.Btn_abrir_camara)
Btn_abrir_galeria.setOnClickListener {
// Toast.makeText(applicationContext, "Abrir galería", Toast.LENGTH_SHORT).show()
abrirGaleria()
dialog.dismiss()
}
Btn_abrir_camara.setOnClickListener {
// Toast.makeText(applicationContext, "Abrir cámara", Toast.LENGTH_SHORT).show()
abrirCamara()
dialog.dismiss()
}
dialog.show()
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Perfil/EditarImagenPerfil.kt | 297688237 |
package com.canodevs.charlapp.Perfil
import android.app.Dialog
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.disklrucache.DiskLruCache.Value
import com.canodevs.charlapp.Modelo.Usuario
import com.canodevs.charlapp.R
import com.google.android.material.button.MaterialButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.hbb20.CountryCodePicker
class PerfilActivity : AppCompatActivity() {
private lateinit var P_Imagen: ImageView
private lateinit var P_n_usuario: TextView
private lateinit var P_email: TextView
private lateinit var P_proveedor : TextView
private lateinit var P_nombres: EditText
private lateinit var P_apellidos: EditText
private lateinit var P_profesion: EditText
private lateinit var P_domicilio: EditText
private lateinit var P_edad: EditText
private lateinit var P_telefono: TextView
private lateinit var Btn_guardar: Button
private lateinit var Editar_imagen: ImageView
private lateinit var Editar_Telefono : ImageView
var user: FirebaseUser? = null
var reference: DatabaseReference? = null
private var codigoTel = ""
private var numeroTel = ""
private var codigo_numero_Tel = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_perfil)
inicializarVariables()
obtenerDatos()
Btn_guardar.setOnClickListener {
actualizarInformacion()
}
Editar_imagen.setOnClickListener{
val intent = Intent(applicationContext, EditarImagenPerfil::class.java)
startActivity(intent)
}
Editar_Telefono.setOnClickListener {
establecerNumTel()
}
}
private fun establecerNumTel() {
// Declarar vistas del cuadro diálogo
val Establecer_Telefono : EditText
val SelectorCodPais : CountryCodePicker
val Btn_aceptar_Telefono : MaterialButton
val dialog = Dialog (this@PerfilActivity)
// Conexión con el diseño
dialog.setContentView(R.layout.cuadro_d_establecer_tel)
// Inicializar vistas
Establecer_Telefono = dialog.findViewById(R.id.Establecer_telefono)
SelectorCodPais = dialog.findViewById(R.id.SelectorCodigoPais)
Btn_aceptar_Telefono = dialog.findViewById(R.id.Btn_aceptar_Telefono)
// Asignar un evento a un boton
Btn_aceptar_Telefono.setOnClickListener {
codigoTel = SelectorCodPais.selectedCountryCodeWithPlus
numeroTel = Establecer_Telefono.text.toString().trim()
codigo_numero_Tel = codigoTel + numeroTel
if (numeroTel.isEmpty()) {
Toast.makeText(applicationContext, "Ingrese su número de teléfono", Toast.LENGTH_SHORT).show()
dialog.dismiss()
} else {
P_telefono.text = codigo_numero_Tel
dialog.dismiss()
}
}
dialog.show()
dialog.setCanceledOnTouchOutside(false)
}
private fun inicializarVariables() {
P_Imagen = findViewById(R.id.P_imagen)
P_n_usuario = findViewById(R.id.P_n_usuario)
P_proveedor = findViewById(R.id.P_proveedor)
P_email = findViewById(R.id.P_email)
P_nombres = findViewById(R.id.P_nombres)
P_apellidos = findViewById(R.id.P_apellidos)
P_profesion = findViewById(R.id.P_profesion)
P_domicilio = findViewById(R.id.P_domicilio)
P_edad = findViewById(R.id.P_edad)
P_telefono = findViewById(R.id.P_telefono)
Btn_guardar = findViewById(R.id.Btn_Guardar)
Editar_imagen = findViewById(R.id.Editar_imagen)
Editar_Telefono = findViewById(R.id.Editar_Telefono)
user = FirebaseAuth.getInstance().currentUser
reference = FirebaseDatabase.getInstance().reference.child("Usuarios").child(user!!.uid)
}
private fun obtenerDatos() {
reference!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
// Obtenemos los datos de Firebase
val usuario: Usuario? = snapshot.getValue(Usuario::class.java)
val str_n_usuario = usuario!!.getN_Usuario()
val str_email = usuario.getEmail()
val str_proveedor = usuario.getProveedor()
val str_nombres = usuario.getNombres()
val str_apellidos = usuario.getApellidos()
val str_profesion = usuario.getProfesion()
val str_domicilio = usuario.getDomicilio()
val str_edad = usuario.getEdad()
val str_telefono = usuario.getTelefono()
// Seteamos la info en las vistas XML
P_n_usuario.text = str_n_usuario
P_email.text = str_email
P_proveedor.text = str_proveedor
P_nombres.setText(str_nombres)
P_apellidos.setText(str_apellidos)
P_profesion.setText(str_profesion)
P_domicilio.setText(str_domicilio)
P_edad.setText(str_edad)
P_telefono.setText(str_telefono)
Glide.with(applicationContext).load(usuario.getImagen())
.placeholder(R.drawable.ic_item_usuario).into(P_Imagen)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
private fun actualizarInformacion() {
val str_nombres = P_nombres.text.toString()
val str_apellidos = P_apellidos.text.toString()
val str_profesion = P_profesion.text.toString()
val str_domicilio = P_domicilio.text.toString()
val str_edad = P_edad.text.toString()
val str_telefono = P_telefono.text.toString()
val hashmap = HashMap<String, Any>()
hashmap["nombres"] = str_nombres
hashmap["apellidos"] = str_apellidos
hashmap["profesion"] = str_profesion
hashmap["domicilio"] = str_domicilio
hashmap["edad"] = str_edad
hashmap["telefono"] = str_telefono
reference!!.updateChildren(hashmap).addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
applicationContext,
"Datos de usuario actualizados",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
applicationContext,
"No se actualizaron los datos de usuario",
Toast.LENGTH_SHORT
).show()
}
}.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"Ha ocurrido un error ${e.message}",
Toast.LENGTH_SHORT
).show()
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Perfil/PerfilActivity.kt | 3978638840 |
package com.canodevs.charlapp.Fragmentos
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.canodevs.charlapp.Adaptador.AdapadorUsuario
import com.canodevs.charlapp.Modelo.Usuario
import com.canodevs.charlapp.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.getValue
class FragmentoUsuarios : Fragment() {
private var usuarioAdaptador: AdapadorUsuario? = null
private var usuarioLista: List<Usuario>? = null
private var rvUsuarios: RecyclerView? = null
private lateinit var Et_buscar_usuario: EditText
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View = inflater.inflate(R.layout.fragment_fragmento_usuarios, container, false)
rvUsuarios = view.findViewById(R.id.RV_usuarios)
rvUsuarios!!.setHasFixedSize(true)
rvUsuarios!!.layoutManager = LinearLayoutManager(context)
Et_buscar_usuario = view.findViewById(R.id.Et_buscar_usuario)
usuarioLista = ArrayList()
ObtenerUsuariosBD()
Et_buscar_usuario.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(
b_usuario: CharSequence?,
start: Int,
before: Int,
count: Int
) {
BuscarUsuario(b_usuario.toString().lowercase())
}
override fun afterTextChanged(s: Editable?) {
}
})
return view
}
private fun ObtenerUsuariosBD() {
val firebaseUser = FirebaseAuth.getInstance().currentUser!!.uid
val reference =
FirebaseDatabase.getInstance().reference.child("Usuarios").orderByChild("n_usuario")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(usuarioLista as ArrayList<Usuario>).clear()
if (Et_buscar_usuario.text.toString().isEmpty()) {
for (sh in snapshot.children) {
val usuario: Usuario? = sh.getValue(Usuario::class.java)
if (!(usuario!!.getUid()).equals(firebaseUser)) {
(usuarioLista as ArrayList<Usuario>).add(usuario)
}
}
usuarioAdaptador = AdapadorUsuario(context!!, usuarioLista!!)
rvUsuarios!!.adapter = usuarioAdaptador
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
private fun BuscarUsuario(buscarUsuario: String) {
val firebaseUser = FirebaseAuth.getInstance().currentUser!!.uid
val consulta =
FirebaseDatabase.getInstance().reference.child("Usuarios").orderByChild("buscar")
.startAt(buscarUsuario).endAt(buscarUsuario + "\uf8ff")
consulta.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(usuarioLista as ArrayList<Usuario>).clear()
for (sh in snapshot.children) {
val usuario: Usuario? = sh.getValue(Usuario::class.java)
if (!(usuario!!.getUid()).equals(firebaseUser)) {
(usuarioLista as ArrayList<Usuario>).add(usuario)
}
}
usuarioAdaptador = AdapadorUsuario(context!!, usuarioLista!!)
rvUsuarios!!.adapter = usuarioAdaptador
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Fragmentos/FragmentoUsuarios.kt | 1554882336 |
package com.canodevs.charlapp.Fragmentos
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.canodevs.charlapp.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FragmentoChats.newInstance] factory method to
* create an instance of this fragment.
*/
class FragmentoChats : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragmento_chats, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentoChats.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FragmentoChats().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Fragmentos/FragmentoChats.kt | 1763731871 |
package com.canodevs.charlapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class RegistroActivity : AppCompatActivity() {
// Instanciamos los botones donde ingresamos los datos
private lateinit var R_Et_nombre_usuario: EditText
private lateinit var R_Et_email: EditText
private lateinit var R_Et_password: EditText
private lateinit var R_Et_r_password: EditText
private lateinit var Btn_registrar: Button
// Instanciamos la autenticación con Firebase
private lateinit var auth: FirebaseAuth
private lateinit var reference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registro)
//supportActionBar!!.title = "Registro"
inicializarVariables()
Btn_registrar.setOnClickListener() {
validarDatos()
}
}
private fun inicializarVariables() {
R_Et_nombre_usuario = findViewById(R.id.R_Et_nombre_usuario)
R_Et_email = findViewById(R.id.R_Et_email)
R_Et_password = findViewById(R.id.R_Et_password)
R_Et_r_password = findViewById(R.id.R_Et_r_password)
Btn_registrar = findViewById(R.id.Btn_registrar)
// Creamos la instancia de Firebase Authentication
auth = FirebaseAuth.getInstance()
}
private fun validarDatos() {
val nombreUsuario: String = R_Et_nombre_usuario.text.toString()
val email: String = R_Et_email.text.toString()
val password: String = R_Et_password.text.toString()
val r_password: String = R_Et_r_password.text.toString()
if (nombreUsuario.isEmpty()) {
Toast.makeText(applicationContext, "Escriba su nombre de usuario", Toast.LENGTH_SHORT)
.show()
} else if (email.isEmpty()) {
Toast.makeText(applicationContext, "Escriba su correo electrónico", Toast.LENGTH_SHORT)
.show()
} else if (password.isEmpty()) {
Toast.makeText(applicationContext, "Escriba su contraseña", Toast.LENGTH_SHORT).show()
} else if (r_password.isEmpty()) {
Toast.makeText(
applicationContext,
"Por favor, repita su contraseña",
Toast.LENGTH_SHORT
).show()
} else if (!password.equals(r_password)) {
Toast.makeText(
applicationContext,
"Las contraseñas deben coincidir",
Toast.LENGTH_SHORT
).show()
} else {
registrarUsuario(email, password)
}
}
private fun registrarUsuario(email: String, password: String) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
var uid: String = ""
uid = auth.currentUser!!.uid
reference =
FirebaseDatabase.getInstance().reference.child("Usuarios").child(uid)
val hashMap = HashMap<String, Any>()
val h_nombre_usuario: String = R_Et_nombre_usuario.text.toString()
val h_email: String = R_Et_email.text.toString()
hashMap["uid"] = uid
hashMap["n_usuario"] = h_nombre_usuario
hashMap["email"] = h_email
hashMap["imagen"] = ""
hashMap["buscar"] = h_nombre_usuario.lowercase()
/*Nuevos datos de usuario*/
hashMap["nombres"] = ""
hashMap["apellidos"] = ""
hashMap["edad"] = ""
hashMap["profesion"] = ""
hashMap["domicilio"] = ""
hashMap["telefono"] = ""
hashMap["estado"] = "offline"
hashMap["proveedor"] = "Email"
reference.updateChildren(hashMap).addOnCompleteListener { task2 ->
if (task2.isSuccessful) {
val intent = Intent(this@RegistroActivity, MainActivity::class.java)
Toast.makeText(
applicationContext,
"¡Registrado correctamente!",
Toast.LENGTH_SHORT
).show()
startActivity(intent)
}
}.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"${e.message}",
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(
applicationContext,
"Ha ocurrido un error",
Toast.LENGTH_SHORT
).show()
}
}
.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"${e.message}",
Toast.LENGTH_SHORT
).show()
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/RegistroActivity.kt | 3731964948 |
package com.canodevs.charlapp.Modelo
class Chat {
private var id_mensaje: String = ""
private var emisor: String = ""
private var receptor: String = ""
private var mensaje: String = ""
private var url: String = ""
private var visto = false
constructor()
constructor(
id_mensaje: String,
emisor: String,
receptor: String,
mensaje: String,
url: String,
visto: Boolean
) {
this.id_mensaje = id_mensaje
this.emisor = emisor
this.receptor = receptor
this.mensaje = mensaje
this.url = url
this.visto = visto
}
//getters y setters
fun getId_Mensaje(): String? {
return id_mensaje
}
fun setId_Mensaje(id_mensaje: String?) {
this.id_mensaje = id_mensaje!!
}
fun getEmisor(): String? {
return emisor
}
fun setEmisor(emisor: String?) {
this.emisor = emisor!!
}
fun getReceptor(): String? {
return receptor
}
fun setReceptor(receptor: String?) {
this.receptor = receptor!!
}
fun getMensaje(): String? {
return mensaje
}
fun setMensaje(mensaje: String?) {
this.mensaje = mensaje!!
}
fun getUrl(): String? {
return url
}
fun setUrl(url: String?) {
this.url = url!!
}
fun isVisto(): Boolean {
return visto
}
fun setIsVisto(visto: Boolean?) {
this.visto = visto!!
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Modelo/Chat.kt | 4008503911 |
package com.canodevs.charlapp.Modelo
class Usuario {
private var uid : String = ""
private var n_usuario : String = ""
private var email : String = ""
private var proveedor : String = ""
private var telefono : String = ""
private var imagen : String = ""
private var buscar : String = ""
private var nombres : String = ""
private var apellidos : String = ""
private var edad : String = ""
private var profesion : String = ""
private var domicilio : String = ""
constructor()
constructor(
uid: String,
n_usuario: String,
email: String,
proveedor: String,
telefono: String,
imagen: String,
buscar: String,
nombres: String,
apellidos: String,
edad: String,
profesion: String,
domicilio: String
) {
this.uid = uid
this.n_usuario = n_usuario
this.email = email
this.proveedor = proveedor
this.telefono = telefono
this.imagen = imagen
this.buscar = buscar
this.nombres = nombres
this.apellidos = apellidos
this.edad = edad
this.profesion = profesion
this.domicilio = domicilio
}
//getters y setters
fun getUid() : String?{
return uid
}
fun setUid(uid : String){
this.uid = uid
}
fun getN_Usuario() : String?{
return n_usuario
}
fun setN_Usuario(n_usuario : String){
this.n_usuario = n_usuario
}
fun getEmail() : String?{
return email
}
fun setEmail(email : String){
this.email = email
}
fun getProveedor () : String {
return proveedor
}
fun getTelefono() : String?{
return telefono
}
fun setProveedor (proveedor : String) {
this.proveedor = proveedor
}
fun setTelefono(telefono : String){
this.telefono = telefono
}
fun getImagen() : String?{
return imagen
}
fun setImagen(imagen : String){
this.imagen = imagen
}
fun getBuscar() : String?{
return buscar
}
fun setBuscar(buscar : String){
this.buscar = buscar
}
fun getNombres() : String?{
return nombres
}
fun setNombres(nombres : String){
this.nombres = nombres
}
fun getApellidos() : String?{
return apellidos
}
fun setApellidos(apellidos : String){
this.apellidos = apellidos
}
fun getEdad() : String?{
return edad
}
fun setEdad(edad : String){
this.edad = edad
}
fun getProfesion() : String?{
return profesion
}
fun setProfesion(profesion : String){
this.profesion = profesion
}
fun getDomicilio() : String?{
return domicilio
}
fun setDomicilio(domicilio : String){
this.domicilio = domicilio
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Modelo/Usuario.kt | 3715867751 |
package com.canodevs.charlapp.Adaptador
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.canodevs.charlapp.Chat.MensajesActivity
import com.canodevs.charlapp.Modelo.Usuario
import com.canodevs.charlapp.R
class AdapadorUsuario (context: Context, listaUsuarios: List<Usuario>) : RecyclerView.Adapter<AdapadorUsuario.ViewHolder?>() {
private val context: Context
private val listaUsuarios : List<Usuario>
init {
this.context = context
this.listaUsuarios = listaUsuarios
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
var nombre_usuario: TextView
var email_usuario: TextView
var imagen_usuario: ImageView
init {
nombre_usuario = itemView.findViewById(R.id.Item_nombre_usuario)
email_usuario = itemView.findViewById(R.id.Item_email_usuario)
imagen_usuario = itemView.findViewById(R.id.Item_imagen)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(context).inflate(R.layout.item_usuario, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return listaUsuarios.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val usuario : Usuario = listaUsuarios[position]
holder.nombre_usuario.text = usuario.getN_Usuario()
holder.email_usuario.text = usuario.getEmail()
Glide.with(context).load(usuario.getImagen()).placeholder(R.drawable.ic_item_usuario).into(holder.imagen_usuario)
holder.itemView.setOnClickListener {
val intent = Intent(context, MensajesActivity::class.java)
// Enviamos el uid del usuario seleccionado
intent.putExtra("uid_usuario", usuario.getUid())
Toast.makeText(context, "Usuario seleccionado: " + usuario.getN_Usuario(), Toast.LENGTH_SHORT).show()
context.startActivity(intent)
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Adaptador/AdapadorUsuario.kt | 3493657762 |
package com.canodevs.charlapp.Adaptador
import android.content.Context
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.bumptech.glide.Glide
import com.canodevs.charlapp.Modelo.Chat
import com.canodevs.charlapp.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
class AdaptadorChat(contexto: Context, chatLista: List<Chat>, imagenUrl: String) :
RecyclerView.Adapter<AdaptadorChat.ViewHolder?>() {
private val contexto: Context
private val chatLista: List<Chat>
private val imagenUrl: String
val firebaseUser: FirebaseUser = FirebaseAuth.getInstance().currentUser!!
init {
this.contexto = contexto
this.chatLista = chatLista
this.imagenUrl = imagenUrl
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// Vistas de item mensaje izquierdo
var imagen_perfil_mensaje: ImageView? = null
var TXT_ver_mensaje: TextView? = null
var imagen_enviada_izquierdo: ImageView? = null
var TXT_mensaje_visto: TextView? = null
// Vistas de item mensaje derecho
var imagen_enviada_derecha: ImageView? = null
init {
imagen_perfil_mensaje = itemView.findViewById(R.id.imagen_perfil_mensaje)
TXT_ver_mensaje = itemView.findViewById(R.id.TXT_ver_mensaje)
imagen_enviada_izquierdo = itemView.findViewById(R.id.imagen_enviada_izquierdo)
TXT_mensaje_visto = itemView.findViewById(R.id.TXT_mensaje_visto)
imagen_enviada_derecha = itemView.findViewById(R.id.imagen_enviada_derecha)
}
}
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
return if (position == 1) {
val view: View = LayoutInflater.from(contexto)
.inflate(com.canodevs.charlapp.R.layout.item_mensaje_derecho, parent, false)
ViewHolder(view)
} else {
val view: View = LayoutInflater.from(contexto)
.inflate(com.canodevs.charlapp.R.layout.item_mensaje_izquierdo, parent, false)
ViewHolder(view)
}
}
override fun getItemCount(): Int {
return chatLista.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val chat: Chat = chatLista[position]
Glide.with(contexto).load(imagenUrl).placeholder(R.drawable.ic_imagen_chat)
.into(holder.imagen_perfil_mensaje!!)
// Si el mensaje contiene imagen
if (chat.getMensaje().equals("Imagen enviada") && !chat.getUrl().equals("")) {
// Condición para el usuario que envía imagen como mensaje
if (chat.getEmisor().equals(firebaseUser!!.uid)) {
holder.TXT_ver_mensaje!!.visibility = View.GONE
holder.imagen_enviada_derecha!!.visibility = View.VISIBLE
Glide.with(contexto).load(chat.getUrl()).placeholder(R.drawable.ic_imagen_enviada).into(holder.imagen_enviada_derecha!!)
}
// Condición para el usuario que nos envía una imagen como mensaje
else if (!chat.getEmisor().equals(firebaseUser!!.uid)) {
holder.TXT_ver_mensaje!!.visibility = View.GONE
holder.imagen_enviada_izquierdo!!.visibility = View.VISIBLE
Glide.with(contexto).load(chat.getUrl()).placeholder(R.drawable.ic_imagen_enviada).into(holder.imagen_enviada_izquierdo!!)
}
}
// Si el mensaje contiene sólo texto
else {
holder.TXT_ver_mensaje!!.text = chat.getMensaje()
}
}
override fun getItemViewType(position: Int): Int {
return if (chatLista[position].getEmisor().equals(firebaseUser!!.uid)) {
1
} else {
0
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/Adaptador/AdaptadorChat.kt | 3820330615 |
package com.canodevs.charlapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
class SplashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
mostrarBienvenida()
}
fun mostrarBienvenida() {
object : CountDownTimer(4000, 1000) {
override fun onTick(millisUntilFinished: Long) {
//TODO("Not yet implemented")
}
override fun onFinish() {
val intent = Intent(applicationContext, Inicio::class.java)
startActivity(intent)
finish()
}
}.start()
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/SplashScreen.kt | 1561991669 |
package com.canodevs.charlapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.button.MaterialButton
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : AppCompatActivity() {
private lateinit var L_Et_email: EditText
private lateinit var L_Et_password: EditText
private lateinit var Btn_login: Button
private lateinit var auth: FirebaseAuth
private lateinit var TXT_ir_registro : MaterialButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//supportActionBar!!.title = "Login"
inicializarVariables()
Btn_login.setOnClickListener {
ValidarDatos()
}
TXT_ir_registro.setOnClickListener {
val intent = Intent(this@LoginActivity, RegistroActivity::class.java)
startActivity(intent)
}
}
private fun inicializarVariables() {
L_Et_email = findViewById(R.id.L_Et_email)
L_Et_password = findViewById(R.id.L_Et_password)
Btn_login = findViewById(R.id.Btn_Login)
auth = FirebaseAuth.getInstance()
TXT_ir_registro = findViewById(R.id.TXT_ir_registro)
}
private fun ValidarDatos() {
val email: String = L_Et_email.text.toString()
val password: String = L_Et_password.text.toString()
if (email.isEmpty()) {
Toast.makeText(applicationContext, "Escribe tu correo electrónico", Toast.LENGTH_SHORT)
.show()
}
if (password.isEmpty()) {
Toast.makeText(applicationContext, "Escribe tu contraseña", Toast.LENGTH_SHORT).show()
} else {
LoginUsuario(email, password)
}
}
private fun LoginUsuario(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
Toast.makeText(
applicationContext,
"Inicio de sesión exitoso",
Toast.LENGTH_SHORT
).show()
startActivity(intent)
finish()
} else {
Toast.makeText(
applicationContext,
"Ha ocurrido un error",
Toast.LENGTH_SHORT
).show()
}
}.addOnFailureListener { e ->
Toast.makeText(
applicationContext,
"{${e.message}}",
Toast.LENGTH_SHORT
).show()
}
}
} | CharlApp/app/src/main/java/com/canodevs/charlapp/LoginActivity.kt | 3237882413 |
package com.example.my1stapi
data class Product(
val brand: String,
val category: String,
val description: String,
val discountPercentage: Double,
val id: Int,
val images: List<String>,
val price: Int,
val rating: Double,
val stock: Int,
val thumbnail: String,
val title: String
) | My1stAPI/app/src/androidTest/java/com/example/my1stapi/Product.kt | 3612026303 |
package com.example.my1stapi
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.my1stapi", appContext.packageName)
}
} | My1stAPI/app/src/androidTest/java/com/example/my1stapi/ExampleInstrumentedTest.kt | 3694109186 |
package com.example.my1stapi
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)
}
} | My1stAPI/app/src/test/java/com/example/my1stapi/ExampleUnitTest.kt | 2625065417 |
package com.example.my1stapi.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) | My1stAPI/app/src/main/java/com/example/my1stapi/ui/theme/Color.kt | 3342175409 |
package com.example.my1stapi.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 My1stAPITheme(
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
)
} | My1stAPI/app/src/main/java/com/example/my1stapi/ui/theme/Theme.kt | 424846830 |
package com.example.my1stapi.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
)
*/
) | My1stAPI/app/src/main/java/com/example/my1stapi/ui/theme/Type.kt | 2180457344 |
package com.example.my1stapi.apis
import com.example.my1stapi.models.MyCart
import retrofit2.Call
import retrofit2.http.GET
interface CartInterface {
@GET("carts")
fun getProductData(): Call<MyCart>
} | My1stAPI/app/src/main/java/com/example/my1stapi/apis/CartInterface.kt | 3973150521 |
package com.example.my1stapi.apis
import com.example.my1stapi.models.MyCart
import com.example.my1stapi.models.ProductModel
import retrofit2.Call
import retrofit2.http.GET
interface Api {
@GET("products")
fun getProductData() : Call<ProductModel>
}
| My1stAPI/app/src/main/java/com/example/my1stapi/apis/Api.kt | 846304529 |
package com.example.my1stapi
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.my1stapi.adapter.ProductAdapter
import com.example.my1stapi.apis.Api
import com.example.my1stapi.models.ProductModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : ComponentActivity() {
lateinit var recyclerView: RecyclerView
lateinit var productAdapter: ProductAdapter
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
val retrofitBuilder = Retrofit.Builder()
.baseUrl("https://dummyjson.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(Api::class.java)
val retrofitData = retrofitBuilder.getProductData()
retrofitData.enqueue(object :Callback<ProductModel?>{
override fun onResponse(call: Call<ProductModel?>, response: Response<ProductModel?>) {
var responseBody = response.body()
val productList = responseBody?.products!!
productAdapter = ProductAdapter(this@MainActivity,productList)
recyclerView.adapter = productAdapter
recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
}
override fun onFailure(call: Call<ProductModel?>, t: Throwable) {
Log.d("Main Activity ", "onFailure: " + t.message)
}
})
}
}
| My1stAPI/app/src/main/java/com/example/my1stapi/MainActivity.kt | 2700883520 |
package com.example.my1stapi
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.my1stapi.adapter.CartAdapter
import com.example.my1stapi.apis.CartInterface
import com.example.my1stapi.models.MyCart
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
class CartActivity : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
lateinit var cartAdapter: CartAdapter
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cart)
recyclerView = findViewById(R.id.recyclerView1)
val retrofitBuilder = Retrofit.Builder()
.baseUrl("https://dummyjson.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(CartInterface::class.java)
val retrofitData = retrofitBuilder.getProductData()
retrofitData.enqueue(object : Callback<MyCart?> {
override fun onResponse(call: Call<MyCart?>, response: Response<MyCart?>) {
var responseBody = response.body()
val productList = responseBody?.carts!!
cartAdapter = CartAdapter(this@CartActivity, productList)
recyclerView.adapter = cartAdapter
recyclerView.layoutManager = LinearLayoutManager(this@CartActivity)
}
override fun onFailure(call: Call<MyCart?>, t: Throwable) {
Log.d("Cart Activity ", "onFailure: " + t.message)
}
})
}
} | My1stAPI/app/src/main/java/com/example/my1stapi/CartActivity.kt | 3341726616 |
package com.example.my1stapi.models
data class Product(
val discountPercentage: Double,
val discountedPrice: Int,
val id: Int,
val price: Int,
val quantity: Int,
val thumbnail: String,
val title: String,
val total: Int
) | My1stAPI/app/src/main/java/com/example/my1stapi/models/Product.kt | 3595167828 |
package com.example.my1stapi.models
import com.example.my1stapi.Product
class ProductModel(
val limit: Int,
val products: List<com.example.my1stapi.Product>,
val skip: Int,
val total: Int,
) | My1stAPI/app/src/main/java/com/example/my1stapi/models/ProductModel.kt | 3577671790 |
package com.example.my1stapi.models
data class MyCart(
val carts: List<Cart>,
val limit: Int,
val skip: Int,
val total: Int
) | My1stAPI/app/src/main/java/com/example/my1stapi/models/MyCart.kt | 815705210 |
package com.example.my1stapi.models
import com.example.my1stapi.models.Product
data class Cart(
val discountedTotal: Int,
val id: Int,
val products: List<Product>,
val total: Int,
val totalProducts: Int,
val totalQuantity: Int,
val userId: Int
) | My1stAPI/app/src/main/java/com/example/my1stapi/models/Cart.kt | 1467039920 |
package com.example.my1stapi.adapter
import android.annotation.SuppressLint
import android.app.Activity
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.example.my1stapi.R
import com.example.my1stapi.models.Cart
import com.example.my1stapi.models.MyCart
import com.squareup.picasso.Picasso
class CartAdapter (val context: Activity, val cartArrayList: List<Cart>) :
RecyclerView.Adapter<CartAdapter.MyViewHolder>(){
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var image: ImageView
var title: TextView
var price: TextView
var quantity: TextView
var total: TextView
var discountPercentage: TextView
var discountPrice: TextView
init {
image= itemView.findViewById(R.id.cartImage)
title = itemView.findViewById(R.id.cartTitle)
price = itemView.findViewById(R.id.cartPrice)
quantity = itemView.findViewById(R.id.CartQuantity)
total = itemView.findViewById(R.id.cartTotal)
discountPercentage = itemView.findViewById(R.id.cartDiscountPercentage)
discountPrice = itemView.findViewById(R.id.cartDiscountPrice)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(context).inflate(R.layout.cartitem,parent,false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return cartArrayList.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = cartArrayList[position]
holder.title.text = "title: "+ currentItem.discountedTotal.toString()
holder.price.text = "price: "+ currentItem.id.toString()
holder.quantity.text ="quantity: "+ currentItem.products.toString()
holder.quantity.text ="quantity: "+ currentItem.total.toString()
holder.total.text ="total: "+ currentItem.totalProducts.toString()
holder.discountPercentage.text ="discountPercentage: "+ currentItem.totalQuantity.toString()
holder.discountPrice.text ="discountPrice: "+ currentItem.userId.toString()
Picasso.get().load(currentItem.products.get(0).thumbnail).into(holder.image)
}
}
| My1stAPI/app/src/main/java/com/example/my1stapi/adapter/CartAdapter.kt | 2337234894 |
package com.example.my1stapi.adapter
import com.example.my1stapi.Product
import android.annotation.SuppressLint
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.my1stapi.R
import com.squareup.picasso.Picasso
class ProductAdapter(val context: Activity, val productArrayList: List<com.example.my1stapi.Product>) :
RecyclerView.Adapter<ProductAdapter.MyViewHolder>() {
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title: TextView
var rating: RatingBar
var image: ImageView
var stock: TextView
var discountPercentage: TextView
var price: TextView
var brand: TextView
init {
title = itemView.findViewById(R.id.productTitle)
image = itemView.findViewById(R.id.ProductImage)
rating = itemView.findViewById(R.id.rating)
stock = itemView.findViewById(R.id.productStock)
discountPercentage = itemView.findViewById(R.id.DiscountPercentage)
price = itemView.findViewById(R.id.ProductPrice)
brand= itemView.findViewById(R.id.productBrand)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(context).inflate(R.layout.eachitem, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return productArrayList.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = productArrayList[position]
holder.title.text = "title: "+ currentItem.title
holder.rating.rating= currentItem.rating.toFloat()
holder.stock.text= "stock: "+ currentItem.stock.toString()
holder.brand.text= "brand: "+ currentItem.brand
holder.discountPercentage.text = "discountPercentage: "+ currentItem.discountPercentage.toString()
holder.price.text ="Price: "+ currentItem.price.toString()
//image view, hoe to show image in imageview if the image is in the form of url,
// 3rd party library
//picasso
Picasso.get().load(currentItem.thumbnail).into(holder.image);
}
} | My1stAPI/app/src/main/java/com/example/my1stapi/adapter/ProductAdapter.kt | 259390103 |
package com.example.customwidget
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| customWidget/android/app/src/main/kotlin/com/example/customwidget/MainActivity.kt | 2892269311 |
package com.example.kotlin_superheros
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.kotlin_superheros", appContext.packageName)
}
} | Kotlin-Superheroes-LazyColumn/app/src/androidTest/java/com/example/kotlin_superheros/ExampleInstrumentedTest.kt | 707237316 |
package com.example.kotlin_superheros
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)
}
} | Kotlin-Superheroes-LazyColumn/app/src/test/java/com/example/kotlin_superheros/ExampleUnitTest.kt | 991268041 |
package com.example.kotlin_superheros.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(8.dp),
medium = RoundedCornerShape(16.dp),
large = RoundedCornerShape(16.dp)
) | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/ui/theme/Shape.kt | 1458719133 |
package com.example.kotlin_superheros.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 md_theme_light_primary = Color(0xFF466800)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFC6F181)
val md_theme_light_onPrimaryContainer = Color(0xFF121F00)
val md_theme_light_secondary = Color(0xFF596248)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFDDE6C6)
val md_theme_light_onSecondaryContainer = Color(0xFF161E0A)
val md_theme_light_tertiary = Color(0xFF396661)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFBCECE6)
val md_theme_light_onTertiaryContainer = Color(0xFF00201D)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFEFCF5)
val md_theme_light_onBackground = Color(0xFF1B1C18)
val md_theme_light_surface = Color(0xFFFEFCF5)
val md_theme_light_onSurface = Color(0xFF1B1C18)
val md_theme_light_surfaceVariant = Color(0xFFE1E4D4)
val md_theme_light_onSurfaceVariant = Color(0xFF45483D)
val md_theme_light_outline = Color(0xFF75786C)
val md_theme_light_inverseOnSurface = Color(0xFFF2F1E9)
val md_theme_light_inverseSurface = Color(0xFF30312C)
val md_theme_light_inversePrimary = Color(0xFFABD468)
val md_theme_light_surfaceTint = Color(0xFF466800)
val md_theme_light_outlineVariant = Color(0xFFC5C8B9)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFABD468)
val md_theme_dark_onPrimary = Color(0xFF223600)
val md_theme_dark_primaryContainer = Color(0xFF344E00)
val md_theme_dark_onPrimaryContainer = Color(0xFFC6F181)
val md_theme_dark_secondary = Color(0xFFC1CAAB)
val md_theme_dark_onSecondary = Color(0xFF2B331D)
val md_theme_dark_secondaryContainer = Color(0xFF414A32)
val md_theme_dark_onSecondaryContainer = Color(0xFFDDE6C6)
val md_theme_dark_tertiary = Color(0xFFA0D0CA)
val md_theme_dark_onTertiary = Color(0xFF013733)
val md_theme_dark_tertiaryContainer = Color(0xFF1F4E4A)
val md_theme_dark_onTertiaryContainer = Color(0xFFBCECE6)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1B1C18)
val md_theme_dark_onBackground = Color(0xFFE4E3DB)
val md_theme_dark_surface = Color(0xFF1B1C18)
val md_theme_dark_onSurface = Color(0xFFE4E3DB)
val md_theme_dark_surfaceVariant = Color(0xFF45483D)
val md_theme_dark_onSurfaceVariant = Color(0xFFC5C8B9)
val md_theme_dark_outline = Color(0xFF8F9285)
val md_theme_dark_inverseOnSurface = Color(0xFF1B1C18)
val md_theme_dark_inverseSurface = Color(0xFFE4E3DB)
val md_theme_dark_inversePrimary = Color(0xFF466800)
val md_theme_dark_surfaceTint = Color(0xFFABD468)
val md_theme_dark_outlineVariant = Color(0xFF45483D)
val md_theme_dark_scrim = Color(0xFF000000) | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/ui/theme/Color.kt | 3551619854 |
package com.example.kotlin_superheros.ui.theme
import android.app.Activity
import android.os.Build
import android.view.View
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.BlendMode.Companion.Color
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColors = darkColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val LightColors = lightColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun Kotlin_SuperherosTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
// Dynamic color in this app is turned off for learning purposes
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 -> DarkColors
else -> LightColors
}
val view = LocalView.current
if (!view.isInEditMode) {
if (!view.isInEditMode) {
SideEffect {
setUpEdgeToEdge(view, darkTheme)
}
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
shapes = Shapes,
content = content
)
}
/**
* Sets up edge-to-edge for the window of this [view]. The system icon colors are set to either
* light or dark depending on whether the [darkTheme] is enabled or not.
*/
private fun setUpEdgeToEdge(view: View, darkTheme: Boolean) {
val window = (view.context as Activity).window
WindowCompat.setDecorFitsSystemWindows(window, false)
window.statusBarColor = androidx.compose.ui.graphics.Color.Transparent.toArgb()
val navigationBarColor = when {
Build.VERSION.SDK_INT >= 29 -> androidx.compose.ui.graphics.Color.Transparent.toArgb()
Build.VERSION.SDK_INT >= 26 -> Color(0xFF, 0xFF, 0xFF, 0x63).toArgb()
// Min sdk version for this app is 24, this block is for SDK versions 24 and 25
else -> Color(0x00, 0x00, 0x00, 0x50).toArgb()
}
window.navigationBarColor = navigationBarColor
val controller = WindowCompat.getInsetsController(window, view)
controller.isAppearanceLightStatusBars = !darkTheme
controller.isAppearanceLightNavigationBars = !darkTheme
} | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/ui/theme/Theme.kt | 1825026633 |
package com.example.kotlin_superheros.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.kotlin_superheros.R
// 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
// )
//)
val Cabin = FontFamily(
Font(R.font.cabin_regular , FontWeight.Normal),
Font(R.font.cabin_bold, FontWeight.Bold )
)
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = Cabin,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
displayLarge = TextStyle(
fontFamily = Cabin,
fontWeight = FontWeight.Normal,
fontSize = 30.sp
),
displayMedium = TextStyle(
fontFamily = Cabin,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
),
displaySmall = TextStyle(
fontFamily = Cabin,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
) | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/ui/theme/Type.kt | 3507855708 |
package com.example.kotlin_superheros
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.width
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.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
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.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.kotlin_superheros.data.Hero
import com.example.kotlin_superheros.data.HeroesRepository.heroes
import com.example.kotlin_superheros.ui.theme.Kotlin_SuperherosTheme
//Name: Sutham Hengsuwan
//ID : 445868
//SODV 3203
//24JANMNTR2
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Kotlin_SuperherosTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
HeroApp()
}
}
}
}
}
@Composable
fun HeroApp() {
Scaffold(
topBar = {
Text(
text = "Superheroes",
style = MaterialTheme.typography.displayLarge,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding( 16.dp)
)
}
) { it ->
LazyColumn(contentPadding = it) {
items(heroes) {
HeroCard(
hero = it,
)
}
}
}
}
@Composable
fun HeroCard(
hero: Hero,
modifier: Modifier = Modifier
) {
Card (
modifier = Modifier
.padding( start = 16.dp , end = 16.dp , bottom = 8.dp)
){
Row(
modifier = modifier
.fillMaxWidth()
.height(104.dp)
) {
Column (
modifier = Modifier
.weight(2f)
.padding( start= 16.dp , top = 16.dp )
){
Text(
text = stringResource(id = hero.nameRes),
style = MaterialTheme.typography.displaySmall,
modifier = Modifier
)
Text(
text = stringResource(id = hero.descriptionRes),
style = MaterialTheme.typography.bodyLarge
)
}
Image(
painter = painterResource(id = hero.imageRes),
contentDescription = null,
modifier = Modifier
.padding( end = 8.dp , top = 16.dp , bottom = 16.dp )
.height(72.dp)
.width(72.dp)
.clip( RoundedCornerShape( 8.dp))
)
}
}
} | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/MainActivity.kt | 1977115199 |
package com.example.kotlin_superheros.data
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.example.kotlin_superheros.R
data class Hero(
@StringRes val nameRes: Int,
@StringRes val descriptionRes: Int,
@DrawableRes val imageRes: Int
)
object HeroesRepository {
val heroes = listOf(
Hero(
nameRes = R.string.hero1,
descriptionRes = R.string.description1,
imageRes = R.drawable.android_superhero1
),
Hero(
nameRes = R.string.hero2,
descriptionRes = R.string.description2,
imageRes = R.drawable.android_superhero2
),
Hero(
nameRes = R.string.hero3,
descriptionRes = R.string.description3,
imageRes = R.drawable.android_superhero3
),
Hero(
nameRes = R.string.hero4,
descriptionRes = R.string.description4,
imageRes = R.drawable.android_superhero4
),
Hero(
nameRes = R.string.hero5,
descriptionRes = R.string.description5,
imageRes = R.drawable.android_superhero5
),
Hero(
nameRes = R.string.hero6,
descriptionRes = R.string.description6,
imageRes = R.drawable.android_superhero6
)
)
} | Kotlin-Superheroes-LazyColumn/app/src/main/java/com/example/kotlin_superheros/data/HeroesRepository.kt | 733967321 |
package com.shubhamtripz.mvvmpractice
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.shubhamtripz.mvvmpractice", appContext.packageName)
}
} | MVVM-Practice/app/src/androidTest/java/com/shubhamtripz/mvvmpractice/ExampleInstrumentedTest.kt | 1423692580 |
package com.shubhamtripz.mvvmpractice
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)
}
} | MVVM-Practice/app/src/test/java/com/shubhamtripz/mvvmpractice/ExampleUnitTest.kt | 176984005 |
package com.shubhamtripz.mvvmpractice.viewmodel
import androidx.lifecycle.ViewModel
import com.shubhamtripz.mvvmpractice.model.CalculatorData
class calculatorViewModel: ViewModel() {
fun calulatesum(num1: Int, num2: Int): CalculatorData{
val sum = num1 + num2
return CalculatorData(num1, num2, sum)
}
} | MVVM-Practice/app/src/main/java/com/shubhamtripz/mvvmpractice/viewmodel/calculatorViewModel.kt | 1474319834 |
package com.shubhamtripz.mvvmpractice.model
data class CalculatorData(
val num1: Int,
val num2: Int,
val sum: Int
) | MVVM-Practice/app/src/main/java/com/shubhamtripz/mvvmpractice/model/CalculatorData.kt | 3342589907 |
package com.shubhamtripz.mvvmpractice.view
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.shubhamtripz.mvvmpractice.databinding.ActivityMainBinding
import com.shubhamtripz.mvvmpractice.viewmodel.calculatorViewModel
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var calculatorViewModel: calculatorViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
calculatorViewModel = ViewModelProvider(this).get(calculatorViewModel::class.java)
binding.calculatorBtn.setOnClickListener {
val num1 = binding.edtnum1.text.toString().toIntOrNull() ?: 0
val num2 = binding.edtnum2.text.toString().toIntOrNull() ?: 0
val result = calculatorViewModel.calulatesum(num1, num2)
binding.resultTextView.text = "${result.sum}"
}
}
}
| MVVM-Practice/app/src/main/java/com/shubhamtripz/mvvmpractice/view/MainActivity.kt | 3203018521 |
package com.dktechh.noteclassic
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.duongkhai.noteclassic", appContext.packageName)
}
} | NoteClassic/app/src/androidTest/java/com/dktechh/noteclassic/ExampleInstrumentedTest.kt | 2049368273 |
package com.dktechh.noteclassic
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)
}
} | NoteClassic/app/src/test/java/com/dktechh/noteclassic/ExampleUnitTest.kt | 10439045 |
package com.dktechh.noteclassic
import android.app.Application
import com.dktechh.noteclassic.di.dataBaseModule
import com.dktechh.noteclassic.di.dispatcherModule
import com.dktechh.noteclassic.di.repositoryModule
import com.dktechh.noteclassic.di.useCaseModule
import com.dktechh.noteclassic.di.viewModelModule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@App)
modules(
dataBaseModule,
repositoryModule,
useCaseModule,
viewModelModule,
dispatcherModule
)
}
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/App.kt | 2446502000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.