content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.countries.graphql.features.country_details_screen.presentation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.countries.graphql.core.state.ui_data_state.UiDataState import com.countries.graphql.core.uitls.error_view.ErrorView import com.countries.graphql.core.uitls.handleOpenConnectionSetting import com.countries.graphql.core.uitls.loading_view.LoadingView import com.countries.graphql.features.composable.InternetConnectionView import com.countries.graphql.features.country_details_screen.domain.viewmodel.DetailedCountryViewModel import com.countries.graphql.features.home_screen.domain.model.DetailedCountry import org.koin.androidx.compose.koinViewModel @Composable fun DetailedCountryScreen( isNetworkAvailable: Boolean, viewModel: DetailedCountryViewModel = koinViewModel() ) { val context = LocalContext.current val state by viewModel.detailedCountryResponseState.collectAsState() InternetConnectionView(isNetworkAvailable, composable = { DetailedCountryScreen(state, viewModel) }, action = { context.handleOpenConnectionSetting() }) } @Composable fun DetailedCountryScreen( uiDataState: UiDataState<DetailedCountry>, viewModel: DetailedCountryViewModel ) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { when (uiDataState) { is UiDataState.Error -> ErrorView(uiDataState.error) { viewModel.getDetailedCountry() } is UiDataState.Loading -> LoadingView() is UiDataState.Loaded -> { val data = viewModel.getCountry() data?.let { DetailedCountry(it) } } } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/presentation/DetailedCountryScreen.kt
1032924896
package com.countries.graphql.features.country_details_screen.presentation 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.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.countries.graphql.features.home_screen.domain.model.DetailedCountry import com.countries.graphql.features.home_screen.domain.model.Languages @Composable fun DetailedCountry(country: DetailedCountry) { Column(Modifier.fillMaxSize()) { Spacer(modifier = Modifier.height(80.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Text( text = country.emoji, fontSize = 30.sp ) Spacer(modifier = Modifier.width(16.dp)) Text( text = country.name, fontSize = 24.sp ) } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text(text = "Continent: " + country.continent) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Currency: " + country.currency) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Capital: " + country.capital) Spacer(modifier = Modifier.height(8.dp)) } Column( Modifier .fillMaxWidth() .padding(horizontal = 15.dp) ) { if (country.languages.isEmpty()) return Text(text = "Languages: ", fontSize = 18.sp) CountryLanguage(languages = country.languages) Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp)) } } } @Composable private fun CountryLanguage(languages: List<Languages>) { LazyColumn(Modifier.fillMaxWidth()) { items(languages) { language -> LanguageItem(languages = language) } } } @Composable private fun LanguageItem(languages: Languages) { Column( Modifier.fillMaxWidth().padding(horizontal = 10.dp), ) { Spacer(modifier = Modifier.height(10.dp)) Text(text = "Code: " + languages.code) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Native: " + languages.native) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Name: " + languages.name) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Rtl: " + languages.rtl) Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp)) } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/presentation/DetailedCountryComposable.kt
52431383
package com.countries.graphql.features.composable import androidx.compose.runtime.Composable import com.countries.graphql.R import com.countries.graphql.core.error_handling.ui_error.error_text.ErrorText import com.countries.graphql.core.uitls.error_view.ErrorView @Composable fun InternetConnectionView( isNetworkAvailable: Boolean, composable: @Composable () -> Unit, action: () -> Unit ) { if (isNetworkAvailable) { composable() } else { ErrorView(ErrorText.StringResource(R.string.errorNetworkUnavailable), action) } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/composable/InternetConnectionComposable.kt
2734132680
package com.countries.graphql.features.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun CircularProgress() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator( modifier = Modifier .align(Alignment.Center) .size(70.dp) ) }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/composable/CircularProgressComposable.kt
188543479
package com.countries.graphql.features.composable import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner @Composable fun ComposableLifeCycle( lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, onCreate: () -> Unit = {}, onStart: () -> Unit = {}, onResume: () -> Unit = {}, onPause: () -> Unit = {}, onStop: () -> Unit = {}, onDestroy: () -> Unit = {}, onAny: () -> Unit = {} ) { val currentOnCreate by rememberUpdatedState(onCreate) val currentOnStart by rememberUpdatedState(onStart) val currentOnResume by rememberUpdatedState(onResume) val currentOnPause by rememberUpdatedState(onPause) val currentOnStop by rememberUpdatedState(onStop) val currentOnDestroy by rememberUpdatedState(onDestroy) val currentOnAny by rememberUpdatedState(onAny) DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_CREATE -> currentOnCreate() Lifecycle.Event.ON_START -> currentOnStart() Lifecycle.Event.ON_RESUME -> currentOnResume() Lifecycle.Event.ON_PAUSE -> currentOnPause() Lifecycle.Event.ON_STOP -> currentOnStop() Lifecycle.Event.ON_DESTROY -> currentOnDestroy() Lifecycle.Event.ON_ANY -> currentOnAny() } } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/composable/LifeCycleComposable.kt
853807248
package com.countries.graphql.features.activities import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.navigation.compose.rememberNavController import com.countries.graphql.core.connectivity.connectivity_manager.ConnectivityManager import com.countries.graphql.navigation.AppNavGraph import com.countries.graphql.ui.theme.CountriesGraphQlTheme import org.koin.android.ext.android.inject import org.koin.core.parameter.parametersOf class MainActivity : ComponentActivity() { private val connectivityManager: ConnectivityManager by inject { parametersOf(this@MainActivity) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) handleNotificationPermission() setContent { CountriesGraphQlTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() val isNetworkAvailable = connectivityManager.isNetworkConnected.observeAsState(true) AppNavGraph(navController, isNetworkAvailable.value) } } } } private fun handleNotificationPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { permissionRequest.launch(android.Manifest.permission.POST_NOTIFICATIONS) } } private val permissionRequest = registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* no need handle action here */ } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/activities/MainActivity.kt
4138765892
package com.countries.graphql.features.home_screen.di import com.countries.graphql.features.country_details_screen.data.repository.DetailedCountryRepositoryImpl import com.countries.graphql.features.country_details_screen.domain.repository.DetailedCountryRepository import com.countries.graphql.features.home_screen.data.data_source.CountriesDataSourceImpl import com.countries.graphql.features.home_screen.data.repository.CountriesRepositoryImpl import com.countries.graphql.features.home_screen.domain.data_source.CountriesDataSource import com.countries.graphql.features.home_screen.domain.repository.CountriesRepository import com.countries.graphql.features.home_screen.domain.usecase.CountriesUseCase import com.countries.graphql.features.home_screen.domain.viewmodel.HomeViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val homeViewModelModule = module { viewModel { HomeViewModel() } } val homeDataSourceModule = module { single<CountriesDataSource> { CountriesDataSourceImpl(get()) } } val homeRepositoryModule = module { single<CountriesRepository> { CountriesRepositoryImpl(get()) } single<DetailedCountryRepository> { DetailedCountryRepositoryImpl(get()) } } val homeUseCaseModule = module { single { CountriesUseCase() } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/di/HomeModule.kt
2162316797
package com.countries.graphql.features.home_screen.data.repository import com.countries.graphql.core.error_handling.throwable.toErrorType import com.countries.graphql.core.state.network_state.State import com.countries.graphql.features.home_screen.domain.data_source.CountriesDataSource import com.countries.graphql.features.home_screen.domain.repository.CountriesRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flowOn class CountriesRepositoryImpl(private val countriesDataSource: CountriesDataSource) : CountriesRepository { override suspend fun getCountries() = countriesDataSource.fetchCountries().catch { emit(State.Error(it.toErrorType())) }.flowOn(Dispatchers.IO) }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/data/repository/CountriesRepositoryImpl.kt
1839114206
package com.countries.graphql.features.home_screen.data.data_source import com.apollographql.apollo3.ApolloClient import com.countries.graphql.CountriesQuery import com.countries.graphql.core.state.network_state.State import com.countries.graphql.features.home_screen.data.mappers.toSimpleCountry import com.countries.graphql.features.home_screen.domain.data_source.CountriesDataSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn class CountriesDataSourceImpl(private val apolloNetwork: ApolloClient) : CountriesDataSource { override suspend fun fetchCountries() = flow { val response = apolloNetwork.query(CountriesQuery()).execute() val data = response.data?.countries?.map { it.toSimpleCountry() } ?: emptyList() if (response.errors.isNullOrEmpty()) emit(State.Success(data)) }.flowOn(Dispatchers.IO) }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/data/data_source/CountriesDataSourceImpl.kt
3132143326
package com.countries.graphql.features.home_screen.data.mappers import com.countries.graphql.CountriesQuery import com.countries.graphql.features.home_screen.domain.model.Languages import com.countries.graphql.features.home_screen.domain.model.SimpleCountry fun CountriesQuery.Country.toSimpleCountry() = SimpleCountry( name = name, capital = capital, code = code, currency = currency, emoji = emoji, native = native, phone = phone, languages = languages.map { it.toLanguage() } ) fun CountriesQuery.Language.toLanguage() = Languages( native = native, name = name, code = code, rtl = rtl )
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/data/mappers/CountriesMapper.kt
96211329
package com.countries.graphql.features.home_screen.domain.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.countries.graphql.core.error_handling.error_type.ErrorType import com.countries.graphql.core.error_handling.error_type_converter.ErrorTypeConverterHandler import com.countries.graphql.core.state.network_state.State import com.countries.graphql.core.state.ui_data_state.UiDataState import com.countries.graphql.features.home_screen.domain.model.SimpleCountry import com.countries.graphql.features.home_screen.domain.usecase.CountriesUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.inject class HomeViewModel : ViewModel(), KoinComponent { private val countriesUseCase: CountriesUseCase by inject() private val errorTypeConverterHandler: ErrorTypeConverterHandler by inject() private val _countriesResponseState = MutableStateFlow<UiDataState<List<SimpleCountry>>>(UiDataState.Loading()) val countriesResponseState = _countriesResponseState.asStateFlow() init { getCountries() } fun getCountries() { viewModelScope.launch { countriesUseCase().collect { when (it) { is State.Success -> it.data?.handleCountriesSuccessState() is State.Error -> it.error.handleCountriesErrorState() } } } } private suspend fun List<SimpleCountry>.handleCountriesSuccessState() = _countriesResponseState.emit(UiDataState.Loaded(this)) private suspend fun ErrorType.handleCountriesErrorState() = _countriesResponseState.emit( UiDataState.Error(errorTypeConverterHandler.convert(this)) ) fun getCountriesSortedByName() = countriesUseCase.getCountriesSortedByName() }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/viewmodel/HomeViewModel.kt
531773162
package com.countries.graphql.features.home_screen.domain.repository import com.countries.graphql.core.state.network_state.State import com.countries.graphql.features.home_screen.domain.model.SimpleCountry import kotlinx.coroutines.flow.Flow interface CountriesRepository { suspend fun getCountries() : Flow<State<List<SimpleCountry>>> }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/repository/CountriesRepository.kt
901461572
package com.countries.graphql.features.home_screen.domain.data_source import com.countries.graphql.core.state.network_state.State import com.countries.graphql.features.home_screen.domain.model.SimpleCountry import kotlinx.coroutines.flow.Flow interface CountriesDataSource { suspend fun fetchCountries() : Flow<State<List<SimpleCountry>>> }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/data_source/CountriesDataSource.kt
1882249202
package com.countries.graphql.features.home_screen.domain.model data class Languages( val native: String, val name: String, val code: String, val rtl: Boolean )
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/model/Languages.kt
1078808389
package com.countries.graphql.features.home_screen.domain.model data class SimpleCountry( val name: String, val capital: String?, val code: String, val currency: String?, val emoji: String, val native: String, val phone: String, val languages: List<Languages> )
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/model/SimpleCountry.kt
375070900
package com.countries.graphql.features.home_screen.domain.model data class DetailedCountry( val name: String, val capital: String, val code: String, val currency: String, val emoji: String, val native: String, val phone: String, val languages: List<Languages>, val continent: String )
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/model/DetailedCountry.kt
1753498297
package com.countries.graphql.features.home_screen.domain.usecase import com.countries.graphql.core.state.network_state.State import com.countries.graphql.features.home_screen.domain.model.SimpleCountry import com.countries.graphql.features.home_screen.domain.repository.CountriesRepository import kotlinx.coroutines.async import kotlinx.coroutines.flow.channelFlow import org.koin.core.component.KoinComponent import org.koin.core.component.inject class CountriesUseCase : KoinComponent { private val countriesRepository: CountriesRepository by inject() private var simpleCountry: List<SimpleCountry>? = null suspend operator fun invoke() = channelFlow { val response = async { countriesRepository.getCountries() } response.await().collect { if (it is State.Success) { simpleCountry = it.data } send(it) } } fun getCountriesSortedByName() = simpleCountry?.sortedBy { it.name }?.filter { it.name != "Israel" } ?: emptyList() }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/domain/usecase/CountriesUseCase.kt
2673108494
package com.countries.graphql.features.home_screen.presentation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.countries.graphql.core.state.ui_data_state.UiDataState import com.countries.graphql.core.uitls.error_view.ErrorView import com.countries.graphql.core.uitls.handleOpenConnectionSetting import com.countries.graphql.core.uitls.loading_view.LoadingView import com.countries.graphql.features.composable.InternetConnectionView import com.countries.graphql.features.home_screen.domain.model.SimpleCountry import com.countries.graphql.features.home_screen.domain.viewmodel.HomeViewModel import org.koin.androidx.compose.koinViewModel @Composable fun HomeScreen( isNetworkAvailable: Boolean, viewModel: HomeViewModel = koinViewModel(), onItemClicked: (String) -> Unit ) { val context = LocalContext.current val uiState by viewModel.countriesResponseState.collectAsState() InternetConnectionView(isNetworkAvailable, composable = { HomeScreen(uiDataState = uiState, viewModel = viewModel, onItemClicked = onItemClicked) }, action = { context.handleOpenConnectionSetting() }) } @Composable private fun HomeScreen( uiDataState: UiDataState<List<SimpleCountry>>, viewModel: HomeViewModel, onItemClicked: (String) -> Unit ) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { when (uiDataState) { is UiDataState.Loading -> LoadingView() is UiDataState.Loaded -> { val data = viewModel.getCountriesSortedByName() Countries(data) { onItemClicked(it) } } is UiDataState.Error -> ErrorView(uiDataState.error) { viewModel.getCountries() } } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/presentation/HomeScreen.kt
725145307
package com.countries.graphql.features.home_screen.presentation import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.countries.graphql.features.home_screen.domain.model.SimpleCountry @Composable fun Countries(countries: List<SimpleCountry>, onItemClicked: (String) -> Unit) { LazyColumn(modifier = Modifier.fillMaxSize()) { items(countries) { country -> CountryItem( country = country, modifier = Modifier .fillMaxWidth() .clickable { onItemClicked(country.code) } .padding(16.dp) ) } } } @Composable private fun CountryItem( country: SimpleCountry, modifier: Modifier = Modifier ) { Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { Text(text = country.emoji, fontSize = 30.sp) Spacer(modifier = Modifier.width(16.dp)) Column(modifier = Modifier.weight(1f)) { Text(text = country.name, fontSize = 24.sp) Spacer(modifier = Modifier.width(16.dp)) Text(text = country.capital ?: "") } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/features/home_screen/presentation/CountryiesComposable.kt
1500776467
package com.countries.graphql.navigation.route sealed class AppNavGraphRoutes(val route : String) { data object SplashScreen : AppNavGraphRoutes("SplashScreen") data object HomeScreen : AppNavGraphRoutes("HomeScreen") data object DetailedCountryScreen : AppNavGraphRoutes("DetailedCountryScreen") }
Countries-GraphQl/app/src/main/java/com/countries/graphql/navigation/route/AppNavGraphRoutes.kt
3137857830
package com.countries.graphql.navigation import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.countries.graphql.features.country_details_screen.presentation.DetailedCountryScreen import com.countries.graphql.features.home_screen.presentation.HomeScreen import com.countries.graphql.navigation.route.AppNavGraphRoutes @Composable fun AppNavGraph( navController: NavHostController, isNetworkAvailable: Boolean ) { NavHost( navController = navController, startDestination = AppNavGraphRoutes.HomeScreen.route ) { //HomeScreen composable(AppNavGraphRoutes.HomeScreen.route) { HomeScreen(isNetworkAvailable) { code -> navController.navigate("${AppNavGraphRoutes.DetailedCountryScreen.route}/$code") } } composable( route = "${AppNavGraphRoutes.DetailedCountryScreen.route}/{code}", arguments = listOf( navArgument("code") { type = NavType.StringType }) ) { DetailedCountryScreen(isNetworkAvailable) } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/navigation/AppNavGraph.kt
265825008
package com.countries.graphql.application import android.app.Application import com.countries.graphql.BuildConfig import com.countries.graphql.core.di.appModule import com.countries.graphql.core.di.dataSourceModule import com.countries.graphql.core.di.networkModule import com.countries.graphql.core.di.repositoriesModule import com.countries.graphql.core.di.singletonModule import com.countries.graphql.core.di.useCaseModule import com.countries.graphql.core.di.viewModelsModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.GlobalContext import timber.log.Timber import zerobranch.androidremotedebugger.AndroidRemoteDebugger class CountriesApplication : Application() { override fun onCreate() { super.onCreate() plantTimberTrees() initRemoteDebugger() GlobalContext.startKoin { androidLogger() androidContext(this@CountriesApplication) modules( appModule, networkModule, viewModelsModule, dataSourceModule, repositoriesModule, useCaseModule, singletonModule ) } } private fun plantTimberTrees() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) Timber.plant(RemoteDebuggerTree()) } } private fun initRemoteDebugger() { if (!BuildConfig.DEBUG) return val remoteDebugger = AndroidRemoteDebugger.Builder(applicationContext).disableInternalLogging() .port(getRemoteDebuggerPort()).build() AndroidRemoteDebugger.init(remoteDebugger) } private fun getRemoteDebuggerPort() = 9096 private inner class RemoteDebuggerTree : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { AndroidRemoteDebugger.Log.log(priority, tag, message, t) } } }
Countries-GraphQl/app/src/main/java/com/countries/graphql/application/CountriesApplication.kt
3934596565
import kotlinx.cli.ArgParser import kotlinx.cli.ArgType import kotlinx.cli.default import kotlinx.cli.required import java.io.File import kotlin.system.measureTimeMillis fun main(args: Array<String>) { val parser = ArgParser("canonical-converter") val matrixArg by parser.option( ArgType.String, shortName = "m", description = "путь до файла или матрица для преобразования в формате \"[[...,0,...,1,...],[...],...]\"" ).required() val isParityCheck by parser.option( ArgType.Boolean, shortName = "p", description = "задана проверочная матрица" ).default(false) val outputFile by parser.option( ArgType.String, shortName = "o", description = "путь до файла для записи результата" ) parser.parse(args) val matrixString = if (isFilePath(matrixArg)) { readFile(matrixArg) } else { matrixArg } val executionTime = measureTimeMillis { val converter = CanonicalConverter() val result = if (isParityCheck) { converter.toGenerative(matrixString) } else { converter.toParityCheck(matrixString) } println(result) outputFile?.let { writeToFile(result, it) } } println("Time: $executionTime ms") } fun isFilePath(path: String): Boolean { val file = File(path) return file.exists() && file.isFile } fun readFile(filename: String): String { val file = File(filename) return file.readText() } fun writeToFile(content: String, filename: String) { val file = File(filename) file.writeText(content) }
canonical-converter/converter-client/src/main/kotlin/Main.kt
1346589343
import model.Matrix import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import parser.MatrixParser internal class MatrixParserAnyTest { private val matrixParser = MatrixParser() @Test fun testCreateMatrixFromString() { val inputString = "[[1, 2, 3],\n[4, 5, 6],\n[7, 8, 9]]" val expectedMatrix = Matrix(3, 3) expectedMatrix[0, 0] = 1; expectedMatrix[0, 1] = 2; expectedMatrix[0, 2] = 3 expectedMatrix[1, 0] = 4; expectedMatrix[1, 1] = 5; expectedMatrix[1, 2] = 6 expectedMatrix[2, 0] = 7; expectedMatrix[2, 1] = 8; expectedMatrix[2, 2] = 9 val resultMatrix = matrixParser.createMatrixFromString(inputString) for (i in 0 until expectedMatrix.rows) { for (j in 0 until expectedMatrix.cols) { assertEquals(expectedMatrix[i, j], resultMatrix[i, j], "Mismatch at position [$i, $j]") } } } @Test fun testCreateStringFromMatrix() { val matrix = Matrix(2, 2) matrix[0, 0] = 1; matrix[0, 1] = 2 matrix[1, 0] = 3; matrix[1, 1] = 4 val expectedString = "[[1, 2],\n[3, 4]]" val resultString = matrixParser.createStringFromMatrix(matrix) assertEquals(expectedString, resultString) } }
canonical-converter/converter-core/src/test/kotlin/MatrixParserAnyTest.kt
589335018
import model.Matrix import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import tester.IsLinearSystemSolutionTester internal class IsLinearSystemSolutionTesterAnyTest { private val tester = IsLinearSystemSolutionTester() @Test fun testValidSolution() { // Setup a simple linear system and its solution val a = Matrix(2, 2) a[0, 0] = 1; a[0, 1] = 1 a[1, 0] = 2; a[1, 1] = 4 val x = Matrix(1, 2) // Solution matrix (considering as a row vector here) x[0, 0] = 1; x[0, 1] = 1 // A solution for demonstration; adjust based on your system assertTrue(tester.test(a, x), "Expected x to be a valid solution for the linear system represented by matrix a") } @Test fun testSolutionWithModulo() { // Example where solution is valid under modulo 2 arithmetic val a = Matrix(2, 2) a[0, 0] = 2; a[0, 1] = 4 a[1, 0] = 6; a[1, 1] = 8 val x = Matrix(1, 2) // Solution that works under modulo 2 x[0, 0] = 1; x[0, 1] = 1 assertTrue(tester.test(a, x), "Expected x to be a valid solution under modulo 2 for the linear system represented by matrix a") } }
canonical-converter/converter-core/src/test/kotlin/IsLinearSystemSolutionTesterAnyTest.kt
2052601760
import model.Matrix import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class MatrixAnyTest { @Test fun testConstructor() { val matrix = Matrix(2, 3) assertEquals(2, matrix.rows) assertEquals(3, matrix.cols) } @Test fun testEye() { val identity = Matrix.eye(3) for (i in 0 until 3) { for (j in 0 until 3) { if (i == j) assertEquals(1, identity[i, j]) else assertEquals(0, identity[i, j]) } } } @Test fun testHstack() { val a = Matrix(2, 2) val b = Matrix(2, 2) a[0, 0] = 1; a[0, 1] = 2; a[1, 0] = 3; a[1, 1] = 4 b[0, 0] = 5; b[0, 1] = 6; b[1, 0] = 7; b[1, 1] = 8 val c = Matrix.hstack(a, b) assertEquals(2, c.rows) assertEquals(4, c.cols) assertEquals(1, c[0, 0]) assertEquals(6, c[0, 3]) } @Test fun testGaussianElimination() { val matrix = Matrix(arrayOf(arrayOf(2, 1, -1), arrayOf(-3, -1, 2), arrayOf(-2, 1, 2))) val result = matrix.gaussianElimination() val expected = arrayOf( arrayOf(1.0, 0.0, 0.0), arrayOf(0.0, 1.0, 0.0), arrayOf(0.0, 0.0, 1.0) ) for (i in expected.indices) { assertArrayEquals(expected[i], result.row(i).map { it.toDouble() }.toTypedArray()) } } @Test fun testRank() { val matrix = Matrix(arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9))) val rank = matrix.rank() assertEquals(2, rank) // For this specific matrix, the rank should be 2. } @Test fun testSubMatrix() { val matrix = Matrix(3, 3) for (i in 0 until 3) { for (j in 0 until 3) { matrix[i, j] = i * 3 + j + 1 // Fill the matrix with numbers 1 through 9 } } val subMatrix = matrix.subMatrix(1, 3, 1, 3) val expected = arrayOf(arrayOf(5, 6), arrayOf(8, 9)) for (i in expected.indices) { assertArrayEquals(expected[i], subMatrix.row(i)) } } @Test fun testDeterminant() { val matrix = Matrix(arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 10))) val determinant = matrix.determinant() assertEquals(-3, determinant) // The determinant for this matrix should be -3. } @Test fun testIsSquare() { val squareMatrix = Matrix(2, 2) val nonSquareMatrix = Matrix(2, 3) assertTrue(squareMatrix.isSquare()) assertFalse(nonSquareMatrix.isSquare()) } @Test fun testTranspose() { val matrix = Matrix(2, 3) matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3 matrix[1, 0] = 4; matrix[1, 1] = 5; matrix[1, 2] = 6 val transposed = matrix.transpose() assertEquals(3, transposed.rows) assertEquals(2, transposed.cols) assertEquals(1, transposed[0, 0]) assertEquals(4, transposed[0, 1]) assertEquals(5, transposed[1, 1]) } }
canonical-converter/converter-core/src/test/kotlin/MatrixAnyTest.kt
4276438059
import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import tester.NonDegeneracyTester import model.Matrix internal class NonDegeneracyTesterAnyTest { private val tester = NonDegeneracyTester() @Test fun testDegenerateMatrixWithZeroRow() { val matrix = Matrix(2, 2) matrix[0, 0] = 0; matrix[0, 1] = 0 matrix[1, 0] = 3; matrix[1, 1] = 4 assertFalse(tester.test(matrix)) } @Test fun testDegenerateMatrixWithZeroDeterminant() { val matrix = Matrix(2, 2) matrix[0, 0] = 1; matrix[0, 1] = 2 matrix[1, 0] = 2; matrix[1, 1] = 4 assertFalse(tester.test(matrix)) } }
canonical-converter/converter-core/src/test/kotlin/NonDegeneracyTesterAnyTest.kt
2761491408
import model.Matrix import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.assertThrows import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import parser.MatrixParser import service.MatrixConverter import kotlin.math.absoluteValue import kotlin.math.min import kotlin.random.Random import kotlin.test.Test @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ConverterAnyTest { @ParameterizedTest @MethodSource("matrices") fun toGenerative(parityCheck: String, generative: String) { val converter = CanonicalConverter() val parser = MatrixParser() val generativeActualString = converter.toGenerative(parityCheck) val generativeActual = parser.createMatrixFromString(generativeActualString) val generativeExpectedMatrix = parser.createMatrixFromString(generative) assert(generativeActual.isTransformableTo(generativeExpectedMatrix)) } @ParameterizedTest @MethodSource("matrices") fun toParityCheck(parityCheck: String, generative: String) { val converter = CanonicalConverter() val parser = MatrixParser() val parityCheckActualString = converter.toParityCheck(generative) val parityCheckActual = parser.createMatrixFromString(parityCheckActualString) val parityCheckExpected = parser.createMatrixFromString(parityCheck) assert(parityCheckActual.isTransformableTo(parityCheckExpected)) } @ParameterizedTest @MethodSource("singularMatrices") fun singularMatricesThrow(matrix: String) { val converter = CanonicalConverter() assertThrows<IllegalArgumentException> { converter.toGenerative(matrix) } assertThrows<IllegalArgumentException> { converter.toParityCheck(matrix) } } @Test fun testToRowEchelonFormMod2() { val matrix = Matrix(arrayOf(arrayOf(1, 0, 1), arrayOf(1, 1, 1))) val expected = Matrix(arrayOf(arrayOf(1, 0, 1), arrayOf(0, 1, 0))) val actual = matrix.toRowEchelonForm(2) assertEquals(expected, actual.first) } private fun transpositionAndCombination(matrix: Matrix): Matrix { // Assuming the submatrix is the entire matrix for simplicity val transposed = matrix.transpose() // Creating an identity matrix of the same size as the transposed matrix val identityMatrix = Matrix.eye(transposed.rows) // Combining the transposed matrix with the identity matrix horizontally return Matrix.hstack(transposed, identityMatrix) } @Test fun testTranspositionAndCombination() { val matrix = Matrix(arrayOf(arrayOf(1, 0), arrayOf(0, 1))) // A simple 2x2 identity matrix for simplicity val expected = Matrix.hstack(matrix.transpose(), Matrix.eye(2)) val actual = transpositionAndCombination(matrix) // This method needs to be accessible for testing assertEquals(expected, actual) } private fun restoreAndApplyModulus(generativeMatrix: Matrix, pivotColumns: List<Int>): Matrix { val restoredMatrix = Matrix(generativeMatrix.rows, generativeMatrix.cols) // Восстановление исходной матрицы G pivotColumns.forEachIndexed { index, pivot -> for (row in 0 until generativeMatrix.rows) { restoredMatrix[row, pivot] = generativeMatrix[row, index] } } (0 until generativeMatrix.cols).filterNot { pivotColumns.contains(it) }.forEachIndexed { index, col -> for (row in 0 until generativeMatrix.rows) { restoredMatrix[row, col] = generativeMatrix[row, index + pivotColumns.size] } } // Applying modulus operation to each element in the matrix val modulusMatrix = restoredMatrix % 2 // Assuming % operator is defined for modulus operation return modulusMatrix } @Test fun testRestorationAndModulus() { val generativeMatrix = Matrix(arrayOf(arrayOf(1, 0, 0, 1), arrayOf(0, 1, 1, 0))) val pivotColumns = listOf(2, 3) val expected = Matrix(arrayOf(arrayOf(0, 1, 1, 0), arrayOf(1, 0, 0, 1))) val actual = restoreAndApplyModulus(generativeMatrix, pivotColumns) // This method needs to be accessible for testing println(actual) assertEquals(expected, actual) } @Test fun test() { val generativeMatrix = Matrix(200, 2000) // G = k=200, n=2000 -> H = (2000-200, 2000) for (i in 0..< generativeMatrix.cols) { for (j in 1..3) { val rowIndex = ((Random.nextInt() + j) % generativeMatrix.rows).absoluteValue generativeMatrix[rowIndex, i] = 1 } } val n = 2000 val k = 200 val check = MatrixConverter.canonical(generativeMatrix) assertEquals(min(n-k, n), check.rank()) } private fun singularMatrices(): Array<Array<Any>> = arrayOf( arrayOf("[[0,1,1,1,0,0],[0,1,1,1,0,0],[1,1,0,0,0,1]]"), arrayOf("[[1,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,0],[0,0,0,0,0,0,0,1],[1,1,1,1,1,1,1,1]]"), arrayOf("[[1,2],[2,4]]"), arrayOf("[[0,0,0],[0,0,0],[0,0,0]]"), arrayOf("[[1,2,3],[2,4,6],[3,6,9]]"), arrayOf("[[0,1,0],[0,2,0],[0,3,0]]") ) private fun matrices(): Array<Array<Any>> = arrayOf( arrayOf( "[[0,1,1,1,0,0],[1,0,1,0,1,0],[1,1,0,0,0,1]]", "[[1,0,0,0,1,1],[0,1,0,1,0,1],[0,0,1,1,1,0]]" ), arrayOf( "[[0,1,1,1,0,0],[1,1,1,0,1,0],[1,0,1,0,0,1]]", "[[1,0,0,0,1,1],[0,1,0,1,1,0],[0,0,1,1,1,1]]" ), arrayOf( "[[0,1,1,0,1],[0,0,0,1,1],[1,1,0,0,1]]", "[[1,0,1,1,1],[1,1,1,0,0]]" ), arrayOf( "[[1,1,0,0,1,1,1,1,1,0,1,1],[0,0,1,1,1,1,0,0,0,1,1,0],[1,1,1,1,0,1,1,1,1,0,0,0],[0,0,0,0,1,0,1,0,0,1,0,1]]", "[[1,1,0,0,0,0,0,0,0,0,0,0],[0,0,1,0,1,1,0,0,0,1,0,0],[0,0,1,0,1,0,1,0,0,0,0,0],[1,0,0,0,0,0,0,1,0,0,0,0],[1,0,0,0,0,0,0,0,1,0,0,0],[0,0,1,1,0,0,0,0,0,0,0,0],[1,0,1,0,0,0,0,0,0,0,1,0],[1,0,1,0,0,0,0,0,0,1,0,1]]" ), arrayOf( "[[0,1,1,1,1,0,0,0],[1,0,1,1,0,1,0,0],[1,1,0,1,0,0,1,0],[1,1,1,0,0,0,0,1]]", "[[1,0,1,0,1,0,1,0],[0,1,1,0,0,1,1,0],[0,0,0,1,1,1,1,0],[1,1,1,1,1,1,1,1]]" ) ) }
canonical-converter/converter-core/src/test/kotlin/ConverterAnyTest.kt
2064878876
import org.junit.jupiter.api.Test import parser.MatrixParser import service.MatrixConverter import kotlin.test.assertTrue class AnyTest { @Test fun test1() { val H1s = MatrixParser().createMatrixFromString( "[[0,0,0,1,1,1,1,0],[0,1,1,0,0,1,1,0],[1,0,1,0,1,0,1,0]]" ) val H1 = MatrixConverter.canonical(H1s) println(H1) val H2 = MatrixParser().createMatrixFromString("[[1,1,1,0,0,0,0,0],[1,0,0,1,1,0,0,0],[0,1,0,1,0,1,0,0],[1,1,0,1,0,0,1,0],[0,0,0,0,0,0,0,1]]") assertTrue { H2.isTransformableTo(H1) } } @Test fun test2() { val H1s = MatrixParser().createMatrixFromString( "[[0,0,1,0,1,1,1,0],[0,1,0,1,1,0,1,0],[1,0,0,1,0,1,1,0]]" ) val H1 = MatrixConverter.canonical(H1s) val H2 = MatrixParser().createMatrixFromString("[[1,1,0,1,0,0,0,0],[0,1,1,0,1,0,0,0],[1,0,1,0,0,1,0,0],[1,1,1,0,0,0,1,0],[0,0,0,0,0,0,0,1]]") println((H2 * H1s.transpose()) % 2) assertTrue { H2.isTransformableTo(H1) } } @Test fun test3() { val h = MatrixParser().createMatrixFromString( "[[0, 0, 1, 0, 1, 1, 1, 0],[0, 1, 0, 1, 1, 0, 1, 0],[1, 0, 0, 1, 0, 1, 1, 0]]" ) println(h.transpose()) } @Test fun test4() { val parser = MatrixParser() //11 //111 //1101 //1011 //11001 //10011 //101001 //100101 //111101 //111011 //110111 //101111 val list = listOf( // parser.createMatrixFromString( // "[[1,1,0,1,0,0,0]," + // "[0,1,1,0,1,0,0]," + // "[0,0,1,1,0,1,0]," + // "[0,0,0,1,1,0,1]]" // ), // parser.createMatrixFromString( // "[[0,0,0,0,3,3,1,1]," + // "[3,0,1,0,0,0,0,0]," + // "[0,3,0,1,3,0,1,0]," + // "[0,1,0,4,3,1,2,0]," + // "[0,3,3,3,1,1,1,0]," + // "[0,3,0,1,0,0,0,0]]" // ), parser.createMatrixFromString( "[[1, 1, 1, 0, 0, 0, 0, 0, 0]," + "[0, 1, 1, 1, 0, 0, 0, 0, 0]," + "[0, 0, 1, 1, 1, 0, 0, 0, 0]," + "[0, 0, 0, 1, 1, 1, 0, 0, 0]," + "[0, 0, 0, 0, 1, 1, 1, 0, 0]," + "[0, 0, 0, 0, 0, 1, 1, 1, 0]," + "[1, 1, 1, 0, 1, 1, 0, 1, 1]]" ) ) for (matrix in list) { println(matrix) val g1 = matrix.toRowEchelonForm(2).first val g2 = matrix.toRowEchelonForm(2).first println() println(g1) println(g2) } } }
canonical-converter/converter-core/src/test/kotlin/AnyTest.kt
2714324375
import parser.MatrixParser import service.MatrixConverter import tester.IsLinearSystemSolutionTester import tester.NonDegeneracyTester class CanonicalConverter { fun toGenerative(matrix: String): String { return convert(matrix, false) } fun toParityCheck(matrix: String): String { return convert(matrix, true) } private fun convert(matrix: String, toParityCheck: Boolean): String { val parser = MatrixParser() val nonDegeneracyTester = NonDegeneracyTester() val isLinearSystemSolutionTester = IsLinearSystemSolutionTester() val from = parser.createMatrixFromString(matrix) require(nonDegeneracyTester.test(from)) { "матрица непригодна для преобразования" } val to = MatrixConverter.canonical(from) if (toParityCheck) { require(isLinearSystemSolutionTester.test(to, from)) { "полученная матрица не является проверочной" } } else { require(isLinearSystemSolutionTester.test(from, to)) { "полученная матрица не является порождающей" } } return parser.createStringFromMatrix(to) } }
canonical-converter/converter-core/src/main/kotlin/CanonicalConverter.kt
1395378393
package parser import model.Matrix import mu.KotlinLogging class MatrixParser { private val logger = KotlinLogging.logger {} fun createMatrixFromString(matrixString: String): Matrix { logger.trace { "входящая строка\n$matrixString" } val rows = matrixString.trim().removeSurrounding("[[", "]]").split("],[","], [", "],\n[") val numRows = rows.size val numCols = rows.first().split(",").size val matrix = Matrix(numRows, numCols) logger.trace { "параметры матрицы\nколичество строк: $numRows\nколичество столбцов: $numCols" } for ((i, row) in rows.withIndex()) { val elements = row.split(",").map { it.trim().toInt() } for ((j, elem) in elements.withIndex()) { matrix[i, j] = elem } } logger.trace { "восстановленная из входящей строки матрица\n$matrixString" } return matrix } fun createStringFromMatrix(matrix: Matrix): String { val numRows = matrix.rows val numCols = matrix.cols val stringBuilder = StringBuilder() stringBuilder.append("[") for (i in 0 until numRows) { stringBuilder.append("[") for (j in 0 until numCols) { stringBuilder.append(matrix[i, j]) if (j < numCols - 1) { stringBuilder.append(", ") } } stringBuilder.append("]") if (i < numRows - 1) { stringBuilder.append(",\n") } } stringBuilder.append("]") return stringBuilder.toString() } }
canonical-converter/converter-core/src/main/kotlin/parser/MatrixParser.kt
2037905957
package model class Matrix { var cols: Int val rows: Int private var data: Array<Array<Int>> constructor(rows: Int, cols: Int) : this( Array(rows) { Array(cols) { 0 } } ) constructor(data: Array<Array<Int>>) { this.rows = data.size this.cols = data[0].size require(rows > 0 && cols > 0) { "количество строк и столбцов должно быть положительным целым числом" } this.data = data } companion object { fun eye(size: Int): Matrix { val result = Matrix(size, size) for (i in 0 until size) { result[i, i] = 1 } return result } fun hstack(a: Matrix, b: Matrix): Matrix { if (a.rows != b.rows) throw IllegalArgumentException("Matrices don't have the same number of rows.") val result = Matrix(a.rows, a.cols + b.cols) for (i in 0 until a.rows) { for (j in 0 until a.cols) { result[i, j] = a[i, j] } for (j in 0 until b.cols) { result[i, j + a.cols] = b[i, j] } } return result } } fun gaussianElimination(): Matrix { val A = this.copy() var lead = 0 for (r in 0 until A.rows) { if (A.cols <= lead) break var i = r while (A.data[i][lead] == 0) { i++ if (A.rows == i) { i = r lead++ if (A.cols == lead) return A } } val temp = A.data[r] A.data[r] = A.data[i] A.data[i] = temp val div = A.data[r][lead] if (div != 0) { // Для избежания деления на ноль for (j in 0 until A.cols) { A.data[r][j] /= div } } for (k in 0 until A.rows) { if (k != r) { val mult = A.data[k][lead] for (j in 0 until A.cols) { A.data[k][j] -= A.data[r][j] * mult } } } lead++ } return A } fun rank(): Int { val ref = this.toRowEchelonForm(2).first var rank = 0 for (i in 0 until ref.rows) { for (j in 0 until ref.cols) { if (ref.data[i][j] != 0) { rank++ break } } } return rank } fun subMatrix(startRow: Int, endRow: Int, startCol: Int, endCol: Int): Matrix { val subRows = endRow - startRow val subCols = endCol - startCol val result = Matrix(subRows, subCols) for (i in 0 until subRows) { for (j in 0 until subCols) { result[i, j] = this[startRow + i, startCol + j] } } return result } fun determinant(): Int { require(isSquare()) { "определитель можно вычислить только для квадратной матрицы" } if (rows == 1) return this[0, 0] if (rows == 2) return this[0, 0] * this[1, 1] - this[1, 0] * this[0, 1] var det = 0 for (col in 0 until cols) { det += this[0, col] * cofactor(0, col) } return det } fun isSquare() = cols == rows private fun cofactor(row: Int, col: Int): Int { return minor(row, col).determinant() * if ((row + col) % 2 == 0) 1 else -1 } private fun minor(row: Int, col: Int): Matrix { val result = Matrix(rows - 1, cols - 1) for (i in 0 until rows) { for (j in 0 until cols) { if (i == row || j == col) continue result[if (i < row) i else i - 1, if (j < col) j else j - 1] = this[i, j] } } return result } /** * Приведение матрицы к ступенчатому виду в кольце по модулю mod. */ fun toRowEchelonForm(mod: Int): Pair<Matrix, List<Int>> { val matrix = copy() val pivotColumns = mutableListOf<Int>() var lead = 0 for (r in 0 until rows) { if (lead >= cols) break var i = r while (matrix[i, lead] % mod == 0) { i++ if (i == rows) { i = r lead++ if (lead == cols) { return Pair(matrix, pivotColumns) } } } // Перестановка строк for (k in 0 until cols) { val temp = matrix[r, k] matrix[r, k] = matrix[i, k] matrix[i, k] = temp } pivotColumns.add(lead) // Приведение элементов столбца к нулю с использованием аддитивной инверсии for (j in 0 until rows) { if (j != r) { val mult = matrix[j, lead] for (k in lead until cols) { val factor = (mult * modInverse(matrix[r, lead], mod)) % mod matrix[j, k] = (matrix[j, k] - factor * matrix[r, k] + mod * mod) % mod } } } lead++ } return Pair(matrix, pivotColumns) } private fun gcdExtended(a: Int, b: Int, x: IntArray, y: IntArray): Int { if (a == 0) { x[0] = 0 y[0] = 1 return b } val x1 = IntArray(1) val y1 = IntArray(1) val gcd = gcdExtended(b % a, a, x1, y1) x[0] = y1[0] - (b / a) * x1[0] y[0] = x1[0] return gcd } private fun modInverse(a: Int, mod: Int): Int { val x = IntArray(1) val y = IntArray(1) val g = gcdExtended(a, mod, x, y) if (g != 1) { throw IllegalArgumentException("Inverse does not exist.") } else { return (x[0] % mod + mod) % mod } } /** * Создает и возвращает глубокую копию этой матрицы. */ fun copy(): Matrix { val newMatrix = Matrix(rows, cols) for (i in 0 until rows) { for (j in 0 until cols) { newMatrix[i, j] = this[i, j] } } return newMatrix } operator fun get(row: Int, col: Int): Int { if (row !in 0 until rows || col !in 0 until cols) { throw IndexOutOfBoundsException("обращение за пределы матрицы") } return data[row][col] } fun row(index: Int): Array<Int> { require(index in 0..<rows) { "обращение за пределы матрицы" } return data[index] } fun column(index: Int): Array<Int> { require(index in 0..<cols) { "обращение за пределы матрицы" } val column = mutableListOf<Int>() data.forEach { column.add(it[index]) } return column.toTypedArray() } operator fun set(row: Int, col: Int, value: Int) { if (row !in 0 until rows || col !in 0 until cols) { throw IndexOutOfBoundsException("запись за пределы матрицы") } data[row][col] = value } private fun plus(left: Matrix, right: Matrix): Matrix { val result = Matrix(rows, cols) if (left.rows != right.rows || left.cols != right.cols) { throw IllegalArgumentException("размеры матриц должны совпадать для операции сложения") } for (i in 0 until rows) { for (j in 0 until cols) { result[i, j] = left[i, j] + right[i, j] } } return result } fun transpose(): Matrix { val result = Matrix(cols, rows) for (i in 0 until rows) { for (j in 0 until cols) { result[j, i] = this[i, j] } } return result } operator fun plus(other: Matrix): Matrix { return plus(this, other) } operator fun plusAssign(other: Matrix) { this.data = plus(this, other).data } operator fun rem(constant: Int): Matrix { val result = Matrix(rows, cols) for (i in 0 until rows) { for (j in 0 until cols) { result[i, j] = this[i, j] % constant } } return result } operator fun times(constant: Int): Matrix { val result = Matrix(rows, cols) for (i in 0 until rows) { for (j in 0 until cols) { result[i, j] = this[i, j] * constant } } return result } operator fun times(other: Matrix): Matrix { if (cols != other.rows) { throw IllegalArgumentException( "количество количество колонок первой матрицы должно совпадать с количеством строк второй при умножении" ) } val n = rows val p = other.cols val m = cols val result = Matrix(n, p) for (i in 0 until n) { for (j in 0 until p) { var sum = 0 for (k in 0 until m) { sum += this[i, k] * other[k, j] } result[i, j] = sum } } return result } fun isTransformableTo(other: Matrix): Boolean { if (this.rows != other.rows || this.cols != other.cols) { throw IllegalArgumentException("матрицы должны иметь одинаковую размерность") } val refThis = this.toRowEchelonForm(2) val refOther = other.toRowEchelonForm(2) // Compare the REF forms of both matrices for (i in 0 until refThis.first.rows) { for (j in 0 until refThis.first.cols) { if (refThis.first.data[i][j] != refOther.first.data[i][j]) { return false } } } return true } override fun toString(): String { // Находим максимальную ширину числа в матрице для выравнивания val maxNumberWidth = data.flatten().maxOfOrNull { it.toString().length } ?: 0 return data.joinToString(separator = "\n") { row -> row.joinToString(separator = " ") { elem -> "%${maxNumberWidth}d".format(elem) } } } fun isZero(): Boolean { return data.flatten().all { it == 0 } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Matrix if (rows != other.rows || cols != other.cols) return false if (!data.contentDeepEquals(other.data)) return false return true } override fun hashCode(): Int { var result = rows result = 31 * result + cols result = 31 * result + data.contentDeepHashCode() return result } }
canonical-converter/converter-core/src/main/kotlin/model/Matrix.kt
2181108329
package tester import model.Matrix interface MatrixTester { fun test(vararg matrices: Matrix): Boolean }
canonical-converter/converter-core/src/main/kotlin/tester/Tester.kt
3919327384
package tester import model.Matrix class IsLinearSystemSolutionTester : MatrixTester { override fun test(vararg matrices: Matrix): Boolean { require(matrices.size == 2) { "количество матриц не соответствует двум: матрица коэффициентов и матрица решений" } val (a: Matrix, x: Matrix) = matrices return (a * x.transpose() % 2).isZero() } }
canonical-converter/converter-core/src/main/kotlin/tester/IsLinearSystemSolutionTester.kt
355229846
package tester import model.Matrix import mu.KotlinLogging class NonDegeneracyTester : MatrixTester { private val logger = KotlinLogging.logger {} override fun test(vararg matrices: Matrix) = matrices.all { if (containsZero(it)) { logger.trace { "матрица вырожденная, так как содержит нулевую строку" } return@all false } if (it.isSquare() && it.determinant() == 0) { logger.trace { "матрица вырожденная, так как ее детерминант равен 0" } return@all false } if (it.rank() < minOf(it.cols, it.rows)) { logger.trace { "матрица вырожденная, так как ее ранг меньше ее порядка" } return@all false } logger.trace { "матрица невырожденная" } return@all true } private fun containsZero(matrix: Matrix): Boolean { for (i in 0..<matrix.rows) { val row = matrix.row(i) val isZero = row.all { it == 0 } if (isZero) { return true } } return false } }
canonical-converter/converter-core/src/main/kotlin/tester/NonDegeneracyTester.kt
4191107093
package service import model.Matrix import mu.KotlinLogging object MatrixConverter { private val logger = KotlinLogging.logger {} fun canonical(matrix: Matrix): Matrix { logger.trace { "исходная матрица\n$matrix" } val (rrefMatrix, pivotColumns) = matrix.toRowEchelonForm(2) logger.trace { "ступенчатый вид\n$rrefMatrix" } logger.trace { "индексы ведущих столбцов\n$pivotColumns" } val rearrangedMatrix = Matrix(matrix.rows, matrix.cols) val columnOrder = pivotColumns + (0 until matrix.cols).filterNot { pivotColumns.contains(it) } columnOrder.forEachIndexed { index, colIndex -> if (index < matrix.rows) { // Перестановка столбцов для ведущих столбцов for (row in 0 until matrix.rows) { rearrangedMatrix[row, index] = rrefMatrix[row, colIndex] } } else { // Заполнение оставшихся столбцов for (row in 0 until matrix.rows) { rearrangedMatrix[row, index] = rrefMatrix[row, colIndex] } } } logger.trace { "перестановка столбцов согласно pivot columns\n$rearrangedMatrix" } // Транспонирование подматрицы A и объединение с единичной матрицей val aMatrix = rearrangedMatrix.subMatrix(0, matrix.rows, matrix.rows, matrix.cols) val aTransposed = aMatrix.transpose() logger.trace { "подматрица A после перестановки и транспонирования\n$aTransposed" } val eyeMatrix = Matrix.eye(aTransposed.rows) val generativeMatrix = Matrix.hstack(aTransposed, eyeMatrix) logger.trace { "порождающая матрица для проверочной с примененной перестановкой\n$generativeMatrix" } // Восстановление исходной матрицы G val restoredG = Matrix(generativeMatrix.rows, generativeMatrix.cols) pivotColumns.forEachIndexed { index, pivot -> for (row in 0 until generativeMatrix.rows) { restoredG[row, pivot] = generativeMatrix[row, index] } } (0 until generativeMatrix.cols).filterNot { pivotColumns.contains(it) }.forEachIndexed { index, col -> for (row in 0 until generativeMatrix.rows) { restoredG[row, col] = generativeMatrix[row, index + pivotColumns.size] } } logger.trace { "восстановленная исходная матрица\n$restoredG" } val restoredGModule = restoredG % 2 logger.trace { "восстановленная исходная матрица с примененным модулем\n$restoredGModule" } return restoredGModule } }
canonical-converter/converter-core/src/main/kotlin/service/MatrixConverter.kt
3060889914
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui import android.app.Application import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory import androidx.lifecycle.viewmodel.CreationExtras import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.example.juicetracker.JuiceTrackerApplication object AppViewModelProvider { val Factory = viewModelFactory { // Initializer for JuiceTrackerViewModel initializer { JuiceTrackerViewModel( juiceTrackerApplication().container.juiceRepository, juiceTrackerApplication().container.notaRepository, juiceTrackerApplication().container.tareaRepository, juiceTrackerApplication().container.multimediaRepository ) } } } /** * Extension function to queries for [Application] object and returns an instance of * [JuiceTrackerApplication]. */ fun CreationExtras.juiceTrackerApplication(): JuiceTrackerApplication = (this[AndroidViewModelFactory.APPLICATION_KEY] as JuiceTrackerApplication)
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/AppViewModelProvider.kt
2913332922
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.juicetracker.data.Model.* import com.example.juicetracker.data.Repositorio.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch /** * View Model which maintain states for [JuiceTrackerApp] */ class JuiceTrackerViewModel( private val juiceRepository: JuiceRepository, private val notaRepository: NotaRepository, private val tareaRepository: TareaRepository, private val multimediaRepository: MultimediaRepository ) : ViewModel() { private val emptyJuice = Juice( 0, "", "", JuiceColor.Red.name, imageUri = null, videoUri = null, audioUri = null, 4 ) private val emptyNota = Nota( 0, "", "", "", "" ) private val emptyTarea = Tarea( 0, "", "", 0, "", 0.0, 0.0, "" ) private val emptyMultimedia = Multimedia( 0, "", null, null, null, null, null ) private val _currentJuiceStream = MutableStateFlow(emptyJuice) val currentJuiceStream: StateFlow<Juice> = _currentJuiceStream val juiceListStream: Flow<List<Juice>> = juiceRepository.juiceStream fun resetCurrentJuice() = _currentJuiceStream.update { emptyJuice } fun updateCurrentJuice(juice: Juice) = _currentJuiceStream.update { juice } fun saveJuice() = viewModelScope.launch { if (_currentJuiceStream.value.id > 0) { juiceRepository.updateJuice(_currentJuiceStream.value) } else { juiceRepository. addJuice(_currentJuiceStream.value) } } fun deleteJuice(juice: Juice) = viewModelScope.launch { juiceRepository.deleteJuice(juice) } //////////////////////////////|Nota|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ private val _currentNotaStream = MutableStateFlow(emptyNota) val currentNotaStream: StateFlow<Nota> = _currentNotaStream val notaListStream: Flow<List<Nota>> = notaRepository.notaStream fun resetCurrentNota() = _currentNotaStream.update { emptyNota } fun updateCurrentNota(nota: Nota) = _currentNotaStream.update { nota } fun saveNota() = viewModelScope.launch { if (_currentNotaStream.value.id > 0) { notaRepository.updateNota(_currentNotaStream.value) } else { notaRepository. addNota(_currentNotaStream.value) } } fun deleteNota(nota: Nota) = viewModelScope.launch { notaRepository.deleteNota(nota) } //////////////////////////////|Tarea|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ private val _currentTareaStream = MutableStateFlow(emptyTarea) val currentTareaStream: StateFlow<Tarea> = _currentTareaStream val tareaListStream: Flow<List<Tarea>> = tareaRepository.tareaStream fun resetCurrentTarea() = _currentTareaStream.update { emptyTarea } fun updateCurrentTarea(tarea: Tarea) = _currentTareaStream.update { tarea } fun saveTarea() = viewModelScope.launch { if (_currentTareaStream.value.id > 0) { tareaRepository.updateTarea(_currentTareaStream.value) } else { tareaRepository. addTarea(_currentTareaStream.value) } } fun deleteTarea(tarea: Tarea) = viewModelScope.launch { tareaRepository.deleteTarea(tarea) } //////////////////////////////|Multimedia|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ private val _currentMultimediaStream = MutableStateFlow(emptyMultimedia) val currentMultimediaStream: StateFlow<Multimedia> = _currentMultimediaStream val multimediaListStream: Flow<List<Multimedia>> = multimediaRepository.multimediaStream fun resetCurrentMultimedia() = _currentMultimediaStream.update { emptyMultimedia } fun updateCurrentMultimedia(multimedia: Multimedia) = _currentMultimediaStream.update { multimedia } fun saveMultimedia() = viewModelScope.launch { multimediaRepository.addMultimedia(_currentMultimediaStream.value) } fun deleteMultimedia(multimedia: Multimedia) = viewModelScope.launch { multimediaRepository.deleteMultimedia(multimedia) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/JuiceTrackerViewModel.kt
357562178
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6750A4) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFEADDFF) val md_theme_light_onPrimaryContainer = Color(0xFF21005D) val md_theme_light_secondary = Color(0xFF625B71) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFE8DEF8) val md_theme_light_onSecondaryContainer = Color(0xFF1D192B) val md_theme_light_tertiary = Color(0xFF7D5260) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD8E4) val md_theme_light_onTertiaryContainer = Color(0xFF31111D) val md_theme_light_error = Color(0xFFB3261E) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_errorContainer = Color(0xFFF9DEDC) val md_theme_light_onErrorContainer = Color(0xFF410E0B) val md_theme_light_outline = Color(0xFF79747E) val md_theme_light_background = Color(0xFFFFFBFE) val md_theme_light_onBackground = Color(0xFF1C1B1F) val md_theme_light_surface = Color(0xFFFFFBFE) val md_theme_light_onSurface = Color(0xFF1C1B1F) val md_theme_light_surfaceVariant = Color(0xFFE7E0EC) val md_theme_light_onSurfaceVariant = Color(0xFF49454F) val md_theme_light_inverseSurface = Color(0xFF313033) val md_theme_light_inverseOnSurface = Color(0xFFF4EFF4) val md_theme_light_inversePrimary = Color(0xFFD0BCFF) val md_theme_light_surfaceTint = Color(0xFF6750A4) val md_theme_light_outlineVariant = Color(0xFFCAC4D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFD0BCFF) val md_theme_dark_onPrimary = Color(0xFF381E72) val md_theme_dark_primaryContainer = Color(0xFF4F378B) val md_theme_dark_onPrimaryContainer = Color(0xFFEADDFF) val md_theme_dark_secondary = Color(0xFFCCC2DC) val md_theme_dark_onSecondary = Color(0xFF332D41) val md_theme_dark_secondaryContainer = Color(0xFF4A4458) val md_theme_dark_onSecondaryContainer = Color(0xFFE8DEF8) val md_theme_dark_tertiary = Color(0xFFEFB8C8) val md_theme_dark_onTertiary = Color(0xFF492532) val md_theme_dark_tertiaryContainer = Color(0xFF633B48) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD8E4) val md_theme_dark_error = Color(0xFFF2B8B5) val md_theme_dark_onError = Color(0xFF601410) val md_theme_dark_errorContainer = Color(0xFF8C1D18) val md_theme_dark_onErrorContainer = Color(0xFFF9DEDC) val md_theme_dark_outline = Color(0xFF938F99) val md_theme_dark_background = Color(0xFF1C1B1F) val md_theme_dark_onBackground = Color(0xFFE6E1E5) val md_theme_dark_surface = Color(0xFF1C1B1F) val md_theme_dark_onSurface = Color(0xFFE6E1E5) val md_theme_dark_surfaceVariant = Color(0xFF49454F) val md_theme_dark_onSurfaceVariant = Color(0xFFCAC4D0) val md_theme_dark_inverseSurface = Color(0xFFE6E1E5) val md_theme_dark_inverseOnSurface = Color(0xFF313033) val md_theme_dark_inversePrimary = Color(0xFF6750A4) val md_theme_dark_surfaceTint = Color(0xFFD0BCFF) val md_theme_dark_outlineVariant = Color(0xFF49454F) val md_theme_dark_scrim = Color(0xFF000000) val Orange = Color(0xFFFF8A00)
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/theme/Color.kt
290112955
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, onError = md_theme_light_onError, errorContainer = md_theme_light_errorContainer, onErrorContainer = md_theme_light_onErrorContainer, outline = md_theme_light_outline, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, inverseSurface = md_theme_light_inverseSurface, inverseOnSurface = md_theme_light_inverseOnSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, onError = md_theme_dark_onError, errorContainer = md_theme_dark_errorContainer, onErrorContainer = md_theme_dark_onErrorContainer, outline = md_theme_dark_outline, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, inverseSurface = md_theme_dark_inverseSurface, inverseOnSurface = md_theme_dark_inverseOnSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun JuiceTrackerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+, set to false for training purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/theme/Theme.kt
1259155561
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.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 ) )
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/theme/Type.kt
3376672484
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.List import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.example.juicetracker.R @Composable fun TareaTrackerFAB( onClick: () -> Unit, modifier: Modifier = Modifier ) { FloatingActionButton( onClick = onClick, modifier = modifier ) { Icon( imageVector = Icons.Default.List, contentDescription = stringResource(R.string.add_task), ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/TareaTrackerFAB.kt
1103368698
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.juicetracker.R import com.example.juicetracker.data.Model.Tarea import com.example.juicetracker.data.Model.Juice @Composable fun TareaTrackerList( tareas: List<Tarea>, onDelete: (Tarea) -> Unit, onUpdate: (Tarea) -> Unit, modifier: Modifier = Modifier ) { LazyColumn( modifier = modifier, contentPadding = PaddingValues(vertical = dimensionResource(R.dimen.padding_small)), ) { items(items = tareas) { tarea -> TareaTrackerListItem( tarea = tarea, onDelete = onDelete, modifier = Modifier .fillMaxWidth() .clickable { onUpdate(tarea) } .padding( vertical = dimensionResource(R.dimen.padding_small), horizontal = dimensionResource(R.dimen.padding_medium) ) ) } } } @Composable fun TareaTrackerListItem( tarea: Tarea, onDelete: (Tarea) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { //JuiceIcon(tarea.color) TareaDetails(tarea, Modifier.weight(1f)) DeleteButtonTarea( onDelete = { onDelete(tarea) }, modifier = Modifier.align(Alignment.Top) ) } } @Composable fun TareaDetails(tarea: Tarea, modifier: Modifier = Modifier) { Column(modifier, verticalArrangement = Arrangement.Top) { Text( text = tarea.tareaTitle, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), ) Text(tarea.tareaBody) } } @Composable fun DeleteButtonTarea(onDelete: () -> Unit, modifier: Modifier = Modifier) { IconButton( onClick = { onDelete() }, ) { Icon( modifier = modifier, painter = painterResource(R.drawable.delete_icon), contentDescription = stringResource(R.string.delete) ) } } /* @Preview @Composable fun TareaTrackerListPreview() { MaterialTheme { TareaTrackerList( tareas = listOf( Tarea(1, "ya fue", "date de baja", 1, "09/08/23", "10/08/23") /* Tarea(1, "Mango", "Yummy!", "Yellow", imageUri = null, videoUri = null, audioUri = null, 5), Tarea(2, "Orange", "Refreshing~", "Orange", imageUri = null, videoUri = null, audioUri = null, 4), Tarea(3, "Grape", "Refreshing~", "Magenta", imageUri = null, videoUri = null, audioUri = null, 2), Tarea(4, "Celery", "Refreshing~", "Green", imageUri = null, videoUri = null, audioUri = null, 1), Tarea(5, "ABC", "Refreshing~", "Red", imageUri = null, videoUri = null, audioUri = null, 4) */ ), onDelete = {}, onUpdate = {}) } }*/
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/TareaTrackerList.kt
2253570815
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.juicetracker.R import com.example.juicetracker.data.Model.Nota @Composable fun NotaTrackerList( notas: List<Nota>, onDelete: (Nota) -> Unit, onUpdate: (Nota) -> Unit, modifier: Modifier = Modifier ) { LazyColumn( modifier = modifier, contentPadding = PaddingValues(vertical = dimensionResource(R.dimen.padding_small)), ) { items(items = notas) { nota -> NotaTrackerListItem( nota = nota, onDelete = onDelete, modifier = Modifier .fillMaxWidth() .clickable { onUpdate(nota) } .padding( vertical = dimensionResource(R.dimen.padding_small), horizontal = dimensionResource(R.dimen.padding_medium) ) ) } } } @Composable fun NotaTrackerListItem( nota: Nota, onDelete: (Nota) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { //JuiceIcon(juice.color) NotaDetails(nota, Modifier.weight(1f)) DeleteButtonNota( onDelete = { onDelete(nota) }, modifier = Modifier.align(Alignment.Top) ) } } @Composable fun NotaDetails(nota: Nota, modifier: Modifier = Modifier) { Column(modifier, verticalArrangement = Arrangement.Top) { Text( text = nota.noteTitle, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), ) Text(nota.noteBody) } } @Composable fun DeleteButtonNota(onDelete: () -> Unit, modifier: Modifier = Modifier) { IconButton( onClick = { onDelete() }, ) { Icon( modifier = modifier, painter = painterResource(R.drawable.delete_icon), contentDescription = stringResource(R.string.delete) ) } } /*@Preview @Composable fun NotaTrackerListPreview() { MaterialTheme { NotaTrackerList( notas = listOf( Nota(1, "Mango", "Yummy!", "Yellow", imageUri = null, videoUri = null, audioUri = null, 5), Nota(2, "Orange", "Refreshing~", "Orange", imageUri = null, videoUri = null, audioUri = null, 4), Nota(3, "Grape", "Refreshing~", "Magenta", imageUri = null, videoUri = null, audioUri = null, 2), Nota(4, "Celery", "Refreshing~", "Green", imageUri = null, videoUri = null, audioUri = null, 1), Nota(5, "ABC", "Refreshing~", "Red", imageUri = null, videoUri = null, audioUri = null, 4) ), onDelete = {}, onUpdate = {}) } }*/
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/NotasTrackerList.kt
2043476506
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.juicetracker.R import com.example.juicetracker.data.Model.Juice @Composable fun JuiceTrackerList( juices: List<Juice>, onDelete: (Juice) -> Unit, onUpdate: (Juice) -> Unit, modifier: Modifier = Modifier ) { LazyColumn( modifier = modifier, contentPadding = PaddingValues(vertical = dimensionResource(R.dimen.padding_small)), ) { items(items = juices) { juice -> JuiceTrackerListItem( juice = juice, onDelete = onDelete, modifier = Modifier .fillMaxWidth() .clickable { onUpdate(juice) } .padding( vertical = dimensionResource(R.dimen.padding_small), horizontal = dimensionResource(R.dimen.padding_medium) ) ) } } } @Composable fun JuiceTrackerListItem( juice: Juice, onDelete: (Juice) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { JuiceIcon(juice.color) JuiceDetails(juice, Modifier.weight(1f)) DeleteButton( onDelete = { onDelete(juice) }, modifier = Modifier.align(Alignment.Top) ) } } @Composable fun JuiceDetails(juice: Juice, modifier: Modifier = Modifier) { Column(modifier, verticalArrangement = Arrangement.Top) { Text( text = juice.name, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), ) Text(juice.description) } } @Composable fun DeleteButton(onDelete: () -> Unit, modifier: Modifier = Modifier) { IconButton( onClick = { onDelete() }, ) { Icon( modifier = modifier, painter = painterResource(R.drawable.delete_icon), contentDescription = stringResource(R.string.delete) ) } } @Preview @Composable fun JuiceTrackerListPreview() { MaterialTheme { JuiceTrackerList( juices = listOf( Juice(1, "Mango", "Yummy!", "Yellow", imageUri = null, videoUri = null, audioUri = null, 5), Juice(2, "Orange", "Refreshing~", "Orange", imageUri = null, videoUri = null, audioUri = null, 4), Juice(3, "Grape", "Refreshing~", "Magenta", imageUri = null, videoUri = null, audioUri = null, 2), Juice(4, "Celery", "Refreshing~", "Green", imageUri = null, videoUri = null, audioUri = null, 1), Juice(5, "ABC", "Refreshing~", "Red", imageUri = null, videoUri = null, audioUri = null, 4) ), onDelete = {}, onUpdate = {}) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/JuiceTrackerList.kt
2331221456
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.foundation.layout.Box import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import com.example.juicetracker.R import com.example.juicetracker.data.Model.JuiceColor /** * Custom icon for juice which is able to adjust for Dark Mode. * contentDescription for Box is added through semantics to support better accessibility. * Icons' contentDescription are nullified as its meaning has been explained by * the box's contentDescription */ @Composable fun JuiceIcon(color: String, modifier: Modifier = Modifier) { val juiceIconContentDescription = stringResource(R.string.juice_color, color) Box( modifier.semantics { contentDescription = juiceIconContentDescription } ) { Icon( painter = painterResource(R.drawable.juice_color), contentDescription = null, tint = JuiceColor.valueOf(color).color, modifier = Modifier.align(Alignment.Center) ) Icon(painter = painterResource(R.drawable.juice_clear_icon), contentDescription = null) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/JuiceIcon.kt
1797335033
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen 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.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.example.juicetracker.R @Composable fun JuiceTrackerFAB( onClick: () -> Unit, modifier: Modifier = Modifier ) { FloatingActionButton( onClick = onClick, modifier = modifier ) { Icon( imageVector = Icons.Default.Add, contentDescription = stringResource(R.string.add_juice), ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/JuiceTrackerFAB.kt
3358361414
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.viewinterop.AndroidView import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView /** * A composable which uses AndroidView to render AdView. * Showing a banner test ad */ @Composable fun AdBanner(modifier: Modifier = Modifier) { AndroidView( modifier = modifier, factory = { context -> AdView(context).apply { setAdSize(AdSize.BANNER) // Use test ad unit ID adUnitId = "ca-app-pub-3940256099942544/6300978111" } }, update = { it.loadAd(AdRequest.Builder().build()) } ) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/AdBanner.kt
3393042975
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.homescreen import androidx.compose.foundation.layout.padding import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import com.example.juicetracker.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun JuiceTrackerTopAppBar(modifier: Modifier = Modifier) { CenterAlignedTopAppBar( modifier = modifier, colors = TopAppBarDefaults.largeTopAppBarColors( containerColor = MaterialTheme.colorScheme.background ), title = { Text( text = stringResource(R.string.tope), modifier = Modifier.padding(horizontal = dimensionResource(R.dimen.padding_medium)), fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onBackground ) } ) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/homescreen/JuiceTrackerTopBar.kt
1964363468
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.bottomsheet import android.Manifest import android.annotation.SuppressLint import android.net.Uri import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import androidx.annotation.RequiresPermission import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column //import androidx.compose.foundation.layout.ColumnScopeInstance.align import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect 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.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.juicetracker.ImagePicker import com.example.juicetracker.R import com.example.juicetracker.data.Model.* import com.example.juicetracker.data.Model.JuiceColor //import com.example.juicetracker.mapas.location.CurrentLocationScreen import com.example.juicetracker.mapas.location.PermissionBox //import com.example.juicetracker.mapas.mapasosmandroidcompose.OSMComposeMapa import com.example.juicetracker.ui.JuiceTrackerViewModel import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.CancellationTokenSource import com.utsman.osmandcompose.DefaultMapProperties import com.utsman.osmandcompose.Marker import com.utsman.osmandcompose.OpenStreetMap import com.utsman.osmandcompose.Polyline import com.utsman.osmandcompose.ZoomButtonVisibility import com.utsman.osmandcompose.rememberCameraState import com.utsman.osmandcompose.rememberMarkerState import com.utsman.osmandcompose.rememberOverlayManagerState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.overlay.CopyrightOverlay import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale // Optando por la API ExperimentalMaterial3 @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalMaterial3Api::class) // Función componible para la interfaz de usuario de la hoja inferior @Composable fun EntryBottomSheet( juiceTrackerViewModel: JuiceTrackerViewModel, sheetScaffoldState: BottomSheetScaffoldState, onCancel: () -> Unit, onSubmit: () -> Unit, modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { // Recopilando el estado actual del jugo mediante un StateFlow val nota by juiceTrackerViewModel.currentNotaStream.collectAsState() var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } // Construyendo el BottomSheetScaffold con encabezado, formulario y contenido personalizado BottomSheetScaffold( modifier = modifier, scaffoldState = sheetScaffoldState, sheetContent = { Column { // Sección de encabezado de la hoja inferior SheetHeader(Modifier.padding(dimensionResource(R.dimen.padding_small))) // Sección de formulario de la hoja inferior SheetForm( nota = nota, onUpdateNota = juiceTrackerViewModel::updateCurrentNota, onCancel = onCancel, onSubmit = onSubmit, modifier = Modifier.padding( horizontal = dimensionResource(R.dimen.padding_medium) ) ) } } ) { // Contenido personalizado proporcionado por el llamador content() } } // Función componible para el encabezado de la hoja inferior @Composable fun SheetHeader(modifier: Modifier = Modifier) { Column(modifier = modifier) { // Texto del titular para la hoja inferior Text( modifier = Modifier.padding(dimensionResource(R.dimen.padding_small)), text = stringResource(R.string.bottom_sheet_headline), style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold) ) // Línea divisoria Divider() } } // Función componible para el contenido del formulario de la hoja inferior @RequiresApi(Build.VERSION_CODES.O) @Composable fun SheetForm( nota: Nota, onUpdateNota: (Nota) -> Unit, onCancel: () -> Unit, onSubmit: () -> Unit, modifier: Modifier = Modifier ){ var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } LazyColumn( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween, //content = ) { item { // Fila de entrada para el nombre del jugo TextInputRow( inputLabel = stringResource(R.string.nota_name), fieldValue = nota.noteTitle, onValueChange = { name -> onUpdateNota(nota.copy(noteTitle = name)) }, modifier = Modifier.fillMaxWidth(), ) } item { // Fila de entrada para la descripción del jugo TextInputRow( inputLabel = stringResource(R.string.nota_description), fieldValue = nota.noteBody, onValueChange = { description -> onUpdateNota(nota.copy(noteBody = description)) }, modifier = Modifier.fillMaxWidth() ) } /*item { // Fila del selector de color para seleccionar el color del jugo ColorSpinnerRow( colorSpinnerPosition = findColorIndex(nota.color), onColorChange = { color -> onUpdateNota(nota.copy(color = NotaColor.values()[color].name)) } ) }*/ item { /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AlarmasScreen( alarmScheduler = AlarmSchedulerImpl(applicationContext)) }*/ ImagePicker() } item { // Fila de botones con botones de cancelar y enviar ButtonRow( modifier = Modifier //.align(Alignment.End) .padding(bottom = dimensionResource(R.dimen.padding_medium)), onCancel = onCancel, onSubmit = onSubmit, submitButtonEnabled = nota.noteTitle.isNotEmpty(), ) } item { CurrentLocationScreen(){ value1, value2, value3 -> longitud = value1 // Actualiza el primer valor recibido en el componente padre latitud = value2 // Actualiza el segundo valor recibido en el componente padre controlmapa = value3} } /*item { if (controlmapa){ OSMComposeMapa( longitud = longitud, latitud = (latitud) ) } }*/ item { Spacer(modifier = Modifier.height(90.dp)) } } } // Función componible para una fila con botones de cancelar y enviar @Composable fun ButtonRow( onCancel: () -> Unit, onSubmit: () -> Unit, submitButtonEnabled: Boolean, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { // Botón de cancelar OutlinedButton( onClick = onCancel, border = null ) { Text(stringResource(android.R.string.cancel).uppercase(Locale.getDefault())) } // Botón de enviar Button( onClick = onSubmit, ) { Text(stringResource(R.string.save).uppercase(Locale.getDefault())) } } Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } } } // Función componible para una fila con un campo de entrada de texto @Composable fun TextInputRow( inputLabel: String, fieldValue: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier ) { // Fila de entrada genérica con un campo de texto InputRow(inputLabel, modifier) { TextField( modifier = Modifier.padding(bottom = dimensionResource(R.dimen.padding_small)), value = fieldValue, onValueChange = onValueChange, singleLine = true, maxLines = 1, // Personalización de los colores del campo de texto según el tema Material colors = TextFieldDefaults.colors( focusedContainerColor = colorScheme.surface, unfocusedContainerColor = colorScheme.surface, disabledContainerColor = colorScheme.surface, ), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next) ) } } // Función componible para una fila de entrada genérica con etiqueta y contenido @Composable fun InputRow( inputLabel: String, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { // Fila que contiene una etiqueta y contenido Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { // Texto de la etiqueta Text( text = inputLabel, fontWeight = FontWeight.SemiBold, // La etiqueta ocupa 1/3 del espacio disponible modifier = modifier.weight(1f) ) // El contenido ocupa 2/3 del espacio disponible Box(modifier = Modifier.weight(2f)) { content() } } } // Función para encontrar el índice de un color dado en el enum NotaColor /*private fun findColorIndex(color: String): Int { val notaColor = NotaColor.valueOf(color) return NotaColor.values().indexOf(notaColor) }*/ //METODO TIPO BOTON PARA Las imagenes//Efren// @Composable fun ImageSelectionButton( onImageSelected: (Uri) -> Unit ) { // Crear el launcher para la actividad de selección de imagen val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent(), onResult = { result -> if (result != null) { // Lógica para manejar la imagen seleccionada onImageSelected(result) } } ) // Botón que activa la selección de imagen desde el almacenamiento Button( onClick = { // Lanzar la actividad de selección de imagen launcher.launch("image/*") }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text(text = "Seleccionar imagen") } } @RequiresApi(Build.VERSION_CODES.O) @SuppressLint("MissingPermission") @Composable fun CurrentLocationScreen(onValuesReceived: (Double, Double, Boolean) -> Unit) { var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } val permissions = listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ) PermissionBox( permissions = permissions, requiredPermissions = listOf(permissions.first()), onGranted = { CurrentLocationContent( usePreciseLocation = it.contains(Manifest.permission.ACCESS_FINE_LOCATION), ){ value1, value2, value3 -> longitud = value1 // Actualiza el primer valor recibido en el componente padre latitud = value2 // Actualiza el segundo valor recibido en el componente padre controlmapa = value3 onValuesReceived(longitud, latitud, controlmapa) } }, ) } @RequiresApi(Build.VERSION_CODES.O) @RequiresPermission( anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION], ) @Composable fun CurrentLocationContent(usePreciseLocation: Boolean, onValuesReceived: (Double, Double, Boolean) -> Unit) { val scope = rememberCoroutineScope() val context = LocalContext.current var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } val locationClient = remember { LocationServices.getFusedLocationProviderClient(context) } var locationInfo by remember { mutableStateOf("") } Column( Modifier .fillMaxWidth() .animateContentSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { /*Button( onClick = { // getting last known location is faster and minimizes battery usage // This information may be out of date. // Location may be null as previously no client has access location // or location turned of in device setting. // Please handle for null case as well as additional check can be added before using the method scope.launch(Dispatchers.IO) { val result = locationClient.lastLocation.await() locationInfo = if (result == null) { "No last known location. Try fetching the current location first" } else { "Current location is \n" + "lat : ${result.latitude}\n" + "long : ${result.longitude}\n" + "fetched at ${System.currentTimeMillis()}" } } }, ) { Text("Get last known location") }*/ Button( onClick = { //To get more accurate or fresher device location use this method scope.launch(Dispatchers.IO) { val priority = if (usePreciseLocation) { Priority.PRIORITY_HIGH_ACCURACY } else { Priority.PRIORITY_BALANCED_POWER_ACCURACY } val result = locationClient.getCurrentLocation( priority, CancellationTokenSource().token, ).await() result?.let { fetchedLocation -> /*val milliseconds = System.currentTimeMillis() val localDate = Instant.ofEpochMilli(milliseconds) .atZone(ZoneId.systemDefault()) .toLocalDate() val formattedDate = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").format(localDate) */ locationInfo = "Localización actual es \n" + "lat : ${fetchedLocation.latitude}\n" + "long : ${fetchedLocation.longitude}\n" + "fetched at ${System.currentTimeMillis()}" longitud = fetchedLocation.longitude latitud = fetchedLocation.latitude } controlmapa = true onValuesReceived(longitud, latitud, controlmapa) } }, ) { Column { Text(text = "Get current location") } } Text( text = locationInfo+"${controlmapa}", ) //Spacer(modifier = Modifier.height(190.dp)) /*if (controlmapa){ OSMComposeMapa( longitud = longitud, latitud = (latitud) ) }*/ } } /*@Composable fun OSMComposeMapa( modifier: Modifier = Modifier.fillMaxSize(), latitud: Double, longitud: Double //viewModel: OpenRouteServiceViewModel ) { //val rutaUiState = viewModel.directUiState // define properties with remember with default value var mapProperties by remember { mutableStateOf(DefaultMapProperties) } // define marker state val depokMarkerState = rememberMarkerState( geoPoint = GeoPoint(latitud, longitud), rotation = 50f // default is 0f ) // setup mapProperties in side effect SideEffect { mapProperties = mapProperties .copy(isTilesScaledToDpi = true) .copy(tileSources = TileSourceFactory.MAPNIK) .copy(isEnableRotationGesture = true) .copy(zoomButtonVisibility = ZoomButtonVisibility.SHOW_AND_FADEOUT) } // define camera state val cameraState = rememberCameraState { geoPoint = GeoPoint(latitud, longitud) zoom = 16.0 // optional, default is 5.0 } /*viewModel.directions_get("driving-car", GeoPoint(20.139261336104898, -101.15026781862757), GeoPoint(20.142110828753893, -101.1787275290486), ) */ //Log.d("GIVO",rutaUiState.value.toString()) // define polyline var geoPointPoluLyne = remember { listOf( GeoPoint(20.1389,-101.15088), GeoPoint(20.1434,-101.1498), GeoPoint(20.14387,-101.15099), GeoPoint(20.14395,-101.15128), GeoPoint(20.14411,-101.15186) ) //rutaUiState.value.resp?.features[0].geometry.coordinates.map { GeoPoint(it[0],it[1]) } } val overlayManagerState = rememberOverlayManagerState() val ctx = LocalContext.current //Agregar nodo Mapa OpenStreetMap(cameraState = cameraState , properties = mapProperties, overlayManagerState = overlayManagerState, onFirstLoadListener = { val copyright = CopyrightOverlay(ctx) overlayManagerState.overlayManager.add(copyright) // add another overlay in this listener }, modifier = modifier.scale(.8f) ) { Marker(state = depokMarkerState, title="${latitud}", snippet = "${longitud}") { // create info window node Column( modifier = Modifier .size(100.dp) .background(color = Color.Gray, shape = RoundedCornerShape(7.dp)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // setup content of info window Text(text = it.title) Text(text = it.snippet, fontSize = 10.sp) } } //if(rutaUiState.value.resp!=null){ // geoPointPoluLyne = rutaUiState.value.resp!!.features[0].geometry.coordinates.map { GeoPoint(it[1],it[0]) } Polyline(geoPoints = geoPointPoluLyne) { } //} } } */
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/bottomsheet/EntryBottomSheet.kt
2680770122
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.bottomsheet import android.Manifest import android.annotation.SuppressLint import android.app.AlarmManager import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.SystemClock import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import androidx.annotation.RequiresPermission import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column //import androidx.compose.foundation.layout.ColumnScopeInstance.align import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect 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.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.app.NotificationCompat import com.example.juicetracker.ImagePicker import com.example.juicetracker.R import com.example.juicetracker.alarmas.AlarmSchedulerImpl import com.example.juicetracker.alarmas.AlarmasScreen /*import com.example.juicetracker.alarmas.AlarmSchedulerImpl import com.example.juicetracker.alarmas.AlarmasScreen*/ import com.example.juicetracker.contexto.contecsto import com.example.juicetracker.data.Model.Tarea import com.example.juicetracker.mapas.location.PermissionBox import com.example.juicetracker.ui.JuiceTrackerViewModel import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.CancellationTokenSource import com.utsman.osmandcompose.DefaultMapProperties import com.utsman.osmandcompose.Marker import com.utsman.osmandcompose.OpenStreetMap import com.utsman.osmandcompose.Polyline import com.utsman.osmandcompose.ZoomButtonVisibility import com.utsman.osmandcompose.rememberCameraState import com.utsman.osmandcompose.rememberMarkerState import com.utsman.osmandcompose.rememberOverlayManagerState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.overlay.CopyrightOverlay import java.time.LocalDateTime import java.util.Locale // Optando por la API ExperimentalMaterial3 @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalMaterial3Api::class) // Función componible para la interfaz de usuario de la hoja inferior @Composable fun EntryBottomSheetTarea( juiceTrackerViewModel: JuiceTrackerViewModel, sheetScaffoldState: BottomSheetScaffoldState, onCancel: () -> Unit, onSubmit: () -> Unit, modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { // Recopilando el estado actual del jugo mediante un StateFlow val tarea by juiceTrackerViewModel.currentTareaStream.collectAsState()//currentJuiceStream.collectAsState() // Construyendo el BottomSheetScaffold con encabezado, formulario y contenido personalizado BottomSheetScaffold( modifier = modifier, scaffoldState = sheetScaffoldState, sheetContent = { Column { // Sección de encabezado de la hoja inferior SheetHeaderTarea(Modifier.padding(dimensionResource(R.dimen.padding_small))) // Sección de formulario de la hoja inferior SheetFormTarea( tarea = tarea, onUpdateTarea = juiceTrackerViewModel::updateCurrentTarea, onCancel = onCancel, onSubmit = onSubmit, modifier = Modifier.padding( horizontal = dimensionResource(R.dimen.padding_medium) ) ) } } ) { // Contenido personalizado proporcionado por el llamador content() } } // Función componible para el encabezado de la hoja inferior @Composable fun SheetHeaderTarea(modifier: Modifier = Modifier) { Column(modifier = modifier) { // Texto del titular para la hoja inferior Text( modifier = Modifier.padding(dimensionResource(R.dimen.padding_small)), text = stringResource(R.string.bottom_sheet_headlineTarea), style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold) ) // Línea divisoria Divider() } } // Función componible para el contenido del formulario de la hoja inferior @RequiresApi(Build.VERSION_CODES.O) @Composable fun SheetFormTarea( tarea: Tarea, onUpdateTarea: (Tarea) -> Unit, onCancel: () -> Unit, onSubmit: () -> Unit, modifier: Modifier = Modifier ){ var secondText by remember { mutableStateOf("") } val estado by remember { mutableStateOf(contecsto.getApplicationContext()) } var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } LazyColumn( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween, //content = ) { item { // Fila de entrada para el nombre del jugo TextInputRowTarea( inputLabel = stringResource(R.string.tarea_name), fieldValue = tarea.tareaTitle, onValueChange = { titulo -> onUpdateTarea(tarea.copy(tareaTitle = titulo)) }, modifier = Modifier.fillMaxWidth(), ) } item { // Fila de entrada para la descripción del jugo TextInputRowTarea( inputLabel = stringResource(R.string.tarea_description), fieldValue = tarea.tareaBody, onValueChange = { description -> onUpdateTarea(tarea.copy(tareaBody = description)) }, modifier = Modifier.fillMaxWidth() ) } item { /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AlarmasScreen( alarmScheduler = AlarmSchedulerImpl(applicationContext)) }*/ ImagePicker() } item { CurrentLocationScreenTarea(){ value1, value2, value3 -> longitud = value1 // Actualiza el primer valor recibido en el componente padre latitud = value2 // Actualiza el segundo valor recibido en el componente padre controlmapa = value3} tarea.longitud=longitud tarea.latitud=latitud //onUpdateTarea(tarea.copy(tareaBody = description)) } item { if (controlmapa){ OSMComposeMapa( longitud = longitud, latitud = (latitud) ) } } item { alarmafinal(valor = estado) } /*item { Spacer(modifier = Modifier.height(90.dp)) }*/ item { // Fila de botones con botones de cancelar y enviar ButtonRowTarea( modifier = Modifier //.align(Alignment.End) .padding(bottom = dimensionResource(R.dimen.padding_medium)), onCancel = onCancel, onSubmit = onSubmit, submitButtonEnabled = tarea.tareaTitle.isNotEmpty() ) } } } // Función componible para una fila con botones de cancelar y enviar @Composable fun ButtonRowTarea( onCancel: () -> Unit, onSubmit: () -> Unit, submitButtonEnabled: Boolean, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { // Botón de cancelar OutlinedButton( onClick = onCancel, border = null ) { Text(stringResource(android.R.string.cancel).uppercase(Locale.getDefault())) } // Botón de enviar Button( onClick = onSubmit, ) { Text(stringResource(R.string.save).uppercase(Locale.getDefault())) } } /*Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } } Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } } Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } } Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } } Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(24.dp) ) { //ACTUA COMO UN BOTON ImageSelectionButton { selectedUri -> println("Imagen seleccionada: $selectedUri") } }*/ } // Función componible para una fila con un campo de entrada de texto @Composable fun TextInputRowTarea( inputLabel: String, fieldValue: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier ) { // Fila de entrada genérica con un campo de texto InputRowTarea(inputLabel, modifier) { TextField( modifier = Modifier.padding(bottom = dimensionResource(R.dimen.padding_small)), value = fieldValue, onValueChange = onValueChange, singleLine = true, maxLines = 1, // Personalización de los colores del campo de texto según el tema Material colors = TextFieldDefaults.colors( focusedContainerColor = colorScheme.surface, unfocusedContainerColor = colorScheme.surface, disabledContainerColor = colorScheme.surface, ), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next) ) } } // Función componible para una fila de entrada genérica con etiqueta y contenido @Composable fun InputRowTarea( inputLabel: String, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { // Fila que contiene una etiqueta y contenido Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { // Texto de la etiqueta Text( text = inputLabel, fontWeight = FontWeight.SemiBold, // La etiqueta ocupa 1/3 del espacio disponible modifier = modifier.weight(1f) ) // El contenido ocupa 2/3 del espacio disponible Box(modifier = Modifier.weight(2f)) { content() } } } //METODO TIPO BOTON PARA Las imagenes//Efren// @Composable fun ImageSelectionButtonTarea( onImageSelected: (Uri) -> Unit ) { // Crear el launcher para la actividad de selección de imagen val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent(), onResult = { result -> if (result != null) { // Lógica para manejar la imagen seleccionada onImageSelected(result) } } ) // Botón que activa la selección de imagen desde el almacenamiento Button( onClick = { // Lanzar la actividad de selección de imagen launcher.launch("image/*") }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text(text = "Seleccionar imagen") } } @RequiresApi(Build.VERSION_CODES.O) @SuppressLint("MissingPermission") @Composable fun CurrentLocationScreenTarea(onValuesReceived: (Double, Double, Boolean) -> Unit) { var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } val permissions = listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ) PermissionBox( permissions = permissions, requiredPermissions = listOf(permissions.first()), onGranted = { CurrentLocationContentTarea( usePreciseLocation = it.contains(Manifest.permission.ACCESS_FINE_LOCATION), ){ value1, value2, value3 -> longitud = value1 // Actualiza el primer valor recibido en el componente padre latitud = value2 // Actualiza el segundo valor recibido en el componente padre controlmapa = value3 onValuesReceived(longitud, latitud, controlmapa) } }, ) } @RequiresApi(Build.VERSION_CODES.O) @RequiresPermission( anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION], ) @Composable fun CurrentLocationContentTarea(usePreciseLocation: Boolean, onValuesReceived: (Double, Double, Boolean) -> Unit) { val scope = rememberCoroutineScope() val context = LocalContext.current var controlmapa by remember { mutableStateOf(false) } var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } val locationClient = remember { LocationServices.getFusedLocationProviderClient(context) } var locationInfo by remember { mutableStateOf("") } Column( Modifier .fillMaxWidth() .animateContentSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { /*Button( onClick = { // getting last known location is faster and minimizes battery usage // This information may be out of date. // Location may be null as previously no client has access location // or location turned of in device setting. // Please handle for null case as well as additional check can be added before using the method scope.launch(Dispatchers.IO) { val result = locationClient.lastLocation.await() locationInfo = if (result == null) { "No last known location. Try fetching the current location first" } else { "Current location is \n" + "lat : ${result.latitude}\n" + "long : ${result.longitude}\n" + "fetched at ${System.currentTimeMillis()}" } } }, ) { Text("Get last known location") }*/ Button( onClick = { //To get more accurate or fresher device location use this method scope.launch(Dispatchers.IO) { val priority = if (usePreciseLocation) { Priority.PRIORITY_HIGH_ACCURACY } else { Priority.PRIORITY_BALANCED_POWER_ACCURACY } val result = locationClient.getCurrentLocation( priority, CancellationTokenSource().token, ).await() result?.let { fetchedLocation -> /*val milliseconds = System.currentTimeMillis() val localDate = Instant.ofEpochMilli(milliseconds) .atZone(ZoneId.systemDefault()) .toLocalDate() val formattedDate = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").format(localDate) */ locationInfo = "Localización actual es \n" + "lat : ${fetchedLocation.latitude}\n" + "long : ${fetchedLocation.longitude}\n" + "fetched at ${System.currentTimeMillis()}" longitud = fetchedLocation.longitude latitud = fetchedLocation.latitude } controlmapa = true onValuesReceived(longitud, latitud, controlmapa) } }, ) { Column { Text(text = "Get current location") } } Text( text = locationInfo+"${controlmapa}", ) //Spacer(modifier = Modifier.height(190.dp)) /*if (controlmapa){ OSMComposeMapa( longitud = longitud, latitud = (latitud) ) }*/ } } @Composable fun OSMComposeMapa( modifier: Modifier = Modifier.fillMaxSize(), latitud: Double, longitud: Double //viewModel: OpenRouteServiceViewModel ) { //val rutaUiState = viewModel.directUiState // define properties with remember with default value var mapProperties by remember { mutableStateOf(DefaultMapProperties) } // define marker state val depokMarkerState = rememberMarkerState( geoPoint = GeoPoint(latitud, longitud), rotation = 50f // default is 0f ) // setup mapProperties in side effect SideEffect { mapProperties = mapProperties .copy(isTilesScaledToDpi = true) .copy(tileSources = TileSourceFactory.MAPNIK) .copy(isEnableRotationGesture = true) .copy(zoomButtonVisibility = ZoomButtonVisibility.SHOW_AND_FADEOUT) } // define camera state val cameraState = rememberCameraState { geoPoint = GeoPoint(latitud, longitud) zoom = 16.0 // optional, default is 5.0 } /*viewModel.directions_get("driving-car", GeoPoint(20.139261336104898, -101.15026781862757), GeoPoint(20.142110828753893, -101.1787275290486), ) */ //Log.d("GIVO",rutaUiState.value.toString()) // define polyline var geoPointPoluLyne = remember { listOf( GeoPoint(20.1389,-101.15088), GeoPoint(20.1434,-101.1498), GeoPoint(20.14387,-101.15099), GeoPoint(20.14395,-101.15128), GeoPoint(20.14411,-101.15186) ) //rutaUiState.value.resp?.features[0].geometry.coordinates.map { GeoPoint(it[0],it[1]) } } val overlayManagerState = rememberOverlayManagerState() val ctx = LocalContext.current //Agregar nodo Mapa OpenStreetMap(cameraState = cameraState , properties = mapProperties, overlayManagerState = overlayManagerState, onFirstLoadListener = { val copyright = CopyrightOverlay(ctx) overlayManagerState.overlayManager.add(copyright) // add another overlay in this listener }, modifier = modifier.scale(.8f) ) { Marker(state = depokMarkerState, title="${latitud}", snippet = "${longitud}") { // create info window node Column( modifier = Modifier .size(100.dp) .background(color = Color.Gray, shape = RoundedCornerShape(7.dp)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // setup content of info window Text(text = it.title) Text(text = it.snippet, fontSize = 10.sp) } } //if(rutaUiState.value.resp!=null){ // geoPointPoluLyne = rutaUiState.value.resp!!.features[0].geometry.coordinates.map { GeoPoint(it[1],it[0]) } Polyline(geoPoints = geoPointPoluLyne) { } //} } } @Composable fun alarmafinal(valor: Context) { val estado = valor if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AlarmasScreen( alarmScheduler = AlarmSchedulerImpl(estado) ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/bottomsheet/EntryBottomSheetTarea.kt
2506745981
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui.bottomsheet import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.viewinterop.AndroidView import com.example.juicetracker.R import com.example.juicetracker.data.Model.JuiceColor /** * Adapter Class implementation for Color Spinner */ class SpinnerAdapter(val onColorChange: (Int) -> Unit) : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { onColorChange(position) } override fun onNothingSelected(parent: AdapterView<*>?) { onColorChange(0) } } /** * Composable which includes a spinner which is rendered through AndroidView * using Spinner view component */ @Composable fun ColorSpinnerRow( colorSpinnerPosition: Int, onColorChange: (Int) -> Unit, modifier: Modifier = Modifier ) { val juiceColorArray = JuiceColor.values().map { juiceColor -> stringResource(juiceColor.label) } InputRow(inputLabel = stringResource(R.string.color), modifier = modifier) { AndroidView( modifier = Modifier.fillMaxWidth(), factory = { context -> Spinner(context).apply { adapter = ArrayAdapter( context, android.R.layout.simple_spinner_dropdown_item, juiceColorArray ) } }, update = { spinner -> spinner.setSelection(colorSpinnerPosition) spinner.onItemSelectedListener = SpinnerAdapter(onColorChange) } ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/bottomsheet/ColorSpinnerRow.kt
1248259687
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.ui import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.SheetValue import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState 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.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import com.example.juicetracker.alarmas.AlarmSchedulerImpl import com.example.juicetracker.alarmas.AlarmasScreen //import com.example.juicetracker.alarmas.AlarmasScreen import com.example.juicetracker.contexto.contecsto import com.example.juicetracker.ui.bottomsheet.EntryBottomSheet import com.example.juicetracker.ui.bottomsheet.EntryBottomSheetTarea import com.example.juicetracker.ui.homescreen.JuiceTrackerFAB import com.example.juicetracker.ui.homescreen.JuiceTrackerList import com.example.juicetracker.ui.homescreen.JuiceTrackerTopAppBar import com.example.juicetracker.ui.homescreen.TareaTrackerFAB import com.example.juicetracker.ui.homescreen.NotaTrackerList import kotlinx.coroutines.launch @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalMaterial3Api::class) @Composable fun JuiceTrackerApp( juiceTrackerViewModel: JuiceTrackerViewModel = viewModel(factory = AppViewModelProvider.Factory) ) { val estado by remember { mutableStateOf(contecsto.getApplicationContext()) } var controlSheet by remember { mutableStateOf(true) } val bottomSheetScaffoldState = rememberBottomSheetScaffoldState( bottomSheetState = rememberStandardBottomSheetState( initialValue = SheetValue.Hidden, skipHiddenState = false, ) ) val bottomSheetScaffoldStateTarea = rememberBottomSheetScaffoldState( bottomSheetState = rememberStandardBottomSheetState( initialValue = SheetValue.Hidden, skipHiddenState = false, ) ) val scope = rememberCoroutineScope() val trackerState by juiceTrackerViewModel.juiceListStream.collectAsState(emptyList()) val trackerStateNota by juiceTrackerViewModel.notaListStream.collectAsState(emptyList()) val scopeTarea = rememberCoroutineScope() val trackerStateTarea by juiceTrackerViewModel.tareaListStream.collectAsState(emptyList()) if (controlSheet){ EntryBottomSheetTarea( juiceTrackerViewModel = juiceTrackerViewModel, sheetScaffoldState = bottomSheetScaffoldStateTarea, modifier = Modifier, onCancel = { scopeTarea.launch { bottomSheetScaffoldStateTarea.bottomSheetState.hide() } }, onSubmit = { juiceTrackerViewModel.saveNota() scopeTarea.launch { bottomSheetScaffoldStateTarea.bottomSheetState.hide() } } ) { Scaffold( topBar = { JuiceTrackerTopAppBar() }, floatingActionButton = { Column { JuiceTrackerFAB( onClick = { juiceTrackerViewModel.resetCurrentNota() scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } controlSheet = true } ) TareaTrackerFAB( onClick = { juiceTrackerViewModel.resetCurrentTarea() scopeTarea.launch { bottomSheetScaffoldStateTarea.bottomSheetState.expand()} controlSheet = false } ) } } ) { contentPadding -> Column(Modifier.padding(contentPadding)) { /*AdBanner( Modifier .fillMaxWidth() .padding( top = dimensionResource(R.dimen.padding_medium), bottom = dimensionResource(R.dimen.padding_small) ) )*/ NotaTrackerList( notas = trackerStateNota, onDelete = { nota -> juiceTrackerViewModel.deleteNota(nota) }, onUpdate = { nota -> juiceTrackerViewModel.updateCurrentNota(nota) scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } }, ) } } } } else{ EntryBottomSheet( juiceTrackerViewModel = juiceTrackerViewModel, sheetScaffoldState = bottomSheetScaffoldState, modifier = Modifier, onCancel = { scope.launch { bottomSheetScaffoldState.bottomSheetState.hide() } }, onSubmit = { juiceTrackerViewModel.saveNota() scope.launch { bottomSheetScaffoldState.bottomSheetState.hide() } } ) { Scaffold( topBar = { JuiceTrackerTopAppBar() }, floatingActionButton = { Column { JuiceTrackerFAB( onClick = { juiceTrackerViewModel.resetCurrentNota() scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } controlSheet = true } ) TareaTrackerFAB( onClick = { juiceTrackerViewModel.resetCurrentTarea() scopeTarea.launch { bottomSheetScaffoldStateTarea.bottomSheetState.expand()} controlSheet = false } ) } } ) { contentPadding -> Column(Modifier.padding(contentPadding)) { /*AdBanner( Modifier .fillMaxWidth() .padding( top = dimensionResource(R.dimen.padding_medium), bottom = dimensionResource(R.dimen.padding_small) ) )*/ JuiceTrackerList( juices = trackerState, onDelete = { juice -> juiceTrackerViewModel.deleteJuice(juice) }, onUpdate = { juice -> juiceTrackerViewModel.updateCurrentJuice(juice) scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } }, ) NotaTrackerList( notas = trackerStateNota, onDelete = { nota -> juiceTrackerViewModel.deleteNota(nota) }, onUpdate = { nota -> juiceTrackerViewModel.updateCurrentNota(nota) scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } }, ) } } } } /*val applicationContext=contecsto.getApplicationContext() AlarmasScreen(alarmScheduler = AlarmSchedulerImpl(applicationContext))*/ }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/ui/JuiceTrackerApp.kt
1891297586
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.example.juicetracker.ui.JuiceTrackerApp import com.example.juicetracker.ui.theme.JuiceTrackerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JuiceTrackerTheme { JuiceTrackerApp() } } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/MainActivity.kt
2405820781
package com.example.juicetracker.contexto import android.app.Application import android.content.Context object contecsto{ private lateinit var appContext: Context fun initialize(application: Application) { appContext = application.applicationContext } fun getApplicationContext(): Context { return appContext } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/contexto/contecsto.kt
2728372087
package com.example.juicetracker.providers import android.content.Context import android.net.Uri import androidx.core.content.FileProvider import com.example.juicetracker.R import java.io.File class ComposeFileProvider : FileProvider( R.xml.filepaths ){ companion object { fun getImageUri(context: Context): Uri { // 1 val directory = File(context.cacheDir, "images") directory.mkdirs() // 2 val file = File.createTempFile( "selected_image_", ".jpg", directory ) // 3 val authority = context.packageName + ".fileprovider" // 4 return getUriForFile( context, authority, file, ) } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/providers/ComposeFileProvider.kt
3663283384
package com.example.juicetracker import android.Manifest import android.content.Context import android.media.MediaPlayer import android.media.MediaRecorder import android.os.Build import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.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.material.icons.Icons import androidx.compose.material.icons.outlined.CheckCircle import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.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.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import java.io.File import java.io.FileOutputStream @OptIn(ExperimentalPermissionsApi::class) @Composable fun GrabarAudioScreen( onClickStGra: () -> Unit, onClickSpGra: () -> Unit, onClickStRe: () -> Unit, onClickSpRe: () -> Unit,){ val context = LocalContext.current val recordAudioPermissionState = rememberPermissionState( Manifest.permission.RECORD_AUDIO ) //Realiza un seguimiento del estado del diálogo de justificación, necesario cuando el usuario requiere más justificación var rationaleState by remember { mutableStateOf<RationaleState?>(null) } /*val fineLocationPermissionState = rememberMultiplePermissionsState( listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ), )*/ Box( Modifier .fillMaxSize() .padding(16.dp), ) { Column( modifier = Modifier .fillMaxWidth() .animateContentSize(), verticalArrangement = Arrangement.spacedBy(16.dp), ) { // Show rationale dialog when needed rationaleState?.run { PermissionRationaleDialog(rationaleState = this) } PermissionRequestButton( isGranted = recordAudioPermissionState.status.isGranted, title = stringResource(R.string.record_audio), onClickStGra, onClickSpGra, onClickStRe, onClickStRe ) { if (recordAudioPermissionState.status.shouldShowRationale) { rationaleState = RationaleState( "Permiso para grabar audio", "In order to use this feature please grant access by accepting " + "the grabar audio dialog." + "\n\nWould you like to continue?", ) { proceed -> if (proceed) { recordAudioPermissionState.launchPermissionRequest() } rationaleState = null } } else { recordAudioPermissionState.launchPermissionRequest() } } } } } @Composable fun PermissionRequestButton(isGranted: Boolean, title: String, onClickStGra: () -> Unit, onClickSpGra: () -> Unit, onClickStRe: () -> Unit, onClickSpRe: () -> Unit, onClick: () -> Unit) { if (isGranted) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon(Icons.Outlined.CheckCircle, title, modifier = Modifier.size(48.dp)) Spacer(Modifier.size(10.dp)) Text(text = title, modifier = Modifier.background(Color.Transparent)) Spacer(Modifier.size(10.dp)) } Column { Button(onClick = onClickStGra) { Text("Iniciar Grabar") } Button(onClick = onClickSpGra) { Text("Parar Grabar") } Button(onClick = onClickStRe) { Text("Iniciar reproducri") } Button(onClick = onClickSpRe) { Text("Parar reproducir") } } } else { Button(onClick = onClick) { Text("Request $title") } } } /** * Simple AlertDialog that displays the given rational state * Cuadro de dialogo simple que muestra el estado del rational */ @Composable fun PermissionRationaleDialog(rationaleState: RationaleState) { AlertDialog(onDismissRequest = { rationaleState.onRationaleReply(false) }, title = { Text(text = rationaleState.title) }, text = { Text(text = rationaleState.rationale) }, confirmButton = { TextButton(onClick = { rationaleState.onRationaleReply(true) }) { Text("Continue") } }, dismissButton = { TextButton(onClick = { rationaleState.onRationaleReply(false) }) { Text("Dismiss") } }) } data class RationaleState( val title: String, val rationale: String, val onRationaleReply: (proceed: Boolean) -> Unit, ) interface AudioRecorder { fun start(outputFile: File) fun stop() } class AndroidAudioRecorder( private val context: Context ): AudioRecorder { private var recorder: MediaRecorder? = null private fun createRecorder(): MediaRecorder { return if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { MediaRecorder(context) } else MediaRecorder() } override fun start(outputFile: File) { createRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) setAudioEncoder(MediaRecorder.AudioEncoder.AAC) setOutputFile(FileOutputStream(outputFile).fd) prepare() start() recorder = this } } override fun stop() { recorder?.stop() recorder?.reset() recorder = null } } class AndroidAudioPlayer( private val context: Context ): AudioRecorder { private var player: MediaPlayer? = null override fun start(outputFile: File) { MediaPlayer.create(context, outputFile.toUri()).apply { player = this start() } } override fun stop() { player?.stop() player?.release() player = null } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/MiAudio.kt
950048873
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import com.example.juicetracker.contexto.contecsto import com.example.juicetracker.data.AppContainer import com.example.juicetracker.data.AppDataContainer class JuiceTrackerApplication : Application() { /** * AppContainer instance used by the rest of classes to obtain dependencies */ lateinit var container: AppContainer override fun onCreate() { super.onCreate() contecsto.initialize(this) container = AppDataContainer(this) val channelId = "alarm_id" val channelName = "alarm_name" val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel( channelId, channelName, NotificationManager.IMPORTANCE_HIGH ) } else { TODO("VERSION.SDK_INT < O") } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.createNotificationChannel(channel) } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/JuiceTrackerApplication.kt
2056217942
package com.example.juicetracker import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton 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.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import coil.compose.AsyncImage import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.ui.PlayerView import com.example.juicetracker.providers.ComposeFileProvider @Composable fun ImagePicker( modifier: Modifier = Modifier, ) { // 1 var hasImage by remember { mutableStateOf(false) } var hasVideo by remember { mutableStateOf(false) } // 2 var imageUri by remember { mutableStateOf<Uri?>(null) } val imagePicker = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent(), onResult = { uri -> // TODO // 3 hasImage = uri != null imageUri = uri } ) val cameraLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicture(), onResult = { success -> hasImage = success } ) val videoLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.CaptureVideo(), onResult = { success -> hasVideo = success } ) val context = LocalContext.current Box( modifier = modifier, contentAlignment = Alignment.Center ) { // 4 /*if ((hasImage or hasVideo) && imageUri != null) { // 5 if(hasImage){ AsyncImage( model = imageUri, modifier = Modifier .fillMaxWidth(1f/2f) .padding(all = 15.dp), contentDescription = "Selected image", ) } if(hasVideo) { VideoPlayer(videoUri = imageUri!!, modifier = Modifier.padding(all = 15.dp) ) } } */ Spacer(modifier = Modifier.padding(all = 15.dp)) Column( modifier = Modifier .align(Alignment.BottomCenter) .padding(bottom = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Row { Column ( modifier = Modifier .weight(1f/3f) .padding(start = 15.dp) ){ Button( modifier = Modifier .padding(top = 16.dp), onClick = { imagePicker.launch("image/*") }, ) { Icon( painter = painterResource(R.drawable.galeria), contentDescription = "Seleccionar imagen", ) } } Column (modifier = Modifier.weight(1f/3f) ){ Button( modifier = Modifier .padding(top = 16.dp, start = 8.dp, end = 8.dp), onClick = { val uri = ComposeFileProvider.getImageUri(context) imageUri = uri cameraLauncher.launch(uri) }, ) { Icon( painter = painterResource(R.drawable.camara), contentDescription = "Tomar foto", ) } } Column ( modifier = Modifier .weight(1f/3f) ){ Button( modifier = Modifier.padding(top = 16.dp, start = 8.dp), onClick = { val uri = ComposeFileProvider.getImageUri(context) imageUri = uri videoLauncher.launch(uri) }, ) { Icon( painter = painterResource(R.drawable.video), contentDescription = "Tomar video", ) } } } } } } @Composable fun VideoPlayer(videoUri: Uri, modifier: Modifier = Modifier.fillMaxWidth()) { val context = LocalContext.current val exoPlayer = remember { SimpleExoPlayer.Builder(context).build().apply { setMediaItem(MediaItem.fromUri(videoUri)) prepare() } } val playbackState = exoPlayer val isPlaying = playbackState?.isPlaying ?: false AndroidView( factory = { context -> PlayerView(context).apply { player = exoPlayer } }, modifier = modifier ) IconButton( onClick = { if (isPlaying) { exoPlayer.pause() } else { exoPlayer.play() } }, modifier = Modifier //.align(Alignment.BottomEnd) .padding(16.dp) ) { Icon( imageVector = if (isPlaying) Icons.Filled.Refresh else Icons.Filled.PlayArrow, contentDescription = if (isPlaying) "Pause" else "Play", tint = Color.White, modifier = Modifier.size(48.dp) ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/TakePhotoVideo.kt
970033083
package com.example.juicetracker.alarmas import android.app.AlarmManager import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import android.os.SystemClock import android.util.Log 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.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField 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.unit.dp import androidx.core.app.NotificationCompat import com.example.juicetracker.R import java.time.LocalDateTime @OptIn(ExperimentalMaterial3Api::class) @Composable fun AlarmasScreen( alarmScheduler: AlarmScheduler){ var secondText by remember { mutableStateOf("") } var messageText by remember { mutableStateOf("") } var alarmItem : AlarmItem? = null Column( modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { OutlinedTextField(value = secondText, onValueChange = { secondText = it }, label = { Text(text = "Delay Second") } ) Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField(value = messageText, onValueChange = { messageText = it }, label = { Text(text = "Message") } ) Spacer(modifier = Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Button(onClick = { /*alarmItem = AlarmItem( alarmTime = LocalDateTime.now().plusSeconds( secondText.toLong() ), message = messageText )*/ alarmItem = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AlarmItem( LocalDateTime.now().plusSeconds(secondText.toLong()), "El mensaje" ) } else { TODO("VERSION.SDK_INT < O") } alarmItem?.let(alarmScheduler::schedule) secondText = "" messageText = "" }) { Text(text = "Schedule") } Spacer(modifier = Modifier.width(8.dp)) Button(onClick = { alarmItem?.let(alarmScheduler::cancel) }) { Text(text = "Cancel") } Spacer(modifier = Modifier.width(8.dp)) } } } class AlarmReceiverPerro : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val message = intent?.getStringExtra("EXTRA_MESSAGE") ?: return val channelId = "alarm_id" context?.let { ctx -> val notificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val builder = NotificationCompat.Builder(ctx, channelId) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle("Alarm Demo") .setContentText("Notification sent with message $message") .setPriority(NotificationCompat.PRIORITY_HIGH) notificationManager.notify(1, builder.build()) } } } data class AlarmItem( val alarmTime : LocalDateTime, val message : String ) interface AlarmScheduler { fun schedule(alarmItem: AlarmItem) fun cancel(alarmItem: AlarmItem) } class AlarmSchedulerImpl( private val context: Context ) : AlarmScheduler { private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager //private val alarmManager = context.getSystemService(AlarmManager::class.java) as AlarmManager override fun schedule(alarmItem: AlarmItem) { val intent = Intent(context, AlarmReceiverPerro::class.java).apply { putExtra("EXTRA_MESSAGE", alarmItem.message) } alarmManager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+10000, PendingIntent.getBroadcast( context, alarmItem.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) Log.e("Alarm", "Alarm set at ") } override fun cancel(alarmItem: AlarmItem) { alarmManager.cancel( PendingIntent.getBroadcast( context, alarmItem.hashCode(), Intent(context, AlarmReceiverPerro::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/alarmas/AlarmReceiverPerro.kt
3217930335
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.mapas.location import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box 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.material.icons.Icons import androidx.compose.material.icons.outlined.CheckCircle import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.MultiplePermissionsState import com.google.accompanist.permissions.PermissionState import com.google.accompanist.permissions.rememberMultiplePermissionsState /** * Simple screen that manages the location permission state */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun LocationPermissions(text: String, rationale: String, locationState: PermissionState) { LocationPermissions( text = text, rationale = rationale, locationState = rememberMultiplePermissionsState( permissions = listOf( locationState.permission ) ) ) } /** * Simple screen that manages the location permission state */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun LocationPermissions(text: String, rationale: String, locationState: MultiplePermissionsState) { var showRationale by remember(locationState) { mutableStateOf(false) } if (showRationale) { PermissionRationaleDialog(rationaleState = RationaleState( title = "Location Permission Access", rationale = rationale, onRationaleReply = { proceed -> if (proceed) { locationState.launchMultiplePermissionRequest() } showRationale = false } )) } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { PermissionRequestButton(isGranted = false, title = text) { if (locationState.shouldShowRationale) { showRationale = true } else { locationState.launchMultiplePermissionRequest() } } } } /** * A button that shows the title or the request permission action. */ @Composable fun PermissionRequestButton(isGranted: Boolean, title: String, onClick: () -> Unit) { if (isGranted) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon(Icons.Outlined.CheckCircle, title, modifier = Modifier.size(48.dp)) Spacer(Modifier.size(10.dp)) Text(text = title, modifier = Modifier.background(Color.Transparent)) } } else { Button(onClick = onClick) { Text("Request $title") } } } /** * Simple AlertDialog that displays the given rational state * Cuadro de dialogo simple que muestra el estado del rational */ @Composable fun PermissionRationaleDialog(rationaleState: RationaleState) { AlertDialog(onDismissRequest = { rationaleState.onRationaleReply(false) }, title = { Text(text = rationaleState.title) }, text = { Text(text = rationaleState.rationale) }, confirmButton = { TextButton(onClick = { rationaleState.onRationaleReply(true) }) { Text("Continue") } }, dismissButton = { TextButton(onClick = { rationaleState.onRationaleReply(false) }) { Text("Dismiss") } }) } data class RationaleState( val title: String, val rationale: String, val onRationaleReply: (proceed: Boolean) -> Unit, )
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/location/LocationPermissions.kt
207513356
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.mapas.location import android.Manifest import android.annotation.SuppressLint import android.os.Looper import androidx.annotation.RequiresPermission import androidx.compose.animation.animateContentSize import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import java.util.concurrent.TimeUnit @SuppressLint("MissingPermission") @Composable fun LocationUpdatesScreen() { val permissions = listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ) // Requires at least coarse permission PermissionBox( permissions = permissions, requiredPermissions = listOf(permissions.first()), ) { LocationUpdatesContent( usePreciseLocation = it.contains(Manifest.permission.ACCESS_FINE_LOCATION), ) } } @RequiresPermission( anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION], ) @Composable fun LocationUpdatesContent(usePreciseLocation: Boolean) { // The location request that defines the location updates var locationRequest by remember { mutableStateOf<LocationRequest?>(null) } // Keeps track of received location updates as text var locationUpdates by remember { mutableStateOf("") } // Only register the location updates effect when we have a request if (locationRequest != null) { LocationUpdatesEffect(locationRequest!!) { result -> // For each result update the text for (currentLocation in result.locations) { locationUpdates = "${System.currentTimeMillis()}:\n" + "- @lat: ${currentLocation.latitude}\n" + "- @lng: ${currentLocation.longitude}\n" + "- Accuracy: ${currentLocation.accuracy}\n\n" + locationUpdates } } } LazyColumn( modifier = Modifier .fillMaxWidth() .animateContentSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { item { // Toggle to start and stop location updates // before asking for periodic location updates, // it's good practice to fetch the current location // or get the last known location Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "Enable location updates") Spacer(modifier = Modifier.padding(8.dp)) Switch( checked = locationRequest != null, onCheckedChange = { checked -> locationRequest = if (checked) { // Define the accuracy based on your needs and granted permissions val priority = if (usePreciseLocation) { Priority.PRIORITY_HIGH_ACCURACY } else { Priority.PRIORITY_BALANCED_POWER_ACCURACY } LocationRequest.Builder(priority, TimeUnit.SECONDS.toMillis(3)).build() } else { null } }, ) } } item { Text(text = locationUpdates) } } } /** * An effect that request location updates based on the provided request and ensures that the * updates are added and removed whenever the composable enters or exists the composition. */ @RequiresPermission( anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION], ) @Composable fun LocationUpdatesEffect( locationRequest: LocationRequest, lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, onUpdate: (result: LocationResult) -> Unit, ) { val context = LocalContext.current val currentOnUpdate by rememberUpdatedState(newValue = onUpdate) // Whenever on of these parameters changes, dispose and restart the effect. DisposableEffect(locationRequest, lifecycleOwner) { val locationClient = LocationServices.getFusedLocationProviderClient(context) val locationCallback: LocationCallback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { currentOnUpdate(result) } } val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_START) { locationClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper(), ) } else if (event == Lifecycle.Event.ON_STOP) { locationClient.removeLocationUpdates(locationCallback) } } // Add the observer to the lifecycle lifecycleOwner.lifecycle.addObserver(observer) // When the effect leaves the Composition, remove the observer onDispose { locationClient.removeLocationUpdates(locationCallback) lifecycleOwner.lifecycle.removeObserver(observer) } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/location/LocationUpdatesScreen.kt
255894945
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.mapas.location import android.Manifest import android.content.Intent import android.os.Build import android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS import android.widget.Toast import androidx.annotation.RequiresApi import androidx.compose.animation.animateContentSize import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon 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.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import com.example.juicetracker.R @RequiresApi(Build.VERSION_CODES.Q) @OptIn(ExperimentalPermissionsApi::class) @Composable fun LocationPermissionScreen() { val context = LocalContext.current // Approximate location access is sufficient for most of use cases val locationPermissionState = rememberPermissionState( Manifest.permission.ACCESS_COARSE_LOCATION, ) // When precision is important request both permissions but make sure to handle the case where // the user only grants ACCESS_COARSE_LOCATION val fineLocationPermissionState = rememberMultiplePermissionsState( listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ), ) // In really rare use cases, accessing background location might be needed. val bgLocationPermissionState = rememberPermissionState( Manifest.permission.ACCESS_BACKGROUND_LOCATION, ) // Keeps track of the rationale dialog state, needed when the user requires further rationale //Realiza un seguimiento del estado del diálogo de justificación, necesario cuando el usuario requiere más justificación var rationaleState by remember { mutableStateOf<RationaleState?>(null) } Box( Modifier .fillMaxSize() .padding(16.dp), ) { Column( modifier = Modifier .fillMaxWidth() .animateContentSize(), verticalArrangement = Arrangement.spacedBy(16.dp), ) { // Show rationale dialog when needed rationaleState?.run { PermissionRationaleDialog(rationaleState = this) } PermissionRequestButton( isGranted = locationPermissionState.status.isGranted, title = stringResource(R.string.approximate_location_access), ) { if (locationPermissionState.status.shouldShowRationale) { rationaleState = RationaleState( "Request approximate location access", "In order to use this feature please grant access by accepting " + "the location permission dialog." + "\n\nWould you like to continue?", ) { proceed -> if (proceed) { locationPermissionState.launchPermissionRequest() } rationaleState = null } } else { locationPermissionState.launchPermissionRequest() } } PermissionRequestButton( isGranted = fineLocationPermissionState.allPermissionsGranted, title = "Precise location access", ) { if (fineLocationPermissionState.shouldShowRationale) { rationaleState = RationaleState( "Request Precise Location", "In order to use this feature please grant access by accepting " + "the location permission dialog." + "\n\nWould you like to continue?", ) { proceed -> if (proceed) { fineLocationPermissionState.launchMultiplePermissionRequest() } rationaleState = null } } else { fineLocationPermissionState.launchMultiplePermissionRequest() } } // Background location permission needed from Android Q, // before Android Q, granting Fine or Coarse location access automatically grants Background // location access if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { PermissionRequestButton( isGranted = bgLocationPermissionState.status.isGranted, title = "Background location access", ) { if (locationPermissionState.status.isGranted || fineLocationPermissionState.allPermissionsGranted) { if (bgLocationPermissionState.status.shouldShowRationale) { rationaleState = RationaleState( "Request background location", "In order to use this feature please grant access by accepting " + "the background location permission dialog." + "\n\nWould you like to continue?", ) { proceed -> if (proceed) { bgLocationPermissionState.launchPermissionRequest() } rationaleState = null } } else { bgLocationPermissionState.launchPermissionRequest() } } else { Toast.makeText( context, "Please grant either Approximate location access permission or Fine" + "location access permission", Toast.LENGTH_SHORT, ).show() } } } } FloatingActionButton( modifier = Modifier.align(Alignment.BottomEnd), onClick = { context.startActivity(Intent(ACTION_LOCATION_SOURCE_SETTINGS)) }, ) { Icon(Icons.Outlined.Settings, "Location Settings") } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/location/LocationPermissionsScreen.kt
3628309845
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.mapas.location import android.Manifest import android.annotation.SuppressLint import androidx.annotation.RequiresPermission import androidx.compose.animation.animateContentSize import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button 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.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.example.juicetracker.mapas.mapasosmandroidcompose.OSMComposeMapa2 import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.CancellationTokenSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await @SuppressLint("MissingPermission") @Composable fun CurrentLocationScreen2() { val permissions = listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ) PermissionBox( permissions = permissions, requiredPermissions = listOf(permissions.first()), onGranted = { CurrentLocationContent( usePreciseLocation = it.contains(Manifest.permission.ACCESS_FINE_LOCATION), ) }, ) } @RequiresPermission( anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION], ) @Composable fun CurrentLocationContent(usePreciseLocation: Boolean) { val scope = rememberCoroutineScope() val context = LocalContext.current var controlmapa by remember { mutableStateOf(false)} var longitud by remember { mutableStateOf(0.0) } var latitud by remember { mutableStateOf(0.0) } val locationClient = remember { LocationServices.getFusedLocationProviderClient(context) } var locationInfo by remember { mutableStateOf("") } Column( Modifier .fillMaxWidth() .animateContentSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Button( onClick = { // getting last known location is faster and minimizes battery usage // This information may be out of date. // Location may be null as previously no client has access location // or location turned of in device setting. // Please handle for null case as well as additional check can be added before using the method scope.launch(Dispatchers.IO) { val result = locationClient.lastLocation.await() locationInfo = if (result == null) { "No last known location. Try fetching the current location first" } else { "Current location is \n" + "lat : ${result.latitude}\n" + "long : ${result.longitude}\n" + "fetched at ${System.currentTimeMillis()}" } } }, ) { Text("Get last known location") } Button( onClick = { //To get more accurate or fresher device location use this method scope.launch(Dispatchers.IO) { val priority = if (usePreciseLocation) { Priority.PRIORITY_HIGH_ACCURACY } else { Priority.PRIORITY_BALANCED_POWER_ACCURACY } val result = locationClient.getCurrentLocation( priority, CancellationTokenSource().token, ).await() result?.let { fetchedLocation -> locationInfo = "Current location is \n" + "lat : ${fetchedLocation.latitude}\n" + "long : ${fetchedLocation.longitude}\n" + "fetched at ${System.currentTimeMillis()}" longitud = fetchedLocation.longitude latitud = fetchedLocation.latitude } controlmapa = true } }, ) { Column { Text(text = "Get current location") } } Text( text = locationInfo+"${controlmapa}", ) Spacer(modifier = Modifier.height(90.dp)) /*if (controlmapa){ OSMComposeMapa( longitud = longitud, latitud = (latitud) ) }*/ } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/location/CurrentLocationScreen.kt
4099221793
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.mapas.location import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.compose.animation.animateContentSize import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.MultiplePermissionsState import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberMultiplePermissionsState /** * The PermissionBox uses a [Box] to show a simple permission request UI when the provided [permission] * is revoked or the provided [onGranted] content if the permission is granted. * * This composable follows the permission request flow but for a complete example check the samples * under privacy/permissions */ @Composable fun PermissionBox( modifier: Modifier = Modifier, permission: String, description: String? = null, contentAlignment: Alignment = Alignment.TopStart, onGranted: @Composable BoxScope.() -> Unit, ) { PermissionBox( modifier, permissions = listOf(permission), requiredPermissions = listOf(permission), description, contentAlignment, ) { onGranted() } } /** * A variation of [PermissionBox] that takes a list of permissions and only calls [onGranted] when * all the [requiredPermissions] are granted. * * By default it assumes that all [permissions] are required. */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun PermissionBox( modifier: Modifier = Modifier, permissions: List<String>, requiredPermissions: List<String> = permissions, description: String? = null, contentAlignment: Alignment = Alignment.TopStart, onGranted: @Composable BoxScope.(List<String>) -> Unit, ) { val context = LocalContext.current var errorText by remember { mutableStateOf("") } val permissionState = rememberMultiplePermissionsState(permissions = permissions) { map -> val rejectedPermissions = map.filterValues { !it }.keys errorText = if (rejectedPermissions.none { it in requiredPermissions }) { "" } else { "${rejectedPermissions.joinToString()} required for the ejemplo perro" } } val allRequiredPermissionsGranted = permissionState.revokedPermissions.none { it.permission in requiredPermissions } Box( modifier = Modifier .fillMaxSize() .then(modifier), contentAlignment = if (allRequiredPermissionsGranted) { contentAlignment } else { Alignment.Center }, ) { if (allRequiredPermissionsGranted) { onGranted( permissionState.permissions .filter { it.status.isGranted } .map { it.permission }, ) } else { PermissionScreen( permissionState, description, errorText, ) FloatingActionButton( modifier = Modifier .align(Alignment.BottomEnd) .padding(16.dp), onClick = { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK data = Uri.parse("package:${context.packageName}") } context.startActivity(intent) }, ) { Icon(imageVector = Icons.Rounded.Settings, contentDescription = "App settings") } } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun PermissionScreen( state: MultiplePermissionsState, description: String?, errorText: String, ) { var showRationale by remember(state) { mutableStateOf(false) } val permissions = remember(state.revokedPermissions) { state.revokedPermissions.joinToString("\n") { " - " + it.permission.removePrefix("android.permission.") } } Column( modifier = Modifier .fillMaxWidth() .animateContentSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Text( text = "ejemplooooo requires permission/s:", style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(16.dp), ) Text( text = permissions, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp), ) if (description != null) { Text( text = description, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp), ) } Button( onClick = { if (state.shouldShowRationale) { showRationale = true } else { state.launchMultiplePermissionRequest() } }, ) { Text(text = "Grant permissions") } if (errorText.isNotBlank()) { Text( text = errorText, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(16.dp), ) } } if (showRationale) { AlertDialog( onDismissRequest = { showRationale = false }, title = { Text(text = "Permissions required by the Ejemploooop") }, text = { Text(text = "El Exemplo requires the following permissions to work:\n $permissions") }, confirmButton = { TextButton( onClick = { showRationale = false state.launchMultiplePermissionRequest() }, ) { Text("Continue") } }, dismissButton = { TextButton( onClick = { showRationale = false }, ) { Text("Dismiss") } }, ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/location/PermissionBox.kt
1019785694
package com.example.juicetracker.mapas.mapasosmandroidcompose import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import com.example.juicetracker.mapas.network.OpenRouteServiceApi import com.example.juicetracker.data.Model.GeoJSONDirection import org.osmdroid.util.GeoPoint import kotlin.coroutines.coroutineContext data class DirectUIstate(var resp: GeoJSONDirection? = null) class OpenRouteServiceViewModel : ViewModel() { var directUiState : MutableState<DirectUIstate> = mutableStateOf(DirectUIstate()) init{ directions_get("driving-car", GeoPoint(20.139261336104898, -101.15026781862757), GeoPoint(20.142110828753893, -101.1787275290486), ) } fun directions_get( profile: String, start: GeoPoint, end: GeoPoint){ viewModelScope.launch(Dispatchers.IO) { val route = OpenRouteServiceApi.retrofitService.directions_get( profile = "driving-car", start = "${start.longitude},${start.latitude}", end = "${end.longitude},${end.latitude}" ) //val route = OpenRouteServiceApi.retrofitService.directions_get() directUiState.value = DirectUIstate(route) Log.d("GIVO ","") } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/mapasosmandroidcompose/OpenRouteServiceViewModel.kt
4198726816
package com.example.juicetracker.mapas.mapasosmandroidcompose 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect 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.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.utsman.osmandcompose.CameraState import com.utsman.osmandcompose.DefaultMapProperties import com.utsman.osmandcompose.Marker import com.utsman.osmandcompose.OpenStreetMap import com.utsman.osmandcompose.Polyline import com.utsman.osmandcompose.ZoomButtonVisibility import com.utsman.osmandcompose.rememberCameraState import com.utsman.osmandcompose.rememberMarkerState import com.utsman.osmandcompose.rememberOverlayManagerState import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.overlay.CopyrightOverlay @Composable fun OSMComposeMapa2( modifier: Modifier = Modifier.fillMaxSize(1f/3f), latitud: Double, longitud: Double //viewModel: OpenRouteServiceViewModel ) { //val rutaUiState = viewModel.directUiState // define properties with remember with default value var mapProperties by remember { mutableStateOf(DefaultMapProperties) } // define marker state val depokMarkerState = rememberMarkerState( geoPoint = GeoPoint(latitud, longitud), rotation = 90f // default is 0f ) // setup mapProperties in side effect SideEffect { mapProperties = mapProperties .copy(isTilesScaledToDpi = true) .copy(tileSources = TileSourceFactory.MAPNIK) .copy(isEnableRotationGesture = true) .copy(zoomButtonVisibility = ZoomButtonVisibility.SHOW_AND_FADEOUT) } // define camera state val cameraState = rememberCameraState { geoPoint = GeoPoint(latitud, longitud) zoom = 18.0 // optional, default is 5.0 } /*viewModel.directions_get("driving-car", GeoPoint(20.139261336104898, -101.15026781862757), GeoPoint(20.142110828753893, -101.1787275290486), ) */ //Log.d("GIVO",rutaUiState.value.toString()) // define polyline var geoPointPoluLyne = remember { listOf(GeoPoint(20.1389,-101.15088), GeoPoint(20.1434,-101.1498), GeoPoint(20.14387,-101.15099), GeoPoint(20.14395,-101.15128), GeoPoint(20.14411,-101.15186)) //rutaUiState.value.resp?.features[0].geometry.coordinates.map { GeoPoint(it[0],it[1]) } } val overlayManagerState = rememberOverlayManagerState() val ctx = LocalContext.current //Agregar nodo Mapa OpenStreetMap(cameraState = cameraState , properties = mapProperties, overlayManagerState = overlayManagerState, onFirstLoadListener = { val copyright = CopyrightOverlay(ctx) overlayManagerState.overlayManager.add(copyright) // add another overlay in this listener }, modifier = modifier ) { Marker(state = depokMarkerState, title="${latitud}", snippet = "${longitud}") { // create info window node Column( modifier = Modifier .size(100.dp) .background(color = Color.Gray, shape = RoundedCornerShape(7.dp)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // setup content of info window Text(text = it.title) Text(text = it.snippet, fontSize = 10.sp) } } //if(rutaUiState.value.resp!=null){ // geoPointPoluLyne = rutaUiState.value.resp!!.features[0].geometry.coordinates.map { GeoPoint(it[1],it[0]) } Polyline(geoPoints = geoPointPoluLyne) { } //} } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/mapasosmandroidcompose/MapasOSMAndroidCompose.kt
2290092423
package com.example.juicetracker.mapas.network import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import com.example.juicetracker.data.Model.GeoJSONDirection import okhttp3.MediaType.Companion.toMediaType import retrofit2.Response import retrofit2.Retrofit import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query private const val BASE_URL = "https://api.openrouteservice.org" private const val API_KEY = "6b3ce3597x51110001cf624819e6024a736b47666fe215764a8bdba7" //obtener esrkey registrandose private val retrofit = Retrofit.Builder() .addConverterFactory(Json{ isLenient = true ignoreUnknownKeys = true} .asConverterFactory("application/json".toMediaType())) .baseUrl(BASE_URL) .build() interface IOpenRouteServiceAPI { @GET("/v2/directions/{profile}") suspend fun directions_get( @Path("profile") profile: String, @Query("api_key") apikey : String = API_KEY, @Query("start") start : String , @Query("end") end : String ): GeoJSONDirection @GET("/v2/directions/driving-car?api_key=xxxxxx&start=8.681495,49.41461&end=8.687872,49.420318") suspend fun directions_get( ): GeoJSONDirection } object OpenRouteServiceApi { val retrofitService : IOpenRouteServiceAPI by lazy { retrofit.create(IOpenRouteServiceAPI::class.java) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/network/OpenRouteServiceAPI.kt
2756655104
package com.example.juicetracker.mapas.mapasgoogle import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.Marker import com.google.maps.android.compose.MarkerState import com.google.maps.android.compose.rememberCameraPositionState @Composable fun MapaComposeGoogle(){ val singapore = LatLng(1.35, 103.87) val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(singapore, 10f) } GoogleMap( modifier = Modifier.fillMaxSize(), cameraPositionState = cameraPositionState ) { Marker( state = MarkerState(position = singapore), title = "Singapore", snippet = "Marker in Singapore" ) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/mapas/mapasgoogle/MapasGoogleCompose.kt
2899532874
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data import android.content.Context import com.example.juicetracker.data.Repositorio.* import com.example.juicetracker.data.RepositorioRoom.* /** * [AppContainer] implementation that provides instance of [RoomJuiceRepository] */ class AppDataContainer(private val context: Context) : AppContainer { /** * Implementation for [JuiceRepository] */ override val juiceRepository: JuiceRepository by lazy { RoomJuiceRepository(AppDatabase.getDatabase(context).juiceDao()) } override val notaRepository: NotaRepository by lazy { RoomNotaRepository(AppDatabase.getDatabase(context).juiceDao()) } override val tareaRepository: TareaRepository by lazy { RoomTareaRepository(AppDatabase.getDatabase(context).juiceDao()) } override val multimediaRepository: MultimediaRepository by lazy { RoomMultimediaRepository(AppDatabase.getDatabase(context).multimediaDao()) } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/AppDataContainer.kt
2036630186
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.RepositorioRoom import com.example.juicetracker.data.Model.Nota import com.example.juicetracker.data.JuiceDao import com.example.juicetracker.data.Repositorio.NotaRepository import kotlinx.coroutines.flow.Flow /** * Implementation of [NotaRepository] interface * which allow access and modification of Juice items through [JuiceDao] */ class RoomNotaRepository(private val notaDao: JuiceDao) : NotaRepository { override val notaStream: Flow<List<Nota>> = notaDao.getAllNota() override suspend fun addNota(nota: Nota) = notaDao.insertNota(nota) override suspend fun deleteNota(nota: Nota) = notaDao.deleteNota(nota) override suspend fun updateNota(nota: Nota) = notaDao.updateNota(nota) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/RepositorioRoom/RoomNotaRepository.kt
2147520873
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.RepositorioRoom import com.example.juicetracker.data.Model.Multimedia import com.example.juicetracker.data.MultimediaDao import com.example.juicetracker.data.Repositorio.MultimediaRepository import kotlinx.coroutines.flow.Flow /** * Implementation of [MultimediaRepository] interface * which allow access and modification of Juice items through [MultimediaDao] */ class RoomMultimediaRepository(private val multimediaDao: MultimediaDao) : MultimediaRepository { override val multimediaStream: Flow<List<Multimedia>> = multimediaDao.getMultimedia(idNota = 1) override suspend fun addMultimedia(multimedia: Multimedia): Unit = multimediaDao.insertMultimedia(multimedia) override suspend fun deleteMultimedia(multimedia: Multimedia) = multimediaDao.deleteMultimedia(multimedia) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/RepositorioRoom/RoomMultimediaRepository.kt
1597510821
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.RepositorioRoom import com.example.juicetracker.data.Model.Juice import com.example.juicetracker.data.JuiceDao import com.example.juicetracker.data.Repositorio.JuiceRepository import kotlinx.coroutines.flow.Flow /** * Implementation of [JuiceRepository] interface * which allow access and modification of Juice items through [JuiceDao] */ class RoomJuiceRepository(private val juiceDao: JuiceDao) : JuiceRepository { override val juiceStream: Flow<List<Juice>> = juiceDao.getAll() override suspend fun addJuice(juice: Juice) = juiceDao.insert(juice) override suspend fun deleteJuice(juice: Juice) = juiceDao.delete(juice) override suspend fun updateJuice(juice: Juice) = juiceDao.update(juice) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/RepositorioRoom/RoomJuiceRepository.kt
1930850011
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.RepositorioRoom import com.example.juicetracker.data.Model.Tarea import com.example.juicetracker.data.JuiceDao import com.example.juicetracker.data.Repositorio.TareaRepository import kotlinx.coroutines.flow.Flow /** * Implementation of [TareaRepository] interface * which allow access and modification of Juice items through [JuiceDao] */ class RoomTareaRepository(private val tareaDao: JuiceDao) : TareaRepository { override val tareaStream: Flow<List<Tarea>> = tareaDao.getAllTarea() override suspend fun addTarea(tarea: Tarea) = tareaDao.insertTarea(tarea) override suspend fun deleteTarea(tarea: Tarea) = tareaDao.deleteTarea(tarea) override suspend fun updateTarea(tarea: Tarea) = tareaDao.updateTarea(tarea) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/RepositorioRoom/RoomTareaRepository.kt
1669779240
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.Repositorio import com.example.juicetracker.data.Model.Multimedia import kotlinx.coroutines.flow.Flow /** * Interface for [MultimediaRepository] which contains method to access and modify juice items */ interface MultimediaRepository { val multimediaStream: Flow<List<Multimedia>> suspend fun addMultimedia(multimedia: Multimedia) suspend fun deleteMultimedia(multimedia: Multimedia) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Repositorio/MultimediaRepository.kt
1983939875
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.Repositorio import com.example.juicetracker.data.Model.Juice import kotlinx.coroutines.flow.Flow /** * Interface for [JuiceRepository] which contains method to access and modify juice items */ interface JuiceRepository { val juiceStream: Flow<List<Juice>> suspend fun addJuice(juice: Juice) suspend fun deleteJuice(juice: Juice) suspend fun updateJuice(juice: Juice) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Repositorio/JuiceRepository.kt
3870389428
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.Repositorio import com.example.juicetracker.data.Model.Tarea import kotlinx.coroutines.flow.Flow /** * Interface for [TareaRepository] which contains method to access and modify juice items */ interface TareaRepository { val tareaStream: Flow<List<Tarea>> suspend fun addTarea(tarea: Tarea) suspend fun deleteTarea(tarea: Tarea) suspend fun updateTarea(tarea: Tarea) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Repositorio/TareaRepository.kt
3234998535
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.Repositorio import com.example.juicetracker.data.Model.Nota import kotlinx.coroutines.flow.Flow /** * Interface for [NotaRepository] which contains method to access and modify nota items */ interface NotaRepository { val notaStream: Flow<List<Nota>> suspend fun addNota(nota: Nota) suspend fun deleteNota(nota: Nota) suspend fun updateNota(nota: Nota) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Repositorio/NotaRepository.kt
4259271026
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.juicetracker.data.Model.* @Database(entities = [Juice::class, Nota::class, Tarea::class, Multimedia::class], version = 4) abstract class AppDatabase: RoomDatabase() { abstract fun juiceDao(): JuiceDao abstract fun multimediaDao(): MultimediaDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { Room.databaseBuilder( context, AppDatabase::class.java, "app_database" ) // Setting this option in your app's database builder means that Room // permanently deletes all data from the tables in your database when it // attempts to perform a migration with no defined migration path. .fallbackToDestructiveMigration() .build() .also { INSTANCE = it } } } } }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/AppDatabase.kt
3267407445
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data.Model import androidx.annotation.StringRes import androidx.compose.ui.graphics.Color import androidx.room.Entity import androidx.room.PrimaryKey import com.example.juicetracker.R import com.example.juicetracker.ui.theme.Orange as OrangeColor /** * Represents a single table in the database * * Note that the color type is different than in the Main branch. * Please remove app and re-install if existing app from the Main branch exist * to avoid database error */ @Entity(tableName = "juice") data class Juice( @PrimaryKey(autoGenerate = true) val id: Long, val name: String, val description: String = "", val color: String, val imageUri: String? = null, val videoUri: String? = null, val audioUri: String? = null, val i: Int, ) @Entity(tableName = "nota") data class Nota( @PrimaryKey(autoGenerate = true) val id: Int, val noteTitle: String, val noteBody: String, val notetvDate: String, val multimedia: String? ) @Entity(tableName = "tarea") data class Tarea( @PrimaryKey(autoGenerate = true) val id: Int, val tareaTitle: String, val tareaBody: String, val estatus: Int, val tareatvDate: String, var latitud: Double, var longitud: Double, val tareaDateFinal: String ) enum class JuiceColor(val color: Color, @StringRes val label: Int) { Red(Color.Red, R.string.red), Blue(Color.Blue, R.string.blue), Green(Color.Green, R.string.green), Cyan(Color.Cyan, R.string.cyan), Yellow(Color.Yellow, R.string.yellow), Magenta(Color.Magenta, R.string.magenta), Orange(OrangeColor, R.string.orange) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Model/Juice.kt
2395901303
package com.example.juicetracker.data.Model import androidx.room.Entity import androidx.room.PrimaryKey @Entity class Multimediab ( @PrimaryKey(autoGenerate = true) val id: Int, val idNote: Int, val type: String, val path: String, val description: String ) @Entity class Multimedia ( @PrimaryKey(autoGenerate = true) val id: Int, val uri: String, val tipo: Int?, val idNota: Int?, val idTarea: Int?, val descripcion: String?, val ruta: String? )
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Model/Multimedia.kt
1319398635
package com.example.juicetracker.data.Model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Serializer @Serializable data class Geometry (val coordinates : List<List<Double>>) @Serializable data class Feature(val geometry : Geometry) @Serializable data class GeoJSONDirection( val type: String, val features: List<Feature> )
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/Model/GeoJSONDirections.kt
2513781270
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update import com.example.juicetracker.data.Model.* import kotlinx.coroutines.flow.Flow /** * Juice Data Access Object which contains methods to access and modify Juice table in Room DB */ @Dao interface JuiceDao { @Query("SELECT * FROM juice") fun getAll(): Flow<List<Juice>> @Insert suspend fun insert(juice: Juice) @Delete suspend fun delete(juice: Juice) @Update suspend fun update(juice: Juice) @Query("SELECT * FROM nota") fun getAllNota(): Flow<List<Nota>> @Insert suspend fun insertNota(nota: Nota) @Delete suspend fun deleteNota(nota: Nota) @Update suspend fun updateNota(nota: Nota) @Query("SELECT * FROM tarea") fun getAllTarea(): Flow<List<Tarea>> @Insert suspend fun insertTarea(tarea: Tarea) @Delete suspend fun deleteTarea(tarea: Tarea) @Update suspend fun updateTarea(tarea: Tarea) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/JuiceDao.kt
1992140825
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.juicetracker.data import com.example.juicetracker.data.Repositorio.* /** * App container for Dependency injection. */ interface AppContainer { val juiceRepository: JuiceRepository val notaRepository: NotaRepository val tareaRepository: TareaRepository val multimediaRepository: MultimediaRepository }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/AppContainer.kt
1189847072
package com.example.juicetracker.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.example.juicetracker.data.Model.Multimedia import kotlinx.coroutines.flow.Flow @Dao interface MultimediaDao { @Insert fun insertMultimedia(multimedia: Multimedia)//: Long @Query("SELECT * FROM multimedia WHERE idNota=:idNota") fun getMultimedia(idNota: Int): Flow<List<Multimedia>> @Delete fun deleteMultimedia(multimedia: Multimedia) }
Movil_II_Notas/app/src/main/java/com/example/juicetracker/data/MultimediaDao.kt
25657499
package com.main.myfirstapp 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.main.myfirstapp", appContext.packageName) } }
MyFirstAppCardPresentation/app/src/androidTest/java/com/main/myfirstapp/ExampleInstrumentedTest.kt
2514095818
package com.main.myfirstapp 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) } }
MyFirstAppCardPresentation/app/src/test/java/com/main/myfirstapp/ExampleUnitTest.kt
2026436075
package com.main.myfirstapp.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)
MyFirstAppCardPresentation/app/src/main/java/com/main/myfirstapp/ui/theme/Color.kt
240953421
package com.main.myfirstapp.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 MyFirstAppTheme( 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 ) }
MyFirstAppCardPresentation/app/src/main/java/com/main/myfirstapp/ui/theme/Theme.kt
133795217
package com.main.myfirstapp.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 ) */ )
MyFirstAppCardPresentation/app/src/main/java/com/main/myfirstapp/ui/theme/Type.kt
893688698
package com.main.myfirstapp import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.ClickableText import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.MailOutline import androidx.compose.material.icons.materialIcon import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.main.myfirstapp.ui.theme.MyFirstAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyFirstAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Ricardo J Moo Vargas") } } } } } @Composable fun Greeting(fullName: String, modifier: Modifier = Modifier) { // add background Column(modifier = modifier .padding(20.dp) .size(300.dp, 500.dp)) { // First section Image( painter = painterResource(id = R.drawable.my_photo), contentDescription = stringResource(id = R.string.my_photo), modifier = Modifier .clip(CircleShape) .align(Alignment.CenterHorizontally) ) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterHorizontally)) { Text( text = "$fullName", modifier = Modifier.padding(8.dp), fontSize = 24.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold ) } Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterHorizontally)) { Text( text = "Desarrollador de Software", modifier = Modifier.padding(8.dp), ) } Spacer(modifier = Modifier.height(30.dp)) // Add some spacing between the sections // Second section Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterHorizontally)) { Icon( Icons.Filled.MailOutline, contentDescription = "User Icon", modifier = Modifier .padding(8.dp) .size(30.dp) ) // Add the icon here Text("[email protected]") } Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterHorizontally)) { Icon( Icons.Filled.Call, contentDescription = "User Icon", modifier = Modifier .padding(8.dp) .size(30.dp) ) // Add the icon here Text("+52 981 593 7333") } Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterHorizontally)) { Icon( painter = painterResource(id = R.drawable.github_mark), contentDescription = "User Icon", modifier = Modifier .padding(8.dp) .size(30.dp) ) // Add the icon here val annotatedText = AnnotatedString(text = "Follow me on Github", spanStyle = SpanStyle(color = Color.Blue)) ClickableText(text = annotatedText, onClick = { offset -> val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/your_username")) }) } // Button section val count = remember { mutableStateOf(0) } val context = LocalContext.current Button(onClick = { count.value++ Toast.makeText(context, "Button clicked ${count.value} times!", Toast.LENGTH_SHORT).show() }, modifier = Modifier.align(Alignment.CenterHorizontally)) { // Center the button horizontally Text("Contact me!") } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyFirstAppTheme { Greeting("Ricardo J Moo Vargas") } }
MyFirstAppCardPresentation/app/src/main/java/com/main/myfirstapp/MainActivity.kt
414572602
package id.ac.pnm.ti2a.diceroller import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("id.ac.pnm.ti2a.diceroller", appContext.packageName) } }
DiceRoller28/app/src/androidTest/java/id/ac/pnm/ti2a/diceroller/ExampleInstrumentedTest.kt
1120422898
package id.ac.pnm.ti2a.diceroller import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
DiceRoller28/app/src/test/java/id/ac/pnm/ti2a/diceroller/ExampleUnitTest.kt
3050141137
package id.ac.pnm.ti2a.diceroller.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
DiceRoller28/app/src/main/java/id/ac/pnm/ti2a/diceroller/ui/theme/Color.kt
3324554018
package id.ac.pnm.ti2a.diceroller.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun DiceRollerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
DiceRoller28/app/src/main/java/id/ac/pnm/ti2a/diceroller/ui/theme/Theme.kt
3834090772
package id.ac.pnm.ti2a.diceroller.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
DiceRoller28/app/src/main/java/id/ac/pnm/ti2a/diceroller/ui/theme/Type.kt
1343438899
package id.ac.pnm.ti2a.diceroller import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import id.ac.pnm.ti2a.diceroller.ui.theme.DiceRollerTheme import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.Spacer import androidx.compose.ui.unit.dp import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.ui.Alignment import androidx.compose.foundation.layout.wrapContentSize class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DiceRollerTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { DiceRollerApp() } } } } } @Preview @Composable fun DiceRollerApp() { DiceWithButtonAndImage(modifier = Modifier .fillMaxSize() .wrapContentSize(Alignment.Center) ) } @Composable fun DiceWithButtonAndImage(modifier: Modifier = Modifier) { var result by remember { mutableStateOf(1) } val imageResource = when (result) { 1 -> R.drawable.dice_1 2 -> R.drawable.dice_2 3 -> R.drawable.dice_3 4 -> R.drawable.dice_4 5 -> R.drawable.dice_5 else -> R.drawable.dice_6 } Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { Image(painter = painterResource(imageResource), contentDescription = result.toString()) Button( onClick = { result = (1..6).random() }, ) { Text(text = stringResource(R.string.roll), fontSize = 24.sp) } } }
DiceRoller28/app/src/main/java/id/ac/pnm/ti2a/diceroller/MainActivity.kt
2000198406
package com.suples import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate import android.os.Bundle; class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "suples" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(null) }
suples/android/app/src/main/java/com/suples/MainActivity.kt
2911553239
package com.suples import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.flipper.ReactNativeFlipper import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List<ReactPackage> = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(this.applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, false) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager) } }
suples/android/app/src/main/java/com/suples/MainApplication.kt
2031986977
package com.example.pruebaapp 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.pruebaapp", appContext.packageName) } }
perfil_Confiapp/app/src/androidTest/java/com/example/pruebaapp/ExampleInstrumentedTest.kt
4257090192