content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package org.grove.taskmanager.broker.input
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.grove.protobuf.metricsmanager.MetricTask
import org.grove.taskmanager.model.mapping.internalModel
import org.grove.taskmanager.service.TaskManagementService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.listener.AcknowledgingMessageListener
import org.springframework.kafka.support.Acknowledgment
import org.springframework.stereotype.Component
import java.util.UUID
@Component
class MetricsManagerKafkaListener(
private val taskManagementService: TaskManagementService
): AcknowledgingMessageListener<UUID, ByteArray> {
@KafkaListener(
topics = ["\${kafka.metrics-manager-consumer.topic.name}"],
groupId = "\${kafka.metrics-manager-consumer.consumer-group-name}"
)
override fun onMessage(
data: ConsumerRecord<UUID, ByteArray>,
acknowledgment: Acknowledgment?
) {
val internalModel = MetricTask
.parseFrom(data.value())
.internalModel
logger.info("Received task for metric ${internalModel.metricId}")
taskManagementService.processTask(internalModel)
logger.info("Task for metric ${internalModel.metricId} processed successfully")
if (acknowledgment == null) {
logger.warn("Kafka acknowledgement is missing")
}
acknowledgment?.acknowledge()
}
private companion object {
val logger: Logger = LoggerFactory.getLogger(MetricsManagerKafkaListener::class.java)
}
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/broker/input/MetricsManagerKafkaListener.kt | 3012137176 |
package org.grove.taskmanager.broker.output.impl
import org.grove.taskmanager.broker.output.SenderService
import org.grove.taskmanager.configuration.properties.KafkaProperties
import org.grove.taskmanager.model.TaskResultInternal
import org.grove.taskmanager.model.mapping.protobufModel
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class KafkaSenderService(
private val kafkaProperties: KafkaProperties,
private val kafkaTemplate: KafkaTemplate<UUID, ByteArray>
): SenderService {
override fun sendTaskResult(result: TaskResultInternal) {
val outputModel = result.protobufModel
val topicName = kafkaProperties.producer.name
kafkaTemplate.send(topicName, result.metricId, outputModel.toByteArray())
}
} | grove-task-manager/src/main/kotlin/org/grove/taskmanager/broker/output/impl/KafkaSenderService.kt | 858920188 |
package org.grove.taskmanager.broker.output
import org.grove.taskmanager.model.TaskResultInternal
interface SenderService {
fun sendTaskResult(result: TaskResultInternal)
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/broker/output/SenderService.kt | 3652530028 |
package org.grove.taskmanager
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class TaskManagerApplication
fun main(args: Array<String>) {
runApplication<TaskManagerApplication>(*args)
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/TaskManagerApplication.kt | 534436766 |
package org.grove.taskmanager.model.mapping
import org.grove.protobuf.metricsmanager.*
import org.grove.taskmanager.exception.MappingException
import org.grove.taskmanager.model.ConsumerInternal
import org.grove.taskmanager.model.MetricTaskInternal
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.UUID
val MetricTask.internalModel get() =
MetricTaskInternal(
metricId = UUID.fromString(metricId),
metricKey = metricKey,
processFrom = if (processFromOrNull == null) {
null
} else {
LocalDateTime.ofEpochSecond(
processFrom.seconds,
processFrom.nanos,
ZoneOffset.UTC
)
},
processTo = LocalDateTime.ofEpochSecond(
processTo.seconds,
processTo.nanos,
ZoneOffset.UTC
),
sourceLink = source.link,
consumer = consumer.internalModel
)
val Consumer.internalModel get() =
ConsumerInternal(
id = UUID.fromString(id),
type = type.internalType,
properties = propertiesList.map(ConsumerProperty::internalType)
)
val ConsumerType.internalType get() = when (this) {
ConsumerType.PROMETHEUS -> ConsumerInternal.Type.PROMETHEUS
ConsumerType.CLICKHOUSE -> ConsumerInternal.Type.CLICKHOUSE
ConsumerType.PROMETHEUS_PUSHGATEWAY -> ConsumerInternal.Type.PROMETHEUS_PUSHGATEWAY
else -> throw MappingException("type", "Consumer")
}
val ConsumerProperty.internalType get() =
ConsumerInternal.Property(key, value)
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/model/mapping/ProtobufModelsExtensions.kt | 2265481849 |
package org.grove.taskmanager.model.mapping
import org.grove.protobuf.taskmanager.MetricTaskResult
import org.grove.protobuf.taskmanager.MetricTaskResultStatus
import org.grove.protobuf.taskmanager.metricTaskResult
import org.grove.taskmanager.model.TaskResultInternal
val TaskResultInternal.protobufModel: MetricTaskResult get() {
val internalModel = this
return metricTaskResult {
metricId = internalModel.metricId.toString()
status = internalModel.status.protobufType
}
}
val TaskResultInternal.Status.protobufType get() = when (this) {
TaskResultInternal.Status.SUCCESSFUL -> MetricTaskResultStatus.SUCCESSFUL
TaskResultInternal.Status.FAILED -> MetricTaskResultStatus.FAILED
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/model/mapping/InternalModelsExtensions.kt | 2055936730 |
package org.grove.taskmanager.model
import java.util.UUID
data class TaskResultInternal(
val metricId: UUID,
val status: Status
) {
enum class Status {
SUCCESSFUL,
FAILED;
}
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/model/TaskResultInternal.kt | 1499716546 |
package org.grove.taskmanager.model
import java.time.LocalDateTime
import java.util.UUID
data class MetricTaskInternal(
val metricId: UUID,
val metricKey: String,
val processFrom: LocalDateTime? = null,
val processTo: LocalDateTime,
val sourceLink: String,
val consumer: ConsumerInternal
)
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/model/MetricTaskInternal.kt | 2147862162 |
package org.grove.taskmanager.model
import java.util.UUID
data class ConsumerInternal(
val id: UUID,
val type: Type,
val properties: List<Property>
) {
enum class Type {
PROMETHEUS,
CLICKHOUSE,
PROMETHEUS_PUSHGATEWAY;
}
data class Property(
val key: String,
val value: String
)
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/model/ConsumerInternal.kt | 579079782 |
package org.grove.taskmanager.service
import org.grove.taskmanager.broker.output.SenderService
import org.grove.taskmanager.model.MetricTaskInternal
import org.grove.taskmanager.model.TaskResultInternal
import org.springframework.stereotype.Service
@Service
class TaskManagementService(
private val senderService: SenderService
) {
fun processTask(task: MetricTaskInternal) {
val status = TaskResultInternal.Status.SUCCESSFUL
senderService.sendTaskResult(
TaskResultInternal(
metricId = task.metricId,
status = status
)
)
}
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/service/TaskManagementService.kt | 120194832 |
package org.grove.taskmanager.exception
class MappingException(val fieldName: String, val messageName: String):
RuntimeException("Unable to map field $fieldName in message $messageName")
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/exception/MappingException.kt | 3860226385 |
package com.example.mytodoappcompose
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.mytodoappcompose", appContext.packageName)
}
} | TaskMania_UASMobcom/app/src/androidTest/java/com/example/mytodoappcompose/ExampleInstrumentedTest.kt | 2202029115 |
package com.example.mytodoappcompose
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)
}
} | TaskMania_UASMobcom/app/src/test/java/com/example/mytodoappcompose/ExampleUnitTest.kt | 304735925 |
package com.example.mytodoappcompose.ui.viewmodels
import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.data.models.TodoTask
import com.example.mytodoappcompose.data.repositories.DataStoreRepository
import com.example.mytodoappcompose.data.repositories.TodoRepository
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.RequestState
import com.example.mytodoappcompose.util.SearchAppBarState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SharedViewModel @Inject constructor(
private val repository: TodoRepository,
private val dataStoreRepository: DataStoreRepository
) :
ViewModel() {
val action: MutableState<Action> = mutableStateOf(Action.NO_ACTION)
fun changeAction(newAction: Action) {
action.value = newAction
}
private val _allTasks =
MutableStateFlow<RequestState<List<TodoTask>>>(RequestState.Idle)
val allTasks: StateFlow<RequestState<List<TodoTask>>> = _allTasks
private val _sortState = MutableStateFlow<RequestState<Priority>>(RequestState.Idle)
val sortState: StateFlow<RequestState<Priority>> = _sortState
// states
val id: MutableState<Int> = mutableStateOf(0)
val title: MutableState<String> = mutableStateOf("")
val description: MutableState<String> = mutableStateOf("")
val priority: MutableState<Priority> = mutableStateOf((Priority.LOW))
init {
getAllTasks()
Log.d("SharedViewModel", "Init block")
readSortState()
}
private val _searchedTasks =
MutableStateFlow<RequestState<List<TodoTask>>>(RequestState.Idle)
val searchedTasks: StateFlow<RequestState<List<TodoTask>>> = _searchedTasks
fun searchDatabase(searchQuery: String) {
_searchedTasks.value = RequestState.Loading
try {
viewModelScope.launch {
// Finds any values that have searchQuery in any position - sql LIKE
repository.searchDatabase(searchQuery = "%$searchQuery%")
.collect { searchedTasks ->
_searchedTasks.value = RequestState.Success(searchedTasks)
}
}
} catch (e: Exception) {
_searchedTasks.value = RequestState.Error(e)
}
searchAppBarState.value = SearchAppBarState.TRIGGERED
}
val lowPriorityTasks: StateFlow<List<TodoTask>> =
repository.sortByLowPriority.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = emptyList()
)
val highPriorityTasks: StateFlow<List<TodoTask>> =
repository.sortByHighPriority.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = emptyList()
)
fun readSortState() {
_sortState.value = RequestState.Loading
try {
viewModelScope.launch {
// Trigger the flow and consume its elements using collect
dataStoreRepository.readSortState
.map { Priority.valueOf(it) }
.collect {
_sortState.value = RequestState.Success(it)
}
}
} catch (e: Exception) {
_sortState.value = RequestState.Error(e)
}
}
fun persistSortState(priority: Priority) {
viewModelScope.launch(Dispatchers.IO) {
dataStoreRepository.persistSortState(priority = priority)
}
}
// state: searchAppBarState
var searchAppBarState: MutableState<SearchAppBarState> =
mutableStateOf(SearchAppBarState.CLOSED)
private set //! I do not understand !!!!!
// state: searchTextState
var searchTextState: MutableState<String> = mutableStateOf("")
private set
// onSearchClicked is an event we're defining that the UI can invoke
// (events flow up from UI)
// event: onSearchClicked
fun onSearchClicked(newSearchAppBarState: SearchAppBarState) {
searchAppBarState.value = newSearchAppBarState
}
// event: onSearchTextChanged
fun onSearchTextChanged(newText: String) {
searchTextState.value = newText
}
// events:
fun onTitleChange(newTitle: String) {
// limit the character count
if (newTitle.length < 20) {
Log.e("onTitleChange",""+newTitle)
title.value = newTitle
}
}
fun onDescriptionChange(newDescription: String) {
description.value = newDescription
}
fun onPrioritySelected(newPriority: Priority) {
priority.value = newPriority
}
fun updateTaskFields(selectedTask: TodoTask?) {
if (selectedTask != null) {
id.value = selectedTask.id
title.value = selectedTask.title
description.value = selectedTask.description
priority.value = selectedTask.priority
} else {
id.value = 0
title.value = ""
description.value = ""
priority.value = Priority.LOW
}
}
fun validateFields(): Boolean {
return title.value.isNotEmpty() && description.value.isNotEmpty()
}
private fun getAllTasks() {
_allTasks.value = RequestState.Loading
try {
viewModelScope.launch {
// Trigger the flow and consume its elements using collect
repository.getAllTasks.collect {
_allTasks.value = RequestState.Success(it)
}
}
} catch (e: Exception) {
_allTasks.value = RequestState.Error(e)
}
}
private val _selectedTask: MutableStateFlow<TodoTask?> = MutableStateFlow(null)
val selectTask: StateFlow<TodoTask?> = _selectedTask
fun getSelectedTask(taskId: Int) {
viewModelScope.launch {
repository.getSelectedTask(taskId = taskId).collect {
_selectedTask.value = it
}
}
}
private fun addTask() {
viewModelScope.launch(Dispatchers.IO) {
val todoTask = TodoTask(
title = title.value,
description = description.value,
priority = priority.value
)
repository.addTask(todoTask = todoTask)
}
searchAppBarState.value = SearchAppBarState.CLOSED
}
private fun updateTask() {
viewModelScope.launch(Dispatchers.IO) {
val todoTask = TodoTask(
id = id.value,
title = title.value,
description = description.value,
priority = priority.value
)
repository.updateTask(todoTask = todoTask)
}
}
private fun deleteTask() {
viewModelScope.launch(Dispatchers.IO) {
val todoTask = TodoTask(
id = id.value,
title = title.value,
description = description.value,
priority = priority.value
)
repository.deleteTask(todoTask = todoTask)
}
}
private fun deleteAllTasks() {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteAllTasks()
}
}
fun handleDatabaseActions(action: Action) {
when (action) {
Action.ADD -> addTask()
Action.UPDATE -> updateTask()
Action.DELETE -> deleteTask()
Action.DELETE_ALL -> deleteAllTasks()
Action.UNDO -> addTask()
else -> {
}
}
this.action.value = Action.NO_ACTION
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/viewmodels/SharedViewModel.kt | 2938869388 |
package com.example.mytodoappcompose.ui.splash
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.mytodoappcompose.R
import com.example.mytodoappcompose.ui.theme.ToDoComposeTheme
import com.example.mytodoappcompose.ui.theme.splashScreenBackgroundColor
import kotlinx.coroutines.delay
@Composable
fun SplashScreen(
navigateToListScreen: () -> Unit
) {
var startAnimation by remember { mutableStateOf(false) }
val offsetState by animateDpAsState(
targetValue = if (startAnimation) 0.dp else 100.dp,
animationSpec = tween(
durationMillis = 1000,
)
)
val alphaState by animateFloatAsState(
targetValue = if (startAnimation) 1f else 0f,
animationSpec = tween(
durationMillis = 1000
)
)
LaunchedEffect(key1 = true, block = {
startAnimation = true
// delay of 3000 ms
delay(3000)
navigateToListScreen()
})
Box(
modifier = Modifier
.fillMaxSize()
.background(color = MaterialTheme.colors.splashScreenBackgroundColor),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier
.size(500.dp)
.offset(y = offsetState)
.alpha(alpha = alphaState),
painter = painterResource(id = getLogo()),
contentDescription = "To Do app Logo"
)
}
}
@Composable
fun getLogo(): Int {
return if (isSystemInDarkTheme()) {
R.drawable.splashicon
} else {
R.drawable.splashicon
}
}
@Preview(showBackground = true)
@Composable
fun PreviewSplashScreen() {
SplashScreen(navigateToListScreen = {})
}
@Preview(showBackground = true)
@Composable
fun PreviewSplashScreenDarkTeam() {
ToDoComposeTheme(darkTheme = true) {
SplashScreen(navigateToListScreen = {})
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/splash/SplashScreen.kt | 1839875107 |
package com.example.mytodoappcompose.ui.screens.list
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import com.example.mytodoappcompose.R
import com.example.mytodoappcompose.ui.theme.fabBackgroundColor
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.SearchAppBarState
import kotlinx.coroutines.launch
@ExperimentalMaterialApi
@Composable
fun ListScreen(
navigateToTaskScreen: (taskId: Int) -> Unit,
sharedViewModel: SharedViewModel,
action: Action
) {
// To call suspend functions safely from inside a composable, use the LaunchedEffect API,
// which triggers a coroutine-scoped side-effect in Compose.
// Instead, see rememberCoroutineScope to obtain a CoroutineScope that may be used to launch
// ongoing jobs scoped to the composition in response to event callbacks.
//! getAllTasks() is in the init block of sharedViewModel
//! Problem: readSortState() is triggered whenever there is a configuration change (rotation)
// Fixed with issue #12 - is in the init block of sharedViewModel
/* LaunchedEffect(true) {
Log.d("ListScreen", "LaunchedEffect triggered")
sharedViewModel.readSortState()
}*/
//! collectAsState() collects values from the StateFlow and represents the latest value
//! via Compose's State API. This will make the Compose code that reads that state value recompose on new emissions.
//! Compose also offers APIs for Android's most popular stream-based solutions, like:
//! LiveData.observeAsState()
val allTasks by sharedViewModel.allTasks.collectAsState() // the type is RequestState<List<TodoTask>>
val sortState by sharedViewModel.sortState.collectAsState() // the type is RequestState<Priority>
val lowPriorityTasks by sharedViewModel.lowPriorityTasks.collectAsState() // the type is List<TodoTask>
val highPriorityTasks by sharedViewModel.highPriorityTasks.collectAsState() // the type is List<TodoTask>
//! 1 - We are declaring a variable searchAppBarState of type SearchAppBarState
//! 2 - sharedViewModel.searchAppBarState is of type MutableState<SearchAppBarState>
//! which is an observable state holder. Since it's observable, it will tell compose
//! whenever it's updated so compose can recompose any composables that read it.
//! 3 - by is the property delegate syntax in Kotlin, it lets us automatically unwrap
//! the State<SearchAppBarState> from the sharedViewModel.searchAppBarState into a regular SearchAppBarState
val searchAppBarState: SearchAppBarState by sharedViewModel.searchAppBarState
//! Alternatively you can do as following:
val searchTextState: String = sharedViewModel.searchTextState.value
val searchedTasks by sharedViewModel.searchedTasks.collectAsState()
// sharedViewModel.handleDatabaseActions(action)
val scaffoldState: ScaffoldState = rememberScaffoldState()
// every time the ListScreen function triggers the following function is triggered
DisplaySnackBar(
scaffoldState = scaffoldState,
handleDatabaseActions = { sharedViewModel.handleDatabaseActions(action) },
taskTitle = sharedViewModel.title.value,
action = action,
onUndoClicked = {
sharedViewModel.action.value = it
},
)
Scaffold(
// to be able to display the snackbar
scaffoldState = scaffoldState,
topBar = {
ListAppBar(
sharedViewModel = sharedViewModel,
searchAppBarState = searchAppBarState,
searchTextState = searchTextState,
onSearchClicked = sharedViewModel::onSearchClicked,
onTextChange = sharedViewModel::onSearchTextChanged
)
},
floatingActionButton = {
ListFab(navigateToTaskScreen = navigateToTaskScreen)
}
) {
ListContent(
navigateToTaskScreen = navigateToTaskScreen,
allTasks = allTasks,
searchAppBarState = searchAppBarState,
searchedTasks = searchedTasks,
lowPriorityTasks = lowPriorityTasks,
highPriorityTasks = highPriorityTasks,
sortState = sortState
)
}
}
@Composable
fun ListFab(
navigateToTaskScreen: (taskId: Int) -> Unit
) {
FloatingActionButton(
onClick = { navigateToTaskScreen(-1) },
backgroundColor = MaterialTheme.colors.fabBackgroundColor
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = stringResource(id = R.string.add_button),
tint = Color.White
)
}
}
@Composable
fun DisplaySnackBar(
scaffoldState: ScaffoldState,
handleDatabaseActions: () -> Unit,
taskTitle: String,
action: Action,
onUndoClicked: (Action) -> Unit
) {
//! May be improved. For now this function is triggered any time there is a
//! recomposition of DisplaySnackBar composable. Ideally, it should be triggered
//! when there is a change in action by means of a LaunchedEffect with key1 = action
handleDatabaseActions()
val scope = rememberCoroutineScope()
LaunchedEffect(key1 = action) {
if (action != Action.NO_ACTION) {
scope.launch {
val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
message = setMessage(action = action, taskTitle = taskTitle),
actionLabel = setActionLabel(action = action)
)
undoDeletedTask(
action = action,
snackBarResult = snackbarResult,
onUndoClicked = onUndoClicked
)
}
}
}
}
private fun setMessage(
action: Action,
taskTitle: String
): String {
return when (action) {
Action.DELETE_ALL -> "All tasks removed."
else -> "${action.name}: $taskTitle"
}
}
private fun setActionLabel(action: Action): String {
return if (action.name == "DELETE") {
"UNDO"
} else {
"OK"
}
}
private fun undoDeletedTask(
action: Action,
snackBarResult: SnackbarResult,
onUndoClicked: (Action) -> Unit
) {
if (snackBarResult == SnackbarResult.ActionPerformed
&& action == Action.DELETE
) {
onUndoClicked(Action.UNDO)
}
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/list/ListScreen.kt | 1994716595 |
package com.example.mytodoappcompose.ui.screens.list
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.data.models.Priority
// Type 'TypeVariable(T)' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import com.example.mytodoappcompose.components.PriorityItem
import com.example.mytodoappcompose.R
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.saveable.rememberSaveable
import com.example.mytodoappcompose.ui.theme.LARGE_PADDING
import com.example.mytodoappcompose.ui.theme.TOP_APP_BAR_HEIGHT
import com.example.mytodoappcompose.ui.theme.topAppBarBackgroundColor
import com.example.mytodoappcompose.ui.theme.topAppBarContentColor
import com.example.mytodoappcompose.components.DisplayAlertDialog
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.SearchAppBarState
// When the user interacts with the UI, the UI raises events such as onClick.
// Those events should notify the app logic, which can then change the app's state.
// When the state changes, the composable functions are called again with the new data.
// This causes the UI elements to be redrawn--this process is called recomposition.
@Composable
fun ListAppBar(
sharedViewModel: SharedViewModel,
searchAppBarState: SearchAppBarState,
searchTextState: String,
onSearchClicked: (SearchAppBarState) -> Unit,
onTextChange: (String) -> Unit
) {
when (searchAppBarState) {
SearchAppBarState.CLOSED ->
DefaultListAppBar(
onSearchClicked = {
// sharedViewModel.searchAppBarState.value = SearchAppBarState.OPENED
onSearchClicked(SearchAppBarState.OPENED)
},
onSortClicked = {
sharedViewModel.persistSortState(it)
},
onDeleteAllConfirmed = {
sharedViewModel.action.value = Action.DELETE_ALL
}
)
else ->
SearchAppBar(
text = searchTextState,
onTextChange = { newText -> onTextChange(newText) },
onCloseClicked = {
onSearchClicked(SearchAppBarState.CLOSED)
onTextChange("")
},
onSearchClicked = {
sharedViewModel.searchDatabase(searchQuery = it)
}
)
}
}
@Composable
fun DefaultListAppBar(
onSearchClicked: () -> Unit,
onSortClicked: (Priority) -> Unit,
onDeleteAllConfirmed: () -> Unit
) {
TopAppBar(
title = {
Text(
text = stringResource(id = R.string.app_bar_text),
color = MaterialTheme.colors.topAppBarContentColor
)
},
backgroundColor = MaterialTheme.colors.topAppBarBackgroundColor,
actions = {
ListAppBarActions(
onSearchClicked = onSearchClicked,
onSortClicked = onSortClicked,
onDeleteAllConfirmed = onDeleteAllConfirmed
)
}
)
}
@Composable
fun ListAppBarActions(
onSearchClicked: () -> Unit,
onSortClicked: (Priority) -> Unit,
onDeleteAllConfirmed: () -> Unit
) {
var openDialog by rememberSaveable { mutableStateOf(false) }
DisplayAlertDialog(
title = "Remove All Tasks?",
message = "Are you sure you want to remove all Tasks?",
openDialog = openDialog,
closeDialog = { openDialog = false },
onYesClicked = { onDeleteAllConfirmed() }
)
SearchAction(onSearchClicked = onSearchClicked)
SortAction(onSortClicked = onSortClicked)
DeleteAllAction(
onDeleteAllConfirmed = {
openDialog = true
})
}
@Composable
fun SearchAction(
onSearchClicked: () -> Unit
) {
IconButton(
onClick = { onSearchClicked() }
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(id = R.string.search_tasks),
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
fun SortAction(
onSortClicked: (Priority) -> Unit
) {
var expanded by remember { mutableStateOf(false) }
IconButton(
onClick = { expanded = true }
) {
Icon(
painter = painterResource(id = R.drawable.ic_filter_list),
contentDescription = stringResource(id = R.string.sort_action),
tint = MaterialTheme.colors.topAppBarContentColor
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
onClick = {
expanded = false
onSortClicked(Priority.LOW)
}
) {
PriorityItem(priority = Priority.LOW)
}
DropdownMenuItem(
onClick = {
expanded = false
onSortClicked(Priority.HIGH)
}
) {
PriorityItem(priority = Priority.HIGH)
}
DropdownMenuItem(
onClick = {
expanded = false
onSortClicked(Priority.NONE)
}
) {
PriorityItem(priority = Priority.NONE)
}
}
}
}
@Composable
fun DeleteAllAction(
onDeleteAllConfirmed: () -> Unit
) {
var expanded by remember { mutableStateOf(false) }
IconButton(
onClick = { expanded = true }
) {
Icon(
painter = painterResource(id = R.drawable.ic_vertical_menu),
contentDescription = stringResource(id = R.string.delete_all_action),
tint = MaterialTheme.colors.topAppBarContentColor
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
onClick = {
expanded = false
onDeleteAllConfirmed()
}
) {
Text(
modifier = Modifier
.padding(start = LARGE_PADDING),
text = stringResource(id = R.string.delete_all_action),
style = MaterialTheme.typography.subtitle2
)
}
}
}
}
@Composable
fun SearchAppBar(
text: String,
onTextChange: (String) -> Unit,
onCloseClicked: () -> Unit,
onSearchClicked: (String) -> Unit
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.height(TOP_APP_BAR_HEIGHT),
elevation = AppBarDefaults.TopAppBarElevation,
color = MaterialTheme.colors.topAppBarBackgroundColor
) {
TextField(
modifier = Modifier
.fillMaxWidth(),
value = text,
onValueChange = onTextChange,
placeholder = {
Text(
text = "Search", //! transfer to strings.xml
color = Color.White,
modifier = Modifier
.alpha(ContentAlpha.medium)
)
},
textStyle = TextStyle(
color = MaterialTheme.colors.topAppBarContentColor,
fontSize = MaterialTheme.typography.subtitle1.fontSize,
),
singleLine = true,
leadingIcon = {
IconButton(
onClick = { /*TODO*/ },
modifier = Modifier
.alpha(ContentAlpha.disabled)
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = "Search Icon", //! transfer to strings.xml
tint = MaterialTheme.colors.topAppBarContentColor
)
}
},
trailingIcon = {
IconButton(
onClick = {
if (text.isNotEmpty()) {
onTextChange("")
} else {
onCloseClicked()
}
},
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Close Icon", //! transfer to strings.xml
tint = MaterialTheme.colors.topAppBarContentColor
)
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Search
),
keyboardActions = KeyboardActions(
onSearch = {
onSearchClicked(text)
}
),
colors = TextFieldDefaults.textFieldColors(
cursorColor = MaterialTheme.colors.topAppBarContentColor,
focusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
backgroundColor = Color.Transparent
)
)
}
}
@Preview
@Composable
fun PreviewDefaultListAppBar() {
DefaultListAppBar(
onSearchClicked = {},
onSortClicked = {},
onDeleteAllConfirmed = {}
)
}
@Preview
@Composable
fun PreviewSearchAppBar() {
SearchAppBar(
text = "",
onTextChange = {},
onCloseClicked = {},
onSearchClicked = {}
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/list/ListAppBar.kt | 327703599 |
package com.example.mytodoappcompose.ui.screens.list
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.mytodoappcompose.R
import com.example.mytodoappcompose.ui.theme.MediumGray
@Composable
fun EmptyContent() {
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
modifier = Modifier.size(120.dp), // size applies to both, width and height, 120.dp
painter = painterResource(id = R.drawable.ic_sad_face),
contentDescription = stringResource(id = R.string.sad_face_icon),
tint = MediumGray
)
Text(
text = stringResource(id = R.string.empty_content),
color = MediumGray,
fontWeight = FontWeight.Bold,
fontSize = MaterialTheme.typography.h6.fontSize
)
Text(
text = stringResource(id = R.string.empty_content_suggest),
color = MediumGray,
fontWeight = FontWeight.Bold,
fontSize = MaterialTheme.typography.h6.fontSize
)
}
}
@Composable
@Preview
private fun EmptyContentPreview() {
EmptyContent()
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/list/EmptyContent.kt | 2864237242 |
package com.example.mytodoappcompose.ui.screens.list
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.ui.theme.*
import com.example.mytodoappcompose.util.RequestState
import com.example.mytodoappcompose.util.SearchAppBarState
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.data.models.TodoTask
@ExperimentalMaterialApi
@Composable
fun ListContent(
navigateToTaskScreen: (taskId: Int) -> Unit,
allTasks: RequestState<List<TodoTask>>,
lowPriorityTasks: List<TodoTask>,
highPriorityTasks: List<TodoTask>,
sortState: RequestState<Priority>,
searchAppBarState: SearchAppBarState,
searchedTasks: RequestState<List<TodoTask>>
) {
if (sortState is RequestState.Success) {
when {
searchAppBarState == SearchAppBarState.TRIGGERED -> {
if (searchedTasks is RequestState.Success) {
HandleListContent(
tasks = searchedTasks.data,
navigateToTaskScreen = navigateToTaskScreen
)
}
}
sortState.data == Priority.NONE -> {
if (allTasks is RequestState.Success) {
HandleListContent(
tasks = allTasks.data,
navigateToTaskScreen = navigateToTaskScreen
)
}
}
sortState.data == Priority.LOW -> {
HandleListContent(
tasks = lowPriorityTasks,
navigateToTaskScreen = navigateToTaskScreen
)
}
sortState.data == Priority.HIGH -> {
HandleListContent(
tasks = highPriorityTasks,
navigateToTaskScreen = navigateToTaskScreen
)
}
}
}
}
@ExperimentalMaterialApi
@Composable
fun HandleListContent(
tasks: List<TodoTask>,
navigateToTaskScreen: (taskId: Int) -> Unit
) {
if (tasks.isEmpty()) EmptyContent() else
DisplayTasks(
tasks = tasks,
navigateToTaskScreen = navigateToTaskScreen
)
}
@ExperimentalMaterialApi
@Composable
fun DisplayTasks(tasks: List<TodoTask>, navigateToTaskScreen: (taskId: Int) -> Unit) {
LazyColumn {
items(
items = tasks,
key = { task -> task.id }
) { task ->
TaskItem(
todoTask = task,
navigateToTaskScreen = navigateToTaskScreen
)
}
}
}
@ExperimentalMaterialApi
@Composable
fun TaskItem(
todoTask: TodoTask,
navigateToTaskScreen: (taskId: Int) -> Unit
) {
Surface(
modifier = Modifier
.fillMaxWidth(),
color = MaterialTheme.colors.taskItemBackgroundColor,
shape = RectangleShape,
elevation = TASK_ITEM_ELEVATION,
onClick = {
navigateToTaskScreen(todoTask.id)
}
) {
Column(
modifier = Modifier
.padding(all = LARGE_PADDING)
.fillMaxWidth()
)
{
Row {
Text(
modifier = Modifier.weight(8f),
text = todoTask.title,
color = MaterialTheme.colors.taskItemTextColor,
style = MaterialTheme.typography.h5,
fontWeight = FontWeight.Bold,
maxLines = 1
)
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentAlignment = Alignment.TopEnd
) {
Canvas(
modifier = Modifier
.size(PRIORITY_INDICATOR_SIZE)
) {
drawCircle(
color = todoTask.priority.color
)
}
}
}
Text(
modifier = Modifier.fillMaxWidth(),
text = todoTask.description,
color = MaterialTheme.colors.taskItemTextColor,
style = MaterialTheme.typography.subtitle1,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
@ExperimentalMaterialApi
@Composable
@Preview
fun TaskItemPreview() {
TaskItem(
todoTask = TodoTask(
id = 0,
title = "Title",
description = "Some random text",
priority = Priority.MEDIUM
),
navigateToTaskScreen = {}
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/list/ListContent.kt | 3857393305 |
package com.example.mytodoappcompose.ui.screens.task
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.components.PriorityDropDown
import com.example.mytodoappcompose.ui.theme.LARGE_PADDING
import com.example.mytodoappcompose.ui.theme.MEDIUM_PADDING
import com.example.mytodoappcompose.data.models.Priority
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TaskContent(
title: String,
onTitleChange: (String) -> Unit,
description: String,
onDescriptionChange: (String) -> Unit,
priority: Priority,
onPrioritySelected: (Priority) -> Unit
) {
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background)
.padding(all = LARGE_PADDING)
) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = title,
onValueChange = { newTitle -> onTitleChange(newTitle) },
label = { Text(text = "Title") },
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Next,
keyboardType = KeyboardType.Text
),
keyboardActions = KeyboardActions(
onNext = {
focusManager.moveFocus(FocusDirection.Down)
}
),
textStyle = MaterialTheme.typography.body1,
singleLine = true
)
Divider(
modifier = Modifier.height(MEDIUM_PADDING),
color = MaterialTheme.colors.background
)
PriorityDropDown(
priority = priority,
onPrioritySelected = onPrioritySelected
)
OutlinedTextField(
modifier = Modifier.fillMaxSize(),
value = description,
onValueChange = { newDescription -> onDescriptionChange(newDescription) },
label = { Text(text = "") },
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Text
),
keyboardActions = KeyboardActions(
onDone = {keyboardController?.hide()}),
textStyle = MaterialTheme.typography.body1
)
}
}
@Composable
@Preview
fun PreviewTaskContent() {
TaskContent(
title = "Luis",
onTitleChange = {},
description = "Description related to title",
onDescriptionChange = {},
priority = Priority.HIGH,
onPrioritySelected = {}
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/task/TaskContent.kt | 3129194848 |
package com.example.mytodoappcompose.ui.screens.task
import android.content.Context
import android.widget.Toast
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.data.models.TodoTask
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.example.mytodoappcompose.util.Action
@Composable
fun TaskScreen(
sharedViewModel: SharedViewModel,
selectedTask: TodoTask?,
navigateToListScreen: (Action) -> Unit
) {
val context = LocalContext.current
Scaffold(
topBar = {
TaskAppBar(
navigateToListScreen = { action ->
if (action == Action.NO_ACTION) {
navigateToListScreen(action)
} else {
if (sharedViewModel.validateFields()) {
navigateToListScreen(action)
} else {
displayToast(context = context)
}
}
},
selectedTask = selectedTask
)
}
) {
TaskContent(
title = sharedViewModel.title.value,
onTitleChange = sharedViewModel::onTitleChange,
description = sharedViewModel.description.value,
onDescriptionChange = sharedViewModel::onDescriptionChange,
priority = sharedViewModel.priority.value,
onPrioritySelected = {
sharedViewModel.onPrioritySelected(it)
}
)
}
}
fun displayToast(context: Context) {
Toast.makeText(
context,
"Fields Empty",
Toast.LENGTH_SHORT
).show()
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/task/TaskScreen.kt | 60507150 |
package com.example.mytodoappcompose.ui.screens.task
import androidx.compose.material.*
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.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.R
import com.example.mytodoappcompose.ui.theme.topAppBarBackgroundColor
import com.example.mytodoappcompose.ui.theme.topAppBarContentColor
import com.example.mytodoappcompose.components.DisplayAlertDialog
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.data.models.TodoTask
import com.example.mytodoappcompose.util.Action
@Composable
fun TaskAppBar(
navigateToListScreen: (Action) -> Unit,
selectedTask: TodoTask?
) {
if (selectedTask == null)
NewTaskAppBar(
navigateToListScreen = navigateToListScreen
)
else ExistingTaskAppBar(
selectedTask = selectedTask,
navigateToListScreen = navigateToListScreen
)
}
@Composable
fun NewTaskAppBar(
navigateToListScreen: (Action) -> Unit
) {
TopAppBar(
navigationIcon = {
BackAction(onBackClicked = navigateToListScreen)
},
title = {
Text(
text = stringResource(id = R.string.app_bar_text),
color = MaterialTheme.colors.topAppBarContentColor
)
},
backgroundColor = MaterialTheme.colors.topAppBarBackgroundColor,
actions = {
AddAction(onAddClicked = navigateToListScreen)
}
)
}
@Composable
fun BackAction(onBackClicked: (Action) -> Unit) {
IconButton(
onClick = {
onBackClicked(Action.NO_ACTION)
}
) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back Arrow",
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
fun AddAction(onAddClicked: (Action) -> Unit) {
IconButton(
onClick = {
onAddClicked(Action.ADD)
}
) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = "Add Task",
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
fun ExistingTaskAppBar(
selectedTask: TodoTask,
navigateToListScreen: (Action) -> Unit
) {
TopAppBar(
navigationIcon = {
CloseAction(onCloseClicked = navigateToListScreen)
},
title = {
Text(
text = selectedTask.title,
color = MaterialTheme.colors.topAppBarContentColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
backgroundColor = MaterialTheme.colors.topAppBarBackgroundColor,
actions = {
ExistingTaskAppBarActions(
selectedTask = selectedTask,
navigateToListScreen = navigateToListScreen
)
}
)
}
@Composable
fun ExistingTaskAppBarActions(
selectedTask: TodoTask,
navigateToListScreen: (Action) -> Unit,
) {
var openDialog by remember { mutableStateOf(false) }
DisplayAlertDialog(
title = "Remove ${selectedTask.title}?",
message = "Are you sure you want to remove ${selectedTask.title}?",
openDialog = openDialog,
closeDialog = { openDialog = false },
onYesClicked = { navigateToListScreen(Action.DELETE) }
)
DeleteAction(onDeleteClicked = {
openDialog = true
})
UpdateAction(onUpdateClicked = navigateToListScreen)
}
@Composable
fun CloseAction(onCloseClicked: (Action) -> Unit) {
IconButton(
onClick = {
onCloseClicked(Action.NO_ACTION)
}
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Close Icon",
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
fun DeleteAction(onDeleteClicked: () -> Unit) {
IconButton(
onClick = {
onDeleteClicked()
}
) {
Icon(
imageVector = Icons.Filled.Delete,
contentDescription = "Delete Icon",
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
fun UpdateAction(onUpdateClicked: (Action) -> Unit) {
IconButton(
onClick = {
onUpdateClicked(Action.UPDATE)
}
) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = "Update Icon",
tint = MaterialTheme.colors.topAppBarContentColor
)
}
}
@Composable
@Preview
fun PreviewNewTaskAppBar() {
NewTaskAppBar(navigateToListScreen = {})
}
@Composable
@Preview
fun PreviewExistingTaskAppBar() {
ExistingTaskAppBar(
navigateToListScreen = {},
selectedTask = TodoTask(
id = 0,
title = "Luis",
description = "The best one",
priority = Priority.HIGH
)
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/screens/task/TaskAppBar.kt | 1865247241 |
package com.example.mytodoappcompose.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/theme/Shape.kt | 3627166251 |
package com.example.mytodoappcompose.ui.theme
import androidx.compose.material.Colors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Blue = Color(0xFF5FBDFF)
val LightBlue = Color(0xFF96EFFF)
val VeryLightBlue = Color(0xFFC5FFF8)
val LightGray = Color(0xFFFCFCFC)
val MediumGray = Color(0xFF9C9C9C)
val DarkGray = Color(0xFF141414)
val LowPriorityColor = Color(0xFF00C980)
val MediumPriorityColor = Color(0xFFFFC114)
val HighPriorityColor = Color(0XFFFF4646)
val NonePriorityColor = MediumGray
// extension properties
val Colors.splashScreenBackgroundColor: Color
@Composable
get() = if (isLight) Blue else Color.Black
val Colors.fabBackgroundColor: Color
@Composable
get() = if (isLight) Teal200 else Purple700
val Colors.topAppBarContentColor: Color
@Composable
get() = if (isLight) Color.White else LightGray
val Colors.topAppBarBackgroundColor: Color
@Composable
get() = if (isLight) LightBlue else Color.Black
val Colors.taskItemTextColor: Color
@Composable
get() = if (isLight) DarkGray else LightGray
val Colors.taskItemBackgroundColor: Color
@Composable
get() = if (isLight) Color.White else DarkGray
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/theme/Color.kt | 109827883 |
package com.example.mytodoappcompose.ui.theme
import androidx.compose.ui.unit.dp
val LARGE_PADDING = 12.dp
val MEDIUM_PADDING = 8.dp
val SMALL_PADDING = 6.dp
val PRIORITY_INDICATOR_SIZE = 16.dp
val TOP_APP_BAR_HEIGHT = 56.dp
val TASK_ITEM_ELEVATION = 2.dp | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/theme/Dimensions.kt | 1457882538 |
package com.example.mytodoappcompose.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import com.example.mytodoappcompose.ui.theme.Typography
private val DarkColorPalette = darkColors(
primary = VeryLightBlue,
primaryVariant = Blue,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = LightBlue,
primaryVariant = Blue,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun ToDoComposeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/theme/Theme.kt | 2249068819 |
package com.example.mytodoappcompose.ui.theme
import androidx.compose.material.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(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/ui/theme/Type.kt | 3367480637 |
package com.example.mytodoappcompose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.material.ExperimentalMaterialApi
import androidx.navigation.NavHostController
import com.example.mytodoappcompose.navigation.SetupNavigation
import com.example.mytodoappcompose.ui.theme.ToDoComposeTheme
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import dagger.hilt.android.AndroidEntryPoint
@ExperimentalMaterialApi
@ExperimentalAnimationApi
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private lateinit var navController: NavHostController
private val sharedViewModel by viewModels<SharedViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ToDoComposeTheme {
navController = rememberAnimatedNavController()
SetupNavigation(
navController = navController,
sharedViewModel = sharedViewModel,
changeAction = sharedViewModel::changeAction,
action = sharedViewModel.action.value
)
}
}
}
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/MainActivity.kt | 2314681822 |
package com.example.mytodoappcompose.di
import android.content.Context
import androidx.room.Room
import com.example.mytodoappcompose.data.TodoDao
import com.example.mytodoappcompose.data.TodoDatabase
import com.example.mytodoappcompose.util.Constants.DATABASE_NAME
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Singleton
@Provides
fun provideDatabase(
@ApplicationContext context: Context
): TodoDatabase = Room.databaseBuilder(
context,
TodoDatabase::class.java,
DATABASE_NAME
).build()
@Singleton
@Provides
fun provideDao(database: TodoDatabase): TodoDao = database.todoDao()
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/di/DatabaseModule.kt | 440517789 |
package com.example.mytodoappcompose.util
sealed class RequestState<out T> {
object Idle : RequestState<Nothing>()
object Loading : RequestState<Nothing>()
data class Success<T>(val data: T) : RequestState<T>()
data class Error(val error: Throwable) : RequestState<Nothing>()
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/util/RequestState.kt | 434368414 |
package com.example.mytodoappcompose.util
enum class Action {
ADD,
UPDATE,
DELETE,
DELETE_ALL,
UNDO,
NO_ACTION
}
fun String?.toAction(): Action {
return when {
this == "ADD" -> {
Action.ADD
}
this == "UPDATE" -> {
Action.UPDATE
}
this == "DELETE" -> {
Action.DELETE
}
this == "DELETE_ALL" -> {
Action.DELETE_ALL
}
this == "UNDO" -> {
Action.UNDO
}
else -> Action.NO_ACTION
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/util/Action.kt | 3064894545 |
package com.example.mytodoappcompose.util
object Constants {
const val DATABASE_TABLE = "todo_table"
const val DATABASE_NAME = "todo_database"
const val LIST_SCREEN = "list/{action}"
const val TASK_SCREEN = "task/{taskId}"
const val LIST_ARGUMENT_KEY = "action"
const val TASK_ARGUMENT_KEY = "taskId"
const val PREFERENCE_NAME = "todo_preferences"
const val PREFERENCE_KEY = "sort_state"
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/util/Constants.kt | 897729146 |
package com.example.mytodoappcompose.navigation.destinations
import androidx.compose.material.ExperimentalMaterialApi
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.example.mytodoappcompose.ui.screens.list.ListScreen
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.Constants.LIST_ARGUMENT_KEY
import com.example.mytodoappcompose.util.Constants.LIST_SCREEN
@ExperimentalMaterialApi
fun NavGraphBuilder.listComposable(
navigateToTaskScreen: (taskId: Int) -> Unit,
sharedViewModel: SharedViewModel,
action: Action
) {
composable(
route = LIST_SCREEN,
arguments = listOf(navArgument(LIST_ARGUMENT_KEY) {
type = NavType.StringType
})
) {
ListScreen(navigateToTaskScreen = navigateToTaskScreen, sharedViewModel = sharedViewModel, action =action)
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/navigation/destinations/ListComposable.kt | 2735679554 |
package com.example.mytodoappcompose.navigation
import androidx.navigation.NavHostController
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.Constants.LIST_SCREEN
class Screens(navController: NavHostController) {
val list: (Action) -> Unit = { action ->
navController.navigate(route = "list/${action.name}") {
popUpTo(LIST_SCREEN) { inclusive = true }
}
}
// when we go from List to Task screen we do not want to pop off the List screen
// from our backstack, we want to keep it alive
val task: (Int) -> Unit = { taskId ->
navController.navigate(route = "task/$taskId")
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/navigation/Screens.kt | 1437971896 |
package com.example.mytodoappcompose.navigation
import android.util.Log
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import com.google.accompanist.navigation.animation.composable
import androidx.navigation.navArgument
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.example.mytodoappcompose.ui.screens.list.ListScreen
import com.example.mytodoappcompose.ui.screens.task.TaskScreen
import com.example.mytodoappcompose.ui.splash.SplashScreen
import com.example.mytodoappcompose.ui.viewmodels.SharedViewModel
import com.example.mytodoappcompose.util.Action
import com.example.mytodoappcompose.util.toAction
@ExperimentalAnimationApi
@ExperimentalMaterialApi
@Composable
fun SetupNavigation(
navController: NavHostController,
sharedViewModel: SharedViewModel,
changeAction: (Action) -> Unit,
action: Action
) {
Log.d("SetupNavigation", "Recomposition of SetupNavigation")
AnimatedNavHost(
navController = navController,
startDestination = "splash" // SPLASH_SCREEN
) {
// definition of navigation destinations
// routes are represented as strings.
// A named argument is provided inside routes in curly braces like this {argument}.
composable(
route = "splash", // SPLASH_SCREEN
exitTransition = {
when (targetState.destination.route) {
"list/{action}" ->
slideOutHorizontally(targetOffsetX = { -1000 }, animationSpec = tween(300))
else -> null
}
},
) {
SplashScreen(
navigateToListScreen = {
navController.navigate(route = "list/${Action.NO_ACTION}") {
popUpTo("splash") { inclusive = true }
}
}
)
}
composable(
route = "list/{action}", // LIST_SCREEN
arguments = listOf(
navArgument("action") {
// Make argument type safe
type = NavType.StringType
})
) { entry -> // Look up "action" in NavBackStackEntry's arguments
val actionArg = entry.arguments?.getString("action").toAction()
var myAction by rememberSaveable { mutableStateOf(Action.NO_ACTION) }
// whenever myAction changes the block of code inside is triggered
LaunchedEffect(key1 = myAction) {
if (actionArg != myAction) {
myAction = actionArg
changeAction(myAction) // sharedViewModel.action.value = myAction
}
}
ListScreen(
navigateToTaskScreen = { taskId ->
navController.navigate(route = "task/$taskId")
},
sharedViewModel = sharedViewModel,
action = action,
)
}
composable(
route = "task/{taskId}", // TASK_SCREEN
arguments = listOf(
navArgument("taskId") {
// Make argument type safe
type = NavType.IntType
}),
enterTransition = {
slideInHorizontally(initialOffsetX = { -1000 }, animationSpec = tween(300))
}
) { entry -> // Look up "taskId" in NavBackStackEntry's arguments
val taskId = entry.arguments!!.getInt("taskId")
LaunchedEffect(key1 = taskId, block = {
sharedViewModel.getSelectedTask(taskId = taskId)
})
val selectedTask by sharedViewModel.selectTask.collectAsState()
// Log.d("SetupNavigation", "selectedTask = $selectedTask")
// Everytime selectedTask changes the block of code is triggered
LaunchedEffect(key1 = selectedTask) {
if (selectedTask != null || taskId == -1) {
sharedViewModel.updateTaskFields(selectedTask)
}
}
// sharedViewModel.updateTaskFields(selectedTask)
TaskScreen(
sharedViewModel = sharedViewModel,
selectedTask = selectedTask,
navigateToListScreen = { action ->
navController.navigate(route = "list/${action.name}") {
popUpTo("list/{action}") { inclusive = true }
}
}
)
}
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/navigation/Navigation.kt | 330175076 |
package com.example.mytodoappcompose.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.ui.theme.LARGE_PADDING
import com.example.mytodoappcompose.ui.theme.PRIORITY_INDICATOR_SIZE
@Composable
fun PriorityItem(priority: Priority){
Row(
verticalAlignment = Alignment.CenterVertically
) {
Canvas(modifier = Modifier.size(PRIORITY_INDICATOR_SIZE)){
drawCircle(color = priority.color)
}
Text(
text = priority.name,
color = MaterialTheme.colors.onSurface,
style = MaterialTheme.typography.subtitle2,
modifier = Modifier.padding(start = LARGE_PADDING)
)
}
}
@Composable
@Preview
fun PriorityItemPreview(){
PriorityItem(priority = Priority.HIGH)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/components/PriorityItem.kt | 2263577066 |
package com.example.mytodoappcompose.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.mytodoappcompose.data.models.Priority
@Composable
fun PriorityDropDown(
priority: Priority,
onPrioritySelected: (Priority) -> Unit
) {
// sometimes you need to place the imports manually, for setValue and getValue
var expanded by remember { mutableStateOf(false) }
val angle:Float by animateFloatAsState(
targetValue = if (expanded) 180f else 0f
)
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.background)
.height(60.dp)
.clickable(onClick = { expanded = true })
.border(
width = 1.dp,
color = MaterialTheme.colors.onSurface.copy(
alpha = ContentAlpha.disabled
),
shape = MaterialTheme.shapes.small
),
verticalAlignment = Alignment.CenterVertically
) {
Canvas(
modifier = Modifier
.size(16.dp)
.weight(weight = 1f)
) {
drawCircle(color = priority.color)
}
Text(
modifier = Modifier
.weight(weight = 8f),
text = priority.name,
style = MaterialTheme.typography.subtitle2
)
IconButton(
modifier = Modifier
.alpha(ContentAlpha.medium)
.rotate(degrees = angle)
.weight(weight = 1.5f),
onClick = { expanded = true }
) {
Icon(
imageVector = Icons.Filled.ArrowDropDown,
contentDescription = "Drop-Down Arrow Icon"
)
}
DropdownMenu(
modifier = Modifier
.fillMaxWidth(fraction = 0.94f),
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
onClick = {
expanded = false
onPrioritySelected(Priority.LOW)
}
) {
PriorityItem(priority = Priority.LOW)
}
DropdownMenuItem(
onClick = {
expanded = false
onPrioritySelected(Priority.MEDIUM)
}
) {
PriorityItem(priority = Priority.MEDIUM)
}
DropdownMenuItem(
onClick = {
expanded = false
onPrioritySelected(Priority.HIGH)
}
) {
PriorityItem(priority = Priority.HIGH)
}
}
}
}
@Composable
@Preview
private fun PriorityDropDownPreview() {
PriorityDropDown(
priority = Priority.LOW,
onPrioritySelected = {}
)
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/components/PriorityDropDown.kt | 3460930293 |
package com.example.mytodoappcompose.components
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.ui.screens.task.TaskContent
@Composable
fun DisplayAlertDialog(
title: String,
message: String,
openDialog: Boolean,
closeDialog: () -> Unit,
onYesClicked: () -> Unit,
) {
if (openDialog) {
AlertDialog(
title = {
Text(
text = title,
fontSize = MaterialTheme.typography.h5.fontSize,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
text = message,
fontSize = MaterialTheme.typography.subtitle1.fontSize,
fontWeight = FontWeight.Normal
)
},
confirmButton = {
Button(
onClick = {
onYesClicked()
closeDialog()
})
{
Text(text = "Yes")
}
},
dismissButton = {
OutlinedButton(onClick = { closeDialog() })
{
Text(text = "No")
}
},
onDismissRequest = { closeDialog() }
)
}
}
@Composable
@Preview()
fun DisplayAlertDialogPreview() {
MaterialTheme{
Surface(modifier = Modifier.fillMaxSize()) {
DisplayAlertDialog(
title = "Remove All Tasks?",
message = "Are you sure you want to remove all Tasks?",
openDialog = true,
closeDialog = {},
onYesClicked = {}
)
}
}
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/components/DisplayAlertDialog.kt | 3913791250 |
package com.example.mytodoappcompose
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class TodoApplication: Application()
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/TodoApplication.kt | 1388010464 |
package com.example.mytodoappcompose.data
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.mytodoappcompose.data.TodoDao
import com.example.mytodoappcompose.data.models.TodoTask
@Database(entities = [TodoTask::class], version = 1, exportSchema = false)
abstract class TodoDatabase : RoomDatabase() {
// abstract function that returns the TodoDao.
abstract fun todoDao(): TodoDao
// Define a companion object. The companion object allows access to the methods
// for creating or getting the database using the class name as the qualifier.
/* companion object {
@Volatile
private var INSTANCE: TodoDatabase? = null
fun getDatabase(context: Context): TodoDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
TodoDatabase::class.java,
"item_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
return instance
}
}
}*/
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/TodoDatabase.kt | 1124379769 |
package com.example.mytodoappcompose.data.repositories
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.util.Constants.PREFERENCE_KEY
import com.example.mytodoappcompose.util.Constants.PREFERENCE_NAME
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
import javax.inject.Inject
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCE_NAME)
// we are going to inject this repository inside SharedViewModel
@ViewModelScoped
class DataStoreRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
private object PreferenceKeys {
val sortKey = stringPreferencesKey(name = PREFERENCE_KEY)
}
private val dataStore = context.dataStore
suspend fun persistSortState(priority: Priority) {
dataStore.edit { preference ->
preference[PreferenceKeys.sortKey] = priority.name
}
}
val readSortState: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
val sortState = preferences[PreferenceKeys.sortKey] ?: Priority.NONE.name
sortState
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/repositories/DataStoreRepository.kt | 3477379463 |
package com.example.mytodoappcompose.data.repositories
import com.example.mytodoappcompose.data.TodoDao
import com.example.mytodoappcompose.data.models.TodoTask
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@ViewModelScoped
class TodoRepository @Inject constructor(private val todoDao: TodoDao) {
val getAllTasks: Flow<List<TodoTask>> = todoDao.getAllTasks()
val sortByLowPriority: Flow<List<TodoTask>> = todoDao.sortByLowPriority()
val sortByHighPriority: Flow<List<TodoTask>> = todoDao.sortByHighPriority()
fun getSelectedTask(taskId: Int): Flow<TodoTask> {
return todoDao.getSelectedTask(taskId = taskId)
}
suspend fun addTask(todoTask: TodoTask) {
todoDao.addTask(todoTask = todoTask)
}
suspend fun updateTask(todoTask: TodoTask) {
todoDao.updateTask(todoTask = todoTask)
}
suspend fun deleteTask(todoTask: TodoTask) {
todoDao.deleteTask(todoTask = todoTask)
}
suspend fun deleteAllTasks() {
todoDao.deleteAllTasks()
}
fun searchDatabase(searchQuery: String): Flow<List<TodoTask>> {
return todoDao.searchDatabase(searchQuery = searchQuery)
}
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/repositories/TodoRepository.kt | 3498588610 |
package com.example.mytodoappcompose.data.models
import androidx.compose.ui.graphics.Color
import com.example.mytodoappcompose.ui.theme.HighPriorityColor
import com.example.mytodoappcompose.ui.theme.LowPriorityColor
import com.example.mytodoappcompose.ui.theme.MediumPriorityColor
import com.example.mytodoappcompose.ui.theme.NonePriorityColor
enum class Priority(val color: Color) {
HIGH(color = HighPriorityColor),
MEDIUM(color = MediumPriorityColor),
LOW(color = LowPriorityColor),
NONE(color = NonePriorityColor)
}
| TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/models/Priority.kt | 254217075 |
package com.example.mytodoappcompose.data.models
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.mytodoappcompose.data.models.Priority
import com.example.mytodoappcompose.util.Constants.DATABASE_TABLE
// This class represents a database entity in your app.
// Above the TodoTask class declaration, annotate the data class with @Entity.
// Use tableName argument to give the todo_table as the SQLite table name.
@Entity(tableName = DATABASE_TABLE)
data class TodoTask(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val title: String,
val description: String,
val priority: Priority
) | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/models/TodoTask.kt | 2886274489 |
package com.example.mytodoappcompose.data
import androidx.room.*
import com.example.mytodoappcompose.data.models.TodoTask
import kotlinx.coroutines.flow.Flow
// Data Access Object - where you define your database interactions.
@Dao
interface TodoDao {
// The database operations can take a long time to execute, so they should run on a separate
// thread. Make the function a suspend function, so that this function can be called from a coroutine.
// The argument OnConflict tells the Room what to do in case of a conflict.
// The OnConflictStrategy.IGNORE strategy ignores a new item if it's primary key is already in the database.
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addTask(todoTask: TodoTask)
@Update
suspend fun updateTask(todoTask: TodoTask)
@Delete
suspend fun deleteTask(todoTask: TodoTask)
@Query("DELETE from todo_table")
suspend fun deleteAllTasks()
// Using Flow or LiveData as return type will ensure you get notified whenever the data in the database changes.
// It is recommended to use Flow in the persistence layer.
// The Room keeps this Flow updated for you, which means you only need to explicitly get the data once.
// Because of the Flow return type, Room also runs the query on the background thread.
// You don't need to explicitly make it a suspend function and call inside a coroutine scope.
@Query("SELECT * from todo_table WHERE id = :taskId")
fun getSelectedTask(taskId: Int): Flow<TodoTask>
@Query("SELECT * from todo_table ORDER BY id ASC")
fun getAllTasks(): Flow<List<TodoTask>>
@Query("SELECT * from todo_table WHERE title LIKE :searchQuery OR description LIKE :searchQuery")
fun searchDatabase(searchQuery:String):Flow<List<TodoTask>>
@Query("SELECT * FROM todo_table ORDER BY CASE WHEN priority LIKE 'L%' THEN 1 WHEN priority LIKE 'M%' THEN 2 WHEN priority LIKE 'H%' THEN 3 END")
fun sortByLowPriority(): Flow<List<TodoTask>>
@Query("SELECT * FROM todo_table ORDER BY CASE WHEN priority LIKE 'H%' THEN 1 WHEN priority LIKE 'M%' THEN 2 WHEN priority LIKE 'L%' THEN 3 END")
fun sortByHighPriority(): Flow<List<TodoTask>>
} | TaskMania_UASMobcom/app/src/main/java/com/example/mytodoappcompose/data/TodoDao.kt | 1782432963 |
package com.example.test_application
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.test_application", appContext.packageName)
}
} | tests_repo/app/src/androidTest/java/com/example/test_application/ExampleInstrumentedTest.kt | 4097549721 |
package com.example.test_application
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)
}
} | tests_repo/app/src/test/java/com/example/test_application/ExampleUnitTest.kt | 980089815 |
package com.example.test_application
import org.junit.Assert.*
import org.junit.Test
class RegistrationUtilTest {
@Test
fun `empty username returns false`() {
val result = RegistrationUtil.validateRegistrationInput(
"",
"123",
"123"
)
assertFalse(result)
}
@Test
fun `valid username and correctly repeated password returns true`() {
val result = RegistrationUtil.validateRegistrationInput(
"Philipp",
"123",
"123"
)
assertTrue(result)
}
@Test
fun `username already exists returns false`() {
val result = RegistrationUtil.validateRegistrationInput(
"Carl",
"123",
"123"
)
assertFalse(result)
}
@Test
fun `incorrectly confirmed password returns false`() {
val result = RegistrationUtil.validateRegistrationInput(
"Philipp",
"123456",
"abcdefg"
)
assertFalse(result)
}
@Test
fun `empty password returns false`() {
val result = RegistrationUtil.validateRegistrationInput(
"Philipp",
"",
""
)
assertFalse(result)
}
@Test
fun `less than 2 digit password returns false`() {
val result = RegistrationUtil.validateRegistrationInput(
"Philipp",
"abcdefg5",
"abcdefg5"
)
assertFalse(result)
}
} | tests_repo/app/src/test/java/com/example/test_application/RegistrationUtilTest.kt | 247658361 |
package com.example.test_application.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) | tests_repo/app/src/main/java/com/example/test_application/ui/theme/Color.kt | 3602650049 |
package com.example.test_application.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 Test_ApplicationTheme(
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
)
} | tests_repo/app/src/main/java/com/example/test_application/ui/theme/Theme.kt | 365424669 |
package com.example.test_application.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
)
*/
) | tests_repo/app/src/main/java/com/example/test_application/ui/theme/Type.kt | 1180897125 |
package com.example.test_application
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.test_application.ui.theme.Test_ApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Test_ApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Test_ApplicationTheme {
Greeting("Android")
}
} | tests_repo/app/src/main/java/com/example/test_application/MainActivity.kt | 20239341 |
package com.example.test_application
object RegistrationUtil {
private val existingUsers = listOf("Peter", "Carl")
/**
* the input is not valid if...
* ...the username/password is empty
* ...the username is already taken
* ...the confirmed password is not the same as the real password
* ...the password contains less than 2 digits
*/
fun validateRegistrationInput(
username: String,
password: String,
confirmedPassword: String
): Boolean {
if(username.isEmpty() || password.isEmpty()) {
return false
}
if(username in existingUsers) {
return false
}
if(password != confirmedPassword) {
return false
}
if(password.count { it.isDigit() } < 2) {
return false
}
return true
}
} | tests_repo/app/src/main/java/com/example/test_application/RegistrationUtil.kt | 205110524 |
package com.example.bmicalculatorviewmodelproject
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.bmicalculatorviewmodelproject", appContext.packageName)
}
} | BMI_Calculator_Veiw_Model_Project/app/src/androidTest/java/com/example/bmicalculatorviewmodelproject/ExampleInstrumentedTest.kt | 2135588481 |
package com.example.bmicalculatorviewmodelproject
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)
}
} | BMI_Calculator_Veiw_Model_Project/app/src/test/java/com/example/bmicalculatorviewmodelproject/ExampleUnitTest.kt | 2907268103 |
package com.example.bmicalculatorviewmodelproject.viewmodel
import androidx.lifecycle.ViewModel
import com.example.bmicalculatorviewmodelproject.ResultFragment
class BmiViewModel: ViewModel() {
var bmi = 0.0
var catagory = ""
fun bmiCalculate(weight: Double, height: Double) {
bmi = weight / ((height / 100) * (height / 100))
catagory = when (String.format("%.1f", bmi).toDouble()) {
in 0.0..18.4 -> underweight
in 18.5..24.9 -> normal
in 25.0..29.9 -> overweight
in 30.0..34.9 -> obesity1
in 35.0..39.9 -> obesity2
else -> obesity3
}
}
companion object {
var underweight = "UNDERWEIGHT"
var normal = "NORMAL"
var overweight = "OVERWEIGHT"
var obesity1 = "OBESITY 1"
var obesity2 = "OBESITY 2"
var obesity3 = "OBESITY 3"
}
} | BMI_Calculator_Veiw_Model_Project/app/src/main/java/com/example/bmicalculatorviewmodelproject/viewmodel/BmiViewModel.kt | 2262821770 |
package com.example.bmicalculatorviewmodelproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | BMI_Calculator_Veiw_Model_Project/app/src/main/java/com/example/bmicalculatorviewmodelproject/MainActivity.kt | 1677779747 |
package com.example.bmicalculatorviewmodelproject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.bmicalculatorviewmodelproject.databinding.FragmentHomeBinding
import com.example.bmicalculatorviewmodelproject.viewmodel.BmiViewModel
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var viewModel: BmiViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(requireActivity()).get(BmiViewModel::class.java)
binding.btn.setOnClickListener {
val weight = binding.weightEtx.text.toString().toDouble()
val height = binding.heightEtx.text.toString().toDouble()
viewModel.bmiCalculate(weight,height)
findNavController().navigate(R.id.result_action)
}
return binding.root
}
} | BMI_Calculator_Veiw_Model_Project/app/src/main/java/com/example/bmicalculatorviewmodelproject/HomeFragment.kt | 1001070436 |
package com.example.bmicalculatorviewmodelproject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import com.example.bmicalculatorviewmodelproject.databinding.FragmentResultBinding
import com.example.bmicalculatorviewmodelproject.viewmodel.BmiViewModel
class ResultFragment : Fragment() {
private lateinit var binding : FragmentResultBinding
private lateinit var viewModel: BmiViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
binding = FragmentResultBinding.inflate(inflater,container,false)
viewModel = ViewModelProvider(requireActivity()).get(BmiViewModel::class.java)
binding.scoreTv.text = String.format("%.1f",viewModel.bmi)
binding.catagoryTv.text = viewModel.catagory
return binding.root
}
} | BMI_Calculator_Veiw_Model_Project/app/src/main/java/com/example/bmicalculatorviewmodelproject/ResultFragment.kt | 3295037418 |
package com.example.myapplication
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.myapplication", appContext.packageName)
}
} | AutomotiveAudioPlayerExample/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
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)
}
} | AutomotiveAudioPlayerExample/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication.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) | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/ui/theme/Color.kt | 2513741509 |
package com.example.myapplication.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 MyApplicationTheme(
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
)
} | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt | 196007232 |
package com.example.myapplication.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
)
*/
) | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/ui/theme/Type.kt | 3481532690 |
package com.example.myapplication
import android.content.ComponentName
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.example.myapplication.ui.theme.MyApplicationTheme
import com.google.common.util.concurrent.MoreExecutors
@UnstableApi
class MainActivity : ComponentActivity() {
private var mediaController: MediaController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column {
Button(onClick = {
val mediaController = mediaController ?: return@Button
if(!mediaController.isConnected) return@Button
mediaController.setMediaItem(PlaybackService.testMediaItem())
mediaController.playWhenReady = true
mediaController.prepare()
}) {
Text(text = "Play")
}
}
}
}
}
}
override fun onStart() {
super.onStart()
val sessionToken = SessionToken(this@MainActivity, ComponentName(this@MainActivity, PlaybackService::class.java))
val controllerFuture = MediaController.Builder(this, sessionToken).buildAsync()
controllerFuture.addListener(
{
mediaController = controllerFuture.get()
},
MoreExecutors.directExecutor()
)
}
override fun onStop() {
mediaController?.release()
mediaController = null
super.onStop()
}
} | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/MainActivity.kt | 3962149135 |
package com.example.myapplication
import androidx.core.net.toUri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.datasource.cache.NoOpCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.session.MediaLibraryService
import androidx.media3.session.MediaSession
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import java.io.File
@UnstableApi
class PlaybackService : MediaLibraryService() {
private lateinit var mediaLibrarySessionCallback: MediaLibrarySessionCallback
private var mediaSession: MediaLibrarySession? = null
override fun onCreate() {
super.onCreate()
val player = ExoPlayer.Builder(this).build()
mediaLibrarySessionCallback = MediaLibrarySessionCallback()
mediaSession = MediaLibrarySession.Builder(this, player, mediaLibrarySessionCallback).build()
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo) = mediaSession
override fun onDestroy() {
mediaSession?.run {
player.release()
release()
mediaSession = null
}
super.onDestroy()
}
companion object {
fun testMediaItem() = MediaItem.Builder()
.setMediaId("id")
.setUri("https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/02_-_Geisha.mp3".toUri())
.setMediaMetadata(
MediaMetadata.Builder()
.setTitle("Test title")
.setArtist("Test artist")
.setIsBrowsable(false)
.setIsPlayable(true)
.setArtworkUri("https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/art.jpg".toUri())
.setMediaType(MediaMetadata.MEDIA_TYPE_MUSIC)
.build()
)
.build()
fun testMediaItems() = mutableListOf(testMediaItem())
}
} | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/PlaybackService.kt | 1032648426 |
package com.example.myapplication
import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.LibraryResult
import androidx.media3.session.MediaLibraryService
import androidx.media3.session.MediaSession
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
@UnstableApi
class MediaLibrarySessionCallback: MediaLibraryService.MediaLibrarySession.Callback {
override fun onGetLibraryRoot(
session: MediaLibraryService.MediaLibrarySession,
browser: MediaSession.ControllerInfo,
params: MediaLibraryService.LibraryParams?
): ListenableFuture<LibraryResult<MediaItem>> {
return Futures.immediateFuture(LibraryResult.ofItem(browsableItem(Root), params))
}
override fun onGetChildren(
session: MediaLibraryService.MediaLibrarySession,
browser: MediaSession.ControllerInfo,
parentId: String,
page: Int,
pageSize: Int,
params: MediaLibraryService.LibraryParams?
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> {
val items = when(parentId) {
Root -> listOf(browsableItem(Playlist))
Playlist -> PlaybackService.testMediaItems()
else -> null
}
return if(items != null) {
Futures.immediateFuture(LibraryResult.ofItemList(items, params))
} else {
Futures.immediateFuture(LibraryResult.ofError(LibraryResult.RESULT_ERROR_BAD_VALUE))
}
}
override fun onGetItem(
session: MediaLibraryService.MediaLibrarySession,
browser: MediaSession.ControllerInfo,
mediaId: String
): ListenableFuture<LibraryResult<MediaItem>> {
val item = when(mediaId) {
Root -> browsableItem(Root)
Playlist -> PlaybackService.testMediaItem()
else -> null
}
return if(item != null) {
Futures.immediateFuture(LibraryResult.ofItem(item, null))
} else {
Futures.immediateFuture(LibraryResult.ofError(LibraryResult.RESULT_ERROR_BAD_VALUE))
}
}
override fun onAddMediaItems(
mediaSession: MediaSession,
controller: MediaSession.ControllerInfo,
mediaItems: MutableList<MediaItem>
): ListenableFuture<MutableList<MediaItem>> {
val items = mediaItems.map {
getItem(it.mediaId) ?: it
}.toMutableList()
return Futures.immediateFuture(items)
}
private fun getItem(mediaId: String): MediaItem? {
val playlist = PlaybackService.testMediaItems()
return playlist.firstOrNull { mediaItem ->
mediaItem.mediaId == mediaId
}
}
private fun browsableItem(title: String): MediaItem {
val metadata = MediaMetadata.Builder()
.setTitle(title)
.setIsBrowsable(true)
.setIsPlayable(false)
.setMediaType(MediaMetadata.MEDIA_TYPE_FOLDER_MIXED)
.build()
return MediaItem.Builder()
.setMediaId(title)
.setMediaMetadata(metadata)
.setSubtitleConfigurations(mutableListOf())
.setUri(Uri.EMPTY)
.build()
}
companion object {
private const val Root = "root"
private const val Playlist = "playlist"
}
} | AutomotiveAudioPlayerExample/app/src/main/java/com/example/myapplication/MediaLibrarySessionCallback.kt | 3129944217 |
package com.example.diceroller
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.diceroller", appContext.packageName)
}
} | Android_Dicee/app/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt | 2731144987 |
package com.example.diceroller
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)
}
} | Android_Dicee/app/src/test/java/com/example/diceroller/ExampleUnitTest.kt | 1412805653 |
package com.example.diceroller.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Android_Dicee/app/src/main/java/com/example/diceroller/ui/theme/Color.kt | 2898381871 |
package com.example.diceroller.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun DiceRollerTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Android_Dicee/app/src/main/java/com/example/diceroller/ui/theme/Theme.kt | 751687589 |
package com.example.diceroller.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Android_Dicee/app/src/main/java/com/example/diceroller/ui/theme/Type.kt | 2881408862 |
package com.example.diceroller
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.StringRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.diceroller.ui.theme.DiceRollerTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DiceRollerTheme {
DiceRollerApp()
}
}
}
}
@Preview
@Composable
fun DiceRollerApp() {
DiceWithButtonAndImage()
}
@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
var result by remember { mutableStateOf(1) }
val imageResource = when (result) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(painter = painterResource(imageResource), contentDescription = result.toString())
Button(onClick = { result = (1..6).random() }) {
Text(stringResource(R.string.roll))
}
}
}
| Android_Dicee/app/src/main/java/com/example/diceroller/MainActivity.kt | 192601733 |
package com.example.hackingprojectjniapp
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.hackingprojectjniapp", appContext.packageName)
}
} | HackingProjectJniApp/app/src/androidTest/java/com/example/hackingprojectjniapp/ExampleInstrumentedTest.kt | 1993515220 |
package com.example.hackingprojectjniapp
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)
}
} | HackingProjectJniApp/app/src/test/java/com/example/hackingprojectjniapp/ExampleUnitTest.kt | 1118881579 |
package com.example.hackingprojectjniapp
import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.webkit.CookieManager
import android.webkit.JavascriptInterface
import android.webkit.URLUtil
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.hackingprojectjniapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
val STORAGE = "storage"
private var filePathCallback: ValueCallback<Array<Uri>>? = null
private val fileRequestCode = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
val myWebView: WebView = findViewById(R.id.webview)
myWebView.settings.javaScriptEnabled = true
myWebView.settings.domStorageEnabled = true
myWebView.webViewClient = WebViewClient()
myWebView.webChromeClient = object : WebChromeClient() {
// For Android 5.0+
override fun onShowFileChooser(
webView: WebView?,
filePathCallback: ValueCallback<Array<Uri>>,
fileChooserParams: FileChooserParams
): Boolean {
[email protected]?.onReceiveValue(null)
[email protected] = filePathCallback
val intent = fileChooserParams.createIntent()
try {
startActivityForResult(intent, fileRequestCode)
} catch (e: Exception) {
[email protected] = null
return false
}
return true
}
}
// myWebView.loadUrl("http://16.16.238.235:8080/noticewrite")
myWebView.loadUrl("http://10.0.2.2:3001")
myWebView.addJavascriptInterface(WebAppInterface(this), "Android")
myWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
val request = DownloadManager.Request(Uri.parse(url))
var fileName = contentDisposition
if (fileName != null && fileName.isNotEmpty()) {
val idxFileName = fileName.indexOf("filename=")
if (idxFileName > -1) {
fileName = fileName.substring(idxFileName + 9).trim { it <= ' ' }
}
if (fileName.endsWith(";")) {
fileName = fileName.substring(0, fileName.length - 1)
}
if (fileName.startsWith("\"") && fileName.startsWith("\"")) {
fileName = fileName.substring(1, fileName.length - 1)
}
} else {
// 파일명(확장자포함) 확인이 안되었을 때 기존방식으로 진행
fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)
}
val adjustedMimeType = if (mimetype.isNullOrEmpty() || mimetype == "application/octet-stream") {
guessMimeTypeFromUrl(url)
} else {
mimetype
}
request.setMimeType(adjustedMimeType)
val cookies = CookieManager.getInstance().getCookie(url)
request.addRequestHeader("cookie", cookies)
request.addRequestHeader("User-Agent", userAgent)
request.setDescription("Downloading file...")
request.setTitle(fileName)
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
fileName
)
val dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
dm.enqueue(request)
Toast.makeText(applicationContext, "다운로드 파일", Toast.LENGTH_LONG).show()
}
// 여기가 C++ 관련 코드!!!
// binding = ActivityMainBinding.inflate(layoutInflater)
// setContentView(binding.root)
//
// // Example of a call to a native method
// binding.sampleText.text = stringFromJNI()
}
fun guessMimeTypeFromUrl(url: String): String {
// URL에서 파일 확장자 추출 및 MIME 타입 추측 로직 구현
// 이 부분은 실제 파일 유형과 URL 구조에 따라 달라질 수 있음
return when {
url.endsWith(".jpg") || url.endsWith(".jpeg") -> "image/jpeg"
url.endsWith(".png") -> "image/png"
url.endsWith(".apk") -> "application/vnd.android.package-archive"
// 기타 다른 파일 확장자에 대한 처리
else -> "application/octet-stream"
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == fileRequestCode) {
if (resultCode == Activity.RESULT_OK) {
val result = if (data == null || resultCode != Activity.RESULT_OK) null else data.data
filePathCallback?.onReceiveValue(arrayOf(Uri.parse(result.toString())))
} else {
filePathCallback?.onReceiveValue(null)
}
filePathCallback = null
}
}
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val myWebView: WebView = findViewById(R.id.webview)
if(myWebView.canGoBack()){
myWebView.goBack()
}
else {
finish()
}
}
}
class WebAppInterface(private val mContext : Context) {
@JavascriptInterface
fun saveMobileStorage(key:String,value:String){
(mContext as MainActivity).writeJwtSharedPreference(key,value)
}
@JavascriptInterface
fun loadMobileStorage(key:String):String{
val mobileVal = (mContext as MainActivity).readJwtSharedPreference(key)
return mobileVal
}
}
fun writeJwtSharedPreference(key:String,value:String) {
val sp = getSharedPreferences(STORAGE,Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putString(key,value)
editor.apply()
}
fun readJwtSharedPreference(key:String):String{
val sp = getSharedPreferences(STORAGE,Context.MODE_PRIVATE)
return sp.getString(key,"") ?: ""
}
/**
* A native method that is implemented by the 'hackingprojectjniapp' native library,
* which is packaged with this application.
*/
// 여기 아래부터 C++ 관련 코드!!!
external fun stringFromJNI(): String
companion object {
// Used to load the 'hackingprojectjniapp' library on application startup.
init {
System.loadLibrary("hackingprojectjniapp")
}
}
} | HackingProjectJniApp/app/src/main/java/com/example/hackingprojectjniapp/MainActivity.kt | 4013206189 |
package com.example.lesson107
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.lesson107", appContext.packageName)
}
} | LearnGit/app/src/androidTest/java/com/example/lesson107/ExampleInstrumentedTest.kt | 4105329618 |
package com.example.lesson107
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)
}
} | LearnGit/app/src/test/java/com/example/lesson107/ExampleUnitTest.kt | 1075884795 |
package com.example.lesson107.ui.home.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lesson107.data.model.Country
import com.example.lesson107.data.source.CountryDataRepository
import com.example.lesson107.data.source.CountryDataSource
import com.example.lesson107.data.source.ResponseResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class CountryViewModel(
private val repository: CountryDataRepository
): ViewModel() {
private val _countries = MutableLiveData<List<Country>>()
val countries: LiveData<List<Country>> = _countries
init {
loadData()
}
@Suppress("unchecked_cast")
private fun loadData() {
viewModelScope.launch(Dispatchers.IO) {
val callback = object : CountryDataSource.DataSourceCallback{
override fun onCompleted(result: ResponseResult) {
if (result is ResponseResult.Success<*>){
val data = (result as ResponseResult.Success<List<Country>>).data
_countries.value = data
}else{
_countries.value = emptyList()
}
}
}
repository.loadData(callback)
}
}
fun cacheData(){
viewModelScope.launch(Dispatchers.IO) {
if (!_countries.value.isNullOrEmpty()){
repository.cacheData(_countries.value!!)
}
}
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/home/viewmodel/CountryViewModel.kt | 2335794245 |
package com.example.lesson107.ui.home.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.lesson107.data.source.CountryDataRepository
class CountryViewModelFactory(
private val repository: CountryDataRepository
): ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(CountryViewModel::class.java)){
return CountryViewModel(repository) as T
}else{
throw IllegalArgumentException("Argument is not class CountryViewModel")
}
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/home/viewmodel/CountryViewModelFactory.kt | 3978612900 |
package com.example.lesson107.ui.home.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.lesson107.R
import com.example.lesson107.data.model.Country
import com.example.lesson107.databinding.ItemCountryBinding
import com.example.lesson107.utils.CountryUtils
class CountryAdapter(
private val countries: MutableList<Country> = mutableListOf(),
private val listener: OnItemClickListener
) : RecyclerView.Adapter<CountryAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding: ItemCountryBinding = ItemCountryBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return countries.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val country = countries[position]
holder.bindData(country, listener)
}
@SuppressLint("NotifyDataSetChanged")
fun updateData(countries: List<Country>) {
this.countries.clear()
this.countries.addAll(countries)
notifyDataSetChanged()
}
class ViewHolder(
private val binding: ItemCountryBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bindData(country: Country, listener: OnItemClickListener) {
binding.textItemName.text = country.countryName
binding.textItemCapital.text = country.capital
val imageUrl = CountryUtils.BASE_URL + CountryUtils.IMAGE_URL + country.flag
Glide.with(binding.root.context)
.load(imageUrl)
.error(R.drawable.vietnam)
.into(binding.imageItemFlag)
binding.root.setOnClickListener {
listener.onItemClick(country)
}
}
}
interface OnItemClickListener {
fun onItemClick(country: Country)
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/home/adapter/CountryAdapter.kt | 1231767072 |
package com.example.lesson107.ui.home
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import com.example.lesson107.R
import com.example.lesson107.data.model.Country
import com.example.lesson107.data.source.CountryDataRepository
import com.example.lesson107.data.source.local.CountryDatabase
import com.example.lesson107.data.source.local.LocalDataSource
import com.example.lesson107.data.source.remote.RemoteDataSource
import com.example.lesson107.databinding.FragmentHomeBinding
import com.example.lesson107.ui.detail.DetailFragment
import com.example.lesson107.ui.detail.viewmodel.CountryItemViewModel
import com.example.lesson107.ui.home.adapter.CountryAdapter
import com.example.lesson107.ui.home.viewmodel.CountryViewModel
import com.example.lesson107.ui.home.viewmodel.CountryViewModelFactory
import com.example.lesson107.utils.CountryUtils
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var adapter: CountryAdapter
private lateinit var countryViewModel: CountryViewModel
private lateinit var shareViewModel: CountryItemViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.toolbarHome.title = getString(R.string.title_home)
setupViews()
setupViewModel()
}
override fun onPause() {
super.onPause()
countryViewModel.cacheData()
}
private fun setupViews() {
val callback = object : CountryAdapter.OnItemClickListener {
override fun onItemClick(country: Country) {
shareViewModel.updateSelectedCountry(country)
switchToDetailFragment()
}
}
adapter = CountryAdapter(listener = callback)
binding.recyclerCountry.adapter = adapter
val divider = DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
AppCompatResources.getDrawable(
requireContext(),
R.drawable.list_divider
)
?.let { divider.setDrawable(it) }
binding.recyclerCountry.addItemDecoration(divider)
}
private fun switchToDetailFragment() {
parentFragmentManager.beginTransaction()
.replace(R.id.fragmentContainerView, DetailFragment::class.java, null)
.addToBackStack(null)
.setReorderingAllowed(true)
.commit()
}
private fun setupViewModel() {
val localDataSource = LocalDataSource(CountryDatabase.instance(requireContext()))
val remoteDataSource = RemoteDataSource()
val selectedDataSource = CountryUtils.checkInternetState(requireContext())
val repository = CountryDataRepository.Builder()
.setLocalDataSource(localDataSource)
.setRemoteDataSource(remoteDataSource)
.setSelectedDataSource(selectedDataSource)
.build()
CountryUtils.selectedDataSource = selectedDataSource
countryViewModel = ViewModelProvider(
this,
CountryViewModelFactory(repository)
)[CountryViewModel::class.java]
countryViewModel.countries.observe(viewLifecycleOwner){
adapter.updateData(it)
}
shareViewModel = ViewModelProvider(requireActivity())[CountryItemViewModel::class.java]
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/home/HomeFragment.kt | 2678508617 |
package com.example.lesson107.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.lesson107.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/MainActivity.kt | 4283430098 |
package com.example.lesson107.ui.detail.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.lesson107.data.model.Country
class CountryItemViewModel: ViewModel() {
private val _country = MutableLiveData<Country>()
val country: LiveData<Country> = _country
fun updateSelectedCountry(country: Country){
_country.value = country
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/detail/viewmodel/CountryItemViewModel.kt | 2523903951 |
package com.example.lesson107.ui.detail
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.example.lesson107.R
import com.example.lesson107.data.model.Country
import com.example.lesson107.databinding.FragmentDetailBinding
import com.example.lesson107.ui.detail.viewmodel.CountryItemViewModel
import com.example.lesson107.utils.CountryUtils
class DetailFragment : Fragment() {
private lateinit var binding: FragmentDetailBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupToolBar()
setupViewModel()
}
private fun setupToolBar(){
binding.toolbarDetail.setNavigationIcon(R.drawable.ic_up)
binding.toolbarDetail.setNavigationOnClickListener {
requireActivity().onBackPressedDispatcher.onBackPressed()
}
}
private fun setupViewModel(){
val viewModel = ViewModelProvider(requireActivity())[CountryItemViewModel::class.java]
viewModel.country.observe(viewLifecycleOwner){
showCountryDetail(it)
}
}
private fun showCountryDetail(country : Country) {
val countryName = getString(R.string.title_nation_detail, country.countryName)
val capital = getString(R.string.title_capital_detail, country.capital)
val population = getString(
R.string.title_population,
CountryUtils.formatNumber(country.population)
)
val area = getString(
R.string.title_area,
CountryUtils.formatNumber(country.area.toFloat())
)
val worldShare = getString(R.string.title_world_share, country.worldShare)
val density = getString(
R.string.title_density,
CountryUtils.formatNumber(country.density.toFloat())
)
// đổ dữ liệu lên view
binding.toolbarDetail.title = country.countryName
binding.textNationName.text = countryName
binding.textCapitalDetail.text = capital
binding.textPopulation.text = population
binding.textArea.text = area
binding.textWorldShare.text = worldShare
binding.textDensity.text = density
val imageUrl = CountryUtils.BASE_URL + CountryUtils.IMAGE_URL + country.flag
Glide.with(this)
.load(imageUrl)
.error(R.drawable.vietnam)
.into(binding.imageFlag)
}
} | LearnGit/app/src/main/java/com/example/lesson107/ui/detail/DetailFragment.kt | 3966796033 |
package com.example.lesson107.utils
import android.content.Context
import android.net.ConnectivityManager
import com.example.lesson107.data.source.SelectedDataSource
import java.text.DecimalFormat
object CountryUtils {
const val BASE_URL = "https://thantrieu.com/"
const val IMAGE_URL = "resources/images/"
var selectedDataSource = SelectedDataSource.REMOTE
fun checkInternetState(context: Context): SelectedDataSource {
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (connMgr.activeNetwork == null) {
SelectedDataSource.LOCAL
} else {
SelectedDataSource.REMOTE
}
}
fun formatNumber(number: Float): String {
val decimalFormat = DecimalFormat("#,###.#")
return decimalFormat.format(number)
}
// upload to git
} | LearnGit/app/src/main/java/com/example/lesson107/utils/CountryUtils.kt | 418051001 |
package com.example.lesson107.data.source
import java.lang.Exception
abstract class ResponseResult {
class Success<T>(val data: T): ResponseResult()
class Error(exception: Exception): ResponseResult()
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/ResponseResult.kt | 694096005 |
package com.example.lesson107.data.source
import com.example.lesson107.data.model.Country
import com.example.lesson107.data.source.local.LocalDataSource
import com.example.lesson107.data.source.remote.RemoteDataSource
class CountryDataRepository(builder: Builder) {
private val selectedDataSource: SelectedDataSource
private val localDataSource: LocalDataSource
private val remoteDataSource: RemoteDataSource
init {
selectedDataSource = builder.selectedDataSource
localDataSource = builder.localDataSource
remoteDataSource = builder.remoteDataSource
}
suspend fun loadData(callback: CountryDataSource.DataSourceCallback) {
if (selectedDataSource == SelectedDataSource.LOCAL) {
localDataSource.loadData(callback)
} else {
remoteDataSource.loadData(callback)
}
}
suspend fun cacheData(data: List<Country>){
localDataSource.clearDatabase()
localDataSource.updateDatabase(data)
}
class Builder {
lateinit var selectedDataSource: SelectedDataSource
lateinit var localDataSource: LocalDataSource
lateinit var remoteDataSource: RemoteDataSource
fun setLocalDataSource(localDataSource: LocalDataSource): Builder {
this.localDataSource = localDataSource
return this
}
fun setRemoteDataSource(remoteDataSource: RemoteDataSource): Builder {
this.remoteDataSource = remoteDataSource
return this
}
fun setSelectedDataSource(selectedDataSource: SelectedDataSource): Builder {
this.selectedDataSource = selectedDataSource
return this
}
fun build(): CountryDataRepository {
return CountryDataRepository(this)
}
}
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/CountryDataRepository.kt | 2263472056 |
package com.example.lesson107.data.source.local
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.lesson107.data.model.Country
@Database(entities = [Country::class], version = 1)
abstract class CountryDatabase : RoomDatabase() {
abstract val countryDao: CountryDao
companion object {
private var _instance: CountryDatabase? = null
@JvmStatic
fun instance(context: Context): CountryDatabase? {
if (_instance == null) {
_instance = Room.databaseBuilder(
context.applicationContext,
CountryDatabase::class.java,
"country_db.db"
).build()
}
return _instance
}
}
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/local/CountryDatabase.kt | 3736214254 |
package com.example.lesson107.data.source.local
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.lesson107.data.model.Country
@Dao
interface CountryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg countries: Country)
@Query("DELETE FROM countries")
suspend fun clearAll()
@Query("SELECT * FROM countries")
suspend fun all(): List<Country>
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/local/CountryDao.kt | 877250623 |
package com.example.lesson107.data.source.local
import com.example.lesson107.data.model.Country
import com.example.lesson107.data.source.CountryDataSource
import com.example.lesson107.data.source.ResponseResult
class LocalDataSource(private val database: CountryDatabase?): CountryDataSource {
override suspend fun loadData(callback: CountryDataSource.DataSourceCallback) {
val data = database?.countryDao?.all()
val result = ResponseResult.Success(data)
callback.onCompleted(result)
}
suspend fun clearDatabase(){
database?.countryDao?.clearAll()
}
suspend fun updateDatabase(countries: List<Country>){
for (country in countries){
database?.countryDao?.insert(country)
}
}
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/local/LocalDataSource.kt | 827234939 |
package com.example.lesson107.data.source
interface CountryDataSource {
suspend fun loadData(callback: DataSourceCallback)
interface DataSourceCallback{
fun onCompleted(result: ResponseResult)
}
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/CountryDataSource.kt | 2619440740 |
package com.example.lesson107.data.source
enum class SelectedDataSource {
LOCAL,
REMOTE
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/SelectedDataSource.kt | 3112213746 |
package com.example.lesson107.data.source.remote
import com.example.lesson107.data.model.Country
import com.example.lesson107.data.source.CountryDataSource
import com.example.lesson107.data.source.ResponseResult
import com.example.lesson107.utils.CountryUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import java.lang.Exception
class RemoteDataSource: CountryDataSource {
override suspend fun loadData(callback: CountryDataSource.DataSourceCallback) {
val service = createRetrofitObject()
val countryListCall = service.countryData
countryListCall.enqueue(object : Callback<List<Country>>{
override fun onResponse(call: Call<List<Country>>, response: Response<List<Country>>) {
if (response.body() != null){
callback.onCompleted(ResponseResult.Success(response.body()))
}
}
override fun onFailure(call: Call<List<Country>>, t: Throwable) {
callback.onCompleted(ResponseResult.Error(Exception(t.message)))
}
})
}
private fun createRetrofitObject(): CountryService{
val retrofit = Retrofit.Builder()
.baseUrl(CountryUtils.BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build()
return retrofit.create(CountryService::class.java)
}
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/remote/RemoteDataSource.kt | 2376801458 |
package com.example.lesson107.data.source.remote
import com.example.lesson107.data.model.Country
import retrofit2.Call
import retrofit2.http.GET
interface CountryService {
@get:GET("resources/braniumapis/country.json")
val countryData: Call<List<Country>>
} | LearnGit/app/src/main/java/com/example/lesson107/data/source/remote/CountryService.kt | 3840929122 |
package com.example.lesson107.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.fasterxml.jackson.annotation.JsonProperty
@Entity(tableName = "countries")
data class Country(
@PrimaryKey
@ColumnInfo("country_id")
@JsonProperty("id")
val countryId: Int = 0,
@ColumnInfo("country_name")
@JsonProperty("name")
val countryName: String = "",
@ColumnInfo("country_capital")
@JsonProperty("capital")
val capital: String = "",
@ColumnInfo("country_flag")
@JsonProperty("flag")
val flag: String = "",
@ColumnInfo("country_population")
@JsonProperty("population")
val population: Float = 0f,
@ColumnInfo("country_area")
@JsonProperty("area")
val area: Int = 0,
@ColumnInfo("country_density")
@JsonProperty("density")
val density: Int = 0,
@ColumnInfo("country_world_share")
@JsonProperty("world_share")
val worldShare: String = ""
)
| LearnGit/app/src/main/java/com/example/lesson107/data/model/Country.kt | 1397318573 |
package com.thecode.aestheticdialogs
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.thecode.aestheticdialogs", appContext.packageName)
}
} | AestheticDialogs/aestheticdialogs/src/androidTest/java/com/thecode/aestheticdialogs/ExampleInstrumentedTest.kt | 3657409178 |
package com.thecode.aestheticdialogs
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)
}
} | AestheticDialogs/aestheticdialogs/src/test/java/com/thecode/aestheticdialogs/ExampleUnitTest.kt | 705870716 |
package com.thecode.aestheticdialogs
interface OnDialogClickListener {
fun onClick(dialog: AestheticDialog.Builder)
} | AestheticDialogs/aestheticdialogs/src/main/java/com/thecode/aestheticdialogs/OnDialogClickListener.kt | 2252868375 |
package com.thecode.aestheticdialogs
import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.annotation.Keep
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import com.thecode.aestheticdialogs.databinding.DialogConnectifyErrorBinding
import com.thecode.aestheticdialogs.databinding.DialogConnectifySuccessBinding
import com.thecode.aestheticdialogs.databinding.DialogEmojiBinding
import com.thecode.aestheticdialogs.databinding.DialogEmotionBinding
import com.thecode.aestheticdialogs.databinding.DialogFlashBinding
import com.thecode.aestheticdialogs.databinding.DialogFlatBinding
import com.thecode.aestheticdialogs.databinding.DialogRainbowBinding
import com.thecode.aestheticdialogs.databinding.DialogToasterBinding
import java.text.SimpleDateFormat
import java.util.Calendar
/**
* Aesthetic Dialog class
* Use Builder to create a new instance.
*
* @author Gabriel The Code
*/
@Keep
class AestheticDialog {
class Builder(
//Necessary parameters
private val activity: Activity,
private val dialogStyle: DialogStyle,
private val dialogType: DialogType
) {
private lateinit var alertDialog: AlertDialog
private val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(activity)
private var title: String = "Title"
private var message: String = "Message"
// Optional features
private var isDarkMode: Boolean = false
private var isCancelable: Boolean = true
private var duration: Int = 0
private var gravity: Int = Gravity.NO_GRAVITY
private var animation: DialogAnimation = DialogAnimation.DEFAULT
private lateinit var layoutView: View
private var onClickListener: OnDialogClickListener = object : OnDialogClickListener {
override fun onClick(dialog: Builder) {
dialog.dismiss()
}
}
/**
* Set dialog title text
*
* @param title
* @return this, for chaining.
*/
fun setTitle(title: String): Builder {
this.title = title
return this
}
/**
* Set dialog message text
*
* @param message
* @return this, for chaining.
*/
fun setMessage(message: String): Builder {
this.message = message
return this
}
/**
* Set dialog mode. Defined by default to false
*
* @param isDarkMode
* @return this, for chaining.
*/
fun setDarkMode(isDarkMode: Boolean): Builder {
this.isDarkMode = isDarkMode
return this
}
/**
* Set an OnClickListener to the dialog
*
* @param onDialogClickListener interface for callback event on click of button.
* @return this, for chaining.
*/
fun setOnClickListener(onDialogClickListener: OnDialogClickListener): Builder {
this.onClickListener = onDialogClickListener
return this
}
/**
* Define if the dialog is cancelable
*
* @param isCancelable
* @return this, for chaining.
*/
fun setCancelable(isCancelable: Boolean): Builder {
this.isCancelable = isCancelable
return this
}
/**
* Define the display duration of the dialog
*
* @param duration in milliseconds
* @return this, for chaining.
*/
fun setDuration(duration: Int): Builder {
if (duration != 0) {
this.duration = duration
Handler(Looper.getMainLooper()).postDelayed({
this.dismiss()
}, duration.toLong())
}
return this
}
/**
* Set the gravity of the dialog
*
* @param gravity in milliseconds
* @return this, for chaining.
*/
fun setGravity(gravity: Int): Builder {
this.gravity = gravity
return this
}
/**
* Set the animation of the dialog
*
* @param animation in milliseconds
* @return this, for chaining.
*/
fun setAnimation(animation: DialogAnimation): Builder {
this.animation = animation
return this
}
/**
* Dismiss the dialog
*
* @return Aesthetic Dialog instance.
*/
fun dismiss(): AestheticDialog {
if (alertDialog.isShowing) {
alertDialog.dismiss()
}
return AestheticDialog()
}
/**
* Choose the dialog animation according to the parameter
*
*/
private fun chooseAnimation() {
alertDialog.window?.attributes?.apply {
when (animation) {
DialogAnimation.ZOOM -> {
windowAnimations = R.style.DialogAnimationZoom
}
DialogAnimation.FADE -> {
windowAnimations = R.style.DialogAnimationFade
}
DialogAnimation.CARD -> {
windowAnimations = R.style.DialogAnimationCard
}
DialogAnimation.SHRINK -> {
windowAnimations = R.style.DialogAnimationShrink
}
DialogAnimation.SWIPE_LEFT -> {
windowAnimations = R.style.DialogAnimationSwipeLeft
}
DialogAnimation.SWIPE_RIGHT -> {
windowAnimations = R.style.DialogAnimationSwipeRight
}
DialogAnimation.IN_OUT -> {
windowAnimations = R.style.DialogAnimationInOut
}
DialogAnimation.SPIN -> {
windowAnimations = R.style.DialogAnimationSpin
}
DialogAnimation.SPLIT -> {
windowAnimations = R.style.DialogAnimationSplit
}
DialogAnimation.DIAGONAL -> {
windowAnimations = R.style.DialogAnimationDiagonal
}
DialogAnimation.WINDMILL -> {
windowAnimations = R.style.DialogAnimationWindMill
}
DialogAnimation.SLIDE_UP -> {
windowAnimations = R.style.DialogAnimationSlideUp
}
DialogAnimation.SLIDE_DOWN -> {
windowAnimations = R.style.DialogAnimationSlideDown
}
DialogAnimation.SLIDE_LEFT -> {
windowAnimations = R.style.DialogAnimationSlideLeft
}
DialogAnimation.SLIDE_RIGHT -> {
windowAnimations = R.style.DialogAnimationSlideRight
}
DialogAnimation.DEFAULT -> {
windowAnimations = R.style.DialogAnimation
}
}
}
}
/**
* Displays the dialog according to the parameters of the Builder
*
* @return Aesthetic Dialog instance.
*/
fun show(): AestheticDialog {
when (dialogStyle) {
DialogStyle.EMOJI -> {
layoutView = activity.layoutInflater.inflate(R.layout.dialog_emoji, null)
DialogEmojiBinding.bind(layoutView).apply {
textMessageEmoji.text = message
textTitleEmoji.text = title
if (dialogType == DialogType.SUCCESS) {
textTitleEmoji.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_success
)
)
dialogIconEmoji.setImageResource(R.drawable.thumbs_up_sign)
} else {
textTitleEmoji.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_error
)
)
dialogIconEmoji.setImageResource(R.drawable.man_shrugging)
}
if (isDarkMode) {
textMessageEmoji.setTextColor(
ContextCompat.getColor(
activity,
R.color.md_white_1000
)
)
dialogLayoutEmoji.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dark_background
)
)
}
imageCloseEmoji.setOnClickListener { onClickListener.onClick(this@Builder) }
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.TOP)
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
activity.resources.getDimensionPixelSize(R.dimen.popup_height_emoji_dialog)
)
}
}
}
}
DialogStyle.DRAKE -> {
layoutView = if (dialogType == DialogType.SUCCESS) {
activity.layoutInflater.inflate(R.layout.dialog_drake_success, null)
} else {
activity.layoutInflater.inflate(R.layout.dialog_drake_error, null)
}
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setGravity(Gravity.CENTER)
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
activity.resources.getDimensionPixelSize(R.dimen.popup_height_drake)
)
}
}
}
DialogStyle.TOASTER -> {
val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(activity)
layoutView = activity.layoutInflater.inflate(R.layout.dialog_toaster, null)
DialogToasterBinding.bind(layoutView).apply {
textMessageToaster.text = message
textTitleToaster.text = title
imageCloseToaster.setOnClickListener { onClickListener.onClick(this@Builder) }
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setGravity(Gravity.TOP)
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
activity.resources.getDimensionPixelSize(R.dimen.popup_height_toaster)
)
}
}
when (dialogType) {
DialogType.ERROR -> {
textTitleToaster.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_error
)
)
verticalViewToaster.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_error
)
)
dialogIconToaster.setImageResource(R.drawable.ic_error_red_24dp)
}
DialogType.SUCCESS -> {
textTitleToaster.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_success
)
)
verticalViewToaster.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_success
)
)
dialogIconToaster.setImageResource(R.drawable.ic_check_circle_green_24dp)
}
DialogType.WARNING -> {
textTitleToaster.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_warning
)
)
verticalViewToaster.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_warning
)
)
dialogIconToaster.setImageResource(R.drawable.ic_warning_orange_24dp)
}
DialogType.INFO -> {
textTitleToaster.setTextColor(
ContextCompat.getColor(
activity,
R.color.dialog_info
)
)
verticalViewToaster.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_info
)
)
dialogIconToaster.setImageResource(R.drawable.ic_info_blue_24dp)
}
}
if (isDarkMode) {
dialogLayoutToaster.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dark_background
)
)
textMessageToaster.setTextColor(
ContextCompat.getColor(
activity,
R.color.md_white_1000
)
)
}
}
}
DialogStyle.RAINBOW -> {
layoutView = activity.layoutInflater.inflate(R.layout.dialog_rainbow, null)
DialogRainbowBinding.bind(layoutView).apply {
when (dialogType) {
DialogType.ERROR -> {
dialogLayoutRainbow.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_error
)
)
dialogIconRainbow.setImageResource(R.drawable.ic_error_red_24dp)
}
DialogType.SUCCESS -> {
dialogLayoutRainbow.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_success
)
)
dialogIconRainbow.setImageResource(R.drawable.ic_check_circle_green_24dp)
}
DialogType.WARNING -> {
dialogLayoutRainbow.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_warning
)
)
dialogIconRainbow.setImageResource(R.drawable.ic_warning_orange_24dp)
}
DialogType.INFO -> {
dialogLayoutRainbow.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dialog_info
)
)
dialogIconRainbow.setImageResource(R.drawable.ic_info_blue_24dp)
}
}
textMessageRainbow.text = message
textTitleRainbow.text = title
imageCloseRainbow.setOnClickListener { onClickListener.onClick(this@Builder) }
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setGravity(Gravity.TOP)
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
activity.resources.getDimensionPixelSize(R.dimen.popup_height_emoji_dialog)
)
}
}
}
}
DialogStyle.CONNECTIFY -> {
val imgClose: AppCompatImageView
val textTitle: AppCompatTextView
val textMessage: AppCompatTextView
val layoutDialog: LinearLayoutCompat
if (dialogType == DialogType.SUCCESS) {
layoutView = activity.layoutInflater.inflate(
R.layout.dialog_connectify_success,
null
)
val binding = DialogConnectifySuccessBinding.bind(layoutView)
binding.apply {
layoutDialog = dialogLayoutConnectifySuccess
imgClose = imageCloseConnectifySuccess
textTitle = textTitleConnectifySuccess
textMessage = textMessageConnectifySuccess
}
} else {
layoutView =
activity.layoutInflater.inflate(R.layout.dialog_connectify_error, null)
val binding = DialogConnectifyErrorBinding.bind(layoutView)
binding.apply {
layoutDialog = dialogLayoutConnectifyError
imgClose = imageCloseConnectifyError
textTitle = textTitleConnectifyError
textMessage = textMessageConnectifyError
}
}
textTitle.text = title
textMessage.text = message
imgClose.setOnClickListener { onClickListener.onClick(this@Builder) }
if (isDarkMode) {
layoutDialog.setBackgroundColor(
ContextCompat.getColor(
activity,
R.color.dark_background
)
)
textMessage.setTextColor(
ContextCompat.getColor(
activity,
R.color.md_white_1000
)
)
}
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.TOP)
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
}
}
}
DialogStyle.FLASH -> {
layoutView = activity.layoutInflater.inflate(R.layout.dialog_flash, null)
val binding = DialogFlashBinding.bind(layoutView)
binding.apply {
if (dialogType == DialogType.SUCCESS) {
dialogFrameFlash.setBackgroundResource(R.drawable.rounded_green_gradient_bg)
imgIconFlash.setImageResource(R.drawable.circle_validation_success)
} else {
dialogFrameFlash.setBackgroundResource(R.drawable.rounded_red_gradient_bg)
imgIconFlash.setImageResource(R.drawable.circle_validation_error)
}
dialogMessageFlash.text = message
dialogTitleFlash.text = title
btnActionFlash.setOnClickListener { onClickListener.onClick(this@Builder) }
dialogBuilder.setView(binding.root)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.CENTER)
setLayout(
activity.resources.getDimensionPixelSize(R.dimen.popup_width),
activity.resources.getDimensionPixelSize(R.dimen.popup_height)
)
}
}
}
}
DialogStyle.EMOTION -> {
layoutView = activity.layoutInflater.inflate(R.layout.dialog_emotion, null)
val binding = DialogEmotionBinding.bind(layoutView)
binding.apply {
if (dialogType == DialogType.SUCCESS) {
imgIconEmotion.setImageResource(R.drawable.smiley_success)
dialogLayoutEmotion.setBackgroundResource(R.drawable.background_emotion_success)
} else {
imgIconEmotion.setImageResource(R.drawable.smiley_error)
dialogLayoutEmotion.setBackgroundResource(R.drawable.background_emotion_error)
}
val sdf = SimpleDateFormat("HH:mm")
val hour = sdf.format(Calendar.getInstance().time)
dialogMessageEmotion.text = message
dialogTitleEmotion.text = title
dialogHourEmotion.text = hour
dialogBuilder.setView(binding.root)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.CENTER)
setLayout(
WindowManager.LayoutParams.WRAP_CONTENT,
activity.resources.getDimensionPixelSize(R.dimen.popup_height_emotion)
)
}
}
}
}
DialogStyle.FLAT -> {
layoutView = activity.layoutInflater.inflate(R.layout.dialog_flat, null)
DialogFlatBinding.bind(layoutView).apply {
dialogMessageFlat.text = message
dialogTitleFlat.text = title
btnActionFlat.setOnClickListener { onClickListener.onClick(this@Builder) }
when (dialogType) {
DialogType.ERROR -> {
dialogIconFlat.setImageResource(R.drawable.ic_error_red_24dp)
btnActionFlat.setBackgroundResource(R.drawable.btn_red_selector)
dialogFrameFlat.setBackgroundResource(R.drawable.rounded_rect_red)
}
DialogType.SUCCESS -> {
dialogIconFlat.setImageResource(R.drawable.ic_check_circle_green_24dp)
btnActionFlat.setBackgroundResource(R.drawable.btn_green_selector)
dialogFrameFlat.setBackgroundResource(R.drawable.rounded_rect_green)
}
DialogType.WARNING -> {
dialogIconFlat.setImageResource(R.drawable.ic_warning_orange_24dp)
btnActionFlat.setBackgroundResource(R.drawable.btn_yellow_selector)
dialogFrameFlat.setBackgroundResource(R.drawable.rounded_rect_yellow)
}
DialogType.INFO -> {
dialogIconFlat.setImageResource(R.drawable.ic_info_blue_24dp)
btnActionFlat.setBackgroundResource(R.drawable.btn_blue_selector)
dialogFrameFlat.setBackgroundResource(R.drawable.rounded_rect_blue)
}
}
if (isDarkMode) {
dialogLayoutFlat.setBackgroundResource(R.drawable.rounded_dark_bg)
dialogTitleFlat.setTextColor(
ContextCompat.getColor(
activity,
R.color.md_white_1000
)
)
dialogMessageFlat.setTextColor(
ContextCompat.getColor(
activity,
R.color.md_white_1000
)
)
dialogMessageFlat.text = message
dialogTitleFlat.text = title
btnActionFlat.setOnClickListener { onClickListener.onClick(this@Builder) }
}
}
dialogBuilder.setView(layoutView)
alertDialog = dialogBuilder.create()
alertDialog.apply {
chooseAnimation()
show()
window?.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.CENTER)
setLayout(
activity.resources.getDimensionPixelSize(R.dimen.popup_width),
activity.resources.getDimensionPixelSize(R.dimen.popup_height)
)
}
}
}
}
alertDialog.setCancelable(isCancelable)
if (gravity != Gravity.NO_GRAVITY) {
alertDialog.window?.setGravity(gravity)
}
return AestheticDialog()
}
}
}
enum class DialogAnimation {
DEFAULT,
SLIDE_UP, SLIDE_DOWN,
SLIDE_LEFT, SLIDE_RIGHT,
SWIPE_LEFT, SWIPE_RIGHT,
IN_OUT, CARD, SHRINK, SPLIT, DIAGONAL, SPIN, WINDMILL, FADE, ZOOM
}
enum class DialogStyle {
EMOJI, DRAKE, TOASTER, CONNECTIFY, FLAT, RAINBOW, FLASH, EMOTION
}
enum class DialogType {
SUCCESS, ERROR, WARNING, INFO
} | AestheticDialogs/aestheticdialogs/src/main/java/com/thecode/aestheticdialogs/AestheticDialog.kt | 1245201117 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.