content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.exceptions.logManager import android.content.Context import android.content.Intent import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import java.io.File import java.util.Calendar class ExceptionLogManager(context: Context) { private val baseExceptionHandler: Thread.UncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() as Thread.UncaughtExceptionHandler private lateinit var lastException: Pair<Thread?, Throwable?> data class ExceptionData( val thread: String? = null, val throwable: String? = null, val timestamp: Long? = null, ) var enabled = false var isShowLog = true private val gson = Gson() private val listType = object : TypeToken<List<ExceptionData>>() {}.type private val calendar = Calendar.getInstance() private val countDay = 7 private val dayInMilliseconds = 86400000L private val fileManager = FileManager(context) private val currentFileName get() = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis.toString() + ".json" companion object { private val _exceptionHandler: MutableStateFlow<ExceptionData?> = MutableStateFlow(null) val exceptionHandler: StateFlow<ExceptionData?> get() = _exceptionHandler.asStateFlow() const val CUSTOM_INTENT_ACTION = "exceptions.logManager" const val EXCEPTION_KEY = "exceptionKey" } init { Thread.setDefaultUncaughtExceptionHandler { thread: Thread?, throwable: Throwable? -> throwable?.let { throwableObject -> if (enabled) { val newExceptionData = ExceptionData( thread.toString(), throwable.toString(), calendar.timeInMillis ) val listData = convertDataToList(fileManager.readFromFile(currentFileName)) listData.add(newExceptionData) val outString = gson.toJson(listData, listType) fileManager.writeToFile(outString, currentFileName) lastException = Pair(thread, throwable) if (isShowLog) { val intent = Intent(CUSTOM_INTENT_ACTION).apply { putExtra(EXCEPTION_KEY, throwableObject.toString()) } context.sendBroadcast(intent) _exceptionHandler.value = newExceptionData } else { throwLastExceptionToDefaultHandler() } } } } fileManager.getFileListFromDirectory().forEach { currentFile -> if (currentFile.toLong() / dayInMilliseconds > countDay) { fileManager.deleteLocalFile(currentFileName) } } } private fun throwLastExceptionToDefaultHandler() { if ((lastException.first != null) and (lastException.second != null)) baseExceptionHandler.uncaughtException(lastException.first!!, lastException.second!!) } private fun convertDataToList(dataString: String?): MutableList<ExceptionData> { val list = mutableListOf<ExceptionData>() if (!dataString.isNullOrEmpty()) { list.addAll(gson.fromJson(dataString, listType)) } return list } }
ExceptionManager/app/src/main/java/com/example/exceptions/logManager/ExceptionLogManager.kt
1063062214
package com.example.exceptions import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.exceptions.databinding.FragmentSecondBinding /** * A simple [Fragment] subclass as the second destination in the navigation. */ class SecondFragment : Fragment() { private var _binding: FragmentSecondBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSecondBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonSecond.setOnClickListener { findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
ExceptionManager/app/src/main/java/com/example/exceptions/SecondFragment.kt
4079404807
package com.example.lily02 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.lily02", appContext.packageName) } }
carnation/lily02/src/androidTest/java/com/example/lily02/ExampleInstrumentedTest.kt
1984201175
package com.example.lily02 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) } }
carnation/lily02/src/test/java/com/example/lily02/ExampleUnitTest.kt
430510847
package com.example.lily02.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)
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Color.kt
4116153557
package com.example.lily02.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 CarnationTheme( 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 ) }
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Theme.kt
4073700100
package com.example.lily02.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 ) */ )
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Type.kt
3773931958
package com.example.lily02 import androidx.lifecycle.viewmodel.compose.viewModel import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.absolutePadding 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.lazy.items import androidx.compose.foundation.magnifier import androidx.compose.material3.Button import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.Checkbox import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.lily02.data.Task import com.example.lily02.model.TodoListViewModel import com.example.lily02.ui.theme.CarnationTheme import androidx.compose.runtime.livedata.observeAsState class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme // TodoApp() TodoAppViewModel() } } } } val dummyTasks = mutableListOf( Task(id = 1, title = "买菜"), Task(id = 2, title = "做饭"), Task(id = 3, title = "洗衣服") ) @Composable fun TodoListScreen( tasks: List<Task>, onTaskCheckedChange: (Int, Boolean) -> Unit, delete: (Int) -> Unit ) { LazyColumn { items(tasks) { task -> TaskItem(task = task, onTaskCheckedChange = onTaskCheckedChange, delete) } } } @Composable fun TaskItem(task: Task, onTaskCheckedChange: (Int, Boolean) -> Unit, delete: (Int) -> Unit) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp) ) { Checkbox( checked = task.completed, onCheckedChange = { isChecked -> onTaskCheckedChange(task.id, isChecked) } ) Text( text = task.title, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(start = 8.dp) ) Button(onClick = { delete(task.id) }, modifier = Modifier.absolutePadding(left = 50.dp)) { Text(text = "删除") } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "MutableCollectionMutableState") @OptIn(ExperimentalMaterial3Api::class) @Composable fun TodoApp() { // remember 只会记住重组后的 但不会帮助您在配置更改后保持状态 //rememberSaveable 置更改后保持状态(横竖屏的切换) //mutableStateListOf不能被委托的原因委托属性需要实现 getValue() 和 setValue() 方法。 // 而 mutableStateListOf<Task>() 本身并没有实现这两个方法,因此无法作为委托属性使用。 // val todosList = rememberSaveable { mutableStateListOf<Task>() } var tasks by remember { mutableStateOf(dummyTasks) } var newTodo by remember { mutableStateOf("") } Scaffold( content = { Column { CenterAlignedTopAppBar(title = { Text(text = "TodoList") }) Spacer(modifier = Modifier.height(10.dp)) TodoListScreen(tasks = tasks, { taskId, isChecked -> tasks = tasks.map { task -> if (task.id == taskId) { task.copy(completed = isChecked) } else { task } }.toMutableList() }, { taskId -> tasks = tasks.filter { it.id != taskId }.toMutableList() }) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { tasks += Task(id = tasks.size + 1, title = newTodo) } ) { Text(text = "添加") } } } } ) } @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "MutableCollectionMutableState") @Composable fun TodoListWithAddDelete() { var todos by remember { mutableStateOf(mutableListOf("Todo 1", "Todo 2")) } var newTodo by remember { mutableStateOf("") } Column( modifier = Modifier.padding(16.dp) ) { // 添加新的待办事项 Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { if (newTodo.isNotBlank()) { todos.add(newTodo) newTodo = "" } } ) { Text(text = "添加") } } Spacer(modifier = Modifier.height(16.dp)) // 显示当前的待办事项列表 Column { todos.forEach { todo -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { Text(text = todo, modifier = Modifier.weight(1f)) Button(onClick = { todos.remove(todo) }) { Text(text = "删除") } } } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun TodoAppViewModel(viewModel: TodoListViewModel = TodoListViewModel()) { val tasks by viewModel.tasks.observeAsState(viewModel.dummyTaskModels) var newTodo by remember { mutableStateOf("") } Scaffold( content = { Column { CenterAlignedTopAppBar(title = { Text(text = "TodoList") }) Spacer(modifier = Modifier.height(10.dp)) TodoListScreen( tasks = tasks, onTaskCheckedChange = { taskId, isChecked -> viewModel.updateTask(taskId, isChecked) }, delete = { taskId -> viewModel.deleteTask(taskId) } ) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { viewModel.addTask(newTodo) newTodo = "" } ) { Text(text = "添加") } } } } ) }
carnation/lily02/src/main/java/com/example/lily02/MainActivity.kt
3190870531
package com.example.lily02.model import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.lily02.data.Task class TodoListViewModel : ViewModel() { val dummyTaskModels = mutableListOf( Task(id = 1, title = "买菜"), Task(id = 2, title = "做饭"), Task(id = 3, title = "洗衣服") ) //task为变实时数据 private val _tasks = MutableLiveData<MutableList<Task>>().apply { value = dummyTaskModels.toMutableList() } val tasks: LiveData<MutableList<Task>> = _tasks fun updateTask(taskId: Int, isChecked: Boolean) { val updatedTasks = _tasks.value?.map { task -> if (task.id == taskId) { task.copy(completed = isChecked) } else { task } }?.toMutableList() _tasks.value = updatedTasks } fun deleteTask(taskId: Int) { val updatedTasks = _tasks.value?.filter { it.id != taskId }?.toMutableList() _tasks.value = updatedTasks } fun addTask(title: String) { val newTask = Task(id = (_tasks.value?.size ?: 0) + 1, title = title) _tasks.value = _tasks.value?.plus(newTask)?.toMutableList() } }
carnation/lily02/src/main/java/com/example/lily02/model/TodoListViewModel.kt
2052243229
package com.example.lily02.data data class Task(val id: Int, val title: String, var completed: Boolean = false)
carnation/lily02/src/main/java/com/example/lily02/data/Task.kt
3417034745
package com.example.lily03 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.lily03", appContext.packageName) } }
carnation/lily03/src/androidTest/java/com/example/lily03/ExampleInstrumentedTest.kt
2759303565
package com.example.lily03 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) } }
carnation/lily03/src/test/java/com/example/lily03/ExampleUnitTest.kt
3828562345
package com.example.lily03.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)
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Color.kt
4180651164
package com.example.lily03.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 CarnationTheme( 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 ) }
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Theme.kt
4011659504
package com.example.lily03.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 ) */ )
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Type.kt
914601358
package com.example.lily03 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.lily03.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Column { Text( text = "Hello $name!", modifier = modifier ) Image( painter = painterResource(id = R.drawable.local_image), contentDescription = "Local Image" ) AsyncImage( model = "https://marketplace.canva.cn/NsFNI/MADwRLNsFNI/1/screen_2x/canva-blue-textured-background-MADwRLNsFNI.jpg", contentDescription = "Translated description of what the image contains" ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/lily03/src/main/java/com/example/lily03/MainActivity.kt
3236888909
package com.example.carnation 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.carnation", appContext.packageName) } }
carnation/app/src/androidTest/java/com/example/carnation/ExampleInstrumentedTest.kt
3693745205
package com.example.carnation 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) } }
carnation/app/src/test/java/com/example/carnation/ExampleUnitTest.kt
1596470850
package com.example.carnation.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)
carnation/app/src/main/java/com/example/carnation/ui/theme/Color.kt
2753908392
package com.example.carnation.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 CarnationTheme( 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 ) }
carnation/app/src/main/java/com/example/carnation/ui/theme/Theme.kt
1766391820
package com.example.carnation.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 ) */ )
carnation/app/src/main/java/com/example/carnation/ui/theme/Type.kt
1944784460
package com.example.carnation import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.carnation.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") ArtistCard() } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun ArtistCard() { Column{ Text("Alfred Sisley") Text("3 minutes ago") WithConstraintsComposable() FlowRowSimpleUsageExample() } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun FlowRowSimpleUsageExample() { FlowRow( modifier = Modifier.padding(8.dp) , horizontalArrangement = Arrangement.SpaceAround ) { Text("3 minutes ago") Text("3 minutes ago") Text("3 minutes ago") Box(modifier = Modifier.padding(8.dp).height(200.dp).background(color = Color.Blue)){ Text("3 minutes ago") } } } @Composable fun WithConstraintsComposable() { BoxWithConstraints { Text("My minHeight is $minHeight while my maxWidth is $maxWidth") } } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/app/src/main/java/com/example/carnation/MainActivity.kt
3261108219
package com.example.lily 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.lily", appContext.packageName) } }
carnation/lily/src/androidTest/java/com/example/lily/ExampleInstrumentedTest.kt
2850923828
package com.example.lily 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) } }
carnation/lily/src/test/java/com/example/lily/ExampleUnitTest.kt
2686021068
package com.example.lily.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)
carnation/lily/src/main/java/com/example/lily/ui/theme/Color.kt
736339034
package com.example.lily.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 CarnationTheme( 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 ) }
carnation/lily/src/main/java/com/example/lily/ui/theme/Theme.kt
1969905346
package com.example.lily.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 ) */ )
carnation/lily/src/main/java/com/example/lily/ui/theme/Type.kt
1401923170
package com.example.lily import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.Person import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.Scaffold import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.vector.ImageVector import com.example.lily.ui.theme.CarnationTheme /////底部导航栏的实现 // class MainActivity3 : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme BottomNavigationExample() } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun BottomNavigationExample() { // 创建底部导航栏的状态 var selectedIndex by remember { mutableIntStateOf(0) } // 创建底部导航栏的项目 val items = listOf( NavItem.Home, NavItem.Profile, NavItem.Settings ) Scaffold( bottomBar = { NavigationBar() { items.forEachIndexed { index, item -> NavigationBarItem( icon = { Icon(imageVector = item.icon, contentDescription = null) }, label = { Text(text = item.title) }, selected = selectedIndex == index, onClick = { selectedIndex = index } ) } } } ) { // 根据选中的索引显示不同的页面内容 when (selectedIndex) { 0 -> TabContent(text = "Tab 1 Content") 1 -> TabContent(text = "Tab 2 Content") 2 -> TabContent(text = "Tab 3 Content") } } } @Composable fun TabContent(text: String) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = text) } } // 底部导航 sealed class NavItem(var route: String, var icon: ImageVector, var title: String) { object Home : NavItem("home", Icons.Rounded.Home, "Home") object Profile : NavItem("profile", Icons.Rounded.Person, "Profile") object Settings : NavItem("settings", Icons.Rounded.Settings, "Settings") }
carnation/lily/src/main/java/com/example/lily/MainActivity3.kt
905388834
package com.example.lily import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.findNavController import com.example.lily.ui.theme.CarnationTheme import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { Greeting("你好,世界") } } } override fun onResume() { super.onResume() delayAndNavigate() } //直线任务kotlin的协程 private fun delayAndNavigate() { CoroutineScope(Dispatchers.Main).launch { delay(3000L) // 延时 3 秒,单位为毫秒 startActivityToNewScreen() // 调用跳转方法 } } private fun startActivityToNewScreen() { val intent = Intent(this, MainActivity3::class.java) startActivity(intent) } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = name, modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/lily/src/main/java/com/example/lily/MainActivity.kt
3283292938
package com.example.lily import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.lily.ui.theme.CarnationTheme class MainActivity2 : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { NavGraph() } } } } @Composable fun NavGraph() { val navController = rememberNavController() NavHost( navController = navController, startDestination = "home" ) { composable("home") { HomeScreen(navController = navController) } composable("details") { DetailsScreen() } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailsScreen() { // Scaffold (topBar ={ AppBar()}){ // // } Column(modifier = Modifier.fillMaxWidth()) { Text(text = "详情页") } } @Composable fun AppBar() { Text(text = "详情页") } @Composable fun HomeScreen(navController: NavHostController) { Column(modifier = Modifier.fillMaxWidth()) { Text(text = "主页") Button(onClick = { navController.navigate("details") }) { Text(text = "跳转去详情页") } } }
carnation/lily/src/main/java/com/example/lily/MainActivity2.kt
3739084797
package com.example.lily01 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.lily01", appContext.packageName) } }
carnation/lily01/src/androidTest/java/com/example/lily01/ExampleInstrumentedTest.kt
3680561016
package com.example.lily01 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) } }
carnation/lily01/src/test/java/com/example/lily01/ExampleUnitTest.kt
3296094532
package com.example.lily01.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)
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Color.kt
3789552654
package com.example.lily01.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 CarnationTheme( 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 ) }
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Theme.kt
3568846616
package com.example.lily01.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 ) */ )
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Type.kt
1092000703
package com.example.lily01 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.lily01.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { Column( modifier = Modifier.fillMaxSize() ) { ItemExample("屏幕显示") { Item1() } ItemExample("简单布局") { Item2() } ItemExample("简单控件") { Item3() } ItemExample("图形基础") { Item4() } ItemExample("计算器") {Item5() } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } } @Composable fun ItemExample(name: String, child: @Composable () -> Unit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Box(modifier= Modifier.height(10.dp)) Text(text = name, textAlign = TextAlign.Center) Box(modifier= Modifier.height(10.dp)) child() } } @Composable fun Item1() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "文本视图") GotoButton({}, "文字大小") GotoButton({}, "文字颜色") } } } @Composable fun Item2() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "视图宽高") GotoButton({}, "空白间隔") GotoButton({}, "对齐方式") } } } @Composable fun Item3() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "线性布局(方向)") GotoButton({}, "线性布局(权重)") GotoButton({}, "按钮点击") } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "英文大小写") GotoButton({}, "按钮点击") GotoButton({}, "按钮长按") } } } @Composable fun Item4() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "图像拉伸") GotoButton({}, "图像按钮") GotoButton({}, "图文混排") } } } @Composable fun Item5() { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { GotoButton({}, "简单计算器") } } @Composable fun GotoButton(onClick: () -> Unit, name: String) { Button(onClick = onClick) { Text(text = name ) } }
carnation/lily01/src/main/java/com/example/lily01/MainActivity.kt
3023500572
package com.application.fitlife 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.application.fitlife", appContext.packageName) } }
FitLife/app/src/androidTest/java/com/application/fitlife/ExampleInstrumentedTest.kt
1866289734
package com.application.fitlife 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) } }
FitLife/app/src/test/java/com/application/fitlife/ExampleUnitTest.kt
3943972416
package com.application.fitlife class GraphSampleDataGenerator { fun dailyScoresArrayData(): IntArray { return intArrayOf(84,87,85,88,99,96,75,88,87,95,92,81,97,76,96,97,80,100,77,77,79,91,96,78,76,98,82,98,83) } fun heartRatesArrayData(): IntArray { return intArrayOf(72,67,78,66,66, 78, 78, 61, 67, 62, 76, 71, 76, 69, 61, 60, 62, 78, 79, 78, 72, 70, 70, 72, 60, 71, 79, 78, 70) } fun respiratoryRatesArrayData(): IntArray { return intArrayOf(13,18,17,18,17,14,13,12,17,17,13,12,13,15,17,14,14,14,12,12,13,18,15,15,16,12,12,15,16) } fun userWeightArrayData(): IntArray { return intArrayOf(90,90,90,90,90,90,90,90,89,89,89,89,88,88,88,88,88,87,87,87,87,87,86,86,86,85,85,85,85) } fun createAndPopulateArray(): IntArray { // Step 1: Define an array to store integers val intArray = IntArray(5) // You can change the size as needed // Step 2: Write a loop to push a new value into the array for (i in intArray.indices) { // You can replace the logic here to get the value you want to push val newValue = i * 2 intArray[i] = newValue } // Step 3: Return the populated array return intArray } }
FitLife/app/src/main/java/com/application/fitlife/GraphSampleDataGenerator.kt
227613478
package com.application.fitlife import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.app.Activity import android.content.ContentValues import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Color import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.media.MediaMetadataRetriever import android.net.Uri import android.os.AsyncTask import android.os.Handler import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.application.fitlife.data.MyDatabaseHelper import java.util.* import kotlin.math.abs import kotlin.math.pow import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter class MainActivity : AppCompatActivity() { // defining the UI elements private lateinit var heartRateText: TextView private lateinit var userAge: EditText private lateinit var userWeight: EditText private lateinit var userHeight: EditText // maintaining a unique ID to acts a primary key reference for the database table. // for this project we are using the current date as the primary key as we are interested in only maintaining one row per day. // so any new data coming into the table for the current date which is already present in the table, then the code logic would only update the table instead of inserting a new row. private lateinit var sharedPreferences: SharedPreferences // camera implementation pre requisites val CAMERA_ACTIVITY_REQUEST_CODE = 1 // Define a request code (any integer) private val eventHandler = Handler() // respiratory rate accelerometer pre-requisites private val dataCollectionIntervalMillis = 100 // Sampling interval in milliseconds private val accelValuesX = ArrayList<Float>() private val accelValuesY = ArrayList<Float>() private val accelValuesZ = ArrayList<Float>() private var isMeasuringRespiratoryRate = false private val measurementDuration = 45000L // 45 seconds private val slowTask = SlowTask() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // sharedPreferences is something similar to the localStorage and sessionStorage we get in JavaScript sharedPreferences = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE) // generating a new unique ID val uniqueId = generateUniqueId() // Store the unique ID in SharedPreferences val editor = sharedPreferences.edit() editor.putString(getString(R.string.unique_id), uniqueId) editor.apply() // accessing the heart Rate UI element and setting the TextView to be disabled so that the user cannot edit it. heartRateText = findViewById<TextView>(R.id.heartRateText) heartRateText.text = "0" heartRateText.isEnabled = false // accessing the respiratory Rate UI element and setting the TextView to be disabled so that the user cannot edit it. val respiratoryRateText = findViewById<TextView>(R.id.respiratoryRateText) respiratoryRateText.isEnabled = false // accessing the user age, weight and height metric fields. userAge = findViewById(R.id.editTextAge) userHeight = findViewById(R.id.editTextHeight) userWeight = findViewById(R.id.editTextWeight) val userAgeValue = userAge.text.toString() val userHeightValue = userHeight.text.toString() val userWeightValue = userWeight.text.toString() Log.d("userMetricValues", "age = $userAgeValue ; height = $userHeightValue ; weight = $userWeightValue"); // making sure that the text view components that is: app title and the tag line for the app title are disabled so that the user cannot edit it. val tagLinePartViewTwo: TextView = findViewById(R.id.tagLinePart2) tagLinePartViewTwo.isEnabled = false val appTitleView: TextView = findViewById(R.id.appTitle) appTitleView.isEnabled = false // Measure heart rate button val measureHeartRateButton = findViewById<Button>(R.id.heartRate) measureHeartRateButton.setOnClickListener { val intent = Intent(this@MainActivity, CameraActivity::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivityForResult(intent, CAMERA_ACTIVITY_REQUEST_CODE) } // Respiratory rate calculation val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) val sensorListener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent?) { // Handle accelerometer data here if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) { val x = event.values[0] val y = event.values[1] val z = event.values[2] accelValuesX.add(x) accelValuesY.add(y) accelValuesZ.add(z) } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // Handle accuracy changes if needed } } val measureRespiratoryRate = findViewById<Button>(R.id.respiratoryRate) measureRespiratoryRate.setOnClickListener { Toast.makeText(baseContext, "Started measuring respiratory rate", Toast.LENGTH_SHORT).show() if (!isMeasuringRespiratoryRate) { isMeasuringRespiratoryRate = true accelValuesX.clear() accelValuesY.clear() accelValuesZ.clear() sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) eventHandler.postDelayed({ sensorManager.unregisterListener(sensorListener) val respiratoryRate = calculateRespiratoryRate() respiratoryRateText.text = respiratoryRate.toString() Toast.makeText(baseContext, "Respiratory rate calculation completed :" + respiratoryRate.toString(), Toast.LENGTH_SHORT).show() isMeasuringRespiratoryRate = false }, measurementDuration) } } val dbHelper = MyDatabaseHelper(this) val recordMetricsButton = findViewById<Button>(R.id.recordMetrics) recordMetricsButton.setOnClickListener { val userAgeValueRecordedOnButtonClick = userAge.text.toString() val userHeightValueRecordedOnButtonClick = userHeight.text.toString() val userWeightValueRecordedOnButtonClick = userWeight.text.toString() Log.d("recordMetricsButtonuserMetricValues", "age = $userAgeValueRecordedOnButtonClick ; height = $userHeightValueRecordedOnButtonClick ; weight = $userWeightValueRecordedOnButtonClick"); insertOrUpdateDatabaseEntry(dbHelper, uniqueId, heartRateText.text.toString(), respiratoryRateText.text.toString(), userAgeValueRecordedOnButtonClick, userWeightValueRecordedOnButtonClick, userHeightValueRecordedOnButtonClick) Toast.makeText(baseContext, "Uploaded Metrics to database", Toast.LENGTH_SHORT).show() } val recentAnalyticsButton = findViewById<Button>(R.id.recentAnalytics) recentAnalyticsButton.setOnClickListener { val intent = Intent(this@MainActivity, GraphsAndAnalyticsActivity::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivity(intent) } val startExerciseButton = findViewById<Button>(R.id.startExercise) startExerciseButton.setOnClickListener { val intent = Intent(this@MainActivity, ShowExercise::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivity(intent) } } fun insertOrUpdateDatabaseEntry(dbHelper: MyDatabaseHelper, uniqueDate: String, heart_rate: String, respiratory_rate: String, age: String, weight: String, height: String) { val db = dbHelper.writableDatabase // Check if the entry with the given vitals_id exists val generatedUniqueDateFromFunction = generateUniqueDate() Log.d("generatedUniqueDateFromFunction", generatedUniqueDateFromFunction) val cursor = db.rawQuery("SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(generatedUniqueDateFromFunction)) val values = ContentValues() if (heart_rate == "") { values.put("heart_rate", "72") } else { values.put("heart_rate", heart_rate) } if (respiratory_rate == "") { values.put("respiratory_rate", "15") } else { values.put("respiratory_rate", respiratory_rate) } if (weight == "") { values.put("weight", "90") } else { values.put("weight", weight) } if (height == "") { values.put("height", "170") } else { values.put("height", height) } // values.put("heart_rate", heart_rate.toFloatOrNull() ?: 0.0f) // values.put("respiratory_rate", respiratory_rate.toFloatOrNull() ?: 0.0f) // values.put("weight", weight.toFloatOrNull() ?: 0.0f) // values.put("height", height.toFloatOrNull() ?: 0.0f) Log.d("insertOrUpdateDatabaseEntry", "Primary Key Date = $generatedUniqueDateFromFunction heart_rate: $heart_rate, respiratory_rate: $respiratory_rate, weight: $weight, height: $height") if (cursor.count > 0) { // Entry with the vitals_id already exists, update it db.update( MyDatabaseHelper.TABLE_NAME_USER_METRICS, values, "${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(generatedUniqueDateFromFunction) ) } else { values.put("date", generatedUniqueDateFromFunction) // Entry with the vitals_id doesn't exist, insert a new record db.insert(MyDatabaseHelper.TABLE_NAME_USER_METRICS, null, values) } cursor.close() db.close() } private fun generateUniqueId(): String { // Get current timestamp in milliseconds val timestamp = System.currentTimeMillis() // Generate a random UUID val randomUUID = UUID.randomUUID() // Combine the timestamp and randomUUID to create a unique ID return "$timestamp-${randomUUID.toString()}" } private fun generateUniqueDate(): String { val currentDate = LocalDate.now(ZoneId.systemDefault()) val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") var formattedDate = currentDate.format(formatter) formattedDate = formattedDate.toString() return formattedDate } private fun calculateRespiratoryRate():Int { var previousValue = 0f var currentValue = 0f previousValue = 10f var k = 0 println("x size : " + accelValuesX.size) println("Y size : " + accelValuesY.size) println("Z size : " + accelValuesZ.size) for (i in 11 until accelValuesX.size) { currentValue = kotlin.math.sqrt( accelValuesZ[i].toDouble().pow(2.0) + accelValuesX[i].toDouble().pow(2.0) + accelValuesY[i].toDouble() .pow(2.0) ).toFloat() if (abs(x = previousValue - currentValue) > 0.10) { k++ } previousValue=currentValue } val ret= (k/45.00) return (ret*30).toInt() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CAMERA_ACTIVITY_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { val videoUri = data?.getStringExtra("videoUri") if (videoUri != null) { Toast.makeText(baseContext, "Calculating heart rate", Toast.LENGTH_SHORT).show() val path = convertMediaUriToPath(Uri.parse(videoUri)) slowTask.execute(path) // heartRateText.text = data?.getStringExtra("heartRate") } } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(baseContext, "Video not recorded", Toast.LENGTH_SHORT).show() } } } fun convertMediaUriToPath(uri: Uri?): String { val proj = arrayOf(MediaStore.Images.Media.DATA) val cursor = contentResolver.query(uri!!, proj, null, null, null) val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() val path = cursor.getString(column_index) cursor.close() return path } inner class SlowTask : AsyncTask<String, String, String?>() { public override fun doInBackground(vararg params: String?): String? { Log.d("MainActivity", "Executing slow task in background") var m_bitmap: Bitmap? = null var retriever = MediaMetadataRetriever() var frameList = ArrayList<Bitmap>() try { retriever.setDataSource(params[0]) var duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT) var aduration = duration!!.toInt() var i = 10 while (i < aduration) { val bitmap = retriever.getFrameAtIndex(i) frameList.add(bitmap!!) i += 5 } } catch (m_e: Exception) { } finally { retriever?.release() var redBucket: Long = 0 var pixelCount: Long = 0 val a = mutableListOf<Long>() for (i in frameList) { redBucket = 0 i.width i.height for (y in 0 until i.height) { for (x in 0 until i.width) { val c: Int = i.getPixel(x, y) pixelCount++ redBucket += Color.red(c) + Color.blue(c) + Color.green(c) } } a.add(redBucket) } val b = mutableListOf<Long>() for (i in 0 until a.lastIndex - 5) { var temp = (a.elementAt(i) + a.elementAt(i + 1) + a.elementAt(i + 2) + a.elementAt(i + 3) + a.elementAt(i + 4)) / 4 b.add(temp) } var x = b.elementAt(0) var count = 0 for (i in 1 until b.lastIndex) { var p=b.elementAt(i.toInt()) if ((p-x) > 3500) { count = count + 1 } x = b.elementAt(i.toInt()) } var rate = ((count.toFloat() / 45) * 60).toInt() return (rate/2).toString() } } override fun onPostExecute(result: String?) { super.onPostExecute(result) if (result != null) { Toast.makeText(baseContext, "Heart rate calculation completed : $result", Toast.LENGTH_SHORT).show() heartRateText.text = result } } } }
FitLife/app/src/main/java/com/application/fitlife/MainActivity.kt
3682821780
package com.application.fitlife import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.ProgressBar import android.widget.Spinner import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.application.fitlife.data.MyDatabaseHelper import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.BarGraphSeries import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries import com.application.fitlife.GraphSampleDataGenerator class GraphsAndAnalyticsActivity : AppCompatActivity() { private lateinit var spinner: Spinner private lateinit var graphView: GraphView private lateinit var scoreButton: Button private lateinit var weightButton: Button private lateinit var heartRateButton: Button private lateinit var respiratoryRateButton: Button private var progressBar: ProgressBar? = null private var progressText: TextView? = null private var currentAttribute = "score" private var todaysDailyScore = 0; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_graphs_and_analytics) spinner = findViewById(R.id.spinner) graphView = findViewById(R.id.graphView) scoreButton = findViewById(R.id.scoreButton) weightButton = findViewById(R.id.weightButton) heartRateButton = findViewById(R.id.heartRateButton) respiratoryRateButton = findViewById(R.id.respiratoryRateButton) // set the id for the progressbar and progress text progressBar = findViewById(R.id.progress_bar); progressText = findViewById(R.id.progress_text); ArrayAdapter.createFromResource( this, R.array.graph_types, android.R.layout.simple_spinner_item ).also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = adapter graphView.removeAllSeries() } // by default showing the line graph for score for the past recent data defaultUpdateGraph("score") scoreButton.setOnClickListener { currentAttribute = "score" updateGraph("score") } weightButton.setOnClickListener { currentAttribute = "weight" updateGraph("weight") } heartRateButton.setOnClickListener { currentAttribute = "heart_rate" updateGraph("heart_rate") } respiratoryRateButton.setOnClickListener { currentAttribute = "respiratory_rate" updateGraph("respiratory_rate") } graphView.removeAllSeries() spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long ) { // Handle the selected item here val selectedItem = parentView?.getItemAtPosition(position).toString() // You can perform actions based on the selected item // For example, update the UI, trigger a function, etc. // Example: updateGraph(selectedItem) Log.d("dropDownSelectedItem" , selectedItem) println("dropDown Selected Item - $selectedItem") updateGraph(currentAttribute) } override fun onNothingSelected(parentView: AdapterView<*>?) { // Do nothing here } } } private fun updateGraph(metric: String) { val series = when (spinner.selectedItem.toString()) { "Line Graph" -> LineGraphSeries<DataPoint>(getDataPoints(metric)) "Bar Graph" -> BarGraphSeries<DataPoint>(getDataPoints(metric)) else -> throw IllegalArgumentException("Invalid graph type") } graphView.removeAllSeries() graphView.addSeries(series) //graphView.viewport.isXAxisBoundsManual = true graphView.viewport.setMinX(0.0) // need to update this to show case the past 10 days data so the maximum value of x should be 10. graphView.viewport.setMaxX(30.0) // Enable scrolling graphView.viewport.isScrollable = true } private fun defaultUpdateGraph(metric: String) { val series = LineGraphSeries<DataPoint>(getDataPoints(metric)) graphView.removeAllSeries() graphView.addSeries(series) //graphView.viewport.isXAxisBoundsManual = true graphView.viewport.setMinX(0.0) // need to update this to show case the past 10 days data so the maximum value of x should be 10. graphView.viewport.setMaxX(30.0) // Enable scrolling graphView.viewport.isScrollable = true } private fun getDataPoints(metric: String): Array<DataPoint> { // Replace this with your actual logic to get the data points val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase val cursor = db.rawQuery( "SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} ORDER BY ${MyDatabaseHelper.COLUMN_NAME_DATE} DESC LIMIT 30", arrayOf() ) val scoresDataArray = mutableListOf<DataPoint>() val weightDataArray = mutableListOf<DataPoint>() val heartRateDataArray = mutableListOf<DataPoint>() val respiratoryRateDataArray = mutableListOf<DataPoint>() val emptyDataArray = mutableListOf<DataPoint>() if (cursor != null && cursor.moveToFirst()) { var day = 1 do { // You can retrieve data from the cursor using column indices or column names val dateIDIndex = cursor.getColumnIndex("date") val dateValue = cursor.getString(dateIDIndex) val scoreIndex = cursor.getColumnIndex("score") val scoreValue = cursor.getDouble(scoreIndex) val heartRateIndex = cursor.getColumnIndex("heart_rate") val heartRateValue = cursor.getDouble(heartRateIndex) val respiratoryRateIndex = cursor.getColumnIndex("respiratory_rate") val respiratoryRateValue = cursor.getDouble(respiratoryRateIndex) val weightIndex = cursor.getColumnIndex("weight") val weightValue = cursor.getDouble(weightIndex) // Now you can use the retrieved data as needed // Example: Log the values Log.d("getDataPointsQueryResponse", "Primary Key Date = $dateValue Score: $scoreValue, Weight: $weightValue, Heart Rate: $heartRateValue, Respiratory Rate: $respiratoryRateValue") // update the mutable scores data array var scoreDataPoint = DataPoint(day.toDouble(), scoreValue.toDouble()) scoresDataArray.add(scoreDataPoint) // update the mutable weights data array var weightDataPoint = DataPoint(day.toDouble(), weightValue.toDouble()) weightDataArray.add(weightDataPoint) // update the mutable heart rate data array var heartRateDataPoint = DataPoint(day.toDouble(), heartRateValue.toDouble()) heartRateDataArray.add(heartRateDataPoint) // update the mutable respiratory rate data array var respiratoryRateDataPoint = DataPoint(day.toDouble(), respiratoryRateValue.toDouble()) respiratoryRateDataArray.add(respiratoryRateDataPoint) if (day == 1) { todaysDailyScore = scoreValue.toInt(); if (todaysDailyScore == 0) { progressText?.text = "00" } else { progressText?.text = "" + todaysDailyScore } progressBar?.setProgress(todaysDailyScore) Log.d("todaysDailyScore" , todaysDailyScore.toString()) } day += 1 // Continue iterating if there are more rows } while (false) } // while (cursor.moveToNext()) // val dataArray = mutableListOf<DataPoint>() // // var dataPoint = DataPoint(0.0, 1.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(1.0, 5.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(2.0, 3.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(3.0, 2.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(4.0, 6.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(5.0, 7.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(6.0, 8.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(7.0, 9.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(8.0, 10.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(9.0, 11.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(10.0, 12.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(11.0, 13.0) // dataArray.add(dataPoint) var graphSampleDataGeneratorClassObject = GraphSampleDataGenerator() // getting random data for scores val randomDailyScoresDataArray = graphSampleDataGeneratorClassObject.dailyScoresArrayData() var day = 2 for (randomScoreValue in randomDailyScoresDataArray) { var dataPoint = DataPoint(day.toDouble(), randomScoreValue.toDouble()) scoresDataArray.add(dataPoint) day += 1 } // getting random data for heart rates val randomHeartRatesDataArray = graphSampleDataGeneratorClassObject.heartRatesArrayData() day = 2 for (randomHeartRate in randomHeartRatesDataArray) { var dataPoint = DataPoint(day.toDouble(), randomHeartRate.toDouble()) heartRateDataArray.add(dataPoint) day += 1 } // getting random data for respiratory rates val randomRespiratoryRatesDataArray = graphSampleDataGeneratorClassObject.respiratoryRatesArrayData() day = 2 for (randomRespiratoryRate in randomRespiratoryRatesDataArray) { var dataPoint = DataPoint(day.toDouble(), randomRespiratoryRate.toDouble()) respiratoryRateDataArray.add(dataPoint) day += 1 } // getting random data for respiratory rates val randomWeightDataArray = graphSampleDataGeneratorClassObject.userWeightArrayData() day = 2 for (randomWeight in randomWeightDataArray) { var dataPoint = DataPoint(day.toDouble(), randomWeight.toDouble()) weightDataArray.add(dataPoint) day += 1 } if (metric == "score") { return scoresDataArray.toTypedArray() } if (metric == "weight") { return weightDataArray.toTypedArray() } if (metric == "heart_rate") { return heartRateDataArray.toTypedArray() } if (metric == "respiratory_rate") { return respiratoryRateDataArray.toTypedArray() } return emptyDataArray.toTypedArray() // return arrayOf( // DataPoint(0.0, 1.0), // DataPoint(1.0, 5.0), // DataPoint(2.0, 3.0), // DataPoint(3.0, 2.0), // DataPoint(4.0, 6.0), // DataPoint(5.0, 7.0), // DataPoint(6.0, 8.0), // DataPoint(7.0, 9.0), // DataPoint(8.0, 10.0), // DataPoint(9.0, 11.0), // DataPoint(10.0, 12.0), // DataPoint(11.0, 13.0) // ) } }
FitLife/app/src/main/java/com/application/fitlife/GraphsAndAnalyticsActivity.kt
1262602412
package com.application.fitlife import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import com.application.fitlife.data.Workout import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.UserMetrics import java.time.LocalDate import java.time.format.DateTimeFormatter import kotlin.math.abs import kotlin.math.ceil import kotlin.random.Random class FuzzyLogicControllerWorkoutSuggestions { companion object { // Format a Date object to a String using the specified pattern fun suggestWorkouts(db: SQLiteDatabase, muscleGroups: List<String>, workoutTypes: List<String>, userMetrics: UserMetrics, sessionId: String): List<Long> { // profile the user metrics and rate the user // Calculate user BMI var userBMI = 23.5 userBMI = calculateBMI(userMetrics.height, userMetrics.weight) val bmiRating = calculateBMIRating(userBMI, 18.5, 29.9) val heartRateRating = calculateHeartRateRating( userMetrics.heartRate, 60.0, 100.0 ) val respiratoryRateRating = calculateRespiratoryRateRating( userMetrics.respiratoryRate, 12.0, 20.0 ) val bmiWeight = 0.4 val heartRateWeight = 0.3 val respiratoryRateWeight = 0.3 val overallRating = (bmiRating * bmiWeight + heartRateRating * heartRateWeight + respiratoryRateRating * respiratoryRateWeight) val selectedWorkouts: List<Workout> = getWorkoutsByFiltersAndRating(db, muscleGroups, workoutTypes, overallRating) for (workout in selectedWorkouts) { println("Workout ID: ${workout.id} Title: ${workout.title} ${workout.description}") } return insertWorkoutSuggestions(db, sessionId, selectedWorkouts) } private fun insertWorkoutSuggestions(db: SQLiteDatabase, sessionId: String, selectedWorkouts: List<Workout>): List<Long> { val contentValues = ContentValues() contentValues.put(MyDatabaseHelper.COLUMN_NAME_SESSION_ID, sessionId) contentValues.put(MyDatabaseHelper.COLUMN_NAME_DATE, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) val insertedSuggestionIds = mutableListOf<Long>() for (workout in selectedWorkouts) { contentValues.put(MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID, workout.id) contentValues.put(MyDatabaseHelper.COLUMN_NAME_SCORE, 0.0) contentValues.put(MyDatabaseHelper.COLUMN_NAME_IS_PERFORMED, 0) // Assuming 0 for not performed val suggestionId = db.insert(MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS, null, contentValues) if (suggestionId != -1L) { insertedSuggestionIds.add(suggestionId) } } return insertedSuggestionIds } private fun getWorkoutsByFiltersAndRating(db: SQLiteDatabase, bodyParts: List<String>, types: List<String>, targetRating: Double): List<Workout> { val bodyPartsCondition = if (bodyParts.isNotEmpty()) { "AND ${MyDatabaseHelper.COLUMN_NAME_BODYPART} IN (${bodyParts.joinToString(", ") { "'$it'" }})" } else { "" // Empty string when the list is empty } val typesCondition = if (types.isNotEmpty()) { "AND ${MyDatabaseHelper.COLUMN_NAME_TYPE} IN (${types.joinToString(", ") { "'$it'" }})" } else { "" // Empty string when the list is empty } val lowerBound = targetRating - 2.0 val upperBound = targetRating + 2.0 println("Running query to fetch workouts matching user preferences") val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUTS_INFORMATION} WHERE 1 = 1 $bodyPartsCondition $typesCondition AND ${MyDatabaseHelper.COLUMN_NAME_RATING} >= $lowerBound AND ${MyDatabaseHelper.COLUMN_NAME_RATING} <= $upperBound """.trimIndent() val cursor = db.rawQuery(query, null) val workoutsByMuscleGroup = mutableMapOf<String, MutableList<Workout>>() while (cursor.moveToNext()) { val workout = Workout( id = cursor.getLong(0), title = cursor.getString(1), description = cursor.getString(2), type = cursor.getString(3), bodyPart = cursor.getString(4), equipment = cursor.getString(5), level = cursor.getString(6), rating = cursor.getString(7), ratingDesc = cursor.getString(8), ) workoutsByMuscleGroup.computeIfAbsent(workout.bodyPart) { mutableListOf() }.add(workout) } val totalExercisesToSelect = 10.0 val exercisesPerGroup = if (workoutsByMuscleGroup.isNotEmpty()) { ceil(totalExercisesToSelect / workoutsByMuscleGroup.size) } else { 0 } // Randomly select proportional number of exercises from each group val selectedWorkouts = workoutsByMuscleGroup.flatMap { (_, workouts) -> workouts.shuffled().take(exercisesPerGroup.toInt()) }.take(totalExercisesToSelect.toInt()) return selectedWorkouts } /**Underweight = <18.5 Normal weight = 18.5–24.9 Overweight = 25–29.9 Obesity = BMI of 30 or greater */ private fun calculateBMI(height: Double, weight: Double): Double { if (height == 0.0 || weight == 0.0) return 23.5 return (weight * 100 * 100) / (height * height) } private fun calculateBMIRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 23.0 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateHeartRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 72 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateRespiratoryRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 15 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } } }
FitLife/app/src/main/java/com/application/fitlife/FuzzyLogicControllerWorkoutSuggestions.kt
2564423673
package com.application.fitlife import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.Manifest import android.app.Activity import android.content.ContentValues import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Color import android.media.MediaMetadataRetriever import android.net.Uri import android.os.AsyncTask import android.os.Build import android.os.Handler import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.* import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import androidx.core.content.PermissionChecker import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class CameraActivity : AppCompatActivity() { private var videoCapture: VideoCapture<Recorder>? = null private var recording: Recording? = null private lateinit var cameraExecutor: ExecutorService private lateinit var captureVideo: Button private lateinit var intentToReturn: Intent private lateinit var hiddenButton: Button private var readyToReturn = false private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { requestPermissions() } cameraExecutor = Executors.newSingleThreadExecutor() captureVideo = findViewById<Button>(R.id.video_capture_button) captureVideo.setOnClickListener { handler.postDelayed({ captureVideo() }, 45000) // Stop recording after 10 seconds (10000 milliseconds) captureVideo() } hiddenButton = findViewById<Button>(R.id.hiddenButton) hiddenButton.setOnClickListener { if (readyToReturn) { setResult(Activity.RESULT_OK, intentToReturn) // Finish the activity to return to the calling activity finish() } } } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } companion object { private const val TAG = "BHealthy" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA ).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } private fun requestPermissions() { activityResultLauncher.launch(REQUIRED_PERMISSIONS) } private val activityResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { permissions -> // Handle Permission granted/rejected var permissionGranted = true permissions.entries.forEach { if (it.key in REQUIRED_PERMISSIONS && it.value == false) permissionGranted = false } if (!permissionGranted) { Toast.makeText(baseContext, "Permission request denied", Toast.LENGTH_SHORT).show() } else { startCamera() } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) val cameraView = findViewById<PreviewView>(R.id.viewFinder) cameraProviderFuture.addListener({ // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(cameraView.surfaceProvider) } val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.SD)) .build() videoCapture = VideoCapture.withOutput(recorder) // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera val camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, videoCapture) // Turn on the flash (torch mode) camera.cameraControl.enableTorch(true) } catch(exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } private fun captureVideo() { val videoCapture = this.videoCapture ?: return captureVideo.isEnabled = false val curRecording = recording if (curRecording != null) { // Stop the current recording session. Toast.makeText(baseContext, "Stopped video recording", Toast.LENGTH_SHORT).show() curRecording.stop() recording = null return } // create and start a new recording session val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/BHealthy") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) // .apply { // if (PermissionChecker.checkSelfPermission(this@CameraActivity, // Manifest.permission.RECORD_AUDIO) == // PermissionChecker.PERMISSION_GRANTED) // { // withAudioEnabled() // } // } .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { println("started video recording") Toast.makeText(baseContext, "Video capture started", Toast.LENGTH_SHORT).show() } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { intentToReturn = Intent() intentToReturn.putExtra("videoUri", recordEvent.outputResults.outputUri.toString()) readyToReturn = true hiddenButton.performClick() } else { recording?.close() recording = null Log.e(TAG, "Video capture ends with error: ${recordEvent.error}") } } } } } }
FitLife/app/src/main/java/com/application/fitlife/CameraActivity.kt
1882911439
package com.application.fitlife import android.app.AlertDialog import android.content.ContentValues import android.content.Intent import android.database.sqlite.SQLiteDatabase import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.application.fitlife.FuzzyLogicControllerWorkoutSuggestions.Companion.suggestWorkouts import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.Workout import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.UUID class ShowExercise<SQLiteDatabase> : AppCompatActivity() { companion object { const val USER_HEIGHT = "height" const val USER_WEIGHT = "weight" const val USER_HEART_RATE = "heartRate" const val USER_RESPIRATORY_RATE = "respiratoryRate" } private lateinit var muscleGroupSpinner: Spinner private lateinit var showExercisesButton: Button private lateinit var showExercisesText: TextView private lateinit var submitButton: Button private lateinit var selectedMuscleGroupsText: TextView private lateinit var selectedExerciseTypesText: TextView private lateinit var selectMuscleGroupsButton: Button private lateinit var exercisesList: RecyclerView private lateinit var exercisesAdapter: ExercisesAdapter private lateinit var recyclerView: RecyclerView private lateinit var workoutAdapter: WorkoutCheckboxAdapter private lateinit var selectExerciseTypeButton: Button private val exerciseTypes by lazy { resources.getStringArray(R.array.exercise_types) } private var selectedExerciseTypes: BooleanArray? = null private val muscleGroups by lazy { resources.getStringArray(R.array.muscle_groups) } private var selectedMuscleGroups: BooleanArray? = null private val selectedExercises = mutableListOf<Exercise>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show_exercise) val sessionId = intent.getStringExtra(getString(R.string.unique_id))?: "default_value" selectMuscleGroupsButton = findViewById(R.id.selectMuscleGroupsButton) showExercisesButton = findViewById(R.id.showExercisesButton) selectedMuscleGroupsText = findViewById(R.id.selectedMuscleGroupsText) selectedExerciseTypesText = findViewById(R.id.selectedExerciseTypesText) //showExercisesText = findViewById(R.id.showExercisesText) //exercisesList = findViewById(R.id.exercisesList) selectedMuscleGroups = BooleanArray(muscleGroups.size) selectExerciseTypeButton = findViewById(R.id.selectExerciseTypeButton) recyclerView = findViewById(R.id.exercisesList) recyclerView.layoutManager = LinearLayoutManager(this) selectedExerciseTypes = BooleanArray(exerciseTypes.size) selectExerciseTypeButton.setOnClickListener { showExerciseTypeDialog() } //setupSpinner() submitButton = findViewById(R.id.submitExercisesButton) selectMuscleGroupsButton.setOnClickListener { showMuscleGroupDialog() } val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase showExercisesButton.setOnClickListener { //displaySelectedExercises() val muscleGroupSelections = muscleGroups.filterIndexed { index, _ -> selectedMuscleGroups?.get(index) == true } //Toast.makeText(this, "Selected Exercises: $muscleGroupSelections", Toast.LENGTH_LONG).show() val exerciseTypeSelections = exerciseTypes.filterIndexed { index, _ -> selectedExerciseTypes?.get(index) == true } val userMetrics = MyDatabaseHelper.getUserMetrics(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) val suggestedWorkoutIds = suggestWorkouts( db, muscleGroupSelections, exerciseTypeSelections, userMetrics, sessionId ) //Toast.makeText(this, "Number of Suggested workout Ids: ${suggestedWorkoutIds.size}", Toast.LENGTH_SHORT).show() val workouts = getWorkoutsByIds(db, suggestedWorkoutIds) Toast.makeText(this, "Number of workouts: ${workouts.size}", Toast.LENGTH_SHORT).show() workoutAdapter = WorkoutCheckboxAdapter(workouts) recyclerView.adapter = workoutAdapter // val adapter = WorkoutAdapter(workouts) // recyclerView.adapter = adapter //displayWorkouts(workouts) //Toast.makeText(this, "$suggestedWorkoutIds.size()", Toast.LENGTH_LONG).show(); // Do something with the suggestedWorkoutIds, like displaying them // FuzzyLogicControllerWorkoutSuggestions.showSelectedExercises() } submitButton.setOnClickListener { updateSuggestionScore(db , sessionId) } // exercisesAdapter = ExercisesAdapter(emptyList()) // exercisesList.layoutManager = LinearLayoutManager(this) // exercisesList.adapter = exercisesAdapter } private fun displayWorkouts(workouts: List<Workout>) { //: ${workout.description}Type: ${workout.type}, Body Part: ${workout.bodyPart} val workoutDetails = workouts.map { workout -> "${workout.title}" } // Assuming you have a TextView or any other component to display the workouts val workoutsDisplay = showExercisesText // Replace with your actual TextView ID workoutsDisplay.text = workoutDetails.joinToString("\n\n") } private fun getWorkoutsByIds(db: android.database.sqlite.SQLiteDatabase, ids: List<Long>): List<Workout> { val workouts = mutableListOf<Workout>() // Convert the List<Long> of workout IDs to a comma-separated string for the SQL query val workoutIdList = ids.joinToString(separator = ", ") //Toast.makeText(this, "Workout ID list length: ${workoutIdList.length}", Toast.LENGTH_SHORT).show() Log.d("workoutId", workoutIdList) Toast.makeText(this, "All the Ids: $workoutIdList", Toast.LENGTH_SHORT).show() // SQL query to retrieve exercises val query = """ SELECT wi.*, ws.${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID}, ws.${MyDatabaseHelper.COLUMN_NAME_SCORE} FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} ws JOIN ${MyDatabaseHelper.TABLE_NAME_WORKOUTS_INFORMATION} wi ON wi.${MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID} = ws.${MyDatabaseHelper.COLUMN_NAME_EXERCISE_ID} WHERE ws.${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID} IN ($workoutIdList) """ Log.d("SQLQuery", query) Toast.makeText(this, "All the query: $query", Toast.LENGTH_SHORT).show() val cursor = db.rawQuery(query, null) try { while (cursor.moveToNext()) { val workout = Workout( id = cursor.getLong(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID)), title = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_TITLE)), description = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_DESCRIPTION)), type = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_TYPE)), bodyPart = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_BODYPART)), equipment = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_EQUIPMENT)), level = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_LEVEL)), rating = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_RATING)), ratingDesc = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_RATING_DESC)), score = cursor.getDouble(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_SCORE)), suggestionId = cursor.getLong(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID)) ) workouts.add(workout) } } finally { cursor.close() // Ensure the cursor is closed after use } return workouts } private fun showExerciseTypeDialog() { AlertDialog.Builder(this) .setTitle("Select Exercise Types") .setMultiChoiceItems(exerciseTypes, selectedExerciseTypes) { _, which, isChecked -> selectedExerciseTypes?.set(which, isChecked) } .setPositiveButton("OK") { dialog, _ -> updateSelectedExerciseTypesText() dialog.dismiss() } .setNegativeButton("Cancel", null) .show() } private fun updateSelectedExerciseTypesText() { val selectedTypes = exerciseTypes .filterIndexed { index, _ -> selectedExerciseTypes?.get(index) == true } .joinToString(separator = ", ") selectedExerciseTypesText.text = if (selectedTypes.isEmpty()) { "Selected Exercise Types: None" } else { "Selected Exercise Types: $selectedTypes" } } private fun showMuscleGroupDialog() { AlertDialog.Builder(this) .setTitle("Select Muscle Groups") .setMultiChoiceItems(muscleGroups, selectedMuscleGroups) { _, which, isChecked -> selectedMuscleGroups?.set(which, isChecked) } .setPositiveButton("OK") { dialog, _ -> //updateExercisesList() prepareSelectedExercises() updateSelectedMuscleGroupsText() dialog.dismiss() } .setNegativeButton("Cancel", null) .show() } private fun updateSelectedMuscleGroupsText() { val selectedGroups = muscleGroups .filterIndexed { index, _ -> selectedMuscleGroups?.get(index) == true } .joinToString(separator = ", ") selectedMuscleGroupsText.text = if (selectedGroups.isEmpty()) { "Selected Muscle Groups: None" } else { "Selected Muscle Groups: $selectedGroups" } } private fun displaySelectedExercises() { exercisesAdapter.exercises = selectedExercises exercisesAdapter.notifyDataSetChanged() } private fun prepareSelectedExercises() { selectedExercises.clear() muscleGroups.forEachIndexed { index, muscleGroup -> selectedMuscleGroups?.let { if (it[index]) { selectedExercises.addAll(getExercisesForMuscleGroup(muscleGroup)) } } } } private fun updateSuggestionScore(db: android.database.sqlite.SQLiteDatabase , sessionId: String) { // If workouts are not yet suggested, nothing to update if (!::workoutAdapter.isInitialized) { return } // profile the user metrics and rate the user val selectedExercises = workoutAdapter.workouts .filter { it.isSelected } .map { it.id } // Iterate through selected exercises and update the score in the original list for (suggestionId in selectedExercises) { val selectedWorkout = workoutAdapter.workouts.find { it.id == suggestionId } selectedWorkout?.let { println("Score cxheck ${selectedWorkout.score}") // val updateScoreQuery = """ // UPDATE ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} SET // ${MyDatabaseHelper.COLUMN_NAME_SCORE} = ${selectedWorkout.score} // WHERE ${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID} = ${selectedWorkout.suggestionId} // """ // println(updateScoreQuery) val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase var values = ContentValues() values.put("score", selectedWorkout.score) db.update( MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS, values, "${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID}=?", arrayOf(selectedWorkout.suggestionId.toString()) ) //val cursor = db.rawQuery(updateScoreQuery, null) //cursor.close() } } val dailyScoreCalculatedForUser = ScoringEngine.calculateScore(db , sessionId) Toast.makeText(baseContext, "Today's workout score : $dailyScoreCalculatedForUser", Toast.LENGTH_SHORT).show() val uniqueDate = generateUniqueDate(); val cursor = db.rawQuery("SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(uniqueDate)) var values = ContentValues() values.put("score", dailyScoreCalculatedForUser) if (cursor.count > 0) { // Entry with the vitals_id already exists, update it db.update( MyDatabaseHelper.TABLE_NAME_USER_METRICS, values, "${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(uniqueDate) ) } else { values.put("date", uniqueDate) // Entry with the vitals_id doesn't exist, insert a new record db.insert(MyDatabaseHelper.TABLE_NAME_USER_METRICS, null, values) } } fun generateUniqueDate(): String { val currentDate = LocalDate.now(ZoneId.systemDefault()) val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") var formattedDate = currentDate.format(formatter) formattedDate = formattedDate.toString() return formattedDate } // private fun setupSpinner() { // ArrayAdapter.createFromResource( // this, // R.array.muscle_groups, // Make sure this array is defined in your resources // android.R.layout.simple_spinner_item // ).also { adapter -> // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // muscleGroupSpinner.adapter = adapter // } // // muscleGroupSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { // override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { // val muscleGroup = parent.getItemAtPosition(position).toString() // updateExercisesList(muscleGroup) // } // // override fun onNothingSelected(parent: AdapterView<*>) {} // } // } private fun updateExercisesList() { val exercises = mutableListOf<Exercise>() muscleGroups.forEachIndexed { index, muscleGroup -> selectedMuscleGroups?.let { if (it[index]) { exercises.addAll(getExercisesForMuscleGroup(muscleGroup)) } } } // exercisesAdapter.exercises = exercises // exercisesAdapter.notifyDataSetChanged() // private fun updateExercisesList(muscleGroup: String) { // val exercises = getExercisesForMuscleGroup(muscleGroup) // exercisesAdapter = ExercisesAdapter(exercises) // exercisesList.adapter = exercisesAdapter // exercisesList.layoutManager = LinearLayoutManager(this) // } } } fun getExercisesForMuscleGroup(muscleGroup: String): List<Exercise> { return when (muscleGroup) { "Abdominals" -> listOf(Exercise("Bicep Curls"), Exercise("Tricep Dips"), Exercise("Hammer Curls")) "Adductors" -> listOf(Exercise("Bench Press"), Exercise("Push Ups"), Exercise("Chest Fly")) "Abductors" -> listOf(Exercise("Pull Ups"), Exercise("Deadlifts"), Exercise("Lat Pulldowns")) "Biceps" -> listOf(Exercise("Squats"), Exercise("Leg Press"), Exercise("Lunges")) "Calves" -> listOf(Exercise("Shoulder Press"), Exercise("Lateral Raises"), Exercise("Front Raises")) "Chest" -> listOf(Exercise("Shoulder Press"), Exercise("Lateral Raises"), Exercise("Front Raises")) // Add more muscle groups and exercises as needed else -> emptyList() } } data class Exercise(val name: String, var isSelected: Boolean = false) class WorkoutCheckboxAdapter(val workouts: List<Workout>) : RecyclerView.Adapter<WorkoutCheckboxAdapter.WorkoutViewHolder>() { class WorkoutViewHolder(view: View) : RecyclerView.ViewHolder(view) { val workoutCheckBox: CheckBox = view.findViewById(R.id.workoutCheckBox) val workoutTitleTextView: TextView = view.findViewById(R.id.workoutTitleTextView) val percentageEditText: EditText = view.findViewById(R.id.percentageEditText) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkoutViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.workout_item_checkbox, parent, false) return WorkoutViewHolder(itemView) } override fun onBindViewHolder(holder: WorkoutViewHolder, position: Int) { val workout = workouts[position] holder.workoutTitleTextView.text = workout.title holder.workoutCheckBox.isChecked = false // or any logic you want to determine checked state // Add any click listener if required holder.workoutCheckBox.setOnCheckedChangeListener { _, isChecked -> // Handle checkbox check changes if needed workout.isSelected = isChecked } holder.percentageEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { // This method is called to notify you that characters within `charSequence` are about to be replaced. } override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { // This method is called to notify you that somewhere within `charSequence` has been changed. } override fun afterTextChanged(editable: Editable?) { // This method is called to notify you that somewhere within `editable` has been changed. // This is the ideal place to perform your actions after the text has been changed. val enteredText = editable.toString() var convertedScore = enteredText.toDoubleOrNull() ?: 0.0 workout.score = convertedScore // Do something with the entered text, e.g., update a variable, trigger some logic, etc. } }) } override fun getItemCount() = workouts.size } class ExercisesAdapter(var exercises: List<Exercise>) : RecyclerView.Adapter<ExercisesAdapter.ExerciseViewHolder>() { class ExerciseViewHolder(view: View) : RecyclerView.ViewHolder(view) { val checkBox: CheckBox = view.findViewById(R.id.exerciseCheckBox) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.exercise_item, parent, false) return ExerciseViewHolder(view) } override fun onBindViewHolder(holder: ExerciseViewHolder, position: Int) { val exercise = exercises[position] holder.checkBox.text = exercise.name holder.checkBox.isChecked = exercise.isSelected holder.checkBox.setOnCheckedChangeListener { _, isChecked -> exercise.isSelected = isChecked } } override fun getItemCount() = exercises.size }
FitLife/app/src/main/java/com/application/fitlife/ShowExercise.kt
4013248508
package com.application.fitlife import kotlin.math.abs import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.WorkoutSuggestion import android.database.sqlite.SQLiteDatabase import android.util.Log import com.application.fitlife.data.UserMetrics import java.time.LocalDate import java.time.format.DateTimeFormatter import kotlin.math.min class ScoringEngine { companion object{ const val USER_HEIGHT = "height" const val USER_WEIGHT = "weight" const val USER_HEART_RATE = "heartRate" const val USER_RESPIRATORY_RATE = "respiratoryRate" fun calculateScore(db: SQLiteDatabase , sessionId: String): Double{ var userBMI = 23.5 var userMetrics = MyDatabaseHelper.getUserMetrics(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) userBMI = ScoringEngine.calculateBMI( userMetrics.height, userMetrics.weight ) val bmiRating = ScoringEngine.calculateBMIRating(userBMI, 18.5, 29.9) val heartRateRating = ScoringEngine.calculateHeartRateRating( userMetrics.heartRate, 60.0, 100.0 ) val respiratoryRateRating = ScoringEngine.calculateRespiratoryRateRating( userMetrics.respiratoryRate, 12.0, 20.0 ) val bmiWeight = 0.2 val heartRateWeight = 0.4 val respiratoryRateWeight = 0.4 val overallRating = (bmiRating * bmiWeight + heartRateRating * heartRateWeight + respiratoryRateRating * respiratoryRateWeight) val workoutSuggestions = getPerformedExercisesByDate(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd")) , sessionId) Log.d("workoutSuggestions" , workoutSuggestions.toString()); println("checking where it crashes - step 1 - ${workoutSuggestions.size}") val top10Exercise = workoutSuggestions.slice(0 until min(10, workoutSuggestions.size)) println("checking where it crashes - step 2") val averageScoreTop10 = top10Exercise .map { it.score.toInt() } .toList() .average() println("checking where it crashes - step 3") val totalAvg = workoutSuggestions .map { it.score.toInt() } .toList() .average() println("checking where it crashes - step 4") val restAvg = (totalAvg * workoutSuggestions.size - averageScoreTop10 * top10Exercise.size) / ((workoutSuggestions.size - top10Exercise.size)+1) println("checking where it crashes - step 5 - restAvg = ${restAvg}") val newMin = 70 val newMax = 100 val overallScoring = (newMin + (averageScoreTop10 - 0) * (newMax - newMin) / (100 - 0)) + (overallRating * restAvg / 100) println("checking where it crashes - step 6") println("overallScoring: ${overallScoring} overallRating: ${overallRating} averageScoreTop10: ${averageScoreTop10}") return overallScoring.coerceIn(1.0, 100.0) } private fun getPerformedExercisesByDate(db: SQLiteDatabase, targetDate: String , sessionId: String): List<WorkoutSuggestion> { val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} WHERE ${MyDatabaseHelper.COLUMN_NAME_SESSION_ID} = '$sessionId' ORDER BY ${MyDatabaseHelper.COLUMN_NAME_SCORE} DESC """.trimIndent() val cursor = db.rawQuery(query, null) val workoutSuggestions = mutableListOf<WorkoutSuggestion>() while (cursor.moveToNext()) { val suggestion = WorkoutSuggestion( id = cursor.getLong(0), sessionId = cursor.getString(1), date = cursor.getString(2), exerciseId = cursor.getString(3), score = cursor.getString(4), isPerformed = cursor.getString(5) ) workoutSuggestions.add(suggestion) } cursor.close() return workoutSuggestions } private fun calculateBMI(height: Double, weight: Double): Double { if (height == 0.0 || weight == 0.0) return 23.5 return (weight * 100 * 100) / (height * height) } private fun calculateBMIRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 23.0 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateHeartRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 72 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateRespiratoryRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 15 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } } }
FitLife/app/src/main/java/com/application/fitlife/ScoringEngine.kt
1014515485
import android.content.Context class AppPreferences(context: Context) { private val sharedPreferences = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE) fun isDataLoaded(): Boolean { return sharedPreferences.getBoolean("data_loaded", false) } fun setDataLoaded(isLoaded: Boolean) { sharedPreferences.edit().putBoolean("data_loaded", isLoaded).apply() } }
FitLife/app/src/main/java/com/application/fitlife/data/AppPreferences.kt
3113041641
package com.application.fitlife.data data class WorkoutSuggestion( val id: Long, val sessionId: String, val date: String, val exerciseId: String, val score: String, val isPerformed: String, )
FitLife/app/src/main/java/com/application/fitlife/data/WorkoutSuggestion.kt
761908354
package com.application.fitlife.data import AppPreferences import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.provider.BaseColumns import com.opencsv.CSVReaderBuilder import java.io.InputStreamReader class MyDatabaseHelper(private val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { // Table contents are grouped together in an anonymous object. companion object FitLife : BaseColumns { const val DATABASE_NAME = "fit_life_db" const val DATABASE_VERSION = 1 const val TABLE_NAME_WORKOUT_SUGGESTIONS = "workout_suggestions" const val WORKOUTS_INFORMATION_FILENAME = "WorkoutsInformation.csv" const val TABLE_NAME_WORKOUTS_INFORMATION = "workouts_information" const val TABLE_NAME_USER_METRICS = "userMetrics" const val COLUMN_NAME_TITLE = "title" const val COLUMN_NAME_DESCRIPTION = "description" const val COLUMN_NAME_HEART_RATE = "heart_rate" const val COLUMN_NAME_WORKOUT_ID = "workout_id" const val COLUMN_NAME_DATE = "date" const val COLUMN_NAME_TYPE = "type" const val COLUMN_NAME_BODYPART = "bodyPart" const val COLUMN_NAME_EQUIPMENT = "equipment" const val COLUMN_NAME_LEVEL = "level" const val COLUMN_NAME_RATING = "rating" const val COLUMN_NAME_RATING_DESC = "ratingDesc" const val USER_TABLE_NAME = "userDetails" const val COLUMN_NAME_IS_PERFORMED = "is_performed" const val COLUMN_NAME_SUGGESTION_ID = "suggestion_id" const val COLUMN_NAME_SESSION_ID = "session_id" const val COLUMN_NAME_RESPIRATORY_RATE = "respiratory_rate" const val COLUMN_NAME_SCORE = "score" const val COLUMN_NAME_WEIGHT = "weight" const val COLUMN_NAME_HEIGHT = "height" const val COLUMN_NAME_EXERCISE_ID = "workout_id" const val COLUMN_NAME_USER_ID = "user_id" const val COLUMN_NAME_AGE = "age" const val COLUMN_NAME_USERNAME = "user_name" fun getUserMetrics(db: SQLiteDatabase, targetDate: String): UserMetrics { val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE} = '$targetDate' """.trimIndent() val cursor = db.rawQuery(query, null) val userMetrics = UserMetrics( id = 0, height = 0.0, weight = 0.0, score = 0.0, heartRate = 0.0, respiratoryRate = 0.0 ) while (cursor.moveToNext()) { val userMetrics = UserMetrics( id = cursor.getLong(0), height = cursor.getDouble(1), weight = cursor.getDouble(2), score = cursor.getDouble(3), heartRate = cursor.getDouble(4), respiratoryRate = cursor.getDouble(5) ) } cursor.close() return userMetrics } } override fun onCreate(db: SQLiteDatabase?) { println("Creating database and tables required") val createUserMetricsTableQuery = "CREATE TABLE $TABLE_NAME_USER_METRICS (" + "$COLUMN_NAME_DATE TEXT PRIMARY KEY, " + "$COLUMN_NAME_HEIGHT REAL," + "$COLUMN_NAME_WEIGHT REAL," + "$COLUMN_NAME_SCORE REAL," + "$COLUMN_NAME_HEART_RATE REAL," + "$COLUMN_NAME_RESPIRATORY_RATE REAL)" db?.execSQL(createUserMetricsTableQuery) val createUserDetailsTableQuery = "CREATE TABLE $USER_TABLE_NAME (" + "$COLUMN_NAME_USER_ID TEXT PRIMARY KEY, " + "$COLUMN_NAME_AGE REAL," + "$COLUMN_NAME_USERNAME TEXT)" db?.execSQL(createUserDetailsTableQuery) val workoutsInformationTableQuery = "CREATE TABLE $TABLE_NAME_WORKOUTS_INFORMATION (" + "$COLUMN_NAME_WORKOUT_ID INTEGER PRIMARY KEY, " + "$COLUMN_NAME_TITLE TEXT," + "$COLUMN_NAME_DESCRIPTION TEXT," + "$COLUMN_NAME_TYPE TEXT," + "$COLUMN_NAME_BODYPART TEXT," + "$COLUMN_NAME_EQUIPMENT TEXT," + "$COLUMN_NAME_LEVEL TEXT," + "$COLUMN_NAME_RATING REAL," + "$COLUMN_NAME_RATING_DESC TEXT)" val workoutSuggestionsTableQuery = "CREATE TABLE $TABLE_NAME_WORKOUT_SUGGESTIONS (" + "$COLUMN_NAME_SUGGESTION_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "$COLUMN_NAME_SESSION_ID TEXT," + "$COLUMN_NAME_DATE TEXT," + "$COLUMN_NAME_EXERCISE_ID INTEGER," + "$COLUMN_NAME_SCORE REAL," + "$COLUMN_NAME_IS_PERFORMED INTEGER," + "FOREIGN KEY($COLUMN_NAME_EXERCISE_ID) REFERENCES $TABLE_NAME_WORKOUTS_INFORMATION($COLUMN_NAME_WORKOUT_ID))" db?.execSQL(workoutsInformationTableQuery) insertDataFromCsvIfNotLoaded(db, WORKOUTS_INFORMATION_FILENAME) db?.execSQL(workoutSuggestionsTableQuery) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_USER_METRICS") db?.execSQL("DROP TABLE IF EXISTS $USER_TABLE_NAME") db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_WORKOUTS_INFORMATION") db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_WORKOUT_SUGGESTIONS") onCreate(db) } fun readCsvFile(fileName: String): List<Array<String>> { context.assets.open(fileName).use { inputStream -> InputStreamReader(inputStream).use { inputStreamReader -> return CSVReaderBuilder(inputStreamReader) .withSkipLines(1) .build() .readAll() } } } fun insertDataFromCsvIfNotLoaded(db: SQLiteDatabase?, fileName: String) { val preferences = AppPreferences(context) println("Loading workout data to app") if (!preferences.isDataLoaded()) { val csvData = readCsvFile(fileName) for (row in csvData) { val values = ContentValues().apply { put(COLUMN_NAME_WORKOUT_ID, row[0]) put(COLUMN_NAME_TITLE, row[1]) put(COLUMN_NAME_DESCRIPTION, row[2]) put(COLUMN_NAME_TYPE, row[3]) put(COLUMN_NAME_BODYPART, row[4]) put(COLUMN_NAME_EQUIPMENT, row[5]) put(COLUMN_NAME_LEVEL, row[6]) put(COLUMN_NAME_RATING, row[7]) put(COLUMN_NAME_RATING_DESC, row[8]) } db?.insert(TABLE_NAME_WORKOUTS_INFORMATION, null, values) } // Mark data as loaded preferences.setDataLoaded(true) } } }
FitLife/app/src/main/java/com/application/fitlife/data/MyDatabaseHelper.kt
2492098470
package com.application.fitlife.data data class UserMetrics ( val id: Long, val height: Double, val weight: Double, val score: Double, val heartRate: Double, val respiratoryRate: Double, )
FitLife/app/src/main/java/com/application/fitlife/data/UserMetrics.kt
2641299083
package com.application.fitlife.data data class Workout( val id: Long, val title: String, val description: String, val type: String, val bodyPart: String, val equipment: String, val level: String, val rating: String, val ratingDesc: String, var isSelected: Boolean = false, var suggestionId: Long = 0, var score: Double = 0.0 )
FitLife/app/src/main/java/com/application/fitlife/data/Workout.kt
425237246
package com.andy.kotlindelivery 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.andy.kotlindelivery", appContext.packageName) } }
KotlinDelivery_Frontend/app/src/androidTest/java/com/andy/kotlindelivery/ExampleInstrumentedTest.kt
1000394233
package com.andy.kotlindelivery 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) } }
KotlinDelivery_Frontend/app/src/test/java/com/andy/kotlindelivery/ExampleUnitTest.kt
3235825342
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Part interface UsuariosRoutes { @POST("usuarios/create") fun register (@Body usuario: Usuario) : Call<ResponseHttp> @FormUrlEncoded @POST("usuarios/login") fun login(@Field("email") email:String, @Field("contrasena") contrasena: String) : Call<ResponseHttp> @Multipart @PUT("usuarios/update") fun update( @Part image: MultipartBody.Part, @Part("user") user: RequestBody, @Header("Authorization") token: String ): Call<ResponseHttp> @PUT("usuarios/updateWithoutImage") fun updateWithoutImage( @Body usuario: Usuario, @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/UsuariosRoutes.kt
2682221528
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.ResponseHttp import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path interface ProductosRoutes { @GET("productos/findByCategoria/{id_categoria}") fun findByCategoria( @Path("id_categoria") idCategoria: String, @Header("Authorization") token: String ): Call<ArrayList<Producto>> @Multipart //Es multipart porque se enviara una imagen @POST("productos/create") fun create( @Part images: Array<MultipartBody.Part?>, @Part("producto") producto: RequestBody, //el nombre debe ser igual al del archivo controller del backend @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/ProductosRoutes.kt
1760282437
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Part interface CategoriasRoutes { @GET("categorias/getAll") fun getAll( @Header("Authorization") token: String ): Call<ArrayList<Categoria>> @Multipart //Es multipart porque se enviara una imagen @POST("categorias/create") fun create( @Part image: MultipartBody.Part, @Part("categoria") categoria: RequestBody, //el nombre debe ser igual al del archivo controller del backend @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/CategoriasRoutes.kt
2785279235
package com.andy.kotlindelivery.fragments.restaurant import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Spinner import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import com.andy.kotlindelivery.R import com.andy.kotlindelivery.adapters.CategoriasAdapters import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.CategoriasProviders import com.andy.kotlindelivery.providers.ProductosProviders import com.andy.kotlindelivery.utils.SharedPref import com.github.dhaval2404.imagepicker.ImagePicker import com.google.gson.Gson import com.tommasoberlose.progressdialog.ProgressDialogFragment import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File class RestaurantProductFragment : Fragment() { var TAG = "RestaurantProductFragment" var gson = Gson() var myView: View? = null var editTextNombre: EditText? = null var editTextDescription: EditText? = null var editTextPreeio: EditText? = null var imageViewProduct1: ImageView? = null var imageViewProduct2: ImageView? = null var imageViewProduct3: ImageView? = null var spinnerCategoria: Spinner? = null var btnCreateProduct : Button? = null var imageFile1: File? = null var imageFile2: File? = null var imageFile3: File? = null var categoriasProvider: CategoriasProviders? = null var productosProviders: ProductosProviders? = null var usuario: Usuario? = null var sharedPref: SharedPref? = null var categorias = ArrayList<Categoria>() var idCategoria = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_restaurant_product, container, false) editTextNombre= myView?.findViewById(R.id.edittxt_nombre) editTextDescription= myView?.findViewById(R.id.edittxt_description) editTextPreeio = myView?.findViewById(R.id.edittxt_precio) imageViewProduct1= myView?.findViewById(R.id.imageview_prodcut1) imageViewProduct2 = myView?.findViewById(R.id.imageview_prodcut2) imageViewProduct3 =myView?.findViewById(R.id.imageview_prodcut3) spinnerCategoria = myView?.findViewById(R.id.spinner_categoria) btnCreateProduct = myView?.findViewById(R.id.btn_create_product) btnCreateProduct?.setOnClickListener { createProduct() } imageViewProduct1?.setOnClickListener { selectImage(101) } imageViewProduct2?.setOnClickListener { selectImage(102) } imageViewProduct3?.setOnClickListener { selectImage(103) } sharedPref = SharedPref(requireActivity()) getUserFromSession() categoriasProvider = CategoriasProviders(usuario?.sessionToken!!) productosProviders = ProductosProviders(usuario?.sessionToken!!) getCategorias() return myView } ///////////////////////////////////////////////////////////////////////// private fun createProduct() { val nombreProducto = editTextNombre?.text.toString() val descriptionProducto = editTextDescription?.text.toString() val precioText = editTextPreeio?.text.toString() val files = ArrayList<File>() if ( isValidForm(nombreProducto, descriptionProducto,precioText) ){ val producto = Producto( nombre = nombreProducto, descripcion = descriptionProducto, precio = precioText.toDouble(), idCategoria = idCategoria ) Log.d(TAG, "Producto $producto") files.add(imageFile1!!) files.add(imageFile2!!) files.add(imageFile3!!) Log.d(TAG, "Imagenes $files") ProgressDialogFragment.showProgressBar(requireActivity()) productosProviders?.create(files, producto)?.enqueue(object: Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp> ) { ProgressDialogFragment.hideProgressBar(requireActivity()) Log.d(TAG, "Response: ${response}") Log.d(TAG, "Body: ${response.body()}") Toast.makeText(requireContext(), response.body()?.message, Toast.LENGTH_LONG).show() if(response.body()?.isSucces == true){ resetForm() } } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { ProgressDialogFragment.hideProgressBar(requireActivity()) Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////// private fun getCategorias(){ Log.d(TAG, "getCategorias() : ${categoriasProvider}") categoriasProvider?.getAll()?.enqueue(object: Callback<ArrayList<Categoria>> { override fun onResponse( call: Call<ArrayList<Categoria>>, response: Response<ArrayList<Categoria>> ) { if(response.body() != null){ categorias = response.body()!! val arrayAdapter = ArrayAdapter<Categoria>(requireActivity(), android.R.layout.simple_dropdown_item_1line, categorias) spinnerCategoria?.adapter = arrayAdapter spinnerCategoria?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, l: Long ) { idCategoria = categorias[position].id!! Log.d(TAG, "Id categoria : $idCategoria") } override fun onNothingSelected(parent: AdapterView<*>?) { } } } } override fun onFailure(call: Call<ArrayList<Categoria>>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } /////////////////////////////////////////////////////////////////////////////// ////FUNCIONES PARA SELECCIONAR LA IMAGEN DESDE GALERIA override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { val fileUri = data?.data if(requestCode == 101){ imageFile1 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct1?.setImageURI(fileUri) } else if(requestCode == 102){ imageFile2 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct2?.setImageURI(fileUri) } else if(requestCode == 103){ imageFile3 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct3?.setImageURI(fileUri) } } else if (resultCode == ImagePicker.RESULT_ERROR) { Toast.makeText(requireContext(), ImagePicker.getError(data), Toast.LENGTH_SHORT).show() } else { Toast.makeText(requireContext(), "Task Cancelled", Toast.LENGTH_SHORT).show() } } private fun selectImage(requestCode: Int) { ImagePicker.with(this) .crop() .compress(1024) .maxResultSize(1080,1080) .start(requestCode) } ///////////////////////////////////////////////////////////////// //////////////funcion de validacion private fun isValidForm(nombre: String, descripcion: String, precio: String): Boolean{ if(nombre.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa el nombre del producto", Toast.LENGTH_LONG).show() return false } if(descripcion.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa la descripcion del producto", Toast.LENGTH_LONG).show() return false } if(precio.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa el precio del producto", Toast.LENGTH_LONG).show() return false } if(imageFile1 == null){ Toast.makeText(requireContext(), "Ingresa al menos la primer imagen", Toast.LENGTH_LONG).show() return false } if(idCategoria.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa la categoria del producto", Toast.LENGTH_LONG).show() return false } return true } ////////////////////////////////// ////Funcion para limpiar formulario private fun resetForm() { editTextNombre?.setText("") editTextDescription?.setText("") editTextPreeio?.setText("") imageFile1 = null imageFile2 = null imageFile3 = null imageViewProduct1?.setImageResource(R.drawable.ic_image) imageViewProduct2?.setImageResource(R.drawable.ic_image) imageViewProduct3?.setImageResource(R.drawable.ic_image) } ////////////////// /////funciones de sesion private fun getUserFromSession() { //val sharedPref = SharedPref(this,) if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } /////////////////////////////// }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantProductFragment.kt
406402727
package com.andy.kotlindelivery.fragments.restaurant import android.app.Activity import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import com.andy.kotlindelivery.R import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.CategoriasProviders import com.andy.kotlindelivery.utils.SharedPref import com.github.dhaval2404.imagepicker.ImagePicker import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File class RestaurantCategoryFragment : Fragment() { var TAG = "RestaurantCategoryFragment" var categoriasProvider: CategoriasProviders? = null var sharedPref: SharedPref? = null var usuario: Usuario? = null var myView: View? = null var imageViewCategory: ImageView? =null var editTextCategory: EditText? = null var buttonCrearCategory: Button? = null private var imageFile: File? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_restaurant_category, container, false) sharedPref = SharedPref(requireActivity()) imageViewCategory = myView?.findViewById(R.id.image_view_category) editTextCategory = myView?.findViewById(R.id.edittxt_category) buttonCrearCategory = myView?.findViewById(R.id.btn_create_category) getUserFromSession() categoriasProvider = CategoriasProviders(usuario?.sessionToken!!) Log.d(TAG, "Usuario con Token: ${usuario?.sessionToken!!}") imageViewCategory?.setOnClickListener{ selectImage() } buttonCrearCategory?.setOnClickListener { createCategory() } return myView } /////FUNCION QUE INICIA LA CREACION DE LA CATEGORIA private fun createCategory() { val categoria = editTextCategory?.text.toString() if(imageFile != null){ val category = Categoria(nombre = categoria) Log.d(TAG, "Categoria: $category") categoriasProvider?.create(imageFile!!, category)?.enqueue(object : Callback<ResponseHttp> { override fun onResponse(call: Call<ResponseHttp>, response: Response<ResponseHttp>) { Log.d(TAG, "RESPONSE: $response") Log.d(TAG, "BODY: ${response.body()}") if(response.body()?.isSucces == true){ clearForm() } Toast.makeText(requireContext(), response.body()?.message, Toast.LENGTH_LONG).show() } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } else { Toast.makeText(requireContext(), "Selecciona una imagen", Toast.LENGTH_LONG).show() } } /////////////////////////////////////// private fun clearForm(){ editTextCategory?.setText("") imageFile = null imageViewCategory?.setImageResource(R.drawable.ic_image) } //////////FUNCIONES DE SESION private fun getUserFromSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } ////////////////////////////////////// ///////////SELECCIONAR IMAGEN private val startImageForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> val resultCode = result.resultCode val data = result.data if(resultCode == Activity.RESULT_OK){ val fileUri = data?.data imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewCategory?.setImageURI(fileUri) } else if (resultCode == ImagePicker.RESULT_ERROR){ Toast.makeText(requireContext(), ImagePicker.getError(data), Toast.LENGTH_LONG).show() } else { Toast.makeText(requireContext(), "Tarea se cancelo", Toast.LENGTH_LONG).show() } } private fun selectImage() { ImagePicker.with(this) .crop() .compress(1024) .maxResultSize(1080,1080) .createIntent { intent -> startImageForResult.launch(intent) } } ////////////////////////////////// }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantCategoryFragment.kt
1093867302
package com.andy.kotlindelivery.fragments.restaurant import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.andy.kotlindelivery.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [RestaurantOrdersFragment.newInstance] factory method to * create an instance of this fragment. */ class RestaurantOrdersFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_restaurant_orders, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment RestaurantOrdersFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = RestaurantOrdersFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantOrdersFragment.kt
436715949
package com.andy.kotlindelivery.fragments.delivery import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.andy.kotlindelivery.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [DeliveryOrdersFragment.newInstance] factory method to * create an instance of this fragment. */ class DeliveryOrdersFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_delivery_orders, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DeliveryOrdersFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = DeliveryOrdersFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/delivery/DeliveryOrdersFragment.kt
3196194907
package com.andy.kotlindelivery.fragments.client import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.andy.kotlindelivery.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ClientOrderaFragment.newInstance] factory method to * create an instance of this fragment. */ class ClientOrderFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_client_order, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ClientOrderaFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ClientOrderFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientOrderFragment.kt
2576615231
package com.andy.kotlindelivery.fragments.client import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.shopping_bag.ClientShoppingBagActivity import com.andy.kotlindelivery.adapters.CategoriasAdapters import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.CategoriasProviders import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response class ClientCategoriesFragment : Fragment() { val gson = Gson() var TAG = "ClientCategoriesFragment" var myView: View? = null var recyclerViewCategorias: RecyclerView? = null var categoriasProvider: CategoriasProviders? = null var adapter: CategoriasAdapters? = null var usuario: Usuario? = null var sharedPref: SharedPref? = null var categorias = ArrayList<Categoria>() var toolbar: Toolbar? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_client_categories, container, false) setHasOptionsMenu(true) toolbar = myView?.findViewById(R.id.toolbar) toolbar?.setTitleTextColor(ContextCompat.getColor(requireContext(), R.color.black)) toolbar?.title = "Categorias" (activity as AppCompatActivity).setSupportActionBar(toolbar) recyclerViewCategorias = myView?.findViewById(R.id.recyclerview_categorias) recyclerViewCategorias?.layoutManager = LinearLayoutManager(requireContext()) sharedPref = SharedPref(requireActivity()) getUserFromSession() categoriasProvider = CategoriasProviders(usuario?.sessionToken!!) Log.d(TAG, "categoriasProvider : ${usuario?.sessionToken!!}") getCategorias() return myView } //////// override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_shopping_bag, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if(item.itemId == R.id.item_shopping_bag){ goToShoppingBag() } return super.onOptionsItemSelected(item) } private fun goToShoppingBag(){ val i = Intent(requireContext(), ClientShoppingBagActivity::class.java) startActivity(i) } //////////////////////////////////////////////////// private fun getCategorias(){ Log.d(TAG, "getCategorias() : ${categoriasProvider}") categoriasProvider?.getAll()?.enqueue(object: Callback<ArrayList<Categoria>> { override fun onResponse(call: Call<ArrayList<Categoria>>, response: Response<ArrayList<Categoria>> ) { if(response.body() != null){ categorias = response.body()!! adapter = CategoriasAdapters(requireActivity(), categorias) recyclerViewCategorias?.adapter = adapter } } override fun onFailure(call: Call<ArrayList<Categoria>>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } private fun getUserFromSession() { //val sharedPref = SharedPref(this,) if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientCategoriesFragment.kt
3404397954
package com.andy.kotlindelivery.fragments.client import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.MainActivity import com.andy.kotlindelivery.activities.SelectRolesActivity import com.andy.kotlindelivery.activities.client.update.ClientUpdateActivity import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide import com.google.gson.Gson import de.hdodenhof.circleimageview.CircleImageView class ClientProfileFragment : Fragment() { var myView: View? = null var buttonSeleccinarRol : Button? = null var buttonUpdateProfile : Button? = null var circleImageUser:CircleImageView? = null var textViewNombre: TextView? = null var textViewCorreo: TextView? = null var textViewTelefono: TextView? = null var imageViewLogout: ImageView?= null var sharedPref: SharedPref? =null var usuario: Usuario? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_client_profile, container, false) sharedPref = SharedPref(requireActivity()) buttonSeleccinarRol = myView?.findViewById(R.id.btn_select_rol) buttonUpdateProfile = myView?.findViewById(R.id.btn_update_profile) textViewNombre = myView?.findViewById(R.id.textview_name) textViewCorreo = myView?.findViewById(R.id.textview_email) textViewTelefono= myView?.findViewById(R.id.textview_phone) circleImageUser = myView?.findViewById(R.id.circle_image_user) imageViewLogout = myView?.findViewById(R.id.imageview_logout) buttonSeleccinarRol?.setOnClickListener { goToRolSelect() } buttonUpdateProfile?.setOnClickListener { goToUpdate() } imageViewLogout?.setOnClickListener { logout() } getUserFormSession() textViewNombre?.text = "${usuario?.nombre} ${usuario?.apellido}" textViewCorreo?.text = usuario?.email textViewTelefono?.text = usuario?.telefono if(!usuario?.image.isNullOrBlank()){ Glide.with(requireContext()).load(usuario?.image).into(circleImageUser!!) } return myView } private fun getUserFormSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d("Fragment Client Profile", "Usuario: $usuario") } } private fun goToUpdate(){ val i = Intent(requireContext(), ClientUpdateActivity::class.java) startActivity(i) } private fun logout(){ sharedPref?.remove("user") val i = Intent(requireContext(), MainActivity::class.java) startActivity(i) } private fun goToRolSelect() { val i = Intent(requireContext(), SelectRolesActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(i) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientProfileFragment.kt
640256822
package com.andy.kotlindelivery.providers import com.andy.kotlindelivery.api.ApiRoutes import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.routers.UsuariosRoutes import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import java.io.File class UsuariosProviders(val token: String? = null) { private var usuariosRoutes: UsuariosRoutes? = null private var usuariosRoutesToken: UsuariosRoutes? = null init { val api =ApiRoutes() usuariosRoutes =api.getUsuariosRoutes() if(token != null){ usuariosRoutesToken = api.getUsuariosRoutesGetToken(token!!) } } fun register(usuario: Usuario): Call<ResponseHttp>?{ return usuariosRoutes?.register(usuario) } fun login(email: String, contrasena:String): Call<ResponseHttp>?{ return usuariosRoutes?.login(email, contrasena) } fun update(file:File, usuario: Usuario):Call<ResponseHttp>? { val reqFile = RequestBody.create(MediaType.parse("image/*"), file) val image = MultipartBody.Part.createFormData("image", file.name, reqFile) val requestBody = RequestBody.create(MediaType.parse("text/plain"), usuario.toJson()) return usuariosRoutesToken?.update(image, requestBody, token!!) } fun updateWhitoutImage(usuario: Usuario): Call<ResponseHttp>?{ return usuariosRoutesToken?.updateWithoutImage(usuario, token!!) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/UsuariosProviders.kt
1826269683
package com.andy.kotlindelivery.providers import com.andy.kotlindelivery.api.ApiRoutes import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.routers.CategoriasRoutes import com.andy.kotlindelivery.routers.ProductosRoutes import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import java.io.File class ProductosProviders(val token: String) { private var productosRoutes: ProductosRoutes? = null init { val api = ApiRoutes() productosRoutes = api.getProductosRoutes(token) } fun findByCategoria(idCategoria: String): Call<ArrayList<Producto>> ?{ return productosRoutes?.findByCategoria(idCategoria, token) } fun create(files: List<File>, producto: Producto): Call<ResponseHttp>? { val images = arrayOfNulls< MultipartBody.Part>(files.size) for (i in 0 until files.size) { val reqFile = RequestBody.create(MediaType.parse("image/*"), files[i]) images[i] = MultipartBody.Part.createFormData("image", files[i].name, reqFile) } val requestBody = RequestBody.create(MediaType.parse("text/plain"), producto.toJson()) return productosRoutes?.create(images, requestBody, token!!) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/ProductosProviders.kt
1434426178
package com.andy.kotlindelivery.providers import com.andy.kotlindelivery.api.ApiRoutes import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.routers.CategoriasRoutes import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import java.io.File class CategoriasProviders(val token: String) { private var categoriasRoutes: CategoriasRoutes? = null init { val api = ApiRoutes() categoriasRoutes = api.getCategoriasRoutesGetToken(token) } fun getAll(): Call<ArrayList<Categoria>> ?{ return categoriasRoutes?.getAll(token) } fun create(file: File, categoria: Categoria): Call<ResponseHttp>? { val reqFile = RequestBody.create(MediaType.parse("image/*"), file) val image = MultipartBody.Part.createFormData("image", file.name, reqFile) val requestBody = RequestBody.create(MediaType.parse("text/plain"), categoria.toJson()) return categoriasRoutes?.create(image, requestBody, token!!) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/CategoriasProviders.kt
1845768753
package com.andy.kotlindelivery.utils import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.util.Log import com.google.gson.Gson class SharedPref(activity:Activity) { private var prefs: SharedPreferences? = null init { prefs = activity.getSharedPreferences("com.andy.kotlindelivery", Context.MODE_PRIVATE) } //metodo que guarda la sesion fun save(key:String, objeto: Any) { try{ val gson = Gson() val json = gson.toJson(objeto) with(prefs?.edit()) { this?.putString(key, json) this?.commit() } }catch (e: Exception) { Log.d("ERROR", "Err: ${e.message}") } } //metodo que obtiene la data del metodo save() fun getData(key: String): String? { val data = prefs?.getString(key, "") return data } // FUNCION PARA CERRAR SESION fun remove(key: String){ prefs?.edit()?.remove(key)?.apply() } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/utils/SharedPref.kt
1144079281
package com.andy.kotlindelivery.models import com.google.gson.annotations.SerializedName class Rol ( @SerializedName("id") val id: String, @SerializedName("nombre") val nombre: String, @SerializedName("imagen") val imagen: String, @SerializedName("ruta") val ruta: String ){ override fun toString(): String { return "Rol(id='$id', nombre='$nombre', imagen='$imagen', ruta='$ruta')" } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Rol.kt
3544019830
package com.andy.kotlindelivery.models import com.google.gson.Gson import com.google.gson.annotations.SerializedName class Categoria( val id: String? = null, val nombre: String, val image: String? = null ) { fun toJson(): String { return Gson().toJson(this) } override fun toString(): String { //return "Categoria(id=$id, nombre=$nombre, image=$image)" return nombre } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Categoria.kt
645518434
package com.andy.kotlindelivery.models import com.google.gson.JsonObject import com.google.gson.annotations.SerializedName class ResponseHttp( @SerializedName("message") val message : String, @SerializedName("succes") val isSucces : Boolean, @SerializedName("data") val data : JsonObject, @SerializedName("error") val error : String, ) { override fun toString(): String { return "ResponseHttp(message='$message', isSucces=$isSucces, data=$data, error='$error')" } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/ResponseHttp.kt
290894754
package com.andy.kotlindelivery.models import com.google.gson.Gson import com.google.gson.annotations.SerializedName class Producto( @SerializedName("id") val id: String? = null, @SerializedName("nombre") val nombre: String, @SerializedName("descripcion") val descripcion: String, @SerializedName("precio") val precio: Double, @SerializedName("image1") val imagen1: String? = null, @SerializedName("image2") val imagen2: String? = null, @SerializedName("image3") val imagen3: String? = null, @SerializedName("id_categoria") val idCategoria: String, @SerializedName("quantity") var quantity: Int? = null, ) { fun toJson(): String { return Gson().toJson(this) } override fun toString(): String { return "Producto(id=$id, nombre='$nombre', descripcion='$descripcion', precio=$precio, imagen1=$imagen1, imagen2=$imagen2, imagen3=$imagen3, idCategoria='$idCategoria', quantity=$quantity)" } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Producto.kt
728315161
package com.andy.kotlindelivery.models import com.google.gson.Gson import com.google.gson.annotations.SerializedName class Usuario ( @SerializedName("id") var id : String? = null, @SerializedName("nombre") var nombre:String, @SerializedName("apellido") var apellido : String, @SerializedName("email") val email:String, @SerializedName("telefono") var telefono : String, @SerializedName("contrasena") val contrasena:String, @SerializedName("image") var image : String? = null, @SerializedName("session_token") val sessionToken:String? = null, @SerializedName("is_available") val is_available : Boolean? = null, @SerializedName("roles") val roles: ArrayList<Rol>? = null //array de objetos ) { override fun toString(): String { return "Usuario(id=$id, nombre='$nombre', apellido='$apellido', email='$email', telefono='$telefono', contrasena='$contrasena', image=$image, sessionToken=$sessionToken, is_available=$is_available, roles=$roles)" } fun toJson(): String { return Gson().toJson(this) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Usuario.kt
2859392721
package com.andy.kotlindelivery.adapters import android.app.Activity import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide class CategoriasAdapters (val context: Activity, val categorias:ArrayList<Categoria>): RecyclerView.Adapter<CategoriasAdapters.CategoriasViewHolder>() { val sharedPref = SharedPref(context) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoriasViewHolder{ val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_categorias, parent, false) ///instacias la vista en la que se esta trabajando return CategoriasViewHolder(view) } override fun getItemCount(): Int { return categorias.size } override fun onBindViewHolder(holder: CategoriasViewHolder, position: Int) { val categoria = categorias[position] // cada una de las categorias Log.d("Categorias adapter", "Categoiras : $categoria") holder.textViewCategoria.text = categoria.nombre Glide.with(context).load(categoria.image).into(holder.imageViewCategoria) holder.itemView.setOnClickListener { goToProductos( categoria ) } } private fun goToProductos( categoria: Categoria) { val i = Intent(context, ClientProductsListActivity::class.java) i.putExtra("idCategoria", categoria.id) context.startActivity(i) } class CategoriasViewHolder(view: View): RecyclerView.ViewHolder(view){ val textViewCategoria: TextView val imageViewCategoria: ImageView init { textViewCategoria = view.findViewById(R.id.textview_category) imageViewCategoria = view.findViewById(R.id.imageview_category) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/CategoriasAdapters.kt
262881218
package com.andy.kotlindelivery.adapters import android.app.Activity import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity import com.andy.kotlindelivery.activities.delivery.home.DeliveryHomeActivity import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity import com.andy.kotlindelivery.models.Rol import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide class RolesAdapters (val context: Activity, val roles:ArrayList<Rol>): RecyclerView.Adapter<RolesAdapters.RolesViewHolder>() { val sharedPref = SharedPref(context) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RolesViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_roles, parent, false) ///instacias la vista en la que se esta trabajando return RolesViewHolder(view) } override fun getItemCount(): Int { return roles.size } override fun onBindViewHolder(holder: RolesViewHolder, position: Int) { val rol = roles[position] holder.textViewRol.text = rol.nombre Glide.with(context).load(rol.imagen).into(holder.imageViewRol) holder.itemView.setOnClickListener { goToRol( rol ) } } private fun goToRol(rol: Rol) { val typeActivity = when( rol.nombre) { "RESTAURANTE" -> RestaurantHomeActivity::class.java "REPARTIDOR" -> DeliveryHomeActivity::class.java else -> ClientHomeActivity::class.java } sharedPref.save("rol", rol.nombre) val i = Intent(context, typeActivity) context.startActivity(i) } class RolesViewHolder(view: View): RecyclerView.ViewHolder(view){ val textViewRol: TextView val imageViewRol: ImageView init { textViewRol = view.findViewById(R.id.textView_rol) imageViewRol = view.findViewById(R.id.imageView_rol) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/RolesAdapters.kt
4225489925
package com.andy.kotlindelivery.adapters import android.app.Activity import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.products.details.ClientProductsDetailActivity import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide import com.google.gson.Gson class ProductosAdapters (val context: Activity, val productos:ArrayList<Producto>): RecyclerView.Adapter<ProductosAdapters.ProductosViewHolder>() { val sharedPref = SharedPref(context) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductosViewHolder{ val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_productos, parent, false) ///instacias la vista en la que se esta trabajando return ProductosViewHolder(view) } override fun getItemCount(): Int { return productos.size } override fun onBindViewHolder(holder: ProductosViewHolder, position: Int) { val producto = productos[position] // cada una de las categorias Log.d("Productos adapter", "Productos : $producto") holder.textViewNombre.text = producto.nombre holder.textViewPrecio.text = "$${producto.precio}" Glide.with(context).load(producto.imagen1).into(holder.imageViewProducto) holder.itemView.setOnClickListener { goToDetail( producto ) } } private fun goToDetail( producto: Producto) { val i = Intent(context, ClientProductsDetailActivity::class.java) i.putExtra("producto", producto.toJson()) context.startActivity(i) } class ProductosViewHolder(view: View): RecyclerView.ViewHolder(view){ val textViewNombre: TextView val textViewPrecio: TextView val imageViewProducto: ImageView init { textViewNombre = view.findViewById(R.id.txtview_nombre) textViewPrecio = view.findViewById(R.id.txtview_precio) imageViewProducto = view.findViewById(R.id.imageview_producto) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/ProductosAdapters.kt
4225021946
package com.andy.kotlindelivery.adapters import android.app.Activity import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.products.details.ClientProductsDetailActivity import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity import com.andy.kotlindelivery.activities.client.shopping_bag.ClientShoppingBagActivity import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide import com.google.gson.Gson import kotlin.math.sign class ShoppingBagAdapters (val context: Activity, val productos:ArrayList<Producto>): RecyclerView.Adapter<ShoppingBagAdapters.ShoppingBagViewHolder>() { val sharedPref = SharedPref(context) init{ (context as ClientShoppingBagActivity).setTotal(getTotal()) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingBagViewHolder{ val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_shopping_bag , parent, false) ///instacias la vista en la que se esta trabajando return ShoppingBagViewHolder(view) } override fun getItemCount(): Int { return productos.size } override fun onBindViewHolder(holder: ShoppingBagViewHolder, position: Int) { val producto = productos[position] // cada una de las categorias Log.d("Productos adapter", "Productos : $producto") holder.textViewNombre.text = producto.nombre holder.textViewPrecio.text = "$${producto.precio * producto.quantity!!}" holder.textViewContador.text = "${producto.quantity}" Glide.with(context).load(producto.imagen1).into(holder.imageViewProducto) holder.imageViewAdd.setOnClickListener { addItem(producto, holder) } holder.imageViewRemove.setOnClickListener { removeItem(producto, holder) } holder.imageViewDelete.setOnClickListener { deleteProducto(position) } // holder.itemView.setOnClickListener { goToDetail( producto ) } } private fun getTotal(): Double{ var total = 0.0 for(p in productos) { total = total + (p.quantity!! + p.precio) } return total } private fun deleteProducto(position: Int) { productos.removeAt(position) notifyItemRemoved(position) notifyItemRangeRemoved(position, productos.size) sharedPref.save("order", productos) (context as ClientShoppingBagActivity).setTotal(getTotal()) } ///// FUNCIONES PARA INCREMENTAR Y DECREMENTAR LA CANTIDAD DE PRODUCTOS private fun getIndexOf(idProducto: String): Int{ var pos = 0 for(p in productos) if(p.id == idProducto){ return pos } pos ++ return -1 } private fun addItem(producto: Producto, holder: ShoppingBagViewHolder){ val index = getIndexOf(producto.id!!) producto.quantity = producto.quantity!! +1 productos[index].quantity = producto.quantity holder.textViewContador.text = "${producto?.quantity}" holder.textViewPrecio.text = "$${producto.quantity!! * producto.precio}" sharedPref.save("order", productos) (context as ClientShoppingBagActivity).setTotal(getTotal()) } private fun removeItem(producto: Producto, holder: ShoppingBagViewHolder){ if(producto.quantity!! > 1) { val index = getIndexOf(producto.id!!) producto.quantity = producto.quantity!! -1 productos[index].quantity = producto.quantity holder.textViewContador.text = "${producto?.quantity}" holder.textViewPrecio.text = "$${producto.quantity!! * producto.precio}" sharedPref.save("order", productos) (context as ClientShoppingBagActivity).setTotal(getTotal()) } } // private fun goToDetail( producto: Producto) { // val i = Intent(context, ClientProductsDetailActivity::class.java) // i.putExtra("producto", producto.toJson()) // context.startActivity(i) // } ///INICIALIZA Y ASIGNA LAS VARIABLES DEL RECYCLERVIEW class ShoppingBagViewHolder(view: View): RecyclerView.ViewHolder(view){ val textViewNombre: TextView val textViewPrecio: TextView val imageViewProducto: ImageView val textViewContador: TextView val imageViewRemove: ImageView val imageViewAdd: ImageView val imageViewDelete: ImageView init { textViewNombre = view.findViewById(R.id.textview_nombre) textViewPrecio = view.findViewById(R.id.textview_precio) textViewContador = view.findViewById(R.id.textview_contador) imageViewRemove = view.findViewById(R.id.image_remove) imageViewAdd = view.findViewById(R.id.image_add) imageViewDelete = view.findViewById(R.id.image_delete) imageViewProducto = view.findViewById(R.id.imageview_producto) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/ShoppingBagAdapters.kt
927053026
package com.andy.kotlindelivery.api import com.andy.kotlindelivery.routers.CategoriasRoutes import com.andy.kotlindelivery.routers.ProductosRoutes import com.andy.kotlindelivery.routers.UsuariosRoutes class ApiRoutes { val API_URL = "http://192.168.100.92:3000/api/" val retrofit = RetrofitClient() fun getUsuariosRoutes(): UsuariosRoutes { return retrofit.getClient(API_URL).create(UsuariosRoutes::class.java) } fun getUsuariosRoutesGetToken(token: String): UsuariosRoutes{ return retrofit.getClientWebToken(API_URL, token).create(UsuariosRoutes::class.java) } fun getCategoriasRoutesGetToken(token: String): CategoriasRoutes{ return retrofit.getClientWebToken(API_URL, token).create(CategoriasRoutes::class.java) } fun getProductosRoutes(token: String): ProductosRoutes{ return retrofit.getClientWebToken(API_URL, token).create(ProductosRoutes::class.java) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/api/ApiRoutes.kt
3213437976
package com.andy.kotlindelivery.api import android.annotation.SuppressLint import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class RetrofitClient { fun getClient(url: String) : Retrofit { return Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .build() } fun getClientWebToken(url: String, token: String): Retrofit { val client = OkHttpClient.Builder() client.addInterceptor{ chain -> val request= chain.request() val newRequest =request.newBuilder().header("Authorization", token) chain.proceed(newRequest.build()) } return Retrofit.Builder() .baseUrl(url) .client(client.build()) .addConverterFactory(GsonConverterFactory.create()) .build() } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/api/RetrofitClient.kt
1260320848
package com.andy.kotlindelivery.activities.restaurant.home import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.MainActivity import com.andy.kotlindelivery.fragments.client.ClientProfileFragment import com.andy.kotlindelivery.fragments.restaurant.RestaurantCategoryFragment import com.andy.kotlindelivery.fragments.restaurant.RestaurantOrdersFragment import com.andy.kotlindelivery.fragments.restaurant.RestaurantProductFragment import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.utils.SharedPref import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.gson.Gson class RestaurantHomeActivity : AppCompatActivity() { private val TAG = "RestaurantHomeActivity" // var buttonLogout: Button? = null var sharedPref: SharedPref? = null var bottomNavigation: BottomNavigationView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_restaurant_home) sharedPref = SharedPref(this) //Abre el fragment por defecto openFragment(RestaurantOrdersFragment()) //buttonLogout = findViewById(R.id.btn_logout) //buttonLogout?.setOnClickListener { logout() } bottomNavigation = findViewById(R.id.bottom_navigation) bottomNavigation?.setOnItemSelectedListener { when (it.itemId){ R.id.item_home -> { openFragment(RestaurantOrdersFragment()) true } R.id.item_category -> { openFragment(RestaurantCategoryFragment()) true } R.id.item_product -> { openFragment(RestaurantProductFragment()) true } R.id.item_profile -> { openFragment(ClientProfileFragment()) true } else -> false } } getUserFormSession() } /// barra de navegacion private fun openFragment(fragment: Fragment){ val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } private fun logout(){ sharedPref?.remove("user") val i = Intent(this, MainActivity::class.java) startActivity(i) } private fun getUserFormSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $user") } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/restaurant/home/RestaurantHomeActivity.kt
3069758857
package com.andy.kotlindelivery.activities import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.os.Bundle import android.text.TextUtils import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity import com.andy.kotlindelivery.activities.delivery.home.DeliveryHomeActivity import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.UsuariosProviders import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { var imageViewGotoRegister: ImageView? = null var editTxtEmail: EditText? = null var editTxTContrasena: EditText? = null var btnLogin: Button? = null var usuarioProvider = UsuariosProviders() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) imageViewGotoRegister = findViewById(R.id.imgview_goregister) editTxtEmail = findViewById(R.id.edittxt_email) editTxTContrasena = findViewById(R.id.edittxt_contrasena) btnLogin = findViewById(R.id.btn_login) imageViewGotoRegister?.setOnClickListener{ goToRegister() } btnLogin?.setOnClickListener { login() } getUserFromSession() } private fun login(){ val email = editTxtEmail?.text.toString() //NULL POINTE EXCEPTION val contrasena = editTxTContrasena?.text.toString() if (isValidForm(email,contrasena)) { usuarioProvider.login(email,contrasena)?.enqueue(object : Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) { Log.d("MainActivity", "Respuesta: ${response.body()}" ) Log.d("MainActivity", "Datos enviados: ${email} " ) Log.d("MainActivity", "Datos enviados: ${contrasena} " ) if(response.body()?.isSucces == true) { Toast.makeText(this@MainActivity, response.body()?.message, Toast.LENGTH_LONG).show() saveUserInSession(response.body()?.data.toString()) //goToClientHome() } else { Toast.makeText(this@MainActivity, "Los datos son incorrectos1", Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d("MainActivity", "Hubo un error ${t.message}") Toast.makeText(this@MainActivity, "Hubo un error ${t.message}", Toast.LENGTH_LONG).show() } }) } else { Toast.makeText(this@MainActivity, "No es valido", Toast.LENGTH_LONG).show() } } private fun goToClientHome() { val i = Intent(this, ClientHomeActivity::class.java) i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK //ELIMINA EL HISTORIAL DE PANTALLA startActivity(i) } private fun goToRestaurantHome() { val i = Intent(this, RestaurantHomeActivity::class.java) i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK startActivity(i) } private fun goToDeliveryHome() { val i = Intent(this, DeliveryHomeActivity::class.java) i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK startActivity(i) } private fun goToRolSelect() { val i = Intent(this, SelectRolesActivity::class.java) i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK startActivity(i) } private fun saveUserInSession(data: String) { val sharedPreferences = SharedPref(this) val gson = Gson() val user = gson.fromJson(data, Usuario::class.java) sharedPreferences.save("user", user) if (user.roles?.size!! > 1){ //tiene mas de un rol goToRolSelect() } else { //tiene un rol goToClientHome() } } fun String.isEmailValid() : Boolean{ return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches() } //Ya que la sesion ha sido iniciada nos mandara directamente a la pantalla de ClientHomeActivity private fun getUserFromSession() { val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion val user = gson.fromJson(sharedPref.getData("user"), Usuario::class.java) Log.d("MainActivity","Usuario: $user") if(!sharedPref.getData("rol").isNullOrBlank()) { val rol = sharedPref.getData("rol")?.replace("\"", "") Log.d("MainActivity", "Rol $rol") when( rol ){ "RESTAURANTE" -> goToRestaurantHome() "REPARTIDOR" -> goToDeliveryHome() "CLIENTE" -> goToClientHome() else -> goToClientHome() } } } } private fun isValidForm(email:String, contrasena:String) : Boolean{ if(email.isBlank()) { Toast.makeText(this,"Debes ingresar el email", Toast.LENGTH_LONG).show() return false } if(contrasena.isBlank()) { Toast.makeText(this,"Debes ingresar la contraseña", Toast.LENGTH_LONG).show() return false } if(!email.isEmailValid()) { return false } return true } private fun goToRegister(){ val i = Intent( this, RegisterActivity::class.java) startActivity(i) finish() } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/MainActivity.kt
2837446731
package com.andy.kotlindelivery.activities import android.content.ContentValues.TAG import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.UsuariosProviders import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response class RegisterActivity : AppCompatActivity() { var imageViewLogin: ImageView? = null var editTxtNombre : EditText? = null var editTxtApellido : EditText? = null var editTxtEmailRegs : EditText? = null var editTxtTelefono : EditText? = null var editTxtContrasenaRegs : EditText? = null var editTxtContrasenaConfirm : EditText? = null var btnRegistro : Button? = null // var usuariosProviders = UsuariosProviders() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) imageViewLogin = findViewById(R.id.imgview_gologin) editTxtNombre = findViewById(R.id.edittxt_nombre) editTxtApellido = findViewById(R.id.edittxt_apellido) editTxtEmailRegs = findViewById(R.id.edittxt_emailregister) editTxtTelefono = findViewById(R.id.edittxt_telelfono) editTxtContrasenaRegs = findViewById(R.id.edittxt_contrasenaregister) editTxtContrasenaConfirm = findViewById(R.id.edittxt_contrasenaconfirm) btnRegistro = findViewById(R.id.btn_registro) imageViewLogin?.setOnClickListener{ gotoLogin() } btnRegistro?.setOnClickListener { register() } } private fun register(){ var nombre = editTxtNombre?.text.toString() var apellido = editTxtApellido?.text.toString() var emailRegistro = editTxtEmailRegs?.text.toString() var telefono = editTxtTelefono?.text.toString() var contrasenaRegistro = editTxtContrasenaRegs?.text.toString() var contrasenaConfirmacion = editTxtContrasenaConfirm?.text.toString() if(isValidForm(nombre=nombre, apellido=apellido, emailRegistro=emailRegistro, telefono=telefono, contrasenaRegistro=contrasenaRegistro, contrasenaConfirma=contrasenaConfirmacion)){ val usuario = Usuario( nombre = nombre, apellido = apellido, email = emailRegistro, telefono = telefono, contrasena = contrasenaRegistro ) usuariosProviders.register(usuario)?.enqueue(object: Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp> ) { if(response.body()?.isSucces == true) { saveUserInSession(response.body()?.data.toString()) goToClientHome() } Toast.makeText(this@RegisterActivity, response.body()?.message, Toast.LENGTH_LONG).show() Log.d( TAG, "Response: $response" ) Log.d( TAG, "Body: ${response.body()}" ) Log.d(TAG, "Los datos son: ${usuario} ") } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d(TAG, "Se produjo un error ${t.message}") Toast.makeText(this@RegisterActivity, "Se produjo un error ${t.message}", Toast.LENGTH_LONG).show() } }) // Toast.makeText(this, "El formulario es valido", Toast.LENGTH_SHORT).show() } } //////////////////////////////////////// private fun goToClientHome() { //val i = Intent(this, ClientHomeActivity::class.java) val i = Intent(this, SaveImageActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(i) } private fun saveUserInSession(data: String) { val sharedPreferences = SharedPref(this) val gson = Gson() val user = gson.fromJson(data, Usuario::class.java) sharedPreferences.save("user", user) } /////////////////////////////// fun String.isEmailValid() : Boolean{ return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches() } private fun isValidForm( nombre : String, apellido : String, emailRegistro : String, telefono : String, contrasenaRegistro : String, contrasenaConfirma : String ) : Boolean{ if(nombre.isBlank()) { Toast.makeText(this,"Debes ingresar el nombre", Toast.LENGTH_LONG).show() return false } if(apellido.isBlank()) { Toast.makeText(this,"Debes ingresar el apellido", Toast.LENGTH_LONG).show() return false } if(emailRegistro.isBlank()) { Toast.makeText(this,"Debes ingresar el email", Toast.LENGTH_LONG).show() return false } if(telefono.isBlank()) { Toast.makeText(this,"Debes ingresar el telefono", Toast.LENGTH_LONG).show() return false } if(contrasenaRegistro.isBlank()) { Toast.makeText(this,"Debes ingresar la contraseña", Toast.LENGTH_LONG).show() return false } if(contrasenaConfirma.isBlank()) { Toast.makeText(this,"Debes volver a introducir la contraseña", Toast.LENGTH_LONG).show() return false } if(!emailRegistro.isEmailValid()) { return false } if(contrasenaRegistro != contrasenaConfirma) { Toast.makeText(this,"Las contraseñas no coinciden", Toast.LENGTH_LONG).show() } return true } private fun gotoLogin() { val i = Intent(this, MainActivity::class.java) startActivity(i) finish() } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/RegisterActivity.kt
873369646
package com.andy.kotlindelivery.activities import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import com.andy.kotlindelivery.R import com.github.dhaval2404.imagepicker.ImagePicker import de.hdodenhof.circleimageview.CircleImageView import java.io.File import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.UsuariosProviders import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response class SaveImageActivity : AppCompatActivity() { var TAG = "SaveImageActivity" var circleImageUser: CircleImageView? = null var buttonNext: Button? = null var buttonConfirm: Button? = null private var imageFile: File? = null var userProvider: UsuariosProviders? =null var user: Usuario? = null var sharedPref: SharedPref? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_save_imagectivity) sharedPref = SharedPref(this) getUserFormSession() userProvider = UsuariosProviders(user?.sessionToken) circleImageUser = findViewById(R.id.cirlce_image) buttonConfirm = findViewById(R.id.btn_confirm) buttonNext = findViewById(R.id.btn_next) circleImageUser?.setOnClickListener{ selectImage() } buttonNext?.setOnClickListener{ goToClientHome() } buttonConfirm?.setOnClickListener{ saveImage() } } private fun saveImage() { if(imageFile != null && user != null ) { userProvider?.update(imageFile!!, user!!)?.enqueue(object : Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp> ) { Log.d(TAG, "RESPONSE: $response") Log.d(TAG, "BODY: ${response.body()}") saveUserInSession(response.body()?.data.toString()) } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(this@SaveImageActivity, "Error ${t.message}", Toast.LENGTH_LONG) .show() } }) } else { Toast.makeText(this@SaveImageActivity, "Los datos del usuario no pueden ser nulas", Toast.LENGTH_LONG).show() } } private fun saveUserInSession(data: String) { val gson = Gson() val user = gson.fromJson(data, Usuario::class.java) sharedPref?.save("user", user) goToClientHome() } private fun goToClientHome() { val i = Intent(this, ClientHomeActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK //ELIMINA EL HISTORIAL DE PANTALLA startActivity(i) } private fun getUserFormSession() { val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) } } private val startImageForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> val resultCode = result.resultCode val data = result.data if(resultCode == Activity.RESULT_OK){ val fileUri = data?.data imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor circleImageUser?.setImageURI(fileUri) } else if (resultCode == ImagePicker.RESULT_ERROR){ Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_LONG).show() } else { Toast.makeText(this, "Tarea se cancelo", Toast.LENGTH_LONG).show() } } private fun selectImage() { ImagePicker.with(this) .crop() .compress(1024) .maxResultSize(1080,1080) .createIntent { intent -> startImageForResult.launch(intent) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/SaveImageActivity.kt
421572402
package com.andy.kotlindelivery.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.adapters.RolesAdapters import com.andy.kotlindelivery.models.Rol import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson class SelectRolesActivity : AppCompatActivity() { var recyclerViewRoles: RecyclerView? = null var user: Usuario? = null var adapter: RolesAdapters? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_select_roles) recyclerViewRoles = findViewById(R.id.recyclerview_roles) recyclerViewRoles?.layoutManager = LinearLayoutManager(this) getUserFromSession() adapter = RolesAdapters(this, user?.roles!!) recyclerViewRoles?.adapter = adapter } private fun getUserFromSession() { val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion user = gson.fromJson(sharedPref.getData("user"), Usuario::class.java) } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/SelectRolesActivity.kt
2319649508
package com.andy.kotlindelivery.activities.delivery.home import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.MainActivity import com.andy.kotlindelivery.fragments.client.ClientProfileFragment import com.andy.kotlindelivery.fragments.delivery.DeliveryOrdersFragment import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.utils.SharedPref import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.gson.Gson class DeliveryHomeActivity : AppCompatActivity() { private val TAG = "DeliveryHomeActivity" // var buttonLogout: Button? = null var sharedPref: SharedPref? = null var bottomNavigation: BottomNavigationView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_delivery_home) sharedPref = SharedPref(this) //Abre el fragment por defecto openFragment(DeliveryOrdersFragment()) //buttonLogout = findViewById(R.id.btn_logout) //buttonLogout?.setOnClickListener { logout() } bottomNavigation = findViewById(R.id.bottom_navigation) bottomNavigation?.setOnItemSelectedListener { when (it.itemId){ R.id.item_orders -> { openFragment(DeliveryOrdersFragment()) true } R.id.item_profile -> { openFragment(ClientProfileFragment()) true } else -> false } } getUserFormSession() } /// barra de navegacion private fun openFragment(fragment: Fragment){ val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } private fun logout(){ sharedPref?.remove("user") val i = Intent(this, MainActivity::class.java) startActivity(i) } private fun getUserFormSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $user") } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/delivery/home/DeliveryHomeActivity.kt
908429420
package com.andy.kotlindelivery.activities.client.shopping_bag import android.content.res.ColorStateList import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.andy.kotlindelivery.R import com.andy.kotlindelivery.adapters.ShoppingBagAdapters import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import com.google.gson.reflect.TypeToken class ClientShoppingBagActivity : AppCompatActivity() { var recyclerViewShoppingBag: RecyclerView? = null var btnNext: Button? = null var textViewTotal: TextView? = null var toolbar: Toolbar? = null var adapter: ShoppingBagAdapters? = null var sharedPref: SharedPref? = null var gson = Gson() var seleeccionarProducto = ArrayList<Producto>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_client_shopping_bag) sharedPref = SharedPref(this) recyclerViewShoppingBag = findViewById(R.id.recyclerview_shopping_bag) btnNext = findViewById(R.id.btn_next) textViewTotal = findViewById(R.id.textview_total) toolbar = findViewById(R.id.toolbar) toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black)) toolbar?.title = "Tu orden" setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) //habilita la flecha hacia atras recyclerViewShoppingBag?.layoutManager = LinearLayoutManager(this) getPoductosFromSharedPref() } fun setTotal(total: Double){ textViewTotal?. text = "$${total}" } private fun getPoductosFromSharedPref(){ Log.d("getPoductosFrom", "SahredPref antes del if ${sharedPref?.getData("order")} ") if(!sharedPref?.getData("order").isNullOrBlank()) { val type = object: TypeToken<ArrayList<Producto>>() {}.type seleeccionarProducto = gson.fromJson(sharedPref?.getData("order"), type) adapter = ShoppingBagAdapters(this, seleeccionarProducto) recyclerViewShoppingBag?.adapter = adapter } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/shopping_bag/ClientShoppingBagActivity.kt
1304639856
package com.andy.kotlindelivery.activities.client.home import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import com.andy.kotlindelivery.R import com.andy.kotlindelivery.activities.MainActivity import com.andy.kotlindelivery.fragments.client.ClientCategoriesFragment import com.andy.kotlindelivery.fragments.client.ClientOrderFragment import com.andy.kotlindelivery.fragments.client.ClientProfileFragment import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.utils.SharedPref import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.gson.Gson class ClientHomeActivity : AppCompatActivity() { private val TAG = "ClientHomeActivity" // var buttonLogout: Button? = null var sharedPref: SharedPref? = null var bottomNavigation: BottomNavigationView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_client_home) sharedPref = SharedPref(this) //Abre el fragment por defecto openFragment(ClientCategoriesFragment()) //buttonLogout = findViewById(R.id.btn_logout) //buttonLogout?.setOnClickListener { logout() } bottomNavigation = findViewById(R.id.bottom_navigation) bottomNavigation?.setOnItemSelectedListener { when (it.itemId){ R.id.item_home -> { openFragment(ClientCategoriesFragment()) true } R.id.item_orders -> { openFragment(ClientOrderFragment()) true } R.id.item_profile -> { openFragment(ClientProfileFragment()) true } else -> false } } getUserFromSession() } /// barra de navegacion private fun openFragment(fragment: Fragment){ val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } private fun logout(){ sharedPref?.remove("user") val i = Intent(this, MainActivity::class.java) startActivity(i) } private fun getUserFromSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $user") } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/home/ClientHomeActivity.kt
3310047127
package com.andy.kotlindelivery.activities.client.products.details import android.content.Intent import android.content.res.ColorStateList import android.graphics.Color import android.media.Image import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.andy.kotlindelivery.R import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.utils.SharedPref import com.denzcoskun.imageslider.ImageSlider import com.denzcoskun.imageslider.constants.ScaleTypes import com.denzcoskun.imageslider.models.SlideModel import com.google.gson.Gson import com.google.gson.reflect.TypeToken class ClientProductsDetailActivity : AppCompatActivity() { var TAG = "ClientProductsDetailActivity" var producto: Producto? = null val gson = Gson() var imagenSlider: ImageSlider? = null var txtviewNombre: TextView? = null var txtviewDescripcion: TextView? = null var txtviewContador: TextView? = null var txtviewPrecio: TextView? = null var imageViewAdd: ImageView? = null var imageViewRemove: ImageView? = null var btnAddProducto: Button? = null var contador = 1 var productoPrecio = 0.0 var sharedPref: SharedPref? = null var seleeccionarProducto = ArrayList<Producto>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_client_products_detail) producto = gson.fromJson(intent.getStringExtra("producto"), Producto::class.java) //Log.d(TAG, "Producto $producto") imagenSlider = findViewById(R.id.imageSlider) txtviewNombre = findViewById(R.id.txtview_nombre) txtviewDescripcion = findViewById(R.id.txtview_descripcion) txtviewContador= findViewById(R.id.textview_contador) txtviewPrecio = findViewById(R.id.textview_precio) imageViewAdd= findViewById(R.id.image_add) imageViewRemove= findViewById(R.id.image_remove) btnAddProducto= findViewById(R.id.btn_add_product) sharedPref = SharedPref(this) Log.d(TAG, "SahredPref al inicio ${sharedPref?.getData("order")} ") val imageList = ArrayList<SlideModel>() imageList.add(SlideModel(producto?.imagen1, ScaleTypes.CENTER_CROP)) imageList.add(SlideModel(producto?.imagen2, ScaleTypes.CENTER_CROP)) imageList.add(SlideModel(producto?.imagen3, ScaleTypes.CENTER_CROP)) //Log.d(TAG, "Array de producto $imageList") imagenSlider?.setImageList(imageList) txtviewNombre?.text = producto?.nombre txtviewDescripcion?.text = producto?.descripcion txtviewPrecio?.text = "$${producto?.precio}" imageViewAdd?.setOnClickListener { addItem() } imageViewRemove?.setOnClickListener { removeItem() } btnAddProducto?.setOnClickListener { addToBag() } getPoductosFromSharedPref() } private fun addToBag(){ val index = getIndexOf(producto?.id!!) //indice del producto Log.d(TAG, "addToBag ->Producto id: ${producto?.id!!}") if(index == -1){ //este producto no existe aun en sharedpref if(producto?.quantity == null) { producto?.quantity = 1 } seleeccionarProducto.add(producto!!) } else { //ya existe el producto en shared pref y se edita la cantidad seleeccionarProducto[index].quantity = contador } sharedPref?.save("order", seleeccionarProducto) //Log.d(TAG, "sharedPref: ${sharedPref}") Log.d(TAG, "addToBag: ${seleeccionarProducto}") Toast.makeText(this, "Producto agregado", Toast.LENGTH_LONG).show() } private fun getPoductosFromSharedPref(){ Log.d("getPoductosFrom", "SahredPref antes del if ${sharedPref?.getData("order")} ") if(!sharedPref?.getData("order").isNullOrBlank()) { val type = object: TypeToken<ArrayList<Producto>>() {}.type seleeccionarProducto = gson.fromJson(sharedPref?.getData("order"), type) val index = getIndexOf(producto?.id!!) if(index != -1){ producto?.quantity = seleeccionarProducto[index].quantity txtviewContador?.text = "${producto?.quantity}" productoPrecio = producto?.precio!! * producto?.quantity!! txtviewPrecio?.text = "${productoPrecio}" btnAddProducto?.setText("Editar producto") btnAddProducto?.backgroundTintList = ColorStateList.valueOf(Color.RED) } for( p in seleeccionarProducto) { Log.d("getPoductosFrom", "Shared pref: $p") } } Log.d("getPoductosFrom", "SahredPref despues del if ${sharedPref?.getData("order")} ") } //METODO QUE COMPARA SI YA EXISTE EN SHARED PREF Y ASI PODER EDITAR LA CANTIDAD private fun getIndexOf(idProducto: String): Int{ var pos = 0 for(p in seleeccionarProducto) if(p.id == idProducto){ return pos } pos ++ return -1 } private fun addItem(){ contador++ productoPrecio = producto?.precio!! * contador producto?.quantity = contador txtviewContador?.text = "${producto?.quantity}" txtviewPrecio?.text = "$${productoPrecio}" } private fun removeItem(){ if(contador > 1) { contador-- productoPrecio = producto?.precio!! * contador producto?.quantity = contador txtviewContador?.text = "${producto?.quantity}" txtviewPrecio?.text = "$${productoPrecio}" } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/products/details/ClientProductsDetailActivity.kt
3648501094
package com.andy.kotlindelivery.activities.client.products.list import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.Adapter import com.andy.kotlindelivery.R import com.andy.kotlindelivery.adapters.CategoriasAdapters import com.andy.kotlindelivery.adapters.ProductosAdapters import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.CategoriasProviders import com.andy.kotlindelivery.providers.ProductosProviders import com.andy.kotlindelivery.utils.SharedPref import com.google.gson.Gson import retrofit2.Call import retrofit2.Callback import retrofit2.Response class ClientProductsListActivity : AppCompatActivity() { var TAG = "ClientProductsListActivity" var recyclerViewProductos: RecyclerView? = null var adapter: ProductosAdapters? = null var usuario: Usuario? = null var productosProviders: ProductosProviders? = null var productos: ArrayList<Producto> = ArrayList() var toolbar: Toolbar? = null var sharedPref: SharedPref? = null var idCategoria: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_client_products_list) idCategoria = intent.getStringExtra("idCategoria") Log.d(TAG,"Id categoria: $idCategoria") recyclerViewProductos = findViewById(R.id.recyclerview_productos) recyclerViewProductos?.layoutManager = GridLayoutManager(this, 2) toolbar =findViewById(R.id.toolbar) toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black)) toolbar?.title = "Productos" setSupportActionBar(toolbar) sharedPref = SharedPref(this) getUserFromSession() productosProviders = ProductosProviders(usuario?.sessionToken!!) getProductos() } private fun getProductos(){ productosProviders?.findByCategoria(idCategoria!!)?.enqueue(object: Callback<ArrayList<Producto>> { override fun onResponse( call: Call<ArrayList<Producto>>, response: Response<ArrayList<Producto>> ) { Log.d(TAG,"Response: ${response.body()}") if(response.body() != null){ productos = response.body()!! adapter = ProductosAdapters(this@ClientProductsListActivity, productos) recyclerViewProductos?.adapter = adapter } } override fun onFailure(call: Call<ArrayList<Producto>>, t: Throwable) { Toast.makeText(this@ClientProductsListActivity, t.message, Toast.LENGTH_LONG).show() Log.d(TAG,"Error: ${t.message}") } }) } /////funciones de sesion private fun getUserFromSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/products/list/ClientProductsListActivity.kt
1627037962
package com.andy.kotlindelivery.activities.client.update import android.app.Activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import com.andy.kotlindelivery.R import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.UsuariosProviders import com.andy.kotlindelivery.utils.SharedPref import com.bumptech.glide.Glide import com.github.dhaval2404.imagepicker.ImagePicker import com.google.gson.Gson import de.hdodenhof.circleimageview.CircleImageView import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File class ClientUpdateActivity : AppCompatActivity() { var circleImageUsuario: CircleImageView? = null var editTextNombre: EditText? = null var editTextApellido: EditText? = null var editTextTelefono: EditText? = null var buttonActualizar: Button? = null val TAG = "Client Update Activity" var sharedPref: SharedPref? = null var usuario: Usuario? = null private var imageFile: File? = null var userProvider : UsuariosProviders? = null var toolbar: Toolbar? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_client_update) sharedPref = SharedPref(this) toolbar = findViewById(R.id.toolbar) toolbar?.title = "Editar perfil" toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black)) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) // nos muestra la fecla de ir hacia atras circleImageUsuario = findViewById(R.id.circle_image_user) editTextNombre = findViewById(R.id.edittxt_nombre) editTextApellido = findViewById(R.id.edittxt_apellido) editTextTelefono = findViewById(R.id.edittxt_telelfono) buttonActualizar = findViewById(R.id.btn_update) getUserFromSession() userProvider = UsuariosProviders(usuario?.sessionToken) editTextNombre?.setText(usuario?.nombre) editTextApellido?.setText(usuario?.apellido) editTextTelefono?.setText(usuario?.telefono) if (!usuario?.image.isNullOrBlank()) { Glide.with(this).load(usuario?.image).into(circleImageUsuario!!) } circleImageUsuario?.setOnClickListener { selectImage() } buttonActualizar?.setOnClickListener { updateData() } } private fun getUserFromSession() { //val sharedPref = SharedPref(this,) val gson = Gson() if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } private val startImageForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> val resultCode = result.resultCode val data = result.data if(resultCode == Activity.RESULT_OK){ val fileUri = data?.data imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor circleImageUsuario?.setImageURI(fileUri) } else if (resultCode == ImagePicker.RESULT_ERROR){ Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_LONG).show() } else { Toast.makeText(this, "Tarea se cancelo", Toast.LENGTH_LONG).show() } } private fun selectImage() { ImagePicker.with(this) .crop() .compress(1024) .maxResultSize(1080,1080) .createIntent { intent -> startImageForResult.launch(intent) } } private fun updateData() { var nombre = editTextNombre?.text.toString() var apellido = editTextApellido?.text.toString() var telefono = editTextTelefono?.text.toString() usuario?.nombre = nombre usuario?.apellido = apellido usuario?.telefono = telefono if(imageFile != null) { userProvider?.update(imageFile!!, usuario!!)?.enqueue(object : Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) { Log.d(TAG, "RESPONSE: $response") Log.d(TAG, "BODY: ${response.body()}") Toast.makeText(this@ClientUpdateActivity, response.body()?.message, Toast.LENGTH_LONG).show() if(response.body()?.isSucces == true){ saveUserInSession(response.body()?.data.toString()) } } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(this@ClientUpdateActivity, "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } else { userProvider?.updateWhitoutImage(usuario!!)?.enqueue(object : Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) { Log.d(TAG, "RESPONSE: $response") Log.d(TAG, "BODY: ${response.body()}") Toast.makeText(this@ClientUpdateActivity, response.body()?.message, Toast.LENGTH_LONG).show() if(response.body()?.isSucces == true){ saveUserInSession(response.body()?.data.toString()) } } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(this@ClientUpdateActivity, "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } } private fun saveUserInSession(data: String) { val gson = Gson() val user = gson.fromJson(data, Usuario::class.java) sharedPref?.save("user", user) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/update/ClientUpdateActivity.kt
3744052627
package com.example import com.example.db.ProductsTable import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.transactions.transaction import java.util.UUID fun getTestDb(): Database { return Database.connect( url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", user = "test", driver = "org.h2.Driver", password = "test", ) } fun initTestDb(db: Database) { transaction(db) { SchemaUtils.create(ProductsTable) ProductsTable.insert { it[id] = 1L it[uuid] = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4") it[name] = "Diablo IV" it[amount] = 10L } ProductsTable.insert { it[id] = 2L it[uuid] = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3") it[name] = "Overwatch 2" it[amount] = 1L } ProductsTable.insert { it[id] = 3L it[uuid] = UUID.fromString("d2c02017-61f7-4609-9fa0-da6887aff9c6") it[name] = "Half-Life 3" it[amount] = 10000L } ProductsTable.insert { it[id] = 4L it[uuid] = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc") it[name] = "CyberPunk 2077" it[amount] = 50L } ProductsTable.insert { it[id] = 5L it[uuid] = UUID.fromString("1603b0c2-952e-4400-89b4-49d2e3ee0e62") it[name] = "God of War: Ragnarok" it[amount] = 5L } } }
amount-counter/src/test/kotlin/com/example/TestDb.kt
3018174946
package com.example import com.example.plugins.configureMonitoring import com.example.plugins.configureRouting import com.example.plugins.configureSerialization import com.example.plugins.configureSwagger import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.matchers.shouldBe import io.ktor.client.HttpClient import io.ktor.client.request.get import io.ktor.http.HttpStatusCode.Companion.OK import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import org.junit.jupiter.api.Test class ApplicationTest { @Test fun `app should be configured without any exceptions`() { shouldNotThrowAny { testApplication { application { val db = getTestDb() configurePlugins() configureRouting(db) } } } } @Test fun `monitoring request returns OK(200) response`() { testApplication { testHttpClient().get("/metrics-micrometer").status shouldBe OK } } @Test fun `swagger request returns OK(200) response`() { testApplication { testHttpClient().get("/docs/swagger").status shouldBe OK } } private fun ApplicationTestBuilder.testHttpClient(): HttpClient { environment { module { configureMonitoring() configureSwagger() configureSerialization() } } return createClient {} } }
amount-counter/src/test/kotlin/com/example/ApplicationTest.kt
962364274
package com.example.routing import com.example.db.ProductsTable import com.example.dto.IdsRequestDto import com.example.getTestDb import com.example.initTestDb import com.example.plugins.configureSerialization import com.example.service.PdfPrinterService import com.example.service.ProductsService import configureExceptionHandling import io.kotest.assertions.assertSoftly import io.kotest.matchers.shouldBe import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import io.mockk.every import io.mockk.mockk import kotlinx.serialization.json.Json import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.transactions.transaction import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test class ProductRoutingTest { private val db = getTestDb().also { initTestDb(it) } private val service = ProductsService(db) @AfterAll fun tearDown() { transaction(db) { SchemaUtils.drop(ProductsTable) } } @Test fun `get products endpoint should return correct JSON and status code OK(200)`() { testApplication { val expectedJson = Json.parseToJsonElement( """ [ { "id": "bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4", "name": "Diablo IV", "amount": 10 }, { "id": "bf70093e-a4d4-461b-86ff-6515feee9bb3", "name": "Overwatch 2", "amount": 1 }, { "id": "d2c02017-61f7-4609-9fa0-da6887aff9c6", "name": "Half-Life 3", "amount": 10000 }, { "id": "a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc", "name": "CyberPunk 2077", "amount": 50 }, { "id": "1603b0c2-952e-4400-89b4-49d2e3ee0e62", "name": "God of War: Ragnarok", "amount": 5 } ] """, ) assertSoftly(testHttpClient().get("/api/getProducts")) { Json.parseToJsonElement(bodyAsText()) shouldBe expectedJson status shouldBe HttpStatusCode.OK } } } @Test fun `get summary endpoint should return status code OK(200)`() { testApplication { testHttpClient().post( "/api/getSummary", ) { setBody( IdsRequestDto( ids = listOf( "bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4", "bf70093e-a4d4-461b-86ff-6515feee9bb3", "d2c02017-61f7-4609-9fa0-da6887aff9c6", ), ), ) contentType(ContentType.Application.Json) }.status shouldBe HttpStatusCode.OK } } @Test fun `get summary endpoint should return status code BadRequest(400) in case of not existed ids requested`() { testApplication { testHttpClient().post( "/api/getSummary", ) { setBody( IdsRequestDto( ids = listOf( "bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4", "bf70093e-a4d4-461b-86ff-6515feee9bb3", "111111", ), ), ) contentType(ContentType.Application.Json) }.status shouldBe HttpStatusCode.BadRequest } } @Test fun `get summary endpoint should return status code BadRequest(400) in case ids not provided`() { testApplication { testHttpClient().post("/api/getSummary").status shouldBe HttpStatusCode.BadRequest } } @Test fun `get summary endpoint should return status code internal server error (500) in case ids not provided`() { testApplication { val pdfPrinterService = mockk<PdfPrinterService>().also { every { it.printProductSummaryToByteArray(any()) } throws NumberFormatException() } testHttpClient(pdfPrinterService = pdfPrinterService).post( "/api/getSummary", ) { setBody(IdsRequestDto(listOf("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"))) contentType(ContentType.Application.Json) }.status shouldBe HttpStatusCode.InternalServerError } } @Test fun `get summary endpoint should return status code internal server error (500) in case of uncaught exception`() { testApplication { val productsService = mockk<ProductsService>().also { every { it.getProductsSummary(any()) } throws NullPointerException() } testHttpClient(productsService = productsService).post( "/api/getSummary", ) { setBody(IdsRequestDto(listOf("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"))) contentType(ContentType.Application.Json) }.status shouldBe HttpStatusCode.InternalServerError } } private fun ApplicationTestBuilder.testHttpClient( productsService: ProductsService = service, pdfPrinterService: PdfPrinterService = PdfPrinterService(), ): HttpClient { environment { module { configureExceptionHandling() configureSerialization() configureProductRouting(productsService, pdfPrinterService) } } return createClient { install(ContentNegotiation) { json() } } } }
amount-counter/src/test/kotlin/com/example/routing/ProductRoutingTest.kt
944924279
package com.example.service import com.example.model.ProductsSummary import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow class PdfPrinterServiceTest { private val service = PdfPrinterService() @Test fun `pdf printer service print product summary should not throw any exceptions`() { assertDoesNotThrow { service.printProductSummaryToByteArray(ProductsSummary(emptyList(), 10)) } } }
amount-counter/src/test/kotlin/com/example/service/PdfPrinterServiceTest.kt
1301350604
package com.example.service import com.example.db.ProductsTable import com.example.exception.ItemsNotFoundException import com.example.getTestDb import com.example.initTestDb import com.example.model.Product import com.example.model.ProductsSummary import io.kotest.matchers.shouldBe import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.transactions.transaction import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.util.UUID class ProductsServiceTest { private val db = getTestDb().also { initTestDb(it) } private val service = ProductsService(db) @AfterAll fun tearDown() { transaction(db) { SchemaUtils.drop(ProductsTable) } } @Test fun `get product list fun returns correct list of values`() { val expected = listOf( Product( id = 1, uuid = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"), name = "Diablo IV", amount = 10L, ), Product( id = 2, uuid = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"), name = "Overwatch 2", amount = 1L, ), Product( id = 3, uuid = UUID.fromString("d2c02017-61f7-4609-9fa0-da6887aff9c6"), name = "Half-Life 3", amount = 10000L, ), Product( id = 4, uuid = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"), name = "CyberPunk 2077", amount = 50L, ), Product( id = 5, uuid = UUID.fromString("1603b0c2-952e-4400-89b4-49d2e3ee0e62"), name = "God of War: Ragnarok", amount = 5L, ), ) service.getAllProducts() shouldBe expected } @Test fun `get products summary fun returns correct list of values`() { val expected = ProductsSummary( products = listOf( Product( id = 1, uuid = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"), name = "Diablo IV", amount = 10L, ), Product( id = 2, uuid = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"), name = "Overwatch 2", amount = 1L, ), Product( id = 4, uuid = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"), name = "CyberPunk 2077", amount = 50L, ), ), total = 61L, ) service.getProductsSummary( listOf( UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"), UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"), UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"), ), ) shouldBe expected } @Test fun `get products summary fun returns empty product summary in case of empty list as argument`() { service.getProductsSummary(emptyList()) shouldBe ProductsSummary(products = emptyList(), total = 0L) .also { it.isEmpty() shouldBe true } } @Test fun `get products summary fun throw exception in case of not exists values provided`() { assertThrows<ItemsNotFoundException> { service.getProductsSummary( listOf( UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"), UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"), UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e5"), UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb6"), ), ) }.apply { message shouldBe "Requested ids [bfcfaa0a-e878-48b5-85c8-a4f20e52b3e5, " + "bf70093e-a4d4-461b-86ff-6515feee9bb6] not found" } } }
amount-counter/src/test/kotlin/com/example/service/ProductsServiceTest.kt
3175392692
package com.example.dto import com.example.model.Product import kotlinx.serialization.Serializable @Serializable data class ProductDto( val id: String, val name: String, val amount: Long, ) fun Product.toProductDto(): ProductDto { return ProductDto( id = uuid.toString(), name = name, amount = amount, ) }
amount-counter/src/main/kotlin/com/example/dto/ProductDto.kt
2761653889
package com.example.dto import kotlinx.serialization.Serializable @Serializable data class IdsRequestDto( val ids: List<String>, )
amount-counter/src/main/kotlin/com/example/dto/IdsRequestDto.kt
2255352371
package com.example import com.example.plugins.configureDatabases import com.example.plugins.configureHTTP import com.example.plugins.configureLogging import com.example.plugins.configureMonitoring import com.example.plugins.configureRouting import com.example.plugins.configureSerialization import com.example.plugins.configureSwagger import configureExceptionHandling import io.ktor.server.application.Application import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module) .start(wait = true) } fun Application.module() { val db = configureDatabases() configurePlugins() configureRouting(db) } fun Application.configurePlugins() { configureExceptionHandling() configureLogging() configureMonitoring() configureSerialization() configureHTTP() configureSwagger() }
amount-counter/src/main/kotlin/com/example/Application.kt
3325309733
package com.example.plugins import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.plugins.cors.routing.CORS fun Application.configureHTTP() { install(CORS) { allowMethod(HttpMethod.Options) allowMethod(HttpMethod.Post) allowMethod(HttpMethod.Get) allowHeader(HttpHeaders.ContentType) allowHeader(HttpHeaders.AccessControlExposeHeaders) allowHeader(HttpHeaders.AccessControlRequestHeaders) allowHeader(HttpHeaders.ContentDisposition) anyHost() } }
amount-counter/src/main/kotlin/com/example/plugins/HTTP.kt
1970826979
package com.example.plugins import com.example.routing.configureProductRouting import com.example.service.ProductsService import io.ktor.server.application.Application import org.jetbrains.exposed.sql.Database fun Application.configureRouting( db: Database, ) { configureProductRouting(ProductsService(db)) }
amount-counter/src/main/kotlin/com/example/plugins/Routing.kt
1002514084
import com.example.exception.BadRequestException import com.example.exception.ItemsNotFoundException import com.example.exception.PdfWriterException import io.ktor.http.HttpStatusCode.Companion.BadRequest import io.ktor.http.HttpStatusCode.Companion.InternalServerError import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.plugins.statuspages.StatusPages import io.ktor.server.response.respond import mu.KotlinLogging val log = KotlinLogging.logger {} fun Application.configureExceptionHandling() { install(StatusPages) { exception<Throwable> { call, e -> when (e) { is BadRequestException -> { log.info(e) { "Bad request" } call.respond(BadRequest, e.message) } is ItemsNotFoundException -> { log.info(e) { "Items not found" } call.respond(BadRequest, "One or more requested elements are not found") } is PdfWriterException -> { log.info(e) { "Pdf writer error" } call.respond(InternalServerError) } else -> { log.error(e) { "Uncaught exception was thrown by service" } call.respond(InternalServerError) } } } } }
amount-counter/src/main/kotlin/com/example/plugins/ExceptionHandling.kt
1778430588
package com.example.plugins import io.ktor.serialization.kotlinx.json.json import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.plugins.contentnegotiation.ContentNegotiation fun Application.configureSerialization() { install(ContentNegotiation) { json() } }
amount-counter/src/main/kotlin/com/example/plugins/Serialization.kt
671225728