content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.company.app.domain.use_case
data class AppUseCases(
val getListOfData: GetListOfData,
val deleteData: DeleteData,
val addData: AddData,
val getData: GetData
)
| devenv-android-starter/app/src/main/java/com/company/app/domain/use_case/AppUseCases.kt | 2334998656 |
package com.company.app.domain.use_case
import com.company.app.data.data_source.local.InvalidDataException
import com.company.app.domain.model.AppDomainModel
import com.company.app.domain.repository.AppRepository
class AddData(
private val repository: AppRepository
) {
@Throws(InvalidDataException::class)
suspend operator fun invoke(data: AppDomainModel) {
if (data.title.isBlank()) {
throw InvalidDataException("The title of the entity can't be empty.")
}
repository.insertData(data)
}
} | devenv-android-starter/app/src/main/java/com/company/app/domain/use_case/AddData.kt | 647166986 |
package com.company.app.domain
interface DomainMapper<T, DomainModel> {
fun mapToDomainModel(model: T): DomainModel
fun mapFromDomainModel(domainModel: DomainModel): T
} | devenv-android-starter/app/src/main/java/com/company/app/domain/DomainMapper.kt | 3407242140 |
package com.company.app.domain.model
data class AppDomainModel(
val title: String,
val id: Int? = null
)
| devenv-android-starter/app/src/main/java/com/company/app/domain/model/AppDomainModel.kt | 424353899 |
package com.company.app.domain
data class DataState<out T>(
val data: T? = null,
val error: String? = null,
val loading: Boolean = false
) {
companion object {
fun <T> success(data: T): DataState<T> {
return DataState(data = data)
}
fun <T> error(message: String): DataState<T> {
return DataState(error = message)
}
fun <T> loading(): DataState<T> = DataState(loading = true)
}
}
| devenv-android-starter/app/src/main/java/com/company/app/domain/DataState.kt | 2373739827 |
package com.company.app.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.ExperimentalAnimationApi
import com.company.app.presentation.navigation.MyApp
import com.company.app.util.ConnectivityManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var connectivityManager: ConnectivityManager
override fun onStart() {
super.onStart()
connectivityManager.registerConnectionObserver(this)
}
override fun onDestroy() {
super.onDestroy()
connectivityManager.unregisterConnectionObserver(this)
}
@ExperimentalAnimationApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/MainActivity.kt | 4240320542 |
package com.company.app.presentation.navigation
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.company.app.presentation.screen_first.navigation.FirstScreenDestination
import com.company.app.presentation.screen_first.navigation.firstScreenGraph
import com.company.app.presentation.screen_second.navigation.secondScreenGraph
import com.company.app.theme.AppTheme
@Composable
fun MyApp() {
AppTheme(
darkTheme = true,
) {
Surface(
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = FirstScreenDestination.route
) {
firstScreenGraph(
navController = navController
)
secondScreenGraph(
navController = navController
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
AppTheme {
MyApp()
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/navigation/MyApp.kt | 234054283 |
package com.company.app.presentation.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun GenericDialog(
modifier: Modifier = Modifier,
onDismiss: () -> Unit,
title: String,
description: String? = null,
positiveAction: PositiveAction?,
negativeAction: NegativeAction?,
) {
AlertDialog(
modifier = modifier,
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
if (description != null) {
Text(text = description)
}
},
confirmButton = {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.End,
) {
if (positiveAction != null) {
Button(
modifier = Modifier.padding(end = 8.dp),
onClick = positiveAction.onPositiveAction,
) {
Text(text = positiveAction.positiveBtnTxt)
}
}
}
}, dismissButton = {
if (negativeAction != null) {
Button(
modifier = Modifier.padding(end = 8.dp),
colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.onError),
onClick = negativeAction.onNegativeAction
) {
Text(text = negativeAction.negativeBtnTxt)
}
}
}
)
}
data class PositiveAction(
val positiveBtnTxt: String,
val onPositiveAction: () -> Unit,
)
data class NegativeAction(
val negativeBtnTxt: String,
val onNegativeAction: () -> Unit,
)
class GenericDialogInfo
private constructor(builder: Builder) {
val title: String
val onDismiss: () -> Unit
val description: String?
val positiveAction: PositiveAction?
val negativeAction: NegativeAction?
init {
if (builder.title == null) {
throw Exception("GenericDialog title cannot be null.")
}
if (builder.onDismiss == null) {
throw Exception("GenericDialog onDismiss function cannot be null.")
}
this.title = builder.title!!
this.onDismiss = builder.onDismiss!!
this.description = builder.description
this.positiveAction = builder.positiveAction
this.negativeAction = builder.negativeAction
}
class Builder {
var title: String? = null
private set
var onDismiss: (() -> Unit)? = null
private set
var description: String? = null
private set
var positiveAction: PositiveAction? = null
private set
var negativeAction: NegativeAction? = null
private set
fun title(title: String): Builder {
this.title = title
return this
}
fun onDismiss(onDismiss: () -> Unit): Builder {
this.onDismiss = onDismiss
return this
}
fun description(
description: String
): Builder {
this.description = description
return this
}
fun positive(
positiveAction: PositiveAction?,
): Builder {
this.positiveAction = positiveAction
return this
}
fun negative(
negativeAction: NegativeAction
): Builder {
this.negativeAction = negativeAction
return this
}
fun build() = GenericDialogInfo(this)
}
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/components/GenericDialog.kt | 3559660048 |
package com.company.app.presentation.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun ConnectivityMonitor() {
Column(modifier = Modifier.fillMaxWidth()) {
Text(
"No network connection",
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(8.dp),
style = MaterialTheme.typography.headlineLarge,
color = Color.Red
)
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/components/ConnectivityMonitor.kt | 1693279309 |
package com.company.app.presentation.screen_second
data class EntityTextFieldState(
val text: String = "",
val hint: String = "",
val isHintVisible: Boolean = true
)
| devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/EntityTextFieldState.kt | 1141119822 |
package com.company.app.presentation.screen_second.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.company.app.navigation.AppNavigationDestination
import com.company.app.presentation.screen_second.SecondScreen
object SecondScreenDestination : AppNavigationDestination {
override val route = "screen_second_route"
override val destination = "screen_second_destination"
}
fun NavGraphBuilder.secondScreenGraph(navController: NavController) {
composable(
route = SecondScreenDestination.route +
"?entityId={entityId}",
arguments = listOf(
navArgument(
name = "entityId"
) {
type = NavType.IntType
defaultValue = -1
}
)
) {
SecondScreen(
navController = navController,
)
}
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/navigation/SecondScreenDestination.kt | 915883349 |
package com.company.app.presentation.screen_second.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusState
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
@Composable
fun TransparentHintTextField(
text: String,
hint: String,
modifier: Modifier = Modifier,
isHintVisible: Boolean = true,
onValueChange: (String) -> Unit,
textStyle: TextStyle = TextStyle(),
singleLine: Boolean = false,
onFocusChange: (FocusState) -> Unit
) {
Box(
modifier = modifier
) {
BasicTextField(
value = text,
onValueChange = onValueChange,
singleLine = singleLine,
textStyle = textStyle,
modifier = Modifier
.fillMaxWidth()
.onFocusChanged {
onFocusChange(it)
}
)
if (isHintVisible) {
Text(text = hint, style = textStyle, color = Color.DarkGray)
}
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/components/TransparentHintTextField.kt | 2440619474 |
package com.company.app.presentation.screen_second
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.company.app.data.data_source.local.InvalidDataException
import com.company.app.domain.model.AppDomainModel
import com.company.app.domain.use_case.AppUseCases
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SecondScreenViewModel @Inject constructor(
private val appUseCases: AppUseCases,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _entityTitle = mutableStateOf(EntityTextFieldState(hint = "Enter title..."))
val entityTitle: State<EntityTextFieldState> = _entityTitle
private val _eventFlow = MutableSharedFlow<UiEvent>()
val eventFlow = _eventFlow.asSharedFlow()
private var currententityId: Int? = null
init {
savedStateHandle.get<Int>("entityId")?.let { entityId ->
if (entityId != -1) {
viewModelScope.launch {
appUseCases.getData(entityId)?.also { entity ->
currententityId = entity.id
_entityTitle.value = entityTitle.value.copy(
text = entity.title,
isHintVisible = false
)
}
}
}
}
}
fun onEvent(event: SecondScreenEvent) {
when (event) {
is SecondScreenEvent.EnteredTitle -> {
_entityTitle.value = entityTitle.value.copy(
text = event.value
)
}
is SecondScreenEvent.ChangeTitleFocus -> {
_entityTitle.value = entityTitle.value.copy(
isHintVisible = !event.focusState.isFocused &&
entityTitle.value.text.isBlank()
)
}
is SecondScreenEvent.SaveEntity -> {
viewModelScope.launch {
try {
appUseCases.addData(
AppDomainModel(
title = entityTitle.value.text,
id = currententityId
)
)
_eventFlow.emit(UiEvent.SaveEntity)
} catch (e: InvalidDataException) {
_eventFlow.emit(
UiEvent.ShowSnackbar(
message = e.message ?: "Couldn't save entity"
)
)
}
}
}
}
}
sealed class UiEvent {
data class ShowSnackbar(val message: String) : UiEvent()
data object SaveEntity : UiEvent()
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/SecondScreenViewModel.kt | 4092760616 |
package com.company.app.presentation.screen_second
import androidx.compose.ui.focus.FocusState
sealed class SecondScreenEvent {
data class EnteredTitle(val value: String) : SecondScreenEvent()
data class ChangeTitleFocus(val focusState: FocusState) : SecondScreenEvent()
data object SaveEntity : SecondScreenEvent()
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/SecondScreenEvent.kt | 1831611941 |
package com.company.app.presentation.screen_second
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.company.app.presentation.screen_second.components.TransparentHintTextField
import kotlinx.coroutines.flow.collectLatest
@SuppressLint("UnusedMaterialScaffoldPaddingParameter", "UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun SecondScreen(
navController: NavController,
viewModel: SecondScreenViewModel = hiltViewModel()
) {
val titleState = viewModel.entityTitle.value
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collectLatest { event ->
when (event) {
is SecondScreenViewModel.UiEvent.ShowSnackbar -> {
snackbarHostState.showSnackbar(
message = event.message
)
}
is SecondScreenViewModel.UiEvent.SaveEntity -> {
navController.navigateUp()
}
}
}
}
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = {
viewModel.onEvent(SecondScreenEvent.SaveEntity)
},
modifier = Modifier.background(MaterialTheme.colorScheme.primary)
) {
Icon(imageVector = Icons.Default.Done, contentDescription = "Save")
}
},
snackbarHost = { SnackbarHost(snackbarHostState) }
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
TransparentHintTextField(
text = titleState.text,
hint = titleState.hint,
isHintVisible = titleState.isHintVisible,
onValueChange = {
viewModel.onEvent(SecondScreenEvent.EnteredTitle(it))
},
textStyle = MaterialTheme.typography.headlineLarge.copy(color = Color.White),
singleLine = true,
) {
viewModel.onEvent(SecondScreenEvent.ChangeTitleFocus(it))
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_second/SecondScreen.kt | 1528569766 |
package com.company.app.presentation.screen_first
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.company.app.domain.model.AppDomainModel
import com.company.app.domain.use_case.AppUseCases
import com.company.app.util.ConnectivityManager
import com.company.app.util.DialogQueue
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class FirstScreenViewModel @Inject constructor(
private val appUseCases: AppUseCases,
private val connectivityManager: ConnectivityManager,
) : ViewModel() {
val dialogQueue = DialogQueue()
var loading = mutableStateOf(false)
private set
var isConnected = mutableStateOf(false)
private set
private val _state = mutableStateOf(FirstScreenState())
val state: State<FirstScreenState> = _state
private var getDataJob: Job? = null
init {
getData()
}
fun onEvent(event: FirstScreenEvent) {
when (event) {
is FirstScreenEvent.GetData -> {
getData()
}
is FirstScreenEvent.DeleteData -> {
deleteData(event.appEntity)
}
}
}
private fun getData() {
loading.value = true
getDataJob?.cancel()
getDataJob = appUseCases.getListOfData()
.onEach { data ->
_state.value = state.value.copy(
data = data
)
}
.launchIn(viewModelScope)
}
private fun deleteData(appDomainModel: AppDomainModel) {
loading.value = true
viewModelScope.launch { appUseCases.deleteData(appDomainModel) }
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/FirstScreenViewModel.kt | 3290458525 |
package com.company.app.presentation.screen_first
import com.company.app.domain.model.AppDomainModel
data class FirstScreenState(
val data: List<AppDomainModel> = emptyList(),
) | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/FirstScreenState.kt | 3968094195 |
package com.company.app.presentation.screen_first.navigation
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.company.app.navigation.AppNavigationDestination
import com.company.app.presentation.screen_first.FirstScreen
object FirstScreenDestination : AppNavigationDestination {
override val route = "screen_first_route"
override val destination = "screen_first_destination"
}
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.firstScreenGraph(navController: NavController) {
composable(route = FirstScreenDestination.route) {
FirstScreen(
navController = navController
)
}
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/navigation/FirstScreenDestination.kt | 499843661 |
package com.company.app.presentation.screen_first.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
@Composable
fun DefaultRadioButton(
text: String,
selected: Boolean,
onSelect: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selected,
onClick = onSelect,
colors = RadioButtonDefaults.colors(
selectedColor = MaterialTheme.colorScheme.primary,
unselectedColor = MaterialTheme.colorScheme.onBackground
),
modifier = Modifier.semantics {
contentDescription = text
}
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = text, style = MaterialTheme.typography.bodyLarge)
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/components/DefaultRadioButton.kt | 2599455775 |
package com.company.app.presentation.screen_first
import com.company.app.domain.model.AppDomainModel
sealed class FirstScreenEvent {
data object GetData : FirstScreenEvent()
data class DeleteData(val appEntity: AppDomainModel) : FirstScreenEvent()
}
| devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/FirstScreenEvent.kt | 2181867524 |
package com.company.app.presentation.screen_first
import android.annotation.SuppressLint
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.company.app.presentation.screen_second.navigation.SecondScreenDestination
import com.company.app.theme.AppTheme
import com.company.app.theme.UIState
@ExperimentalAnimationApi
@Composable
@SuppressLint("UnusedMaterialScaffoldPaddingParameter", "UnusedMaterial3ScaffoldPaddingParameter")
fun FirstScreen(
navController: NavController,
viewModel: FirstScreenViewModel = hiltViewModel()
) {
val state = viewModel.state.value
val loading = viewModel.loading.value
val isConnected = viewModel.isConnected.value
val snackbarHostState = remember { SnackbarHostState() }
val dialogQueue = viewModel.dialogQueue
AppTheme(
darkTheme = true,
dialogQueue = dialogQueue.queue.value,
uiState = UIState(loading = loading, offline = isConnected)
) {
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = {
navController.navigate(SecondScreenDestination.route)
},
modifier = Modifier.background(MaterialTheme.colorScheme.primary)
) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Enter")
}
},
snackbarHost = { SnackbarHost(snackbarHostState) }
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
LazyColumn {
item {
Text(
text = "Get List of Data for you again and again and again!",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.fillMaxWidth()
.clickable {
viewModel.onEvent(FirstScreenEvent.GetData)
}
.padding(10.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
items(state.data) {
Text(
text = it.title,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.fillMaxWidth()
.clickable {
viewModel.onEvent(FirstScreenEvent.DeleteData(it))
}
.padding(10.dp)
)
}
}
}
}
}
} | devenv-android-starter/app/src/main/java/com/company/app/presentation/screen_first/FirstScreen.kt | 658431263 |
package com.example.tallermovil
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.tallermovil", appContext.packageName)
}
} | TallerMovil/app/src/androidTest/java/com/example/tallermovil/ExampleInstrumentedTest.kt | 329712785 |
package com.example.tallermovil
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)
}
} | TallerMovil/app/src/test/java/com/example/tallermovil/ExampleUnitTest.kt | 1547214062 |
package com.example.tallermovil
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Geocoder
import android.os.Bundle
import android.os.StrictMode
import android.preference.PreferenceManager
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import org.osmdroid.bonuspack.routing.OSRMRoadManager
import org.osmdroid.bonuspack.routing.RoadManager
import org.osmdroid.config.Configuration.*
import org.osmdroid.events.MapEventsReceiver
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.MapEventsOverlay
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Polyline
import org.osmdroid.views.overlay.TilesOverlay
import java.io.IOException
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
class MapActivity : AppCompatActivity() {
private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient
private var map : MapView? = null
//SENSORES
private lateinit var mSensorManager: SensorManager
private lateinit var mLightSensor: Sensor
private lateinit var mLightSensorListener: SensorEventListener
//Rutas
lateinit var roadManager: RoadManager
private var roadOverlay: Polyline? = null
private var longPressedMarkerOrigin: Marker? = null
private var longPressedMarkerEnd: Marker? = null
//Geocoder
var mGeocoder: Geocoder? = null
override fun onCreate(savedInstanceState: Bundle?) {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
//Rutas
roadManager = OSRMRoadManager(this, "ANDROID")
//Attribute
val mGeocoder = Geocoder(this)
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)!!
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
permisoUbicacion()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this))
map = findViewById<MapView>(R.id.map)
//map.setTileSource(TileSourceFactory.OpenTopo)
map!!.setTileSource(TileSourceFactory.MAPNIK)
map!!.setMultiTouchControls(true)
var darkModeLum: Boolean = false
var lightModeLum: Boolean = true
mLightSensorListener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent?) {
if (event!!.values[0] < 16) {
darkModeLum = true
map!!.overlayManager.tilesOverlay.setColorFilter(TilesOverlay.INVERT_COLORS)
} else {
lightModeLum = true
map!!.overlayManager.tilesOverlay.setColorFilter(null)
}
if(lightModeLum && darkModeLum){
lightModeLum = false
darkModeLum = false
map!!.setTileSource(TileSourceFactory.MAPNIK)
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
}
val editText = findViewById<EditText>(R.id.editTextGeocoder)
//encontrar lugar y mostrar
editText.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
val addressString = editText.text.toString()
if (addressString.isNotEmpty()) {
try {
if (map != null && mGeocoder != null) {
val addresses = mGeocoder!!.getFromLocationName(addressString, 1)
if (addresses != null && addresses.isNotEmpty()) {
val addressResult = addresses[0]
val position = GeoPoint(addressResult.latitude, addressResult.longitude)
Log.i("Geocoder", "Dirección encontrada: ${addressResult.getAddressLine(0)}")
Log.i("Geocoder", "Latitud: ${addressResult.latitude}, Longitud: ${addressResult.longitude}")
//Agregar Marcador al mapa
val marker = createMarker(position, addressString, null, R.drawable.baseline_location_on_24)
marker?.let { map!!.overlays.add(it) }
map!!.controller.setCenter(marker!!.position)
} else {
Log.i("Geocoder", "Dirección no encontrada:" + addressString)
Toast.makeText(this, "Dirección no encontrada", Toast.LENGTH_SHORT)
.show()
}
}
} catch (e: IOException) {
e.printStackTrace()
}
} else {
Toast.makeText(this, "La dirección esta vacía", Toast.LENGTH_SHORT).show()
}
}
true
}
map!!.overlays.add(createOverlayEvents())
}
override fun onResume() {
super.onResume()
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
map!!.onResume() //needed for compass, my location overlays, v6.0.0 and up
mSensorManager.registerListener(mLightSensorListener, mLightSensor,
SensorManager.SENSOR_DELAY_NORMAL)
if (checkLocationPermission()) {
mFusedLocationProviderClient.lastLocation.addOnSuccessListener(this) { location ->
Log.i("LOCATION", "onSuccess location")
if (location != null) {
Log.i("LOCATION", "Longitud: " + location.longitude)
Log.i("LOCATION", "Latitud: " + location.latitude)
val mapController = map!!.controller
mapController.setZoom(15)
val startPoint = GeoPoint(location.latitude, location.longitude);
mapController.setCenter(startPoint);
} else {
Log.i("LOCATION", "FAIL location")
}
}
}
}
override fun onPause() {
super.onPause()
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Configuration.getInstance().save(this, prefs);
map!!.onPause() //needed for compass, my location overlays, v6.0.0 and up
mSensorManager.unregisterListener(mLightSensorListener)
}
private fun checkLocationPermission(): Boolean {
return ContextCompat.checkSelfPermission(
this, android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
fun permisoUbicacion(){
when {
ContextCompat.checkSelfPermission(
this, android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED -> {
// You can use the API that requires the permission.
//performAction(...)
Toast.makeText(this, "Gracias", Toast.LENGTH_SHORT).show()
mFusedLocationProviderClient.lastLocation.addOnSuccessListener(this) { location ->
Log.i("LOCATION", "onSuccess location")
if (location != null) {
Log.i("LOCATION", "Longitud: " + location.longitude)
Log.i("LOCATION", "Latitud: " + location.latitude)
/*
val mapController = map.controller
mapController.setZoom(10.5)
val startPoint = GeoPoint(location.latitude, location.longitude);
mapController.setCenter(startPoint);
*/
} else{
Log.i("LOCATION", "FAIL location")
}
}
}
ActivityCompat.shouldShowRequestPermissionRationale(
this, android.Manifest.permission.ACCESS_FINE_LOCATION) -> {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected, and what
// features are disabled if it's declined.
//showInContextUI(...)
requestPermissions(
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
Permission.MY_PERMISSION_REQUEST_LOCATION)
}
else -> {
// You can directly ask for the permission.
requestPermissions(
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
Permission.MY_PERMISSION_REQUEST_LOCATION)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//val textV = findViewById<TextView>(R.id.textView)
when (requestCode) {
Permission.MY_PERMISSION_REQUEST_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission is granted. Continue the action or workflow
// in your app.
Toast.makeText(this, "Gracias", Toast.LENGTH_SHORT).show()
} else {
// Explain to the user that the feature is unavailable
}
return
}
else -> {
// Ignore all other requests.
}
}
}
private fun createOverlayEvents(): MapEventsOverlay {
val overlayEventos = MapEventsOverlay(object : MapEventsReceiver {
override fun singleTapConfirmedHelper(p: GeoPoint): Boolean {
return false
}
override fun longPressHelper(p: GeoPoint): Boolean {
longPressOnMap(p)
return true
}
})
return overlayEventos
}
private fun longPressOnMap(p: GeoPoint) {
val address = getLocationName(p.latitude, p.longitude)
val myIcon = combineDrawableWithText(resources.getDrawable(R.drawable.baseline_location_on_24, this.theme), getAddressFromCoordinates(p.latitude, p.longitude))
longPressedMarkerEnd?.let { map!!.overlays.remove(it) }
longPressedMarkerEnd = createMarkerWithDrawable(p, address, null, myIcon)
longPressedMarkerEnd?.let { map!!.overlays.add(it) }
val mapController = map!!.controller
mapController.setCenter(p);
if (checkLocationPermission()) {
mFusedLocationProviderClient.lastLocation.addOnSuccessListener(this) { location ->
if (location != null) {
Log.i("LOCATION", "onSuccess location")
val startPoint = GeoPoint(location.latitude, location.longitude);
Log.i("LOCATION", "onSuccess location:" + location.latitude + " - " + location.longitude)
val address = getLocationName(location.latitude, location.longitude)
//val myIcon = combineDrawableWithText(resources.getDrawable(R.drawable.baseline_location_on_24, this.theme), getLocationName(location.latitude, location.longitude))
val myIcon = combineDrawableWithText(resources.getDrawable(R.drawable.baseline_location_on_24, this.theme), getAddressFromCoordinates(location.latitude, location.longitude))
longPressedMarkerOrigin?.let { map!!.overlays.remove(it) }
longPressedMarkerOrigin = createMarkerWithDrawable(startPoint, address, "INICIO", myIcon)
longPressedMarkerOrigin?.let { map!!.overlays.add(it) }
drawRoute(startPoint,p)
} else {
Log.i("LOCATION", "FAIL location")
}
}
}
}
private fun createMarker(p: GeoPoint, title: String?, desc: String?, iconID: Int): Marker? {
var marker: Marker? = null
if (map != null) {
marker = Marker(map)
title?.let { marker.title = it }
desc?.let { marker.subDescription = it }
if (iconID != 0) {
val myIcon = resources.getDrawable(iconID, this.theme)
marker.icon = myIcon
}
marker.position = p
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
}
return marker
}
private fun createMarkerWithDrawable(p: GeoPoint, title: String?, desc: String?, icon: Drawable?): Marker? {
var marker: Marker? = null
if (map != null) {
marker = Marker(map)
title?.let { marker.title = it }
desc?.let { marker.subDescription = it }
marker.icon = icon // Set the icon directly using the provided Drawable
marker.position = p
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
}
return marker
}
private fun drawRoute(start: GeoPoint, finish: GeoPoint) {
val routePoints = ArrayList<GeoPoint>()
routePoints.add(start)
routePoints.add(finish)
val road = roadManager.getRoad(routePoints)
Log.i("OSM_acticity", "Route length: ${road.mLength} klm")
Log.i("OSM_acticity", "Duration: ${road.mDuration / 60} min")
if (map != null) {
roadOverlay?.let { map!!.overlays.remove(it) }
roadOverlay = RoadManager.buildRoadOverlay(road)
roadOverlay?.outlinePaint?.color = Color.RED
roadOverlay?.outlinePaint?.strokeWidth = 10f
map!!.overlays.add(roadOverlay)
Toast.makeText(this, "Distancia de la ruta: ${road.mLength} km", Toast.LENGTH_LONG).show()
}
}
private fun getLocationName (latitude: Double, longitude: Double): String{
var addressFound = "null"
try {
val maxResults = 1
val addresses = mGeocoder?.getFromLocation(latitude, longitude, maxResults)
if (addresses != null && addresses.isNotEmpty()) {
val address = addresses[0]
Log.i("Geocoder", "Dirección encontrada: ${address.getAddressLine(0)}")
Log.i("Geocoder", "Latitud: ${address.latitude}, Longitud: ${address.longitude}")
addressFound = address.getAddressLine(0).toString()
} else {
Log.i("Geocoder", "No se encontró ninguna dirección: " + latitude + " - " + longitude)
}
} catch (e: IOException) {
Log.e("Geocoder", "Error en el geocodificador: ${e.message}")
}
return addressFound
}
fun combineDrawableWithText(drawable: Drawable, text: String): Drawable {
val paddingVertical = 40
val paddingHorizontal = 200
val textSize = 16f
// Calcula ancho y alto total junto con el borde definido
val totalWidth = drawable.intrinsicWidth + paddingHorizontal * 2
val totalHeight = drawable.intrinsicHeight + paddingVertical * 2 + textSize
val bitmap = Bitmap.createBitmap(totalWidth, totalHeight.toInt(), Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Dibujar el Drawable centrado horizontalmente
val drawableLeft = (totalWidth - drawable.intrinsicWidth) / 2
val drawableTop = paddingVertical
drawable.setBounds(drawableLeft, drawableTop, drawableLeft + drawable.intrinsicWidth, drawableTop + drawable.intrinsicHeight)
drawable.draw(canvas)
// Dibujar el texto centrado
val paint = Paint()
paint.color = Color.BLACK
paint.textSize = textSize
paint.isAntiAlias = true
val indiceMedio = text.length / 2
val primerLinea = text.substring(0, indiceMedio)
val textWidth = paint.measureText(primerLinea)
val textX = (totalWidth - textWidth) / 2
val textY = (totalHeight - paddingVertical / 2) - 25
canvas.drawText(primerLinea, textX, textY, paint)
return BitmapDrawable(resources, bitmap)
}
//ALTERNATIVA A GEOCODER
fun getAddressFromCoordinates(latitude: Double, longitude: Double): String {
val client = OkHttpClient()
val url = "https://nominatim.openstreetmap.org/reverse?format=json&lat=$latitude&lon=$longitude&zoom=17&addressdetails=1"
val request = Request.Builder()
.url(url)
.build()
val response = client.newCall(request).execute()
val responseBody = response.body?.string()
var displayName = ""
// Procesado del json recibido especificando el atributo requerido
val gson = Gson()
val jsonObject = gson.fromJson(responseBody, com.google.gson.JsonObject::class.java)
displayName = jsonObject.getAsJsonPrimitive("display_name").asString
return displayName
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/MapActivity.kt | 1057820366 |
package com.example.tallermovil
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val camBtn = findViewById<ImageButton>(R.id.camBtn)
val contactsBtn = findViewById<ImageButton>(R.id.contactBtn)
val mapBtn = findViewById<ImageButton>(R.id.mapBtn)
camBtn.setOnClickListener {
val intent = Intent(this, CameraActivity::class.java)
startActivity(intent)
}
contactsBtn.setOnClickListener {
val intent = Intent(this, ContactsActivity::class.java)
startActivity(intent)
}
mapBtn.setOnClickListener {
val intent = Intent(this, MapActivity::class.java)
startActivity(intent)
}
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/MainActivity.kt | 2822349924 |
package com.example.tallermovil
class Permission {
companion object {
const val MY_PERMISSION_REQUEST_CAMERA = 1
const val MY_PERMISSION_REQUEST_GALLERY = 2
const val IMAGE_PICKER_REQUEST = 3
const val MY_PERMISSION_REQUEST_LOCATION = 0
const val REQUEST_READ_CONTACTS = 5
const val REQUEST_IMAGE_CAPTURE = 6
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/Permission.kt | 394516215 |
package com.example.tallermovil
import android.content.Context
import android.database.Cursor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cursoradapter.widget.CursorAdapter
class ContactAdapter (context: Context?, c: Cursor?, flags: Int) : CursorAdapter(context, c, flags){
private val CONTACT_ID_INDEX = 0
val DISPLAY_NAME_INDEX = 1
override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
return LayoutInflater.from(context)
.inflate(R.layout.view_contact, parent, false)
}
override fun bindView(view: View?, context: Context?, cursor: Cursor?) {
val tvIdContacto = view?.findViewById<TextView>(R.id.idContact)
val tvNombre = view?.findViewById<TextView>(R.id.name)
val idnum = cursor?.getInt(CONTACT_ID_INDEX)
val nombre = cursor?.getString(DISPLAY_NAME_INDEX)
tvIdContacto?.text = idnum?.toString()
tvNombre?.text = nombre
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/ContactAdapter.kt | 1349755814 |
package com.example.tallermovil
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ListView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ContactsActivity : AppCompatActivity() {
var mProjection: Array<String>? = null
var mCursor: Cursor? = null
var mContactsAdapter: ContactAdapter? = null
var mlista: ListView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_contacts)
permisoContactos()
val mlista = findViewById<ListView>(R.id.contacts)
mProjection = arrayOf(ContactsContract.Profile._ID, ContactsContract.Profile.DISPLAY_NAME_PRIMARY)
mContactsAdapter = ContactAdapter(this, null, 0)
mlista?.adapter = mContactsAdapter
if (ContextCompat.checkSelfPermission(
this, android.Manifest.permission.READ_CONTACTS
) == PackageManager.PERMISSION_GRANTED
) {
// Si los permisos están concedidos, inicializa la vista
initView()
} else {
// Solicita permisos si no están concedidos
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.READ_CONTACTS),
Permission.REQUEST_READ_CONTACTS
)
}
mlista.setOnItemClickListener { parent, view, position, id ->
val cursor = mContactsAdapter!!.cursor
val displayNameIndex = mContactsAdapter!!.DISPLAY_NAME_INDEX
if (cursor != null && cursor.moveToPosition(position)) {
val name = cursor.getString(displayNameIndex)
Toast.makeText(this, "Contact name: $name", Toast.LENGTH_SHORT).show()
}
}
}
fun permisoContactos(){
when {
ContextCompat.checkSelfPermission(
this, android.Manifest.permission.READ_CONTACTS
) == PackageManager.PERMISSION_GRANTED -> {
Toast.makeText(this, "Puede ver contactos", Toast.LENGTH_SHORT).show()
initView()
}
ActivityCompat.shouldShowRequestPermissionRationale(
this, android.Manifest.permission.READ_CONTACTS) -> {
// In an educational UI, explain to the user why your app requires this permission
Toast.makeText(this, "Se requiere contactos", Toast.LENGTH_SHORT).show()
requestPermissions(
arrayOf(android.Manifest.permission.READ_CONTACTS),
Permission.REQUEST_READ_CONTACTS)
}
else -> {
// You can directly ask for the permission.
requestPermissions(
arrayOf(android.Manifest.permission.READ_CONTACTS),
Permission.REQUEST_READ_CONTACTS)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
Permission.REQUEST_READ_CONTACTS ->{
if (requestCode == Permission.REQUEST_READ_CONTACTS && resultCode == RESULT_OK) {
initView()
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
Permission.REQUEST_READ_CONTACTS -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission is granted. Continue the action or workflow
// in your app.
initView()
Toast.makeText(this, "Gracias contactos", Toast.LENGTH_SHORT).show()
} else {
// Explain to the user that the feature is unavailable
Toast.makeText(this, "No tengo acceso a contactos", Toast.LENGTH_SHORT).show()
}
return
}
else -> {
// Ignore all other requests.
}
}
}
fun initView() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
mCursor = contentResolver.query(
ContactsContract.Contacts.CONTENT_URI, mProjection, null, null, null
)
mContactsAdapter?.changeCursor(mCursor)
}
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/ContactsActivity.kt | 3456919980 |
package com.example.tallermovil
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
import com.example.tallermovil.Permission.Companion.MY_PERMISSION_REQUEST_CAMERA
import com.example.tallermovil.Permission.Companion.REQUEST_IMAGE_CAPTURE
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class CameraActivity : AppCompatActivity() {
private lateinit var photoUri: Uri
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
val btnCamera = findViewById<Button>(R.id.camBtn)
btnCamera.setOnClickListener {
permisoCamara()
}
val btnGallery = findViewById<Button>(R.id.gallerybtn)
btnGallery.setOnClickListener {
permisoGaleria()
}
}
fun permisoCamara(){
when {
ContextCompat.checkSelfPermission(
this, android.Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED -> {
takePic()
}
ActivityCompat.shouldShowRequestPermissionRationale(
this, android.Manifest.permission.CAMERA) -> {
Toast.makeText(this, "Necesita permiso de camara", Toast.LENGTH_SHORT).show()
requestPermissions(
arrayOf(android.Manifest.permission.CAMERA),
Permission.MY_PERMISSION_REQUEST_CAMERA)
}
else -> {
requestPermissions(
arrayOf(android.Manifest.permission.CAMERA),
Permission.MY_PERMISSION_REQUEST_CAMERA)
}
}
}
fun permisoGaleria(){
when {
ContextCompat.checkSelfPermission(
this, android.Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED -> {
selectPhoto()
}
ActivityCompat.shouldShowRequestPermissionRationale(
this, android.Manifest.permission.READ_EXTERNAL_STORAGE
) -> {
Toast.makeText(this, "La aplicación necesita acceso a la galería para seleccionar fotos", Toast.LENGTH_SHORT).show()
requestPermissions(
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
Permission.MY_PERMISSION_REQUEST_GALLERY
)
}
else -> {
requestPermissions(
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
Permission.MY_PERMISSION_REQUEST_GALLERY
)
}
}
}
fun selectPhoto () {
val permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
val pickImage = Intent(Intent.ACTION_PICK)
pickImage.type = "image/*"
startActivityForResult(pickImage, Permission.IMAGE_PICKER_REQUEST)
} else {
Toast.makeText(this, "No hay permiso de galeria", Toast.LENGTH_SHORT).show()
requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
Permission.MY_PERMISSION_REQUEST_GALLERY)
}
}
fun saveImageToGallery(bitmap: Bitmap): Uri? {
val values = ContentValues()
values.put(MediaStore.Images.Media.DISPLAY_NAME, "Imagen_${System.currentTimeMillis()}")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera") // <-- Change this line
val resolver = contentResolver
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
if (uri != null) {
try {
val outStream = resolver.openOutputStream(uri)
if (outStream != null) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
}
outStream?.close()
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
return uri
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
Permission.IMAGE_PICKER_REQUEST ->{
if(resultCode == Activity.RESULT_OK){
try {
//Logica de seleccion de imagen
val selectedImageUri = data!!.data
if(data.data != null){
val imageView = findViewById<ImageView>(R.id.photo)
imageView.setImageURI(selectedImageUri)
}
} catch (e: FileNotFoundException){
e.printStackTrace()
}
}
}
Permission.REQUEST_IMAGE_CAPTURE -> {
if (resultCode == Activity.RESULT_OK) {
// Load the full-quality image into ImageView
val imageView = findViewById<ImageView>(R.id.photo)
imageView.setImageURI(photoUri)
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
Permission.MY_PERMISSION_REQUEST_CAMERA -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
takePic()
Toast.makeText(this, "Permiso de camara concedido", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Permiso de camara negado", Toast.LENGTH_SHORT).show()
}
}
Permission.MY_PERMISSION_REQUEST_GALLERY -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
selectPhoto()
Toast.makeText(this, "Permiso de galería concedido", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Permiso de galería denegado", Toast.LENGTH_SHORT).show()
}
}
else -> {
// Ignore all other requests.
}
}
}
private fun takePic() {
val permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
if (takePictureIntent.resolveActivity(packageManager) != null) {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
ex.printStackTrace()
null
}
photoFile?.also {
photoUri = FileProvider.getUriForFile(
this,
"com.example.myapp.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(takePictureIntent, Permission.REQUEST_IMAGE_CAPTURE)
}
} else {
Toast.makeText(this, "No hay una cámara disponible en este dispositivo", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "No hay permiso de cámara", Toast.LENGTH_SHORT).show()
requestPermissions(arrayOf(android.Manifest.permission.CAMERA), Permission.MY_PERMISSION_REQUEST_CAMERA)
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
}
} | TallerMovil/app/src/main/java/com/example/tallermovil/CameraActivity.kt | 2340994063 |
package it.unipi.puffotuner
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("it.unipi.puffotuner", appContext.packageName)
}
} | MASSS-Project/app/src/androidTest/java/it/unipi/puffotuner/ExampleInstrumentedTest.kt | 2030787311 |
package it.unipi.puffotuner.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) | MASSS-Project/app/src/main/java/it/unipi/puffotuner/ui/theme/Color.kt | 3075957585 |
package it.unipi.puffotuner.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun GreetingCardTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | MASSS-Project/app/src/main/java/it/unipi/puffotuner/ui/theme/Theme.kt | 958103696 |
package it.unipi.puffotuner.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
)
*/
) | MASSS-Project/app/src/main/java/it/unipi/puffotuner/ui/theme/Type.kt | 1267497739 |
package it.unipi.puffotuner
import android.annotation.SuppressLint
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import it.unipi.puffotuner.audioprocessing.AudioController
import it.unipi.puffotuner.audioprocessing.frequencyToNote
import kotlinx.coroutines.delay
import kotlin.math.PI
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sin
import kotlin.math.tanh
fun normalizeAndClampFrequency(frequency: Float, min: Float, max: Float): Float {
val mid = (min + max) / 2
val range = (max - min) / 2
return range * tanh((frequency - mid) / range) + range + 1
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun TunerScreen(
navController: NavController? = null,
initialReferencePitch: Float = 440f,
lowerPitch: Float = 430f,
upperPitch: Float = 450f,
title: String = "PuffoTuner",
) {
var referencePitch by remember { mutableStateOf(initialReferencePitch) }
var isTuning by remember { mutableStateOf(false) }
var pitch by remember { mutableStateOf(0f) }
Scaffold(topBar = {
TunerAppBar(title = title, modifier = Modifier.fillMaxWidth(), navController = navController)
}) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.height(20.dp))
Slider(
value = referencePitch,
onValueChange = { referencePitch = it.roundToInt().toFloat() },
valueRange = lowerPitch..upperPitch,
steps = 20,
)
Text(text = "$referencePitch Hz", style = MaterialTheme.typography.titleLarge)
Spacer(modifier = Modifier.height(20.dp))
TuningMeter(
centsOff = if (isTuning) pitch - referencePitch else 0f,
needleColor = Color.Red,
arcColors = listOf(Color.Red, Color.Green, Color.Red),
scaleMarkingColors = listOf(Color.DarkGray, Color.LightGray),
scaleMarkings = 10,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(16.dp)
)
val animatableFrequency = remember { Animatable(pitch) }
val phase = remember { Animatable(0f) }
LaunchedEffect(Unit) {
phase.animateTo(
targetValue = (phase.value + 2 * PI).toFloat(), // Increment phase to move the wave
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 1000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
)
)
}
LaunchedEffect(pitch) {
animatableFrequency.animateTo(
targetValue = pitch, animationSpec = tween(durationMillis = 1000)
)
}
if (isTuning) {
val normalizedFrequency =
normalizeAndClampFrequency(pitch, lowerPitch, upperPitch)
FrequencyWave(frequency = normalizedFrequency, phase = phase.value)
} else {
FrequencyWave(frequency = 0f, phase = 0f)
}
Box(
contentAlignment = Alignment.Center, modifier = Modifier
) {
if (isTuning) {
var dots by remember { mutableIntStateOf(1) }
LaunchedEffect(Unit) {
while (isTuning) {
delay(500)
dots = dots % 3 + 1
}
}
val text = "Tuning".plus(".".repeat(dots)).plus(" ".repeat(3 - dots))
Text(text = text, style = MaterialTheme.typography.bodyLarge)
} else {
Text(text = "Ready")
}
}
Spacer(modifier = Modifier.height(20.dp))
val note = frequencyToNote(pitch.toDouble(), referencePitch.toDouble())
NoteIndicator(note = if (isTuning || pitch == 0f) note.prettyPrintItalian() else "-")
val context = LocalContext.current
Button(onClick = {
isTuning = !isTuning
if (isTuning) {
AudioController.startRecording(context = context,
onPitchDetected = { pitch = it.let { if (it.isNaN()) 0f else it } })
}
}) {
Text(text = if (isTuning) "Stop" else "Start")
}
Spacer(modifier = Modifier.height(20.dp))
}
}
}
@Composable
fun FrequencyWave(
frequency: Float, phase: Float, waveColor: Color = Color.Blue, strokeWidth: Float = 4f
) {
Canvas(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
.height(200.dp)
) {
val waveHeight = size.height / 2
val waveWidth = size.width
val centerX = waveWidth / 2
var i = 0
while (i < waveWidth.toInt() * 6) {
val x = i.toFloat() / 6
val angle = (2 * Math.PI * frequency * (x / waveWidth) + phase).toFloat()
val tmp = (-(x - centerX).pow(2) / waveWidth.pow(2) + 1)
val amplitudeModifier = tmp * tmp
val y = waveHeight - (waveHeight * sin(angle) * amplitudeModifier)
drawCircle(
color = waveColor, center = Offset(x, y), radius = 2f, style = Stroke(strokeWidth)
)
i += 1
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
TunerScreen(
initialReferencePitch = 440f,
lowerPitch = 430f,
upperPitch = 450f,
title = "PuffoTuner"
)
} | MASSS-Project/app/src/main/java/it/unipi/puffotuner/TunerScreen.kt | 2512796124 |
package it.unipi.puffotuner
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Surface
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import it.unipi.puffotuner.ui.theme.GreetingCardTheme
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlin.math.cos
import kotlin.math.sin
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
supportActionBar?.hide()
super.onCreate(savedInstanceState)
setContent {
GreetingCardTheme {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val drawerOpen by viewModel.drawerShouldBeOpened
.collectAsStateWithLifecycle()
if (drawerOpen) {
LaunchedEffect(Unit) {
try {
drawerState.open()
} finally {
viewModel.resetOpenDrawerAction()
}
}
}
Surface(
modifier = Modifier.fillMaxSize(),
) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "tunerScreen") {
composable("tunerScreen") { TunerScreen(navController) }
composable("aboutScreen") { AboutScreen(navController) }
}
}
}
}
}
}
class MainViewModel : ViewModel() {
private val _drawerShouldBeOpened = MutableStateFlow(false)
val drawerShouldBeOpened = _drawerShouldBeOpened.asStateFlow()
fun openDrawer() {
_drawerShouldBeOpened.value = true
}
fun resetOpenDrawerAction() {
_drawerShouldBeOpened.value = false
}
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/MainActivity.kt | 4288490129 |
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.Stroke
@Composable
fun SinusoidalWave(pitch: Float, modifier: Modifier = Modifier) {
val wavePaint = Paint().apply {
color = Color.Blue
style = PaintingStyle.Stroke
}
Canvas(modifier = modifier) {
val width = size.width
val height = size.height / 2
val amplitude = 100f // Adjust the amplitude of the wave as needed
val gradient = Brush.verticalGradient(
colors = listOf(Color.Cyan, Color.Blue),
startY = 0f,
endY = size.height
)
for (x in 0..width.toInt()) {
val angle = (x + (pitch - 440f)) * Math.PI / 180 * pitch / 440f
val y = (Math.sin(angle) * amplitude).toFloat() + height
drawCircle(gradient, radius = 10f, center = Offset(x.toFloat(), y))
}
}
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/SinusoidalWave.kt | 2483150532 |
package it.unipi.puffotuner.audioprocessing
import kotlin.math.absoluteValue
import kotlin.math.pow
const val DEFAULT_THRESHOLD = 0.20f
fun parabolicInterpolation(yinBuffer: FloatArray, tau: Int): Float {
if (tau == yinBuffer.size) {
return tau.toFloat()
}
val betterTau = if (0 < tau && tau < yinBuffer.size - 1) {
val s0 = yinBuffer[tau - 1]
val s1 = yinBuffer[tau]
val s2 = yinBuffer[tau + 1]
var adjustment = (s2 - s0) / (2.0f * (2.0f * s1 - s2 - s0))
if (adjustment.absoluteValue > 1) {
adjustment = 0.0f
}
tau + adjustment
} else {
tau.toFloat()
}
return betterTau.absoluteValue
}
fun cumulativeMeanNormalizedDifference(yinBuffer: FloatArray): FloatArray {
val yinBufferCopy = yinBuffer.copyOf()
yinBufferCopy[0] = 1.0f
var runningSum = 0.0f
for (index in 1 until yinBufferCopy.size) {
runningSum += yinBufferCopy[index]
if (runningSum == 0.0f) {
yinBufferCopy[index] = 0.0f
} else {
yinBufferCopy[index] *= index / runningSum
}
}
return yinBufferCopy
}
fun absoluteThreshold(yinBuffer: FloatArray, threshold: Float): Int {
var tau = 2
var minTau = 0
var minVal = 1000.0f
while (tau < yinBuffer.size) {
if (yinBuffer[tau] < threshold) {
while ((tau + 1) < yinBuffer.size && yinBuffer[tau + 1] < yinBuffer[tau]) {
tau += 1
}
return tau
} else {
if (yinBuffer[tau] < minVal) {
minVal = yinBuffer[tau]
minTau = tau
}
}
tau += 1
}
if (minTau > 0) {
return -minTau
}
return 0
}
fun yinPitchDetection(buffer: FloatArray, sr: Int, threshold: Float = DEFAULT_THRESHOLD): Float {
val wLen = buffer.size
val tauRange = (sr * 0.02).toInt()
val diff = FloatArray(tauRange)
for (tau in 0 until tauRange) {
var sum = 0.0f
for (i in 0 until wLen - tau) {
sum += (buffer[i] - buffer[i + tau]).pow(2)
}
diff[tau] = sum
}
val cmndf = cumulativeMeanNormalizedDifference(diff)
val tau = absoluteThreshold(cmndf, threshold)
val betterTau = parabolicInterpolation(cmndf, tau)
return sr.toFloat() / betterTau
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/audioprocessing/PitchDetectorYin.kt | 3986468859 |
package it.unipi.puffotuner.audioprocessing
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
import kotlin.math.ln
import kotlin.math.roundToInt
enum class Tone {
C, D, E, F, G, A, B,
}
enum class Semitone {
NATURAL, SHARP, FLAT;
override fun toString(): String {
return when (this) {
NATURAL -> ""
SHARP -> "♯"
FLAT -> "♭"
}
}
}
data class Note(
val tone: Tone,
val semitone: Semitone,
val octave: Int
) {
fun prettyPrintItalian(): String {
val toneName = when (tone) {
Tone.C -> "Do"
Tone.D -> "Re"
Tone.E -> "Mi"
Tone.F -> "Fa"
Tone.G -> "Sol"
Tone.A -> "La"
Tone.B -> "Si"
}
return "$toneName$semitone"
}
}
fun frequencyToNote(frequency: Double, referencePitch: Double): Note {
val semitoneFromA4 = 12 * ln(frequency / referencePitch) / ln(2.0)
val roundedSemitone = semitoneFromA4.roundToInt()
val totalSemitonesFromC0 = roundedSemitone + 9 + (4 * 12) // C0 is 9 semitones below A4, plus 4 octaves
val octave = totalSemitonesFromC0 / 12
val toneAndSemitone = when (totalSemitonesFromC0.mod(12)) {
0 -> Pair(Tone.C, Semitone.NATURAL)
1 -> Pair(Tone.C, Semitone.SHARP)
2 -> Pair(Tone.D, Semitone.NATURAL)
3 -> Pair(Tone.D, Semitone.SHARP)
4 -> Pair(Tone.E, Semitone.NATURAL)
5 -> Pair(Tone.F, Semitone.NATURAL)
6 -> Pair(Tone.F, Semitone.SHARP)
7 -> Pair(Tone.G, Semitone.NATURAL)
8 -> Pair(Tone.G, Semitone.SHARP)
9 -> Pair(Tone.A, Semitone.NATURAL)
10 -> Pair(Tone.A, Semitone.SHARP)
11 -> Pair(Tone.B, Semitone.NATURAL)
else -> {
throw IllegalArgumentException("Invalid note index")
}
}
return Note(
tone = toneAndSemitone.first,
semitone = toneAndSemitone.second,
octave = octave
)
}
object AudioController {
private val MY_PERMISSIONS_RECORD_AUDIO = 1
fun startRecording(context: Context, onPitchDetected: (Float) -> Unit) {
if (ContextCompat.checkSelfPermission(
context, Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(Manifest.permission.RECORD_AUDIO),
MY_PERMISSIONS_RECORD_AUDIO
)
return
}
CoroutineScope(Dispatchers.IO).launch {
val sampleRate = 44100
val channelConfig = AudioFormat.CHANNEL_IN_MONO
val audioFormat = AudioFormat.ENCODING_PCM_16BIT
val minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)
try {
val audioRecord = AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
channelConfig,
audioFormat,
minBufferSize
)
audioRecord.startRecording()
val buffer = ShortArray(minBufferSize)
while (audioRecord.read(buffer, 0, minBufferSize) > 0) {
val floatBuffer = buffer.map { it.toFloat() }.toFloatArray()
val pitch = yinPitchDetection(floatBuffer, sampleRate)
onPitchDetected(pitch)
}
} catch (e: IllegalStateException) {
Log.e("AudioRecord", "Recording failed: ${e.message}")
} catch (e: IOException) {
Log.e("AudioRecord", "IO Exception: ${e.message}")
}
}
}
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/audioprocessing/AudioController.kt | 2123690260 |
package it.unipi.puffotuner
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.cos
import kotlin.math.sin
@Composable
fun TuningMeter(
centsOff: Float,
modifier: Modifier = Modifier,
//meterHeight: Dp,
//padding: Dp,
needleColor: Color = Color.Red,
arcColors: List<Color>,
scaleMarkingColors: List<Color>,
scaleMarkings: Int
) {
val isNight = isSystemInDarkTheme()
Box(
contentAlignment = Alignment.BottomCenter,
modifier = modifier
.fillMaxWidth()
) {
Canvas(modifier = Modifier.fillMaxSize()) {
val strokeWeight = 8.dp.toPx()
val radius = size.width.coerceAtMost(size.height) * 0.9f - strokeWeight
val center = Offset(x = size.width / 2, y = size.height)
val needleHeight = size.height * 0.7f
drawTuningArc(center, radius, strokeWeight, arcColors)
drawScaleMarkings(center, radius, scaleMarkings, scaleMarkingColors, isNight)
drawNeedle(center, needleHeight, centsOff, needleColor)
drawCircle(
brush = Brush.radialGradient(
colors = listOf(Color.Yellow, Color.Red),
center = center,
radius = strokeWeight / 2,
),
radius = strokeWeight / 2,
center = center,
)
}
}
}
private fun DrawScope.drawTuningArc(center: Offset, radius: Float, strokeWeight: Float, colors: List<Color>) {
drawArc(
brush = Brush.linearGradient(
colors = colors,
start = Offset(x = center.x - radius, y = center.y),
end = Offset(x = center.x + radius, y = center.y),
),
startAngle = 180f,
sweepAngle = 180f,
useCenter = false,
topLeft = Offset(x = center.x - radius, y = center.y - radius),
size = Size(radius * 2, radius * 2),
style = Stroke(width = strokeWeight)
)
}
private fun DrawScope.calculateMarkingRadius(i: Int, radius: Float): Float {
return if (i % 5 == 0) radius - 20.dp.toPx() else radius - 10.dp.toPx()
}
/*
private fun DrawScope.drawScaleMarkings(center: Offset, radius: Float, scaleMarkings: Int, colors: List<Color>) {
for (i in -scaleMarkings..scaleMarkings) {
val angle = -180f / (scaleMarkings * 2) * i
val markingRadius = calculateMarkingRadius(i, radius)
drawScaleLine(center, radius, markingRadius, angle, i, colors)
}
}
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
*/
private fun DrawScope.drawText(text: String, center: Offset, angle: Float, radius: Float, textStyle: TextStyle) {
val textPaint = android.graphics.Paint().apply {
color = textStyle.color?.toArgb() ?: android.graphics.Color.BLACK
textSize = textStyle.fontSize?.value ?: 12f
textAlign = android.graphics.Paint.Align.CENTER
typeface = android.graphics.Typeface.create(android.graphics.Typeface.DEFAULT,
when (textStyle.fontWeight) {
FontWeight.Bold -> android.graphics.Typeface.BOLD
else -> android.graphics.Typeface.NORMAL
})
}
val x = center.x + radius * sin(Math.toRadians(angle.toDouble())).toFloat()
val y = center.y - radius * cos(Math.toRadians(angle.toDouble())).toFloat()
this.drawContext.canvas.nativeCanvas.drawText(
text, x, y, textPaint
)
}
private fun DrawScope.drawScaleMarkings(center: Offset, radius: Float, scaleMarkings: Int, colors: List<Color>, isNight: Boolean) {
val color = if (isNight) Color.White else Color.Black
val textStyle = TextStyle(color = color, fontSize = 25.sp, fontWeight = FontWeight.Bold)
for (i in -scaleMarkings..scaleMarkings) {
val angle = -180f / (scaleMarkings * 2) * i
val markingRadius = calculateMarkingRadius(i, radius)
drawScaleLine(center, radius, markingRadius, angle, i, colors)
when (i) {
-scaleMarkings -> drawText("50", center, angle, radius*0.8f, textStyle)
-scaleMarkings / 2 -> drawText("25", center, angle, radius*0.8f, textStyle)
0 -> drawText("0", center, angle, radius*0.8f, textStyle)
scaleMarkings / 2 -> drawText("-25", center, angle, radius*0.8f, textStyle)
scaleMarkings -> drawText("-50", center, angle, radius*0.8f, textStyle)
}
}
}
fun DrawScope.drawScaleLine(
center: Offset, radius: Float, markingRadius: Float, angle: Float, i: Int, colors: List<Color>
) {
val start = Offset(
x = center.x + radius * sin(Math.toRadians(angle.toDouble() + 180.0)).toFloat(),
y = center.y + radius * cos(Math.toRadians(angle.toDouble() + 180.0)).toFloat()
)
val end = Offset(
x = center.x + markingRadius * sin(Math.toRadians(angle.toDouble() + 180.0)).toFloat(),
y = center.y + markingRadius * cos(Math.toRadians(angle.toDouble() + 180.0)).toFloat()
)
drawLine(
brush = Brush.linearGradient(colors = colors),
start = start,
end = end,
strokeWidth = if (i % 5 == 0) 4.dp.toPx() else 2.dp.toPx()
)
}
private fun DrawScope.drawNeedle(center: Offset, needleHeight: Float, centsOff: Float, needleColor: Color) {
val needleWidth = 4.dp.toPx()
val needleHeadRadius = needleWidth / 2
val color = needleColor
val centsOff = when {
centsOff < -50 -> -50f
centsOff > 50 -> 50f
else -> centsOff
}
rotate(degrees = 90f * centsOff / 50f, pivot = center, block = {
drawLine(
color = color,
start = center,
end = Offset(
x = center.x,
y = center.y - needleHeight + needleHeadRadius
),
strokeWidth = needleWidth
)
drawCircle(
color = color,
radius = needleHeadRadius,
center = Offset(x = center.x, y = center.y - needleHeight + needleHeadRadius),
)
})
}
@Composable
@Preview(showBackground = true)
fun EnhancedTuningMeterPreview() {
TuningMeter(centsOff = 0f,
needleColor = Color.Red,
arcColors = listOf(Color.Red, Color.Green, Color.Red),
scaleMarkingColors = listOf(Color.DarkGray, Color.LightGray),
scaleMarkings = 10,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(16.dp)
)
} | MASSS-Project/app/src/main/java/it/unipi/puffotuner/TuningMeter.kt | 1511611628 |
package it.unipi.puffotuner
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun NoteIndicator(note: String, modifier: Modifier = Modifier) {
BoxWithConstraints(
contentAlignment = Alignment.Center, modifier = modifier
.fillMaxWidth()
.padding(16.dp)
) {
var fontSize = with(LocalDensity.current) { maxWidth.toSp() / 10 }
fontSize = if (fontSize < 24.sp) 24.sp else fontSize
Text(
text = note, style = MaterialTheme.typography.bodyLarge.copy(
fontSize = fontSize, // Ensure a minimum size
fontWeight = FontWeight.Bold
)
)
}
}
@Preview(showBackground = true)
@Composable
fun PreviewNoteIndicator() {
NoteIndicator(note = "A")
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/NoteIndicator.kt | 570662155 |
package it.unipi.puffotuner
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
@Composable
fun TunerAppBar(
modifier: Modifier = Modifier,
navController: NavController? = null,
title: String,
) {
var showMenu by remember { mutableStateOf(false) }
Surface(
modifier = modifier,
color = Color.Gray.copy(alpha = 0.2f)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(title, modifier = Modifier.padding(16.dp))
Box(modifier = Modifier.padding(4.dp)) {
IconButton(
onClick = { showMenu = true }
) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = "Menu"
)
}
DropdownMenu(
expanded = showMenu,
onDismissRequest = { showMenu = false },
modifier = Modifier.background(Color.Transparent)
) {
DropdownMenuItem(onClick = {
showMenu = false
navController?.navigate("aboutScreen")
}, text = { Text("About") })
}
}
}
}
}
@Preview
@Composable
fun TunerAppBarPreview() {
TunerAppBar(title = "Tuner", modifier = Modifier.fillMaxWidth())
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/TunerTopBarApp.kt | 3483665158 |
package it.unipi.puffotuner
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import it.unipi.puffotuner.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AboutScreen(navController: NavController? = null) {
Scaffold(topBar = {
TopAppBar(title = { Text("About") }, navigationIcon = {
IconButton(onClick = { navController?.navigateUp() }) {
Icon(Icons.Filled.ArrowBack, "Back")
}
})
}) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.verticalScroll(rememberScrollState())
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "About Our App",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(20.dp))
Card(
modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
"Developed By",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
Text("Lorenzo Catoni", style = MaterialTheme.typography.titleMedium)
Text("Leonardo Giovannoni", style = MaterialTheme.typography.titleMedium)
}
}
Spacer(modifier = Modifier.height(20.dp))
AnimatedImageComposable()
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "PuffoTuner is an Android application designed for musicians and enthusiasts who seek precision in tuning their instruments. It provides a modern and intuitive user interface that simplifies the tuning process. The app uses advanced audio processing techniques to accurately detect pitch in real-time, that let accommodate various tuning standards.",
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(20.dp))
Text(
"© 2024 Puffo Trillionario. All rights reserved.",
style = MaterialTheme.typography.bodySmall
)
}
}
}
@Composable
fun AnimatedImageComposable() {
val infiniteTransition = rememberInfiniteTransition()
val angle by infiniteTransition.animateFloat(
initialValue = 0f, targetValue = 360f, animationSpec = infiniteRepeatable(
animation = tween(10000, easing = LinearEasing), repeatMode = RepeatMode.Restart
)
)
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) {
Image(
painter = painterResource(id = R.drawable.puffotrillionario), // Replace with your drawable
contentDescription = "Puffo Trillionario",
modifier = Modifier
.size(200.dp)
.rotate(angle)
)
}
}
| MASSS-Project/app/src/main/java/it/unipi/puffotuner/AboutScreen.kt | 898214778 |
package com.dicoding.picodiploma.mycamera
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.dicoding.picodiploma.mycamera", appContext.packageName)
}
} | ImageClassificationUsingCameraX/app/src/androidTest/java/com/dicoding/picodiploma/mycamera/ExampleInstrumentedTest.kt | 2048176264 |
package com.dicoding.picodiploma.mycamera
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)
}
} | ImageClassificationUsingCameraX/app/src/test/java/com/dicoding/picodiploma/mycamera/ExampleUnitTest.kt | 2621350599 |
package com.dicoding.picodiploma.mycamera
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.dicoding.picodiploma.mycamera.CameraActivity.Companion.CAMERAX_RESULT
import com.dicoding.picodiploma.mycamera.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var currentImageUri: Uri? = null
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
showToast("Permission request granted")
} else {
showToast("Permission request denied")
}
}
private fun allPermissionsGranted() =
ContextCompat.checkSelfPermission(
this,
REQUIRED_PERMISSION
) == PackageManager.PERMISSION_GRANTED
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (!allPermissionsGranted()) {
requestPermissionLauncher.launch(REQUIRED_PERMISSION)
}
binding.galleryButton.setOnClickListener { startGallery() }
binding.cameraButton.setOnClickListener { startCamera() }
binding.cameraXButton.setOnClickListener { startCameraX() }
binding.analyzeButton.setOnClickListener {
currentImageUri?.let {
analyzeImage(it)
} ?: run {
showToast(getString(R.string.empty_image_warning))
}
}
}
private fun startGallery() {
launcherGallery.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}
private val launcherGallery = registerForActivityResult(
ActivityResultContracts.PickVisualMedia()
) { uri: Uri? ->
if (uri != null) {
currentImageUri = uri
showImage()
} else {
Log.d("Photo Picker", "No media selected")
}
}
private fun startCamera() {
currentImageUri = getImageUri(this)
launcherIntentCamera.launch(currentImageUri)
}
private val launcherIntentCamera = registerForActivityResult(
ActivityResultContracts.TakePicture()
) { isSuccess ->
if (isSuccess) {
showImage()
}
}
private fun startCameraX() {
val intent = Intent(this, CameraActivity::class.java)
launcherIntentCameraX.launch(intent)
}
private val launcherIntentCameraX = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode == CAMERAX_RESULT) {
currentImageUri = it.data?.getStringExtra(CameraActivity.EXTRA_CAMERAX_IMAGE)?.toUri()
showImage()
}
}
private fun showImage() {
currentImageUri?.let {
Log.d("Image URI", "showImage: $it")
binding.previewImageView.setImageURI(it)
}
}
private fun analyzeImage(uri: Uri) {
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra(ResultActivity.EXTRA_IMAGE_URI, currentImageUri.toString())
startActivity(intent)
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
companion object {
private const val REQUIRED_PERMISSION = Manifest.permission.CAMERA
}
}
| ImageClassificationUsingCameraX/app/src/main/java/com/dicoding/picodiploma/mycamera/MainActivity.kt | 2209741855 |
package com.dicoding.picodiploma.mycamera
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.dicoding.picodiploma.mycamera.databinding.ActivityResultBinding
class ResultActivity : AppCompatActivity() {
private lateinit var binding: ActivityResultBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityResultBinding.inflate(layoutInflater)
setContentView(binding.root)
val imageUri = Uri.parse(intent.getStringExtra(EXTRA_IMAGE_URI))
imageUri?.let {
Log.d("Image URI", "showImage: $it")
binding.resultImage.setImageURI(it)
}
}
companion object {
const val EXTRA_IMAGE_URI = "extra_image_uri"
const val EXTRA_RESULT = "extra_result"
}
} | ImageClassificationUsingCameraX/app/src/main/java/com/dicoding/picodiploma/mycamera/ResultActivity.kt | 1227236376 |
package com.dicoding.picodiploma.mycamera
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
private const val FILENAME_FORMAT = "yyyyMMdd_HHmmss"
private val timeStamp: String = SimpleDateFormat(FILENAME_FORMAT, Locale.US).format(Date())
fun getImageUri(context: Context): Uri {
var uri: Uri? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "$timeStamp.jpg")
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/MyCamera/")
}
uri = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
)
// content://media/external/images/media/1000000062
// storage/emulated/0/Pictures/MyCamera/20230825_155303.jpg
}
return uri ?: getImageUriForPreQ(context)
}
private fun getImageUriForPreQ(context: Context): Uri {
val filesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val imageFile = File(filesDir, "/MyCamera/$timeStamp.jpg")
if (imageFile.parentFile?.exists() == false) imageFile.parentFile?.mkdir()
return FileProvider.getUriForFile(
context,
"${BuildConfig.APPLICATION_ID}.fileprovider",
imageFile
)
//content://com.dicoding.picodiploma.mycamera.fileprovider/my_images/MyCamera/20230825_133659.jpg
}
fun createCustomTempFile(context: Context): File {
val filesDir = context.externalCacheDir
return File.createTempFile(timeStamp, ".jpg", filesDir)
} | ImageClassificationUsingCameraX/app/src/main/java/com/dicoding/picodiploma/mycamera/Utils.kt | 2659717691 |
package com.dicoding.picodiploma.mycamera
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import androidx.camera.core.ImageProxy
import com.google.android.gms.tflite.client.TfLiteInitializationOptions
import com.google.android.gms.tflite.gpu.support.TfLiteGpu
import org.tensorflow.lite.DataType
import org.tensorflow.lite.gpu.CompatibilityList
import org.tensorflow.lite.support.common.ops.CastOp
import org.tensorflow.lite.support.image.ImageProcessor
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.image.ops.ResizeOp
import org.tensorflow.lite.task.core.BaseOptions
import org.tensorflow.lite.task.core.vision.ImageProcessingOptions
import org.tensorflow.lite.task.gms.vision.TfLiteVision
import org.tensorflow.lite.task.gms.vision.classifier.Classifications
import org.tensorflow.lite.task.gms.vision.classifier.ImageClassifier
class ImageClassifierHelper (
var threshold: Float = 0.1f,
var maxResults: Int = 3,
val modelName: String = "mobilenet_v1.tflite",
val context: Context,
val classifierListener: ClassifierListener?
) {
private var imageClassifier: ImageClassifier? = null
interface ClassifierListener {
fun onError(error: String)
fun onResults(
results: List<Classifications>?,
inferenceTime: Long
)
}
init {
TfLiteGpu.isGpuDelegateAvailable(context).onSuccessTask { gpuAvailable ->
val optionsBuilder = TfLiteInitializationOptions.builder()
if (gpuAvailable) {
optionsBuilder.setEnableGpuDelegateSupport(true)
}
TfLiteVision.initialize(context, optionsBuilder.build())
}.addOnSuccessListener {
setupImageClassifier()
}.addOnFailureListener {
classifierListener?.onError(context.getString(R.string.tflitevision_is_not_initialized_yet))
}
}
private fun setupImageClassifier() {
val optionsBuilder = ImageClassifier.ImageClassifierOptions.builder()
.setScoreThreshold(threshold)
.setMaxResults(maxResults)
val baseOptionsBuilder = BaseOptions.builder()
if (CompatibilityList().isDelegateSupportedOnThisDevice){
baseOptionsBuilder.useGpu()
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1){
baseOptionsBuilder.useNnapi()
} else {
// Menggunakan CPU
baseOptionsBuilder.setNumThreads(4)
}
optionsBuilder.setBaseOptions(baseOptionsBuilder.build())
try {
imageClassifier = ImageClassifier.createFromFileAndOptions(
context,
modelName,
optionsBuilder.build()
)
} catch (e: IllegalStateException) {
classifierListener?.onError(context.getString(R.string.image_classifier_failed))
Log.e(TAG, e.message.toString())
}
}
fun classifyImage(image: ImageProxy) {
if (!TfLiteVision.isInitialized()) {
val errorMessage = context.getString(R.string.tflitevision_is_not_initialized_yet)
Log.e(TAG, errorMessage)
classifierListener?.onError(errorMessage)
return
}
if (imageClassifier == null) {
setupImageClassifier()
}
val imageProcessor = ImageProcessor.Builder()
.add(ResizeOp(224, 224, ResizeOp.ResizeMethod.NEAREST_NEIGHBOR))
.add(CastOp(DataType.UINT8))
.build()
val tensorImage = imageProcessor.process(TensorImage.fromBitmap(toBitmap(image)))
val imageProcessingOptions = ImageProcessingOptions.builder()
.setOrientation(getOrientationFromRotation(image.imageInfo.rotationDegrees))
.build()
var inferenceTime = SystemClock.uptimeMillis()
val results = imageClassifier?.classify(tensorImage, imageProcessingOptions)
inferenceTime = SystemClock.uptimeMillis() - inferenceTime
classifierListener?.onResults(
results,
inferenceTime
)
}
private fun getOrientationFromRotation(rotation: Int): ImageProcessingOptions.Orientation {
return when (rotation) {
Surface.ROTATION_270 -> ImageProcessingOptions.Orientation.BOTTOM_RIGHT
Surface.ROTATION_180 -> ImageProcessingOptions.Orientation.RIGHT_BOTTOM
Surface.ROTATION_90 -> ImageProcessingOptions.Orientation.TOP_LEFT
else -> ImageProcessingOptions.Orientation.RIGHT_TOP
}
}
private fun toBitmap(image: ImageProxy): Bitmap {
val bitmapBuffer = Bitmap.createBitmap(
image.width,
image.height,
Bitmap.Config.ARGB_8888
)
image.use { bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer) }
image.close()
return bitmapBuffer
}
companion object {
private const val TAG = "ImageClassifierHelper"
}
} | ImageClassificationUsingCameraX/app/src/main/java/com/dicoding/picodiploma/mycamera/ImageClassifierHelper.kt | 3674851152 |
package com.dicoding.picodiploma.mycamera
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowInsets
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.core.resolutionselector.AspectRatioStrategy
import androidx.camera.core.resolutionselector.ResolutionSelector
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.dicoding.picodiploma.mycamera.databinding.ActivityCameraBinding
import org.tensorflow.lite.task.gms.vision.classifier.Classifications
import java.text.NumberFormat
import java.util.concurrent.Executors
class CameraActivity : AppCompatActivity() {
private lateinit var imageClassifierHelper: ImageClassifierHelper
private lateinit var binding: ActivityCameraBinding
private var cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(binding.root)
}
public override fun onResume() {
super.onResume()
hideSystemUI()
startCamera()
}
private fun startCamera() {
imageClassifierHelper = ImageClassifierHelper(
context = this,
classifierListener = object : ImageClassifierHelper.ClassifierListener {
override fun onError(error: String) {
runOnUiThread {
Toast.makeText(this@CameraActivity, error, Toast.LENGTH_SHORT).show()
}
}
override fun onResults(results: List<Classifications>?, inferenceTime: Long) {
runOnUiThread {
results?.let { it ->
if (it.isNotEmpty() && it[0].categories.isNotEmpty()) {
println(it)
val sortedCategories =
it[0].categories.sortedByDescending { it?.score }
val displayResult =
sortedCategories.joinToString("\n") {
"${it.label} " + NumberFormat.getPercentInstance()
.format(it.score).trim()
}
binding.tvResult.text = displayResult
binding.tvInferenceTime.text = "$inferenceTime ms"
} else {
binding.tvResult.text = ""
binding.tvInferenceTime.text = ""
}
}
}
}
}
)
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val resolutionSelector = ResolutionSelector.Builder()
.setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY)
.build()
val imageAnalyzer = ImageAnalysis.Builder()
.setResolutionSelector(resolutionSelector)
.setTargetRotation(binding.viewFinder.display.rotation)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
.build()
imageAnalyzer.setAnalyzer(Executors.newSingleThreadExecutor()) { image ->
imageClassifierHelper.classifyImage(image)
}
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(binding.viewFinder.surfaceProvider)
}
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
this,
cameraSelector,
preview
)
} catch (exc: Exception) {
Toast.makeText(
this@CameraActivity,
"Gagal memunculkan kamera.",
Toast.LENGTH_SHORT
).show()
Log.e(TAG, "startCamera: ${exc.message}")
}
}, ContextCompat.getMainExecutor(this))
}
private fun hideSystemUI() {
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
supportActionBar?.hide()
}
companion object {
private const val TAG = "CameraActivity"
const val EXTRA_CAMERAX_IMAGE = "CameraX Image"
const val CAMERAX_RESULT = 200
}
} | ImageClassificationUsingCameraX/app/src/main/java/com/dicoding/picodiploma/mycamera/CameraActivity.kt | 2117141542 |
package com.example.share_money_now
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.share_money_now", appContext.packageName)
}
} | Share-Money-Now/app/src/androidTest/java/com/example/share_money_now/ExampleInstrumentedTest.kt | 2172578382 |
package com.example.share_money_now
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)
}
} | Share-Money-Now/app/src/test/java/com/example/share_money_now/ExampleUnitTest.kt | 4151752102 |
package com.example.share_money_now.ui.theme
import androidx.compose.ui.graphics.Color
val PrimaryColor = Color(0xFF47C2FF)
val LightVariant1 = Color(0xFF80AEE5)
val LightVariant2 = Color(0xFFA4C3F9)
val LightVariant3 = Color(0xFFC8D9FF)
val DarkVariant1 = Color(0xFF1A6BB3)
val DarkVariant2 = Color(0xFF00518A)
val DarkVariant3 = Color(0xFF003B66) | Share-Money-Now/app/src/main/java/com/example/share_money_now/ui/theme/Color.kt | 658717894 |
package com.example.share_money_now.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.compose.ui.tooling.preview.Preview
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = PrimaryColor,
secondary = DarkVariant2,
tertiary = LightVariant3
)
private val LightColorScheme = lightColorScheme(
primary = LightVariant2,
secondary = LightVariant1,
tertiary = LightVariant3
/* 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 ShareMoneyNowTheme(
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
)
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/ui/theme/Theme.kt | 2211799467 |
package com.example.share_money_now.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
)
*/
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/ui/theme/Type.kt | 486134369 |
package com.example.share_money_now
import FirebaseManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.Person
import com.google.firebase.auth.FirebaseAuth
import java.util.UUID
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LandingScreen(navController: NavController, firebaseManager: FirebaseManager,
viewModel: CreateGroupViewModel = viewModel()) {
var userName by remember { mutableStateOf(FirebaseAuth.getInstance().currentUser?.displayName) }
var newGroupName by remember { mutableStateOf("") }
var isAddingGroup by remember { mutableStateOf(false) }
val groups by viewModel.items.observeAsState(emptyList())
var groupDescription by remember { mutableStateOf("") }
val CreateGroupViewModel = viewModel<CreateGroupViewModel>()
LaunchedEffect(Unit) {
val currentUserEmail = FirebaseAuth.getInstance().currentUser?.email
currentUserEmail?.let { email ->
CreateGroupViewModel.getItemsByMember(email)
}
}
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Logo
Image(
painter = painterResource(id = R.drawable.sharemoneynowlogo),
contentDescription = "Logo",
modifier = Modifier
.width(250.dp)
.height(100.dp),
)
// User Name Button
Button(
onClick = {
navController.navigate(Screen.UserScreen.route)
},
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
colors = ButtonDefaults.buttonColors(Color.Transparent)
) {
Text(
text = "Welcome " + userName.toString() + "!",
color = Color.Black,
fontSize = 30.sp,
textAlign = TextAlign.Center,
modifier = Modifier.height(50.dp)
)
}
// Group List
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
groups.forEach { item ->
item {
var editableText by remember { mutableIntStateOf(100) }
val textColor =
if (editableText < 0) Color.Red else if (editableText > 0) Color(0xFF006400) else Color.Black
Button(
onClick = {
val groupId = item.id
navController.navigate("group_screen/$groupId")
},
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 0.dp),
colors = ButtonDefaults.buttonColors(Color.Transparent)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.name + " - ",
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier.padding(end = 8.dp),
textAlign = TextAlign.Center
)
Text(
text = "$editableText kr.",
color = textColor,
fontSize = 20.sp,
textAlign = TextAlign.Center
)
}
}
Divider(
color = Color.Gray,
thickness = 1.dp,
modifier = Modifier.fillMaxWidth()
)
}
}
}
// Button to Add New Group
if (!isAddingGroup) {
Button(
onClick = {
isAddingGroup = true
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Add New Group")
}
}
var isButtonClicked by remember { mutableStateOf(false) }
if (newGroupName.isEmpty() && isButtonClicked) {
Text(
text = "Please enter a group name",
color = Color.Red,
fontSize = 18.sp,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
textAlign = TextAlign.Center
)
}
// Text Field to Enter New Group Name
if (isAddingGroup) {
OutlinedTextField(
value = newGroupName,
onValueChange = { newGroupName = it },
label = { Text("New Group Name") },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
)
OutlinedTextField(
value = groupDescription,
onValueChange = { groupDescription = it },
label = { Text("Group Description") },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
)
// Button to Confirm New Group
Button(
onClick = {
val currentUser = FirebaseAuth.getInstance().currentUser
if (currentUser != null) {
CreateGroupViewModel.fetchNameForEmail(currentUser.email ?: "") { associatedName ->
if (associatedName != null) {
val group = Group(
UUID.randomUUID().toString(),
currentUser.email ?: "",
newGroupName,
listOf(Person(currentUser.email ?: "", associatedName)),
groupDescription,
0.0,
mapOf(((currentUser.email).toString()).replace(".","") to 0.0)
)
firebaseManager.createGroup(group)
if (newGroupName.isNotEmpty()) {
newGroupName = ""
isAddingGroup = false
navController.navigate("group_screen/${group.id}")
} else {
isButtonClicked = true
}
} else {
println("Associated name not found for the logged-in user.")
}
}
} else {
println("Current user is null.")
}
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Add Group")
}
Button(
onClick = {
newGroupName = ""
groupDescription = ""
isAddingGroup = false
isButtonClicked = false
},
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(Color(0xFFFF5A5F ))
) {
Text(text = "Cancel")
}
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/LandingScreen.kt | 1192388503 |
package com.example.share_money_now
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.google.firebase.FirebaseApp
import dagger.hilt.android.AndroidEntryPoint
import com.example.share_money_now.ui.theme.ShareMoneyNowTheme
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(this);
super.onCreate(savedInstanceState)
setContent {
ShareMoneyNowTheme{
Navigation()
}
}
}
}
| Share-Money-Now/app/src/main/java/com/example/share_money_now/MainActivity.kt | 3665438235 |
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.PaymentList
import com.example.share_money_now.data_classes.Person
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class FirebaseManager {
private val databaseReference: DatabaseReference
init {
databaseReference = FirebaseDatabase.getInstance("https://share-money-now-default-rtdb.europe-west1.firebasedatabase.app").reference
}
fun createGroup(group: Group) {
val groupsReference = databaseReference.child("groups")
val groupReference = groupsReference.push()
groupReference.setValue(groupReference.key?.let { group.copy(id = it) })
.addOnSuccessListener {
}
.addOnFailureListener { e ->
e.printStackTrace()
}
}
fun addPersonToGroup(groupId: String, person: Person) {
val groupReference = databaseReference.child("groups").child(groupId)
groupReference.child("members").push().setValue(person)
}
fun removePersonFromGroup(groupId: String, personId: String) {
val groupReference = databaseReference.child("groups").child(groupId).child("members").child(personId)
groupReference.removeValue()
}
fun addPersonOnSignUp(person: Person){
val personReference = databaseReference.child("persons").push()
personReference.setValue(person)
}
fun fetchGroupDetails(groupId: String, onDataReceived: (Group?) -> Unit) {
val groupsRef = databaseReference.child("groups").orderByChild("id").equalTo(groupId)
groupsRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val groupData = snapshot.getValue(Group::class.java)
onDataReceived(groupData)
}
override fun onCancelled(error: DatabaseError) {
// Handle database error
onDataReceived(null)
}
})
}
}
| Share-Money-Now/app/src/main/java/com/example/share_money_now/FirebaseManager.kt | 141580913 |
package com.example.share_money_now
import FirebaseManager
import PersonalGroupViewModel
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.Person
import com.google.firebase.auth.FirebaseAuth
import kotlin.math.absoluteValue
import kotlin.math.exp
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun GroupScreen(navController: NavController,
groupId: String?,
firebaseManager: FirebaseManager,
viewModel: PersonalGroupViewModel = viewModel()
) {
var totalAmount by remember { mutableStateOf(0.0) }
var participants by remember { mutableStateOf(listOf("")) }
var showDialog by remember { mutableStateOf(false) }
var showEditDialog by remember { mutableStateOf(false) }
var showDialogExpense by remember { mutableStateOf(false) }
var showDialogPay by remember { mutableStateOf(false) }
var expenseValue by remember { mutableStateOf<Double?>(null) }
var textFieldValue by remember { mutableStateOf(TextFieldValue()) }
var paidAmountMap: Map<String, Double> = emptyMap()
var group by remember { mutableStateOf(Group()) }
var cleanEmail = FirebaseAuth.getInstance().currentUser?.email?.replace(".", "")
var mail by remember { mutableStateOf("") }
var paymentAmount by remember { mutableStateOf(0.0) }
val gId = groupId.toString()
val keyboardController = LocalSoftwareKeyboardController.current
val personalGroupViewModel = viewModel<PersonalGroupViewModel>()
val groupState by personalGroupViewModel.group.collectAsState()
var debt by remember { mutableStateOf(0.0) }
if (!groupId.isNullOrBlank()) {
personalGroupViewModel.findGroupByGroupId(groupId) { firebaseGroupId ->
if (firebaseGroupId != null) {
personalGroupViewModel.fetchGroupDetails(firebaseGroupId) { fetchedGroup ->
if (fetchedGroup != null) {
group = fetchedGroup
participants = fetchedGroup.members.map { it?.name ?: "" }
totalAmount = fetchedGroup.totalAmount
paidAmountMap = fetchedGroup.paidAmount
personalGroupViewModel.setGroup(fetchedGroup)
} else {
}
}
} else {
}
}
}
// LaunchedEffect for fetching group details
LaunchedEffect(groupId) {
if (!groupId.isNullOrBlank()) {
personalGroupViewModel.findGroupByGroupId(groupId) { firebaseGroupId ->
if (firebaseGroupId != null) {
personalGroupViewModel.fetchGroupDetails(firebaseGroupId) { fetchedGroup ->
if (fetchedGroup != null) {
group = fetchedGroup // Update the 'group' variable with fetched data
participants = fetchedGroup.members.map { it?.name ?: "" }
totalAmount = fetchedGroup.totalAmount
paidAmountMap = fetchedGroup.paidAmount
personalGroupViewModel.setGroup(fetchedGroup)
} else {
// Handle scenario when group data is null or not found
}
}
} else {
// Handle scenario when groupId is not found
}
}
}
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = group.name,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
},
actions = {
IconButton(
onClick = {
showEditDialog = true
keyboardController?.show()
}
) {
Icon(
painter = painterResource(id = R.drawable.edit_text),
contentDescription = stringResource(id = R.string.edit_button),
modifier = Modifier.size(24.dp)
)
}
}
)
}
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.padding(16.dp)
) {
// Total Amount
Text(
text = "Total Amount: ",
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
Text(
text = "$totalAmount",
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
// Participants
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
items(participants.size) { index ->
try {
if (group.members.size > 0){
mail = (group.members.get(index)?.email)?.replace(".","") ?: ""
debt = (totalAmount / participants.size) - (paidAmountMap[mail]?.toDouble() ?: 0.0)
}else{
debt = 0.0
}
}
catch (e: Exception){
debt = 0.0
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
// Participant Details
Column {
Text(text = participants.getOrNull(index) ?: "")
Text(text = "$debt" )
}
// Remove Button
Button(onClick = {
val emailToRemove = participants.getOrNull(index) ?: ""
val indexToRemove =
group.members.indexOfFirst { it?.name ?: "" == emailToRemove }
if (indexToRemove != -1) {
// Email is registered and found in the members list
// Remove the Person from the members list
val updatedMembers = group.members.toMutableList().apply {
removeAt(indexToRemove)
}
// Update the group with the modified members list
group = group.copy(members = updatedMembers)
// Update the group in the Firebase Realtime Database
personalGroupViewModel.updateGroupInFirebase(group)
participants = group.members.map { it?.name ?: "" }
}
}
) {
Text(text = "Remove")
}
}
}
}
// Description
Text(
text = "Description: ${group.description}",
)
// Share group expenses Button
Button(
onClick = {
showDialogExpense = true
},
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
) {
Text(text = "Share Group Expense")
}
// Dialog for Share Group Expenses
if (showDialogExpense) {
Dialog(
onDismissRequest = {
showDialogExpense = false
},
content = {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "Enter Expense Amount",
fontSize = 20.sp,
modifier = Modifier
.padding(bottom = 8.dp)
)
OutlinedTextField(
value = expenseValue.toString(),
onValueChange = {
// Handle the case where the input is not a valid double
expenseValue = it.toDoubleOrNull() ?: 0.0
},
label = { Text("Expense Amount") },
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number
),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = {
// Dismiss the dialog without processing the input
showDialogExpense = false
}
) {
Text(text = "Cancel")
}
Spacer(modifier = Modifier.width(16.dp))
TextButton(
onClick = {
totalAmount += expenseValue!!
group = group.copy(totalAmount = totalAmount)
val updatedPaidAmount = group.paidAmount.toMutableMap().apply {
val currentAmount = getOrDefault(cleanEmail, 0.0)
if (cleanEmail != null) {
put(cleanEmail!!, currentAmount + expenseValue!!)
}
}
group = group.copy(paidAmount = updatedPaidAmount)
// Reset the paymentAmount and dismiss the dialog
expenseValue = 0.0
showDialogExpense = false
personalGroupViewModel.updateGroupInFirebase(group)
showDialogExpense = false
}
) {
Text(text = "OK")
}
}
}
}
)
}
// Pay Button
Button(
onClick = {
/*
TODO, IMPLEMENT PAY MY PART FUNCTIONALITY
*/
},
modifier = Modifier
.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(text = "Pay My Part")
}
}
// Add people Button
Button(
onClick = {
showDialog = true
},
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
) {
Text(text = "Add people")
}
if (showEditDialog) {
Dialog(
onDismissRequest = {
showEditDialog = false
keyboardController?.hide()
},
content = {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "Change Group Name",
fontSize = 20.sp,
modifier = Modifier
.padding(bottom = 8.dp)
)
OutlinedTextField(
value = textFieldValue,
onValueChange = {
textFieldValue = it
},
label = { Text("New Group Name") },
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
group = group.copy(name = textFieldValue.text)
personalGroupViewModel.updateGroupInFirebase(group)
showEditDialog = false
keyboardController?.hide()
}
),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = {
showEditDialog = false
keyboardController?.hide()
}
) {
Text(text = "Cancel")
}
Spacer(modifier = Modifier.width(16.dp))
TextButton(
onClick = {
group = group.copy(name = textFieldValue.text)
personalGroupViewModel.updateGroupInFirebase(group)
showEditDialog = false
keyboardController?.hide()
}
) {
Text(text = "Save")
}
}
}
}
)
}
// Dialog for adding people
if (showDialog) {
Dialog(
onDismissRequest = {
showDialog = false
// Hide the keyboard when the dialog is dismissed
keyboardController?.hide()
},
content = {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "Add People",
fontSize = 20.sp,
modifier = Modifier
.padding(bottom = 8.dp)
)
TextField(
value = textFieldValue,
onValueChange = { newValue ->
textFieldValue = newValue
},
label = { Text("Enter email of person") },
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
showDialog = false
keyboardController?.hide()
}
),
colors = TextFieldDefaults.textFieldColors(
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
cursorColor = contentColorFor(MaterialTheme.colorScheme.background)
),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = {
showDialog = false
// Hide the keyboard when the "Cancel" button is clicked
keyboardController?.hide()
}
) {
Text(text = "Cancel")
}
Spacer(modifier = Modifier.width(16.dp))
TextButton(
onClick = {
val emailToAdd = textFieldValue.text
personalGroupViewModel.checkIfEmailExistsInFirebase(emailToAdd) { isEmailRegistered ->
if (isEmailRegistered) {
// Email is registered, add the participant
participants = participants.toMutableList().apply {
add(emailToAdd)
}
// Fetch the associated name for the emailToAdd from the database
personalGroupViewModel.fetchNameForEmail(emailToAdd) { associatedName ->
if (associatedName != null) {
// Use the associated name when creating the new Person
val newPerson = Person(emailToAdd, associatedName)
group = group.copy(members = group.members + newPerson)
val updatedPaidAmount = group.paidAmount.toMutableMap().apply {
put((emailToAdd.toString()).replace(".",""), 0.0) // Assuming you want to initialize the new user with 0.0 paidAmount
}
group = group.copy(paidAmount = updatedPaidAmount)
// Update the group in the Firebase Realtime Database
personalGroupViewModel.updateGroupInFirebase(group)
// Update participants with the names of the current members
participants = group.members.map { it?.name ?: "" }
showDialog = false
// Hide the keyboard when the "Add" button is clicked
keyboardController?.hide()
} else {
// Handle the scenario when the associated name is not found
println("Associated name not found for the email: $emailToAdd")
}
}
} else {
// Handle the scenario when the email is not registered
// You might want to display an error message or take appropriate action
// For now, let's just print a message
println("Email is not registered in Firebase.")
}
}
}
) {
Text(text = "Add")
}
}
}
}
)
}
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/GroupScreen.kt | 3828626767 |
package com.example.share_money_now.firebaseauth.di
import com.example.share_money_now.firebaseauth.data.AuthRepository
import com.example.share_money_now.firebaseauth.data.AuthRepositoryImpl
import com.google.firebase.auth.FirebaseAuth
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun providesFirebaseAuth() = FirebaseAuth.getInstance()
@Provides
@Singleton
fun providesRepositoryImpl(firebaseAuth: FirebaseAuth):AuthRepository{
return AuthRepositoryImpl(firebaseAuth)
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/firebaseauth/di/AppModule.kt | 979475620 |
package com.example.share_money_now.firebaseauth.util
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
class Loading<T>(data: T? = null) : Resource<T>(data)
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/firebaseauth/util/Resource.kt | 3773636164 |
package com.example.share_money_now.firebaseauth
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ApplicationFirebaseAuth:Application() {
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/firebaseauth/ApplicationFirebaseAuth.kt | 1427168345 |
package com.example.share_money_now.firebaseauth.data
import com.example.share_money_now.firebaseauth.util.Resource
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserProfileChangeRequest
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class AuthRepositoryImpl @Inject constructor(
private val firebaseAuth: FirebaseAuth,
) : AuthRepository {
override fun loginUser(email: String, password: String): Flow<Resource<AuthResult>> {
return flow {
emit(Resource.Loading())
val result = firebaseAuth.signInWithEmailAndPassword(email, password).await()
emit(Resource.Success(result))
}.catch {
emit(Resource.Error(it.message.toString()))
}
}
override fun registerUser(email: String, password: String, name:String): Flow<Resource<AuthResult>> {
return flow {
emit(Resource.Loading())
val result = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
result?.user?.updateProfile(UserProfileChangeRequest.Builder().setDisplayName(name).build())?.await()
emit(Resource.Success(result))
}.catch {
emit(Resource.Error(it.message.toString()))
}
}
override fun logOut() {
firebaseAuth.signOut()
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/firebaseauth/data/AuthRepositoryImpl.kt | 12177054 |
package com.example.share_money_now.firebaseauth.data
import com.example.share_money_now.firebaseauth.util.Resource
import com.google.firebase.auth.AuthResult
import kotlinx.coroutines.flow.Flow
interface AuthRepository {
fun loginUser(email:String, password:String): Flow<Resource<AuthResult>>
fun registerUser(email:String, password:String, name:String): Flow<Resource<AuthResult>>
fun logOut()
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/firebaseauth/data/AuthRepository.kt | 2185421249 |
package com.example.share_money_now
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
@Composable
fun WelcomeScreen(navController: NavController) {
val context = LocalContext.current
Column(
modifier = Modifier
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Logo
Image(
painter = painterResource(id = R.drawable.sharemoneynowlogo), //temp logo
contentDescription = "Logo",
modifier = Modifier
.width(250.dp)
.height(200.dp)
)
// Welcome Text
Text(
text = "Welcome to Share-Money-Now",
fontWeight = FontWeight.Bold,
fontSize = 26.sp,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 50.dp),
textAlign = TextAlign.Center
)
// Sign In Button
Button(
onClick = {
navController.navigate(Screen.SigninScreen.route)
},
modifier = Modifier
.width(200.dp)
.padding(bottom = 16.dp)
) {
Text(
text = "Sign in",
fontSize = 20.sp
)
}
// Sign Up Button
Button(
onClick = {
navController.navigate(Screen.SignupScreen.route)
},
modifier = Modifier.width(200.dp)
) {
Text(
text = "Sign up",
fontSize = 20.sp
)
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/WelcomeScreen.kt | 2679008659 |
package com.example.share_money_now.data_classes
data class Group(
val id: String = "",
val ownerId: String = "",
val name: String = "",
val members: List<Person?> = emptyList(),
val description: String = "",
val totalAmount: Double = 0.0,
var paidAmount: Map<String, Double> = emptyMap()
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/data_classes/Group.kt | 915497688 |
package com.example.share_money_now.data_classes
data class Payment(
val name: String,
val cost: Double,
val members: List<Person?> = emptyList()
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/data_classes/Payment.kt | 449304188 |
package com.example.share_money_now.data_classes
data class Person(
val email: String = "",
val name: String = "",
val groups: List<Group> = emptyList()
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/data_classes/Person.kt | 1802160634 |
package com.example.share_money_now.data_classes
data class PaymentList(
var groupId: String,
var paymentList: List<Payment> = emptyList(),
var paidAmount: Map<Person, Double> = emptyMap(),
var individualCostAmount: Map<Person, Double> = emptyMap()
)
| Share-Money-Now/app/src/main/java/com/example/share_money_now/data_classes/PaymentList.kt | 3843821772 |
package com.example.share_money_now
import FirebaseManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.share_money_now.login_screen.SigninScreen
import com.example.share_money_now.signup_screen.SignupScreen
import com.google.firebase.auth.FirebaseAuth
@Composable
fun Navigation() {
val navController = rememberNavController()
// Check if the user is already signed in
val isUserSignedIn by remember { mutableStateOf(checkUserSignedIn()) }
NavHost(navController = navController, startDestination = getStartDestination(isUserSignedIn)) {
composable(route = Screen.WelcomeScreen.route){
WelcomeScreen(navController = navController)
}
composable(route = Screen.SigninScreen.route) {
SigninScreen(navController = navController)
}
composable(route = Screen.SignupScreen.route) {
SignupScreen(navController = navController, firebaseManager = FirebaseManager())
}
composable(route = Screen.LandingScreen.route) {
LandingScreen(navController = navController, firebaseManager = FirebaseManager())
}
composable(route = Screen.UserScreen.route) {
UserScreen(navController = navController)
}
composable(route = Screen.ExpensesScreen.route) {
ExpensesScreen(navController = navController)
}
composable(
route = "group_screen/{groupId}",
arguments = listOf(
navArgument(name = "groupId")
{type = NavType.StringType}
)
) { backstackEntry ->
GroupScreen(navController = navController, groupId = backstackEntry.arguments?.getString("groupId"), firebaseManager = FirebaseManager())
//GroupScreen(navController = navController)
}
}
}
private fun checkUserSignedIn(): Boolean {
return FirebaseAuth.getInstance().currentUser != null
}
private fun getStartDestination(isUserSignedIn: Boolean): String {
return if (isUserSignedIn) {
Screen.LandingScreen.route
} else {
Screen.WelcomeScreen.route
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/Navigation.kt | 3136997151 |
package com.example.share_money_now.login_screen
data class SignInState(
val isLoading: Boolean = false,
val isSuccess: String? = "",
val isError: String? = ""
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/login_screen/SignInState.kt | 524920681 |
package com.example.share_money_now.login_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.share_money_now.firebaseauth.data.AuthRepository
import com.example.share_money_now.firebaseauth.util.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SignInViewModel @Inject constructor(
private val repository: AuthRepository
): ViewModel() {
val _signInState = Channel<SignInState>()
val signInState = _signInState.receiveAsFlow()
fun loginUser(email:String, password:String) = viewModelScope.launch {
repository.loginUser(email, password).collect{result ->
when(result){
is Resource.Success -> {
_signInState.send(SignInState(isSuccess = "Sign In Succes"))
}
is Resource.Loading ->{
_signInState.send(SignInState(isLoading = true))
}
is Resource.Error -> {
_signInState.send(SignInState(isError = result.message))
}
}
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/login_screen/SignInViewModel.kt | 1013233463 |
package com.example.share_money_now.login_screen
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.share_money_now.R
import com.example.share_money_now.Screen
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SigninScreen(
navController: NavController,
viewModel: SignInViewModel = hiltViewModel()
) {
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val state = viewModel.signInState.collectAsState(initial = null)
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Welcome Text
Image(
painter = painterResource(id = R.drawable.sharemoneynowlogo) ,
contentDescription = "Logo",
modifier = Modifier
.width(250.dp)
.height(200.dp)
)
Text(
text = "Sign In",
fontWeight = FontWeight.Bold,
fontSize = 17.sp,
modifier = Modifier.padding(bottom = 16.dp)
)
// Email TextField
TextField(
value = email,
onValueChange = { email = it },
placeholder = { Text("Email") },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
// Password TextField
TextField(
value = password,
onValueChange = { password = it },
placeholder = { Text("Password") },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
// Sign In Button
Button(
onClick = {
scope.launch {
viewModel.loginUser(email, password)
navController.navigate(Screen.LandingScreen.route)
}
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Sign In")
}
Text(
text = "Don't have an account? Sign Up",
color = Color.Gray,
modifier = Modifier
.clickable {
navController.navigate(Screen.SignupScreen.route)
}
.padding(16.dp)
)
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/login_screen/SigninScreen.kt | 2672900236 |
package com.example.share_money_now
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.*
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.UserProfileChangeRequest
import java.io.Console
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserScreen(navController: NavController) {
var userName by remember { mutableStateOf(FirebaseAuth.getInstance().currentUser?.displayName) }
var userEmail by remember { mutableStateOf(FirebaseAuth.getInstance().currentUser?.email) }
var newDebtUpdatesEnabled by remember { mutableStateOf(true) }
var groupUpdatesEnabled by remember { mutableStateOf(true) }
var isEditing by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Title
Text(
text = "User Settings",
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(top = 16.dp),
textAlign = TextAlign.Center
)
// User Information
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
if (isEditing) {
OutlinedTextField(
value = userName ?: "",
onValueChange = { userName = it },
label = { Text("Name") },
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = userEmail ?: "",
onValueChange = { userEmail = it },
label = { Text("Email") },
modifier = Modifier.fillMaxWidth()
)
} else {
// Display current user information as Text components
Text(text = "Name: $userName", fontSize = 20.sp)
Text(text = "Email: $userEmail", fontSize = 20.sp)
}
}
Spacer(modifier = Modifier.width(16.dp))
}
// Button to toggle editing state
Button(
onClick = { isEditing = !isEditing },
modifier = Modifier
.width(200.dp)
.padding(top = 16.dp)
) {
Text(
text = if (isEditing) "Cancel" else "Edit Information",
fontSize = 17.sp,
)
}
// Button to update username and email
if (isEditing) {
Button(
onClick = {
updateFirebaseUserInfo(userName ?: "", userEmail ?: "")
isEditing = false
},
modifier = Modifier
.width(200.dp)
.padding(top = 16.dp)
) {
Text(
text = "Update Information",
fontSize = 17.sp,
)
}
}
// New Debt and Group Updates
Text(
text = "Notification Settings",
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp),
textAlign = TextAlign.Center
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "New Debt Updates", fontSize = 18.sp)
Switch(
checked = newDebtUpdatesEnabled,
onCheckedChange = {
newDebtUpdatesEnabled = it
// Handle switch state change for New Debt Updates
}
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Group Updates", fontSize = 18.sp)
Switch(
checked = groupUpdatesEnabled,
onCheckedChange = {
groupUpdatesEnabled = it
// Handle switch state change for Group Updates
}
)
}
// Button to Change Password
Button(
onClick = {
FirebaseAuth.getInstance().signOut()
navController.navigate(Screen.WelcomeScreen.route)
},
modifier = Modifier
.width(200.dp)
.padding(top = 16.dp)
) {
Text(
text = "Log Out",
fontSize = 17.sp,
)
}
}
}
// Function to update user information in Firebase
fun updateFirebaseUserInfo(newName: String, newEmail: String) {
val user = FirebaseAuth.getInstance().currentUser
val profileUpdater = UserProfileChangeRequest.Builder()
.setDisplayName(newName)
.build()
user?.updateProfile(profileUpdater)
?.addOnCompleteListener { task ->
if (task.isSuccessful) {
user.updateEmail(newEmail)
.addOnCompleteListener { emailTask ->
if (emailTask.isSuccessful) {
println("User information updated successfully.")
} else {
println("Failed to update email.")
}
}
} else {
println("Failed to update user information.")
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/UserScreen.kt | 495784440 |
package com.example.share_money_now.signup_screen
import FirebaseManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.share_money_now.R
import com.example.share_money_now.Screen
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.Person
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.launch
import java.util.UUID
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SignupScreen(
navController: NavController,
viewModel: SignUpViewModel = hiltViewModel(),
firebaseManager: FirebaseManager
) {
var name by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val scope = rememberCoroutineScope()
val context = LocalContext.current
val state = viewModel.signUpState.collectAsState(initial = null)
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Welcome Text
Image(
painter = painterResource(id = R.drawable.sharemoneynowlogo) ,
contentDescription = "Logo",
modifier = Modifier
.width(250.dp)
.height(200.dp)
)
Text(
text = "Sign Up",
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
modifier = Modifier.padding(bottom = 16.dp)
)
// Name TextField
TextField(
value = name,
onValueChange = { name = it },
placeholder = { Text("Name") },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
// Email TextField
TextField(
value = email,
onValueChange = { email = it },
placeholder = { Text("Email") },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
// Password TextField
TextField(
value = password,
onValueChange = { password = it },
placeholder = { Text("Password") },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
// Sign Up Button
Button(
onClick = {
scope.launch {
viewModel.registerUser(email, password, name)
val person = Person(email, name)
firebaseManager.addPersonOnSignUp(person)
navController.navigate(Screen.LandingScreen.route)
}
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Sign up")
}
Text(
text = "Already have an account? Sign In",
color = Color.Gray,
modifier = Modifier
.clickable {
navController.navigate(Screen.SigninScreen.route)
}
.padding(16.dp)
)
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/signup_screen/SignupScreen.kt | 706049095 |
package com.example.share_money_now.signup_screen
data class SignUpState(
val isLoading: Boolean = false,
val isSuccess: String? = "",
val isError: String? = ""
) | Share-Money-Now/app/src/main/java/com/example/share_money_now/signup_screen/SignUpState.kt | 29464261 |
package com.example.share_money_now.signup_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.share_money_now.data_classes.Person
import com.example.share_money_now.firebaseauth.data.AuthRepository
import com.example.share_money_now.firebaseauth.util.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
private val repository: AuthRepository
): ViewModel() {
val _signUpState = Channel<SignUpState>()
val signUpState = _signUpState.receiveAsFlow()
fun registerUser(email:String, password:String, name:String) = viewModelScope.launch {
repository.registerUser(email, password, name).collect{result ->
when(result){
is Resource.Success -> {
_signUpState.send(SignUpState(isSuccess = "Sign In Succes"))
}
is Resource.Loading ->{
_signUpState.send(SignUpState(isLoading = true))
}
is Resource.Error -> {
_signUpState.send(SignUpState(isError = result.message))
}
}
}
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/signup_screen/SignUpViewModel.kt | 400615976 |
import androidx.lifecycle.ViewModel
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.Person
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class PersonalGroupViewModel : ViewModel() {
private val databaseReference: DatabaseReference =
FirebaseDatabase.getInstance("https://share-money-now-default-rtdb.europe-west1.firebasedatabase.app").reference
private val _group = MutableStateFlow<Group?>(null)
val group: StateFlow<Group?> = _group
fun setGroup(group: Group?) {
_group.value = group
}
fun fetchGroupDetails(groupId: String, onDataReceived: (Group?) -> Unit) {
val groupsRef = databaseReference.child("groups").child(groupId)
groupsRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val groupData = snapshot.getValue(Group::class.java)
onDataReceived(groupData)
}
override fun onCancelled(error: DatabaseError) {
onDataReceived(null)
}
})
}
fun findGroupByGroupId(firebaseGroupId: String, onDataReceived: (String?) -> Unit) {
val groupsRef = databaseReference.child("groups")
val query = groupsRef.orderByChild("id").equalTo(firebaseGroupId)
query.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (childSnapshot in snapshot.children) {
val groupId = childSnapshot.key
onDataReceived(groupId)
return
}
} else {
onDataReceived(null)
}
}
override fun onCancelled(error: DatabaseError) {
onDataReceived(null)
}
})
}
fun checkIfEmailExistsInFirebase(email: String, callback: (Boolean) -> Unit) {
val personsRef = databaseReference.child("persons")
personsRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val isEmailRegistered = snapshot.childrenCount > 0
callback(isEmailRegistered)
}
override fun onCancelled(error: DatabaseError) {
error.toException().printStackTrace()
callback(false)
}
})
}
fun updateGroupInFirebase(group: Group) {
val groupsReference = databaseReference.child("groups")
groupsReference.child(group.id).setValue(group)
.addOnSuccessListener {
}
.addOnFailureListener { e ->
e.printStackTrace()
}
}
fun fetchNameForEmail(email: String, callback: (String?) -> Unit) {
val usersReference = databaseReference.child("persons")
usersReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val userSnapshot = snapshot.children.first()
val user = userSnapshot.getValue(Person::class.java)
callback(user?.name)
} else {
callback(null)
}
}
override fun onCancelled(error: DatabaseError) {
error.toException().printStackTrace()
callback(null)
}
})
}
}
| Share-Money-Now/app/src/main/java/com/example/share_money_now/PersonalGroupViewModel.kt | 107211353 |
package com.example.share_money_now
sealed class Screen(val route: String) {
object WelcomeScreen : Screen ("welcome_screen")
object SigninScreen : Screen ("signin_screen")
object SignupScreen : Screen ("signup_screen")
object LandingScreen : Screen ("landing_screen")
object UserScreen: Screen ("user_screen")
object GroupScreen: Screen ("group_screen")
object ExpensesScreen : Screen ("expenses_screen")
}
| Share-Money-Now/app/src/main/java/com/example/share_money_now/Screen.kt | 1269432338 |
import android.app.Application
import com.google.firebase.FirebaseApp
class FirebaseInit : Application() {
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this)
}
}
| Share-Money-Now/app/src/main/java/com/example/share_money_now/FirebaseInit.kt | 2789445093 |
package com.example.share_money_now
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
@Composable
fun ExpensesScreen (navController: NavController){
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/ExpensesScreen.kt | 3762276168 |
package com.example.share_money_now
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.share_money_now.data_classes.Group
import com.example.share_money_now.data_classes.Person
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class CreateGroupViewModel : ViewModel() {
private val databaseReference = FirebaseDatabase.getInstance("https://share-money-now-default-rtdb.europe-west1.firebasedatabase.app")
private val _groups = MutableLiveData<List<Group>>()
val items: LiveData<List<Group>> get() = _groups
fun getItemsByMember(personEmail: String) {
val query = databaseReference.getReference("groups")
query.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val groupList = mutableListOf<Group>()
for (itemSnapshot in snapshot.children) {
val item = itemSnapshot.getValue(Group::class.java)
item?.let {
if (personEmail in it.members.mapNotNull { member -> member?.email }) {
groupList.add(it)
}
}
}
_groups.value = groupList
}
override fun onCancelled(error: DatabaseError) {
}
})
}
fun fetchNameForEmail(email: String, callback: (String?) -> Unit) {
val usersReference = databaseReference.reference.child("persons")
usersReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val userSnapshot = snapshot.children.first()
val user = userSnapshot.getValue(Person::class.java)
callback(user?.name)
} else {
callback(null)
}
}
override fun onCancelled(error: DatabaseError) {
error.toException().printStackTrace()
callback(null)
}
})
}
} | Share-Money-Now/app/src/main/java/com/example/share_money_now/CreateGroupViewModel.kt | 2087934760 |
package com.example.tictactoegame
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.tictactoegame", appContext.packageName)
}
} | Android-TicTacToeGame/app/src/androidTest/java/com/example/tictactoegame/ExampleInstrumentedTest.kt | 590715858 |
package com.example.tictactoegame
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-TicTacToeGame/app/src/test/java/com/example/tictactoegame/ExampleUnitTest.kt | 2833267295 |
package com.example.tictactoegame
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import com.example.tictactoegame.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
var player = "p1"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.b1.setOnClickListener {
buttonclick(binding.b1)
}
binding.b2.setOnClickListener {
buttonclick(binding.b2)
}
binding.b3.setOnClickListener {
buttonclick(binding.b3)
}
binding.b4.setOnClickListener {
buttonclick(binding.b4)
}
binding.b5.setOnClickListener {
buttonclick(binding.b5)
}
binding.b6.setOnClickListener {
buttonclick(binding.b6)
}
binding.b7.setOnClickListener {
buttonclick(binding.b7)
}
binding.b8.setOnClickListener {
buttonclick(binding.b8)
}
binding.b9.setOnClickListener {
buttonclick(binding.b9)
}
binding.btnReset.setOnClickListener {
reset()
}
}
fun buttonclick(btn: Button) {
if (btn.text == "") {
if (player == "p1") {
player = "p2"
btn.text = "X"
} else {
player = "p1"
btn.text = "O"
}
}
win()
}
fun win() {
if ((binding.b1.text == "X" && binding.b2.text == "X" && binding.b3.text == "X")
|| (binding.b4.text == "X" && binding.b5.text == "X" && binding.b6.text == "X")
|| (binding.b7.text == "X" && binding.b8.text == "X" && binding.b9.text == "X")
|| (binding.b1.text == "X" && binding.b5.text == "X" && binding.b9.text == "X")
|| (binding.b3.text == "X" && binding.b5.text == "X" && binding.b7.text == "X")
|| (binding.b1.text == "X" && binding.b4.text == "X" && binding.b7.text == "X")
|| (binding.b2.text == "X" && binding.b5.text == "X" && binding.b8.text == "X")
|| (binding.b3.text == "X" && binding.b6.text == "X" && binding.b9.text == "X")
) {
binding.txtResult.text = "X won the Game"
toast("X won the Game")
disableButtons()
}
else if ((binding.b1.text == "O" && binding.b2.text == "O" && binding.b3.text == "O")
|| (binding.b4.text == "O" && binding.b5.text == "O" && binding.b6.text == "O")
|| (binding.b7.text == "O" && binding.b8.text == "O" && binding.b9.text == "O")
|| (binding.b1.text == "O" && binding.b5.text == "O" && binding.b9.text == "O")
|| (binding.b3.text == "O" && binding.b5.text == "O" && binding.b7.text == "O")
|| (binding.b1.text == "O" && binding.b4.text == "O" && binding.b7.text == "O")
|| (binding.b2.text == "O" && binding.b5.text == "O" && binding.b8.text == "O")
|| (binding.b3.text == "O" && binding.b6.text == "O" && binding.b9.text == "O")
) {
binding.txtResult.text = "O won the Game"
toast("O won the Game")
disableButtons()
}
else if (binding.b1.text != ""
&& binding.b2.text != ""
&& binding.b3.text != ""
&& binding.b4.text != ""
&& binding.b5.text != ""
&& binding.b6.text != ""
&& binding.b7.text != ""
&& binding.b8.text != ""
&& binding.b9.text != ""
) {
toast("Tie Game")
binding.txtResult.text = "Match Draw/Tie"
}
}
fun toast(msg: String) {
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
}
fun reset() {
binding.b1.text = ""
binding.b2.text = ""
binding.b3.text = ""
binding.b4.text = ""
binding.b5.text = ""
binding.b6.text = ""
binding.b7.text = ""
binding.b8.text = ""
binding.b9.text = ""
binding.b1.isEnabled = true
binding.b2.isEnabled = true
binding.b3.isEnabled = true
binding.b4.isEnabled = true
binding.b5.isEnabled = true
binding.b6.isEnabled = true
binding.b7.isEnabled = true
binding.b8.isEnabled = true
binding.b9.isEnabled = true
}
fun disableButtons() {
binding.b1.isEnabled = false
binding.b2.isEnabled = false
binding.b3.isEnabled = false
binding.b4.isEnabled = false
binding.b5.isEnabled = false
binding.b6.isEnabled = false
binding.b7.isEnabled = false
binding.b8.isEnabled = false
binding.b9.isEnabled = false
}
} | Android-TicTacToeGame/app/src/main/java/com/example/tictactoegame/MainActivity.kt | 3257727404 |
package com.muhammedjasir.androidnotesapp
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.muhammedjasir.androidnotesapp", appContext.packageName)
}
} | AndroidNotesApp/app/src/androidTest/java/com/muhammedjasir/androidnotesapp/ExampleInstrumentedTest.kt | 2248106968 |
package com.muhammedjasir.androidnotesapp
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)
}
} | AndroidNotesApp/app/src/test/java/com/muhammedjasir/androidnotesapp/ExampleUnitTest.kt | 3104586708 |
package com.muhammedjasir.androidnotesapp
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
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
}
}
} | AndroidNotesApp/app/src/main/java/com/muhammedjasir/androidnotesapp/MainActivity.kt | 1694412311 |
package com.example.paymentassignment
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class PaymentAssignmentApplicationTests {
@Test
fun contextLoads() {
}
}
| payment-assignment/src/test/kotlin/com/example/paymentassignment/PaymentAssignmentApplicationTests.kt | 1834464949 |
package com.example.paymentassignment.order
import org.springframework.data.repository.kotlin.CoroutineCrudRepository
interface OrderRepository : CoroutineCrudRepository<Order, Long> {
fun findTop1ByOrderTokenOrderByCreatedAtDesc(orderToken: String): Order?
}
| payment-assignment/src/main/kotlin/com/example/paymentassignment/order/OrderRepository.kt | 1570764274 |
package com.example.paymentassignment.order
import com.example.paymentassignment.bankbook.Bankbook
import com.example.paymentassignment.market.Market
import org.springframework.stereotype.Service
import java.math.BigDecimal
@Service
class OrderService(
private val orderRepository: OrderRepository,
) {
suspend fun saveOrder(
bankbook: Bankbook,
market: Market,
price: BigDecimal,
orderToken: String,
): Order {
val order = Order(
customer = bankbook.customer,
market = market,
price = price,
orderToken = orderToken,
)
return orderRepository.save(order)
}
fun getLastOrder(orderToken: String) =
orderRepository.findTop1ByOrderTokenOrderByCreatedAtDesc(orderToken)
}
| payment-assignment/src/main/kotlin/com/example/paymentassignment/order/OrderService.kt | 3755770099 |
package com.example.paymentassignment.order
import com.example.paymentassignment.customer.Customer
import com.example.paymentassignment.market.Market
import com.example.paymentassignment.util.BaseEntity
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
import java.math.BigDecimal
/**
* 주문 정보는 id, 생성 시간( createdAt ), 수정 시간( updatedAt ),
* 가맹점 ( 1:1 ), 회원 ( 1:1 ), 상품 정보( 1:N ) 및 수량, 총 결제 금액
* 주문이 실패하면 exception 이 발생하고 payment history 에 FAIL 이라는 상태값을 넣어줍니다.
*
* 상품 정보( 1:N ), 총 결제 금액 에서 상품의 정보가 추후에 변경이 되면 주문에 영향을 받게 됩니다. ( 고민 )
* 상품 snap shot 을 만들지... 만들게 된다면 어떻게 관리를 해야할지...
*/
@Table(name = "order_table")
class Order(
@Id
val id: Long = 0,
val orderToken: String,
val customer: Customer,
val market: Market,
val price: BigDecimal,
): BaseEntity() {
} | payment-assignment/src/main/kotlin/com/example/paymentassignment/order/Order.kt | 2450042259 |
package com.example.paymentassignment.extension
/**
* live template 으로 extension method 정의 하는 것도 고려
* import com.example.paymentassignment.extension.plus
* import com.example.paymentassignment.extension.times
* import com.example.paymentassignment.extension.minus
* import com.example.paymentassignment.extension.div
*/
import java.math.BigDecimal
import java.math.RoundingMode
suspend operator fun BigDecimal.plus(other: Number): BigDecimal = this.add(other.toBigDecimal())
suspend operator fun BigDecimal.minus(other: Number): BigDecimal = this.subtract(other.toBigDecimal())
suspend operator fun BigDecimal.times(other: Number): BigDecimal = this.multiply(other.toBigDecimal())
suspend operator fun BigDecimal.div(other: Number): BigDecimal = this.divide(other.toBigDecimal(), RoundingMode.HALF_EVEN)
suspend fun Number.toBigDecimal() =
when (this) {
is Int -> BigDecimal.valueOf(this.toLong())
is Long -> BigDecimal.valueOf(this)
is Float, is Double -> BigDecimal(this.toString())
is BigDecimal -> this
else -> throw IllegalArgumentException()
}!!
| payment-assignment/src/main/kotlin/com/example/paymentassignment/extension/BigDecimalsExtension.kt | 780090160 |
package com.example.paymentassignment.bankbook
import org.springframework.data.repository.kotlin.CoroutineCrudRepository
interface BankbookRepository : CoroutineCrudRepository<Bankbook, Long> {
suspend fun findByAccountNumber(accountNumber: String): Bankbook?
}
| payment-assignment/src/main/kotlin/com/example/paymentassignment/bankbook/BankbookRepository.kt | 4072660447 |
package com.example.paymentassignment.bankbook
import org.springframework.stereotype.Service
import java.lang.IllegalArgumentException
import java.math.BigDecimal
@Service
class BankbookService(
private val bankbookRepository: BankbookRepository,
) {
suspend fun getBankbookByAccountNumber(accountNumber: String) =
bankbookRepository.findByAccountNumber(accountNumber)
?: throw IllegalArgumentException()
suspend fun payMoney(bankbook: Bankbook, price: BigDecimal) {
bankbook.balance -= price
bankbookRepository.save(bankbook)
}
}
| payment-assignment/src/main/kotlin/com/example/paymentassignment/bankbook/BankbookService.kt | 1167437951 |
package com.example.paymentassignment.bankbook
import com.example.paymentassignment.customer.Customer
import com.example.paymentassignment.util.BaseEntity
import org.springframework.data.annotation.Id
import java.math.BigDecimal
/**
* 통장은 id, 생성 시간( createdAt ), 수정 시간( updatedAt ), 계좌 번호, 잔고 를 가지고 있습니다.
*/
class Bankbook(
@Id
val id: Long = 0,
val customer: Customer,
val accountNumber: String,
var balance: BigDecimal,
): BaseEntity()
| payment-assignment/src/main/kotlin/com/example/paymentassignment/bankbook/Bankbook.kt | 2422039459 |
package com.example.paymentassignment.util
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import java.time.LocalDateTime
open class BaseEntity(
@CreatedDate
var createdAt: LocalDateTime? = null,
@LastModifiedDate
var updatedAt: LocalDateTime? = null,
) {
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun hashCode(): Int {
return super.hashCode()
}
} | payment-assignment/src/main/kotlin/com/example/paymentassignment/util/BaseEntity.kt | 3053401388 |
package com.example.paymentassignment.config
import org.springframework.context.annotation.Configuration
import org.springframework.data.r2dbc.config.EnableR2dbcAuditing
@Configuration
@EnableR2dbcAuditing
class R2dbcConfig | payment-assignment/src/main/kotlin/com/example/paymentassignment/config/R2dbcConfig.kt | 2492053660 |
package com.example.paymentassignment
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class PaymentAssignmentApplication
fun main(args: Array<String>) {
runApplication<PaymentAssignmentApplication>(*args)
}
| payment-assignment/src/main/kotlin/com/example/paymentassignment/PaymentAssignmentApplication.kt | 3834238171 |
package com.example.paymentassignment.controller
import com.example.paymentassignment.paymenthistory.PaymentHistory
import java.math.BigDecimal
data class PaymentResponse(
val marketName: String,
val price: BigDecimal,
val isSuccess: Boolean,
) {
companion object {
fun of(paymentHistory: PaymentHistory) =
PaymentResponse(
marketName = paymentHistory.market.name,
price = paymentHistory.price,
isSuccess = paymentHistory.isSuccess,
)
}
} | payment-assignment/src/main/kotlin/com/example/paymentassignment/controller/PaymentResponse.kt | 2873706782 |
package com.example.paymentassignment.controller
import java.math.BigDecimal
data class PaymentRequest(
val price: BigDecimal,
val accountNumber: String,
) | payment-assignment/src/main/kotlin/com/example/paymentassignment/controller/PaymentRequest.kt | 638766400 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.