content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.loginuione.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoginUiOneTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Mobile_Projet/Login_Register/LoginUiOne/app/src/main/java/com/example/loginuione/ui/theme/Theme.kt
3257667521
package com.example.loginuione.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Mobile_Projet/Login_Register/LoginUiOne/app/src/main/java/com/example/loginuione/ui/theme/Type.kt
4088122488
package com.example.loginuione import android.media.Image 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.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.Green import androidx.compose.ui.graphics.Color.Companion.Red import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.loginuione.ui.theme.LoginUiOneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginUiOneTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { //Greeting("Android") LoginUiOne() } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } //ici je desinne mon premier interface login @Preview(showBackground = true) @Composable fun LoginUiOne(){ //composant parent ou le grand conteneur Scaffold( topBar = { TopAppBar( //title = { Text(text = "Longin UI") }, title = { Text(text = "") }, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { //ici je creai un Menu //Icon(imageVector = Icons.Default.Menu, contentDescription = "Menu") } } ) }, //creation du contenue : les elements seront positionée tous dans un composant Coloumn ou on va les empiler les un a la suite des autre content = { Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { //creation de nos differents composant Image( painter = painterResource(id = R.mipmap.login), contentDescription ="Image Login" , contentScale = ContentScale.Crop, modifier = Modifier.size(160.dp), ) //je met de l'espace entre l'image et le text Spacer(modifier = Modifier.height(6.dp)) //creation des Deux Input / TextField var textState by remember { mutableStateOf("") } OutlinedTextField( value = textState, onValueChange = {newValue -> textState = newValue}, //label = {Text(text = "Telephone")}, placeholder = {Text(text = "Telephone")}, ) //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(6.dp)) OutlinedTextField( value = textState, onValueChange = {newValue -> textState = newValue}, //label = {Text(text = "PassWord")}, placeholder = {Text(text = "Mot de passe")}, ) //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(5.dp)) //je position les deux boutons d'inscription et de connexion dans une row' Row( modifier = Modifier.padding(8.dp), horizontalArrangement = Arrangement.Center, ) { //premier bouton Button( onClick = { /*TODO*/ } , //Rq ici il faut eviter de mettre le fillMaxWidth sur le Modifier //modifier = Modifier.padding(8.dp), modifier = Modifier .padding(10.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Green, ) ) { Text( text = "Connexion", fontWeight = FontWeight.Bold ) } //deuxieme bouton Button( onClick = { /*TODO*/ } , //Rq ici il faut eviter de mettre le fillMaxWidth sur le Modifier modifier = Modifier .padding(10.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Red, ) ) { Text( text = "Inscription", fontWeight = FontWeight.Bold, ) } } //je sort du Row je revient dans la column //je met de l'espace entre les deux boutons precedent et mon text mot de passe oublie Spacer(modifier = Modifier.height(4.dp)) Text( text = "Mot de Passe oublié ?", style = MaterialTheme.typography.body1 ) } } ) } @Preview(showBackground = true) @Composable fun DefaultPreview() { LoginUiOneTheme { Greeting("Android") } }
Mobile_Projet/Login_Register/LoginUiOne/app/src/main/java/com/example/loginuione/MainActivity.kt
773559678
package com.example.loginuione 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.loginuione", appContext.packageName) } }
Mobile_Projet/Login_Register/LoginUiTwo/app/src/androidTest/java/com/example/loginuione/ExampleInstrumentedTest.kt
3177557000
package com.example.loginuione 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) } }
Mobile_Projet/Login_Register/LoginUiTwo/app/src/test/java/com/example/loginuione/ExampleUnitTest.kt
1170024278
package com.example.loginuione.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Mobile_Projet/Login_Register/LoginUiTwo/app/src/main/java/com/example/loginuione/ui/theme/Shape.kt
2893713088
package com.example.loginuione.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Mobile_Projet/Login_Register/LoginUiTwo/app/src/main/java/com/example/loginuione/ui/theme/Color.kt
2065478410
package com.example.loginuione.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoginUiOneTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Mobile_Projet/Login_Register/LoginUiTwo/app/src/main/java/com/example/loginuione/ui/theme/Theme.kt
3257667521
package com.example.loginuione.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Mobile_Projet/Login_Register/LoginUiTwo/app/src/main/java/com/example/loginuione/ui/theme/Type.kt
4088122488
package com.example.loginuione import android.media.Image 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.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.Green import androidx.compose.ui.graphics.Color.Companion.Red import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.textInputServiceFactory import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.loginuione.ui.theme.LoginUiOneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginUiOneTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { //Greeting("Android") LoginUiTwo() } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } //ici je desinne mon premier interface login grace au @Preview() je peut obtenir une visibilité coté design @Preview(showBackground = true) @Composable fun LoginUiTwo(){ //composant parent ou le grand conteneur // Scaffold( // topBar = { // // TopAppBar( // //title = { Text(text = "Longin UI") }, // title = { Text(text = "") }, // // navigationIcon = { // IconButton(onClick = { /*TODO*/ }) { // //ici je creai un Menu // //Icon(imageVector = Icons.Default.Menu, contentDescription = "Menu") // // } // } // // ) // }, //creation du contenue : les elements seront positionée tous dans un composant Coloumn ou on va les empiler les un a la suite des autre //content = { Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { //creation de nos differents composant Image( painter = painterResource(id = R.mipmap.login), contentDescription ="Image Login" , contentScale = ContentScale.Crop, modifier = Modifier.size(160.dp), ) //je met de l'espace entre l'image et le text Spacer(modifier = Modifier.height(6.dp)) Text( text = "CREATION D'UN NOUVEAU MOT DE PASSE", fontSize = MaterialTheme.typography.h6.fontSize, // mon text aurais une police d'un titre h6 fontWeight = FontWeight.Bold, //je met le text en gras textAlign = TextAlign.Center // JE Centralise mon text ) //je met de l'espace entre l'image et le text Spacer(modifier = Modifier.height(2.dp)) //creation des Deux Input / TextField var textState by remember { mutableStateOf("") } OutlinedTextField( value = textState, onValueChange = {newValue -> textState = newValue}, //label = {Text(text = "Nouveau mot de passe")}, placeholder = {Text(text = "Nouveau mot de passe")}, //placement de l'icon dans le placeholder avant le text leadingIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Filled.Lock, contentDescription ="Icon Lock ou Cadenas pour" ) } }, //placement de l'icon apres le Text Du Placeholder trailingIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Filled.Info, contentDescription ="Icon Lock ou Cadenas pour" ) } } ) //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(6.dp)) OutlinedTextField( value = textState, onValueChange = {newValue -> textState = newValue}, //label = {Text(text = "confirmer le mot de passe")}, placeholder = { Text( text = "confirmer le mot de passe", maxLines = 1,//ici le coupe le texte vu que c'est trop long pour entrer dans le placeholder et comme sa occupait deux ligne j'ai couper sur la premier ligne //overflow = TextOverflow.Visible ) }, singleLine = true,//le texte saisi par le user ici sera contenue sur une seule ligne maxLines = 1, // nombre de ligne devant contenir le text de saisi //placement de l'icon dans le placeholder avant le text leadingIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Filled.Lock, contentDescription ="Icon Lock ou Cadenas pour" ) } }, //placement de l'icon apres le Text Du Placeholder trailingIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Filled.Info, contentDescription ="Icon Lock ou Cadenas pour" ) } } ) //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(5.dp)) //bouton Button( onClick = { /*TODO*/ } , //Rq ici il faut eviter de mettre le fillMaxWidth sur le Modifier //modifier = Modifier.padding(8.dp), modifier = Modifier .padding(10.dp) .fillMaxWidth(), colors = ButtonDefaults.buttonColors( //backgroundColor = Green, //ici je change la couleur de mon bouton ) ) { Text( text = "Enregistrer", fontWeight = FontWeight.Bold ) } //je met de l'espace entre les deux boutons precedent et mon text mot de passe oublie Spacer(modifier = Modifier.height(4.dp)) Text( text = "Se Connecter", style = MaterialTheme.typography.body1 ) } } // ) // // //} @Preview(showBackground = true) @Composable fun DefaultPreview() { LoginUiOneTheme { Greeting("Android") } }
Mobile_Projet/Login_Register/LoginUiTwo/app/src/main/java/com/example/loginuione/MainActivity.kt
2559945541
package com.example.loginuione 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.loginuione", appContext.packageName) } }
Mobile_Projet/TodoList/ToDo-List/app/src/androidTest/java/com/example/loginuione/ExampleInstrumentedTest.kt
3177557000
package com.example.loginuione 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) } }
Mobile_Projet/TodoList/ToDo-List/app/src/test/java/com/example/loginuione/ExampleUnitTest.kt
1170024278
package com.example.loginuione.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Mobile_Projet/TodoList/ToDo-List/app/src/main/java/com/example/loginuione/ui/theme/Shape.kt
2893713088
package com.example.loginuione.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Mobile_Projet/TodoList/ToDo-List/app/src/main/java/com/example/loginuione/ui/theme/Color.kt
2065478410
package com.example.loginuione.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoginUiOneTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Mobile_Projet/TodoList/ToDo-List/app/src/main/java/com/example/loginuione/ui/theme/Theme.kt
3257667521
package com.example.loginuione.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Mobile_Projet/TodoList/ToDo-List/app/src/main/java/com/example/loginuione/ui/theme/Type.kt
4088122488
package com.example.loginuione import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.loginuione.ui.theme.LoginUiOneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginUiOneTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { //Greeting("Android") LoginUiOne() } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } //ici je desinne mon premier interface login @Composable fun LoginUiOne(){ Scaffold( topBar = { TopAppBar( title = { Text(text = "Longin UI") }, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Default.Menu, contentDescription = "Menu") } } ) }, content = { Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { Button( onClick = { /*TODO*/ } , modifier = Modifier .fillMaxWidth() .padding(16.dp)) { Text(text = "Connexion") } } } ) } @Preview(showBackground = true) @Composable fun DefaultPreview() { LoginUiOneTheme { Greeting("Android") } }
Mobile_Projet/TodoList/ToDo-List/app/src/main/java/com/example/loginuione/MainActivity.kt
1270785892
package com.example.loginuione 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.loginuione", appContext.packageName) } }
Mobile_Projet/TodoList/TodoListTest/app/src/androidTest/java/com/example/loginuione/ExampleInstrumentedTest.kt
3177557000
package com.example.loginuione 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) } }
Mobile_Projet/TodoList/TodoListTest/app/src/test/java/com/example/loginuione/ExampleUnitTest.kt
1170024278
package com.example.loginuione.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Mobile_Projet/TodoList/TodoListTest/app/src/main/java/com/example/loginuione/ui/theme/Shape.kt
2893713088
package com.example.loginuione.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Mobile_Projet/TodoList/TodoListTest/app/src/main/java/com/example/loginuione/ui/theme/Color.kt
2065478410
package com.example.loginuione.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoginUiOneTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Mobile_Projet/TodoList/TodoListTest/app/src/main/java/com/example/loginuione/ui/theme/Theme.kt
3257667521
package com.example.loginuione.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Mobile_Projet/TodoList/TodoListTest/app/src/main/java/com/example/loginuione/ui/theme/Type.kt
4088122488
package com.example.loginuione import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.Blue import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.loginuione.ui.theme.LoginUiOneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginUiOneTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { //Greeting("Android") LoginUiTwo() } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } //ici je desinne mon premier interface login grace au @Preview() je peut obtenir une visibilité coté design @Preview(showBackground = true) @Composable fun LoginUiTwo(){ //composant parent ou le grand conteneur // Scaffold( // topBar = { // // TopAppBar( // //title = { Text(text = "Longin UI") }, // title = { Text(text = "") }, // // navigationIcon = { // IconButton(onClick = { /*TODO*/ }) { // //ici je creai un Menu // //Icon(imageVector = Icons.Default.Menu, contentDescription = "Menu") // // } // } // // ) // }, //creation du contenue : les elements seront positionée tous dans un composant Coloumn ou on va les empiler les un a la suite des autre //content = { //declarons notre variable liste mutable qui va stovker notre liste de tache on declare ici pour que avoir une porter dans tous les composant val todoList = remember { mutableStateListOf<String>() } Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { //creation de nos differents composant //je met de l'espace entre lE Haut de l'ecran et le text Spacer(modifier = Modifier.height(10.dp)) Text( text = "AJOUT DES TACHES", fontSize = MaterialTheme.typography.h6.fontSize, // mon text aurais une police d'un titre h6 fontWeight = FontWeight.Bold, //je met le text en gras textAlign = TextAlign.Center // JE Centralise mon text ) //je met de l'espace entre l'image et le text Spacer(modifier = Modifier.height(2.dp)) Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { //creation du TextField et du bouton d'ajout de la task var textState by remember { mutableStateOf("") } OutlinedTextField( value = textState, onValueChange = { newValue -> textState = newValue }, //label = {Text(text = "Saisir Une Tache")}, placeholder = { Text(text = "Saisir une tache") }, modifier = Modifier .width(200.dp) // j'adapte une taille a mon composant au lieu de laisser la taille par defaut .padding() ) Spacer(modifier = Modifier.width(2.dp)) // je creait un peu /ou je met un peu d'espace entre les deux composant de maniere horizontal en utilisant le width ou largueur //bouton d'ajout de la task Button( onClick = { val newTache = textState todoList.add(newTache) }, //Notons que il ne faut pas toujour regarder le preview ou le rendu il daut egalement le regarder sur le telephone car ici sur le "Split/Desing" Mon Bouton depasse mon TextField mais sur le Telephone c'est propre modifier = Modifier .fillMaxHeight(0.12f) // je donne une taille a mon bouton pourquelle soit identique a la taille de ,on TextField .padding(0.5.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Blue, //ici je change la couleur de mon bouton contentColor = White, ) ) { Text( text = "ADD", fontWeight = FontWeight.Bold, fontSize = 15.sp, ) } } //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(5.dp)) Text( text = "LISTE DES TACHES PROGRAMMEES", //fontSize = MaterialTheme.typography.h6.fontSize, // mon text aurais une police d'un titre h6 //fontWeight = FontWeight.Bold, //je met le text en gras //textAlign = TextAlign.Center, // JE Centralise mon text //textDecoration = TextDecoration.Underline, // sa souligne Mon Texte fontWeight = FontWeight.Bold, fontSize = 16.sp, textDecoration = TextDecoration.Underline ) Row(modifier = Modifier.fillMaxSize()) { // on supprime les parenthese de ce composant on rest seulement avec les accolade LazyColumn { itemsIndexed(todoList) { index, todo -> Column( modifier = Modifier .size(20.dp) .background(Color.Blue, shape = CircleShape), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceBetween ) { // text pour l'affichage des numero Text( text = (index + 1).toString(), color = Color.White, textAlign = TextAlign.Center ) // espace entre les numero et les taches name } //Spacer(modifier = Modifier.width(9.dp)) //Text pour afficher la tache proprement dite Text(text = todo.toString()) } } } } } // ) // // //} @Preview(showBackground = true) @Composable fun DefaultPreview() { LoginUiOneTheme { Greeting("Android") } }
Mobile_Projet/TodoList/TodoListTest/app/src/main/java/com/example/loginuione/MainActivity.kt
1080088735
package com.example.loginuione 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.loginuione", appContext.packageName) } }
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/androidTest/java/com/example/loginuione/ExampleInstrumentedTest.kt
3177557000
package com.example.loginuione 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) } }
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/test/java/com/example/loginuione/ExampleUnitTest.kt
1170024278
package com.example.loginuione.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/main/java/com/example/loginuione/ui/theme/Shape.kt
2893713088
package com.example.loginuione.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/main/java/com/example/loginuione/ui/theme/Color.kt
2065478410
package com.example.loginuione.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoginUiOneTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/main/java/com/example/loginuione/ui/theme/Theme.kt
3257667521
package com.example.loginuione.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/main/java/com/example/loginuione/ui/theme/Type.kt
4088122488
package com.example.loginuione import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.Blue import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.toSize import com.example.loginuione.ui.theme.LoginUiOneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginUiOneTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { //Greeting("Android") LoginUiTwo() } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } //Fonction de convertion de devices par defaut en fcfa fun convertion(montantDollar: Double , device: String): Double{ val valeurEchange : Double; if (device.equals("Euro")){ //on sait que : 1$ = 0.92 euro ou sensiblement a 1 donc valeurEchange = 0.92 return montantDollar * valeurEchange; }else if(device.equals("Livre")){ //on sait que : 1$ = 0.76 livre donc valeurEchange = 0.76 return montantDollar * valeurEchange; }else if(device.equals("Yen")){ //on sait que : 1$ = 107.97 yen donc valeurEchange = 107.97 return montantDollar * valeurEchange; }else{ // en FCFA //on sait que : 1$ = 563.63 FCFA donc valeurEchange = 563.63 return montantDollar * valeurEchange; } } @Composable fun affichage(montant:Double,device:String){ Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { // text pour l'affichage du resultat Text( text = " $montant $device ", color = Color.Blue, textAlign = TextAlign.Center ) } } @Preview(showBackground = true) @Composable fun LoginUiTwo(){ //declarons une variable booleens pour le stockage l'orsque notre OutlinedField est Expand var mExpanded by remember { mutableStateOf(false)} // je creais la liste de mes devices val mDevices = listOf<String>("Euro","Livre","Yen","FCFA") //je creais ma variable mutable String pour stocker ma valeurs Device selectionnee var mSelectedText by remember { mutableStateOf("") } //je creais ma variable mutatble pour stocker le montant saisi var mInputTextPrice by remember { mutableStateOf("") } var mTextFieldsize by remember { mutableStateOf(Size.Zero) } //var resultat : Double = 0.0; //initialisation creation d'une variable resultat devant store la valeur de la fonction de convertion var resultat by remember { mutableStateOf(0.0) } // Up Icon When expanded (true) and Down icon when collapsed (fermeture) val icon = if (mExpanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown // creation de notre Widget Coloumn Conteneur parent Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() .padding(20.dp) ) { //creation de nos differents composant Interieurs //je met de l'espace entre le Haut de l'ecran et le text Spacer(modifier = Modifier.height(10.dp)) Text( text = "CONVERTISSEUR DE DEVICES", fontSize = MaterialTheme.typography.h6.fontSize, // mon text aurais une police d'un titre h6 fontWeight = FontWeight.Bold, //je met le text en gras textAlign = TextAlign.Center // JE Centralise mon text ) //je met de l'espace entre l'image et le text Spacer(modifier = Modifier.height(2.dp)) // je creais un outlinedField pour la saisi du prix OutlinedTextField( value = mInputTextPrice, onValueChange = { newValue -> mInputTextPrice = newValue }, //label = {Text(text = "Saisir Le montant En Dolloars $")}, placeholder = { Text(text = "Saisir Le montant En Dolloars $") }, modifier = Modifier .fillMaxWidth(), //ce champ de saisi ne doit contenir que les nombres (on active uniquement le clavier numerique) keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) ) Spacer(modifier = Modifier.height(8.dp)) // espace entre les elements // on creait un deuxieme OutlinedField Pour l'attacher a notre DropDown OutlinedTextField( value = mSelectedText, onValueChange = { newValue -> mSelectedText = newValue }, placeholder = { Text(text = "Choisir une device ") }, modifier = Modifier .fillMaxWidth() .onGloballyPositioned { layoutCoordinates -> //this value is used to assign to the Dropdown the same width mTextFieldsize = layoutCoordinates.size.toSize() }, trailingIcon = { Icon(icon,"icone pour presenter l'ouverture et la fermeture du Dropdown", Modifier.clickable { mExpanded = !mExpanded }) }, ) DropdownMenu( expanded = mExpanded, //recuperation du choix de convertion onDismissRequest = { mExpanded = false }, modifier = Modifier.fillMaxWidth(), ) { mDevices.forEach { label-> DropdownMenuItem(onClick = { mSelectedText = label mExpanded = false }) { Text(text = label) } } } //bouton de convertion Button( onClick = { resultat = convertion(mInputTextPrice.toDouble(), mSelectedText.toString()) }, modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors( backgroundColor = Blue, //ici je change la couleur de mon bouton contentColor = White, ) ) { Text( text = "Convertir", fontWeight = FontWeight.Bold, fontSize = 15.sp, ) } //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(5.dp)) Text( text = "MONTANT CONVERTIS EN :", //fontSize = MaterialTheme.typography.h6.fontSize, // mon text aurais une police d'un titre h6 //fontWeight = FontWeight.Bold, //je met le text en gras //textAlign = TextAlign.Center, // JE Centralise mon text //textDecoration = TextDecoration.Underline, // sa souligne Mon Texte fontWeight = FontWeight.Bold, fontSize = 16.sp, textDecoration = TextDecoration.Underline, fontFamily = FontFamily.Serif, ) //je met de l'espace entre les deux TextField Spacer(modifier = Modifier.height(2.dp)) //appel du composant affichage pour afficher le resultat affichage(resultat,mSelectedText) } } @Preview(showBackground = true) @Composable fun DefaultPreview() { LoginUiOneTheme { Greeting("Android") } }
Mobile_Projet/Convertisseur Devices/ConversionDeviceTest/app/src/main/java/com/example/loginuione/MainActivity.kt
2486826449
package com.example.aviatickets 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.aviatickets", appContext.packageName) } }
android_midterm/app/src/androidTest/java/com/example/aviatickets/ExampleInstrumentedTest.kt
91970574
package com.example.aviatickets import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
android_midterm/app/src/test/java/com/example/aviatickets/ExampleUnitTest.kt
2495463373
package com.example.aviatickets.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.aviatickets.R import com.example.aviatickets.databinding.ActivityMainBinding import com.example.aviatickets.fragment.OfferListFragment class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) supportFragmentManager .beginTransaction() .add(R.id.fragment_container_view, OfferListFragment.newInstance()) .commit() } }
android_midterm/app/src/main/java/com/example/aviatickets/activity/MainActivity.kt
1457783052
package com.example.aviatickets.adapter import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.aviatickets.R import com.example.aviatickets.databinding.ItemOfferBinding import com.example.aviatickets.model.entity.Offer class OfferListAdapter : RecyclerView.Adapter<OfferListAdapter.ViewHolder>() { companion object { private const val OFFER_ADAPTER_TAG = "OfferAdapter" } private val items: ArrayList<Offer> = arrayListOf() fun setItems(offerList: List<Offer>) { items.clear() items.addAll(offerList) notifyDataSetChanged() /** * think about recycler view optimization using diff.util */ } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { Log.d(OFFER_ADAPTER_TAG, "onCreateViewHolder") return ViewHolder( ItemOfferBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { Log.d(OFFER_ADAPTER_TAG, "onBindViewHolder: $position") holder.bind(items[position]) } inner class ViewHolder( private val binding: ItemOfferBinding ) : RecyclerView.ViewHolder(binding.root) { private val context = binding.root.context fun bind(offer: Offer) { val flight = offer.flight with(binding) { departureTime.text = flight.departureTimeInfo arrivalTime.text = flight.arrivalTimeInfo route.text = context.getString( R.string.route_fmt, flight.departureLocation.code, flight.arrivalLocation.code ) duration.text = context.getString( R.string.time_fmt, getTimeFormat(flight.duration).first.toString(), getTimeFormat(flight.duration).second.toString() ) direct.text = context.getString(R.string.direct) price.text = context.getString(R.string.price_fmt, offer.price.toString()) } } private fun getTimeFormat(minutes: Int): Pair<Int, Int> = Pair( first = minutes / 60, second = minutes % 60 ) } }
android_midterm/app/src/main/java/com/example/aviatickets/adapter/OfferListAdapter.kt
283597030
package com.example.aviatickets.fragment import android.bluetooth.BluetoothHidDevice import android.os.Bundle import android.telecom.Call import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.aviatickets.R import com.example.aviatickets.adapter.OfferListAdapter import com.example.aviatickets.databinding.FragmentOfferListBinding import com.example.aviatickets.model.entity.Offer import com.example.aviatickets.model.service.FakeService import com.example.aviatickets.model.network.ApiClient import com.example.aviatickets.model.network.ApiService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.Response class OfferListFragment : Fragment() { companion object { fun newInstance() = OfferListFragment() } private var _binding: FragmentOfferListBinding? = null private val binding get() = _binding!! private val adapter: OfferListAdapter by lazy { OfferListAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentOfferListBinding.inflate(layoutInflater, container, false) return _binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupUI() adapter.setItems(FakeService.offerList) } private fun setupUI() { with(binding) { offerList.adapter = adapter sortRadioGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.sort_by_price -> { /** * implement sorting by price */ } R.id.sort_by_duration -> { /** * implement sorting by duration */ } } } } } val client = ApiClient.instance private val apiService: ApiService = ApiClient.retrofit.create(ApiService::class.java) suspend fun fetchOffers(): List<Offer>? = withContext(Dispatchers.IO) { try { val response = apiService.getOffers() if (response.isSuccessful) { response.body() } else { null // or handle errors as needed } } catch (e: Exception) { null // Handle the exception e.g., no internet connection } } }
android_midterm/app/src/main/java/com/example/aviatickets/fragment/OfferListFragment.kt
1242112931
package com.example.aviatickets.model.entity data class Location( val cityName: String, val code: String )
android_midterm/app/src/main/java/com/example/aviatickets/model/entity/Location.kt
1503829551
package com.example.aviatickets.model.entity data class Offer( val id: String, val price: Int, val flight: Flight )
android_midterm/app/src/main/java/com/example/aviatickets/model/entity/Offer.kt
872707810
package com.example.aviatickets.model.entity data class Airline( val name: String, val code: String )
android_midterm/app/src/main/java/com/example/aviatickets/model/entity/Airline.kt
197109898
package com.example.aviatickets.model.entity /** * think about json deserialization considering its snake_case format */ data class Flight( val departureLocation: Location, val arrivalLocation: Location, val departureTimeInfo: String, val arrivalTimeInfo: String, val flightNumber: String, val airline: Airline, val duration: Int )
android_midterm/app/src/main/java/com/example/aviatickets/model/entity/Flight.kt
3657800238
package com.example.aviatickets.model.network import retrofit2.http.GET import retrofit2.Response import com.example.aviatickets.model.entity.Offer interface ApiService { @GET("offer_list") suspend fun getOffers(): Response<List<Offer>> // Assuming Offer is your data model class }
android_midterm/app/src/main/java/com/example/aviatickets/model/network/APIService.kt
1200233428
package com.example.aviatickets.model.network import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { private const val YOUR_BASE_URL = "https://my-json-server.typicode.com/estharossa/fake-api-demo/offer_list" val retrofit: Retrofit = Retrofit.Builder() .baseUrl("YOUR_BASE_URL") .addConverterFactory(GsonConverterFactory.create()) .build() /** * think about performing network request */ val instance = retrofit.create(ApiService::class.java) }
android_midterm/app/src/main/java/com/example/aviatickets/model/network/ApiClient.kt
4139530175
package com.example.aviatickets.model.service import com.example.aviatickets.model.entity.Airline import com.example.aviatickets.model.entity.Flight import com.example.aviatickets.model.entity.Location import com.example.aviatickets.model.entity.Offer import java.util.UUID object FakeService { val offerList = listOf( Offer( id = UUID.randomUUID().toString(), price = 24550, flight = Flight( departureLocation = Location( cityName = "Алматы", code = "ALA" ), departureTimeInfo = "20:30", arrivalLocation = Location( cityName = "Астана", code = "NQZ" ), arrivalTimeInfo = "22-30", flightNumber = "981", airline = Airline( name = "Air Astana", code = "KC" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 16250, flight = Flight( departureLocation = Location( cityName = "Алматы", code = "ALA" ), departureTimeInfo = "16:00", arrivalLocation = Location( cityName = "Астана", code = "NQZ" ), arrivalTimeInfo = "18-00", flightNumber = "991", airline = Airline( name = "Air Astana", code = "KC" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 8990, flight = Flight( departureLocation = Location( cityName = "Алматы", code = "ALA" ), departureTimeInfo = "09:30", arrivalLocation = Location( cityName = "Астана", code = "NQZ" ), arrivalTimeInfo = "11-10", flightNumber = "445", airline = Airline( name = "FlyArystan", code = "KC" ), duration = 100 ) ), Offer( id = UUID.randomUUID().toString(), price = 14440, flight = Flight( departureLocation = Location( cityName = "Алматы", code = "ALA" ), departureTimeInfo = "14:30", arrivalLocation = Location( cityName = "Астана", code = "NQZ" ), arrivalTimeInfo = "16-00", flightNumber = "223", airline = Airline( name = "SCAT Airlines", code = "DV" ), duration = 90 ) ), Offer( id = UUID.randomUUID().toString(), price = 15100, flight = Flight( departureLocation = Location( cityName = "Алматы", code = "ALA" ), departureTimeInfo = "18:00", arrivalLocation = Location( cityName = "Астана", code = "NQZ" ), arrivalTimeInfo = "20:15", flightNumber = "171", airline = Airline( name = "QazaqAir", code = "IQ" ), duration = 135 ) ) ) }
android_midterm/app/src/main/java/com/example/aviatickets/model/service/FakeService.kt
3729211622
package com.example.cs492_finalproject_rxwatch 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.cs492_finalproject_rxwatch", appContext.packageName) } }
final-project-rxwatch/app/src/androidTest/java/com/example/cs492_finalproject_rxwatch/ExampleInstrumentedTest.kt
1645221513
package com.example.cs492_finalproject_rxwatch 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) } }
final-project-rxwatch/app/src/test/java/com/example/cs492_finalproject_rxwatch/ExampleUnitTest.kt
3974371415
package com.example.cs492_finalproject_rxwatch.ui import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.View import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.database.SearchedDrugViewModel import com.example.cs492_finalproject_rxwatch.utils.OutcomesEnum import com.github.mikephil.charting.animation.Easing import com.github.mikephil.charting.charts.PieChart import com.github.mikephil.charting.data.PieData import com.github.mikephil.charting.data.PieDataSet import com.github.mikephil.charting.data.PieEntry import com.github.mikephil.charting.formatter.PercentFormatter import com.google.android.material.progressindicator.CircularProgressIndicator /** * A simple [Fragment] subclass. * Use the [AdverseEventsFragment.newInstance] factory method to * create an instance of this fragment. * * This fragment is responsible for displaying the adverse events * for a given drug. It uses the OpenFDA API to get the data and * displays it in a pie chart. */ class AdverseEventsFragment : Fragment(R.layout.adverse_events_layout) { //View model for the adverse events fragment private val viewModel: AdverseEventsViewModel by viewModels() //View model for the searched drug. Used to get the most recent searched drug to use in the API call private val searchedDrugsViewModel: SearchedDrugViewModel by viewModels() //Total number of outcomes for the drug private var totalOutcomes: Float = 0f private var outcomeCount = mutableMapOf<String, Int>() //Pie chart for displaying the data private lateinit var pieChart: PieChart private lateinit var adverseHeadline: TextView //Loading indicator for when the API call is being made private lateinit var loadingIndicator: CircularProgressIndicator private lateinit var adverseEventsView: View //Cached drug name for the most recent searched drug private lateinit var cachedDrugName: String @SuppressLint("ResourceType") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adverseEventsView = view.findViewById(R.id.constraint_layout_adverse) loadingIndicator = view.findViewById(R.id.loading_indicator) /* * Whenever a API call is made through the view model that doesn't * used cache data the outcomeCounts will be changed calling this * listener. This function maintains the data set for our pie chart * and sets it up with the values we have stored. */ viewModel.outcomeCounts.observe(viewLifecycleOwner) { outcomes -> //If we have data then we can display it if (outcomes != null) { Log.d("AdverseEventsFragment", outcomes.toString()) adverseEventsView.visibility = View.VISIBLE pieChart = view.findViewById(R.id.pieChart_view) //Set up the headline for the adverse events adverseHeadline = view.findViewById(R.id.adverse_headline) adverseHeadline.text = getString(R.string.adverse_headline, cachedDrugName) //Set up the pie chart val pieDataset: PieDataSet val pieEntries = mutableListOf<PieEntry>() val pieColors = mutableListOf<Int>() totalOutcomes = 0f val reorderedResults = outcomes.results.sortedByDescending { it.term } //Iterate through the data and store it in a map reorderedResults.forEach { count -> totalOutcomes += count.count //Map the 6 values into the only 4 that we want using enum when(count.term) { //If the outcome is not recovered or resolved, recovering or resolving, or recovered or resolved OutcomesEnum.RECOVERED_WITH_LONG_TERM_ISSUES.value, OutcomesEnum.NOT_RECOVERED_OR_RESOLVED.value, OutcomesEnum.RECOVERING_RESOLVING.value, OutcomesEnum.RECOVERED_RESOLVED.value -> { //If the outcome is death, hospitalization, or long lasting effects if (outcomeCount.containsKey("Hospitalization")) { outcomeCount["Hospitalization"] = outcomeCount["Hospitalization"]!! + count.count } else { outcomeCount["Hospitalization"] = count.count } } //If the outcome is death OutcomesEnum.FATAL.value -> { outcomeCount["Death"] = count.count } //If the outcome is unknown OutcomesEnum.UNKNOWN.value -> { outcomeCount["Other"] = count.count } } } //add colors for pie chart pieColors.add(Color.parseColor(getString(R.color.chart_hospitalization))) pieColors.add(Color.parseColor(getString(R.color.chart_death))) pieColors.add(Color.parseColor(getString(R.color.chart_other))) //populating pie chart with data with data we just stored in the // outcomeCount map outcomeCount.forEach { (key, value) -> val percent: Float = (value / totalOutcomes) * 100 pieEntries.add(0, PieEntry(percent, key)) } //set data and colors pieDataset = PieDataSet(pieEntries, "") pieDataset.colors = pieColors //create pie data with our data set and set //other values val pieData = PieData(pieDataset) pieData.setValueTextSize(18f) pieData.setValueFormatter(PercentFormatter(pieChart)) //initialization and customization for pie chart pieChart.data = pieData pieChart.dragDecelerationFrictionCoef = 0.9f pieChart.rotationAngle = 90f pieChart.setHoleColor(Color.parseColor("#eceff4")) pieChart.centerText = getString( R.string.chart_total_events, "%,d".format(totalOutcomes.toInt()) ) pieChart.setCenterTextSize(18f) pieChart.animateY(1400, Easing.EaseInOutQuad) pieChart.setEntryLabelColor(Color.BLACK) pieChart.setUsePercentValues(true) pieChart.isRotationEnabled = true pieChart.isHighlightPerTapEnabled = false pieChart.description.isEnabled = false pieChart.legend.isEnabled = false pieChart.invalidate() } } //Set up an observer for the error status of the API query viewModel.error.observe(viewLifecycleOwner) { error -> if (error != null) { Log.e("AdverseEventsFragment", "Error fetching data: ${error.message}") error.printStackTrace() } } //Set up an observer for the loading status of the API query viewModel.loading.observe(viewLifecycleOwner) { loading -> if (loading) { adverseEventsView.visibility = View.INVISIBLE loadingIndicator.visibility = View.VISIBLE } else{ loadingIndicator.visibility = View.INVISIBLE } } } override fun onResume() { super.onResume() //Set up an observer for the most recent searched drug searchedDrugsViewModel.mostRecentSearchedDrug.observe(viewLifecycleOwner) { drug -> //If we have a drug then we can make the API call if (drug != null) { //Cache the most recent searched drug cachedDrugName = drug[0].drugName //Make the API call using the most recent searched drug val query = "patient.drug.openfda.generic_name:${drug[0].drugName}" viewModel.loadReactionOutcomeCount(query) } } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/AdverseEventsFragment.kt
4017771035
package com.example.cs492_finalproject_rxwatch.ui import android.os.Bundle import android.util.Log import android.view.View import android.widget.ExpandableListView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import com.example.cs492_finalproject_rxwatch.R class ManufacturersListFragment : Fragment(R.layout.manufacturers_list_fragment) { private val args: ManufacturersListFragmentArgs by navArgs() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val searchedDrugName = args.searchedDrugName val drugInfo = args.druginfo val drugName = drugInfo.genericName val manufacturers = drugInfo.manufacturers Log.d("ManufacturersListFragment", "Drug Name: $drugName") Log.d("ManufacturersListFragment", "Manufacturers: $manufacturers") val headingTV: TextView = view.findViewById(R.id.tv_interacting_drug_header) headingTV.text = getString(R.string.mfr_list_heading, drugName, searchedDrugName) val expandableListView = view.findViewById<ExpandableListView>(R.id.elv_manufacturer_names) expandableListView.setAdapter(MfrDrugInteractionsAdapter(requireContext(), manufacturers)) } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/ManufacturersListFragment.kt
2050155911
package com.example.cs492_finalproject_rxwatch.ui import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.cs492_finalproject_rxwatch.data.DrugInfoService import com.example.cs492_finalproject_rxwatch.data.DrugInformation import com.example.cs492_finalproject_rxwatch.data.DrugInformationRepository import kotlinx.coroutines.launch import kotlin.math.log /** * ViewModel for the DrugInformationFragment * @property repository DrugInformationRepository * @property searchResults LiveData<DrugInformation?> * The search results for the drug interaction search * This is a LiveData object that will be updated when the search results are updated * * @property loading LiveData<Boolean> * A LiveData object that will be updated when the search is loading * * @property error LiveData<String?> * A LiveData object that will be updated when there is an error with the search * * @constructor Creates a DrugInformationViewModel */ class DrugInformationViewModel: ViewModel() { // Create a DrugInformationRepository private val repository = DrugInformationRepository(DrugInfoService.create()) // Create LiveData objects for the search results, loading, and error private val _searchResults = MutableLiveData<DrugInformation?>(null) val searchResults: LiveData<DrugInformation?> = _searchResults // Create LiveData objects for the loading and error private val _loading = MutableLiveData<Boolean>(false) val loading: LiveData<Boolean> = _loading // Create LiveData objects for the error private val _error = MutableLiveData<String?>(null) val error: LiveData<String?> = _error /** * Load the drug interactions for the given search query * @param search String * The search query to use to search for drug interactions * This will be the drug name * Example query: * https://api.fda.gov/drug/label.json?search=(drug_interactions:($searchedDrugName))+(_exists_:openfda.generic_name) * * The API documentation says to uses `+AND+` to search multiple fields * However, Retrofit appears to be URL encoding the `+` signs, so it gets double encoded. * Replacing the `+` signs with a space ` ` appears to fix the issue. * * The search query will be used to search the drug label endpoint for the drug interactions */ fun loadDrugInteractions(search: String) { Log.d("DrugInformationViewModel", "Search query: $search") // Use the viewModelScope to launch a coroutine to get the drug information viewModelScope.launch { _loading.value = true // Get the drug information from the repository val result = repository.getDrugInformation(search) _loading.value = false Log.d("DrugInformationViewModel", "Search Results: $result") // Update the search results, loading, and error LiveData objects _searchResults.value = result.getOrNull() // Get the search results _error.value = result.exceptionOrNull()?.message // Get the error message } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/DrugInformationViewModel.kt
4276086623
package com.example.cs492_finalproject_rxwatch.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import com.example.cs492_finalproject_rxwatch.R import com.google.android.material.appbar.MaterialToolbar class MainActivity : AppCompatActivity() { private lateinit var appBarConfig: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) val navHostFragment = supportFragmentManager.findFragmentById( R.id.nav_host_fragment ) as NavHostFragment val navController = navHostFragment.navController appBarConfig = AppBarConfiguration(navController.graph) val topAppBar: MaterialToolbar = findViewById(R.id.top_app_bar) setSupportActionBar(topAppBar) setupActionBarWithNavController(navController, appBarConfig) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfig) || super.onSupportNavigateUp() } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/MainActivity.kt
1088247032
package com.example.cs492_finalproject_rxwatch.ui import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.database.SearchedDrug import okhttp3.internal.http.HttpDate.format import java.util.Calendar import java.util.Date class SearchedDrugsAdapter( private val onRecentlySearchedDrugClicked: (SearchedDrug) -> Unit ) : RecyclerView.Adapter<SearchedDrugsAdapter.SearchedDrugsViewHolder>() { private var searchedDrugs: MutableList<SearchedDrug> = mutableListOf() fun getItemAt(position: Int): SearchedDrug { return searchedDrugs[position] } fun updateDrugs(drugs: MutableList<SearchedDrug>) { notifyItemRangeRemoved(0, searchedDrugs.size) searchedDrugs = drugs notifyItemRangeInserted(0, searchedDrugs.size) } override fun getItemCount(): Int = searchedDrugs.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchedDrugsViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.searched_drug_list_item, parent, false) return SearchedDrugsViewHolder(view, onRecentlySearchedDrugClicked) } override fun onBindViewHolder(holder: SearchedDrugsViewHolder, position: Int) { holder.bind(searchedDrugs[position]) } class SearchedDrugsViewHolder( view: View, onClick: (SearchedDrug) -> Unit ) : RecyclerView.ViewHolder(view) { private val drugTV: TextView = view.findViewById(R.id.tv_drug_name) private val timestampTV: TextView = view.findViewById(R.id.tv_timestamp) private var currentSearchedDrug: SearchedDrug? = null //private member variables for calculating the "x time ago" text private val oneSec = 1000L private val oneMin: Long = 60 * oneSec private val oneHour: Long = 60 * oneMin private val oneDay: Long = 24 * oneHour private val oneMonth: Long = 30 * oneDay private val oneYear: Long = 365 * oneDay init { itemView.setOnClickListener { Log.d("SearchedDrugsViewHolder", "IT: $it") currentSearchedDrug?.let(onClick) } } fun bind(searchedDrug: SearchedDrug) { currentSearchedDrug = searchedDrug drugTV.text = searchedDrug.drugName timestampTV.text = calculateTime(searchedDrug.timestamp) } private fun calculateTime(timestamp: Long): String{ val date = Date(timestamp) val diff = Calendar.getInstance().time.time - date.time val diffMin: Long = diff / oneMin val diffHours: Long = diff / oneHour val diffDays: Long = diff / oneDay val diffMonths: Long = diff / oneMonth val diffYears: Long = diff / oneYear when { diffYears > 0 -> { return if(diffYears == 1L) "1 year ago" else "$diffYears years ago" } diffMonths > 0 -> { return if(diffMonths == 1L) "1 month ago" else "$diffMonths months ago" } diffDays > 0 -> { return if(diffDays == 1L) "yesterday" else "$diffDays days ago" } diffHours > 0 -> { return if(diffHours == 1L) "1 hour ago" else "$diffHours hours ago" } diffMin > 0 -> { return "$diffMin min ago" } else -> { return "just now" } } } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/SearchedDrugsAdapter.kt
769795045
package com.example.cs492_finalproject_rxwatch.ui import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.DrugInteractionsDisplay class InteractingDrugsAdapter( private val onDrugInfoItemClick: (DrugInteractionsDisplay) -> Unit ) : RecyclerView.Adapter<InteractingDrugsAdapter.DrugInteractionsViewHolder>() { private var interactingDrugsList = listOf<DrugInteractionsDisplay>() fun updateDrugInteractionsList(newInteractingDrugsList: List<DrugInteractionsDisplay>?) { notifyItemRangeRemoved(0, interactingDrugsList.size) interactingDrugsList = newInteractingDrugsList ?: listOf() Log.d("InteractingDrugsAdapter", "Updated Drug Interactions List: $interactingDrugsList") notifyItemRangeInserted(0, interactingDrugsList.size) } override fun getItemCount() = interactingDrugsList.size override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): DrugInteractionsViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.interacting_drug_list_item, parent, false) return DrugInteractionsViewHolder(itemView, onDrugInfoItemClick) } override fun onBindViewHolder( holder: DrugInteractionsViewHolder, position: Int ) { holder.bind(interactingDrugsList[position]) } class DrugInteractionsViewHolder( itemView: View, onClick: (DrugInteractionsDisplay) -> Unit ) : RecyclerView.ViewHolder(itemView) { private val nameTV: TextView = itemView.findViewById(R.id.tv_name) private var currentDrugInfo: DrugInteractionsDisplay? = null init { itemView.setOnClickListener { currentDrugInfo?.let(onClick) } } fun bind(drugDisplay: DrugInteractionsDisplay) { currentDrugInfo = drugDisplay val drugName = drugDisplay.genericName nameTV.text = drugName } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/InteractingDrugsAdapter.kt
2837152863
package com.example.cs492_finalproject_rxwatch.ui import android.content.ClipData.Item import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ImageButton import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModel import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.database.SearchedDrug import com.example.cs492_finalproject_rxwatch.data.database.SearchedDrugViewModel import com.google.android.material.snackbar.Snackbar import java.util.Locale class RxSearchFragment : Fragment(R.layout.rx_search_fragment) { private lateinit var searchButton: ImageButton private lateinit var searchBox: EditText private lateinit var searchedDrugList: RecyclerView private val searchedDrugsViewModel: SearchedDrugViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) searchedDrugList = view.findViewById(R.id.searched_drug_list) searchBox = view.findViewById(R.id.et_search_box) searchButton = view.findViewById(R.id.btn_navigate) searchButton.setOnClickListener { val directions = RxSearchFragmentDirections.navigateToDrugReport() val query = searchBox.text.toString().lowercase(Locale.ROOT).trim() Log.d("RxSearchFragment", "Query from text entry: $query") if (!TextUtils.isEmpty(query)) { Log.d("RxSearchFragment", "Search query: $query") searchedDrugsViewModel.addSearchedDrug(SearchedDrug( query, System.currentTimeMillis() )) findNavController().navigate(directions) } else { Snackbar.make( view, "Please enter or select a drug to search.", Snackbar.LENGTH_SHORT ).show() } } searchedDrugList.layoutManager = LinearLayoutManager(requireContext()) searchedDrugList.setHasFixedSize(true) val adapter = SearchedDrugsAdapter(::onRecentlySearchedDrugClicked) searchedDrugList.adapter = adapter searchedDrugsViewModel.searchedDrugs.observe(viewLifecycleOwner) { drugs -> adapter.updateDrugs(drugs.toMutableList()) searchedDrugList.scrollToPosition(0) } val itemTouchCallBack = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.LEFT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val searchedDrug = adapter.getItemAt(viewHolder.absoluteAdapterPosition) searchedDrugsViewModel.deleteDrugByName(searchedDrug.drugName) } } ItemTouchHelper(itemTouchCallBack).attachToRecyclerView(searchedDrugList) } private fun onRecentlySearchedDrugClicked(drug: SearchedDrug) { Log.d("RxSearchFragment", "Clicked on drug: $drug") searchedDrugsViewModel.addSearchedDrug(SearchedDrug( drug.drugName, System.currentTimeMillis() )) val directions = RxSearchFragmentDirections.navigateToDrugReport() findNavController().navigate(directions) } override fun onResume() { super.onResume() searchBox.text.clear() } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/RxSearchFragment.kt
1803236035
package com.example.cs492_finalproject_rxwatch.ui import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.TextView import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.Manufacturer class MfrDrugInteractionsAdapter( var context: Context, private var manufacturers: List<Manufacturer> ) : BaseExpandableListAdapter() { override fun getGroupCount(): Int { return manufacturers.size } override fun getChildrenCount(groupPosition: Int): Int { return 1 } override fun getGroup(groupPosition: Int): Manufacturer { return manufacturers[groupPosition] } override fun getChild(groupPosition: Int, childPosition: Int): Any { return manufacturers[groupPosition].drugInteractions } override fun getGroupId(groupPosition: Int): Long { return groupPosition.toLong() } override fun getChildId(groupPosition: Int, childPosition: Int): Long { return 0 } override fun hasStableIds(): Boolean { return false } override fun getGroupView( groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup? ): View { var convertedView = convertView if (convertedView == null) { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertedView = inflater.inflate(R.layout.manufacturers_group, null) } var itemChild = convertedView!!.findViewById<TextView>(R.id.tv_mfr_group) itemChild.text = getGroup(groupPosition).manufacturerName return convertedView } override fun getChildView( groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup? ): View { var convertedView = convertView if (convertedView == null) { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertedView = inflater.inflate(R.layout.drug_interactions_detail_item, null) } var itemChild = convertedView!!.findViewById<TextView>(R.id.tv_drug_interactions) itemChild.text = getGroup(groupPosition).drugInteractions return convertedView } override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean { return true } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/MfrDrugInteractionsAdapter.kt
2353748564
package com.example.cs492_finalproject_rxwatch.ui import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.cs492_finalproject_rxwatch.data.AdverseEventsRepository import com.example.cs492_finalproject_rxwatch.data.DrugInfoService import com.example.cs492_finalproject_rxwatch.data.Outcomes import kotlinx.coroutines.launch class AdverseEventsViewModel: ViewModel() { private val repository = AdverseEventsRepository(DrugInfoService.create()) private val _outcomeCounts = MutableLiveData<Outcomes?>(null) val outcomeCounts: LiveData<Outcomes?> = _outcomeCounts private val _loading = MutableLiveData<Boolean>(false) val loading: LiveData<Boolean> = _loading private val _error = MutableLiveData<Throwable?>(null) val error: LiveData<Throwable?> = _error fun loadReactionOutcomeCount(search: String) { viewModelScope.launch { _loading.value = true val result = repository.getReactionOutcomeCount(search) _loading.value = false _error.value = result.exceptionOrNull() _outcomeCounts.value = result.getOrNull() } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/AdverseEventsViewModel.kt
2381135998
package com.example.cs492_finalproject_rxwatch.ui import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Button import android.widget.TextView import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.navigation.fragment.findNavController import com.example.cs492_finalproject_rxwatch.R import com.example.cs492_finalproject_rxwatch.data.DrugInteractionsDisplay import com.example.cs492_finalproject_rxwatch.data.Manufacturer import com.example.cs492_finalproject_rxwatch.data.database.SearchedDrugViewModel import com.google.android.material.progressindicator.CircularProgressIndicator /** * A fragment to display the list of drugs that interact with the searched drug. * * This fragment will display a list of drugs that interact with the searched drug. * The user can click on a drug to see the manufacturers of the drug that interact with the searched drug. * The user can also click on the "Adverse Events" button to navigate to the AdverseEventsFragment. * The user can also click on the "Share" button to share the list of drugs that interact with the searched drug. * * @constructor Creates an InteractingDrugsListFragment * * @property viewModel DrugInformationViewModel * The ViewModel for the DrugInformationFragment * * @property searchedDrugsViewModel SearchedDrugViewModel * The ViewModel for the SearchedDrugFragment * * @property adapter InteractingDrugsAdapter * The adapter for the RecyclerView that will display the list of drugs that interact with the searched drug * * @property searchResultsListRV RecyclerView * The RecyclerView that will display the list of drugs that interact with the searched drug * * @property adverseButton Button * The button to navigate to the AdverseEventsFragment * * @property shareButton Button * The button to share the list of drugs that interact with the searched drug * * @property loadingIndicator CircularProgressIndicator * The loading indicator to display when the search is loading * * @property drugsInfoView View * The view to display the list of drugs that interact with the searched drug * * @property errorMessages TextView * The text view to display error messages * * @property searchedDrugName String * The name of the drug that was searched * * @property onViewCreated Function1<View, Unit> * The function to set up the fragment when the view is created * * @property onDrugInfoItemClick Function1<DrugInteractionsDisplay, Unit> * The function to handle when a drug is clicked * * @property buildDrugListShareString Function2<String, List<DrugInteractionsDisplay>, String> * The function to build a string from the list of drugs that interact with the searched drug * that can be shared */ class InteractingDrugsListFragment : Fragment(R.layout.interacting_drugs_list_fragment) { // Create a DrugInformationViewModel private val viewModel: DrugInformationViewModel by viewModels() private val searchedDrugsViewModel: SearchedDrugViewModel by viewModels() private val adapter = InteractingDrugsAdapter(::onDrugInfoItemClick) // The RecyclerView that will display the list of drugs that interact with the searched drug private lateinit var searchResultsListRV: RecyclerView // The title of the drug that was searched private lateinit var drugNameTitle: TextView // The button to navigate to the AdverseEventsFragment private lateinit var adverseButton: Button // The loading indicator to display when the search is loading private lateinit var loadingIndicator: CircularProgressIndicator private lateinit var drugsInfoView: View // The text view to display error messages private lateinit var errorMessages: TextView // The name of the drug that was searched private lateinit var searchedDrugName: String private lateinit var displayListCache: List<DrugInteractionsDisplay> /** * Set up the fragment when the view is created * * This function will set up the fragment when the view is created. * It will set up the RecyclerView and buttons. * It will also set up observers for the loading status and error status of the API query. * * @param view View * The view that was created * * @param savedInstanceState Bundle? * The saved instance state */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Set up the RecyclerView and buttons drugNameTitle = view.findViewById(R.id.drug_name_title) adverseButton = view.findViewById(R.id.btn_navigate_to_adverse) loadingIndicator = view.findViewById(R.id.loading_indicator) drugsInfoView = view.findViewById(R.id.drugs_info) errorMessages = view.findViewById(R.id.tv_error_message) displayListCache = listOf() // Set up the RecyclerView and buttons adverseButton.setOnClickListener { val directions = InteractingDrugsListFragmentDirections.navigateToAdverseEvents() findNavController().navigate(directions) } /* * The API documentation says to uses `+AND+` to search multiple fields * However, Retrofit appears to be URL encoding the `+` signs, so it gets double encoded. * Replacing the `+` signs with a space ` ` appears to fix the issue. * */ searchedDrugsViewModel.mostRecentSearchedDrug.observe(viewLifecycleOwner) { drug -> // Set up the RecyclerView and buttons searchedDrugName = drug[0].drugName // Get the name of the drug that was searched drugNameTitle.text = getString(R.string.search_results_title, searchedDrugName) // Set the title of the drug that was searched Log.d("InteractingDrugsListFragment", "Searched drug outside observe: $searchedDrugName") val query = "drug_interactions:$searchedDrugName AND _exists_:openfda.generic_name" // Create the query to search for drug interactions Log.d("InteractingDrugsListFragment", "Query: $query") viewModel.loadDrugInteractions(query) // Load the drug interactions for the given search query searchResultsListRV = view.findViewById(R.id.rv_search_results) searchResultsListRV.layoutManager = LinearLayoutManager(requireContext()) searchResultsListRV.setHasFixedSize(true) searchResultsListRV.adapter = adapter /** * The function to handle when a drug is clicked * * This function will handle when a drug is clicked. * It will navigate to the ManufacturersListFragment with the drug that was clicked. * * @param drugInfo DrugInteractionsDisplay * The drug that was clicked */ viewModel.searchResults.observe(viewLifecycleOwner) { drugInformationResults -> /** * The function to build a string from the list of drugs that interact with the searched drug * that can be shared * * This function will take a list of DrugInfo objects from the API results and build a string from them * that can be incorporated in a ShareSheet. * * @param searchedDrug String * The name of the drug that was searched * * @param drugList List<DrugInteractionsDisplay> * The list of drugs that interact with the searched drug * * @return String * The string from the list of drugs that interact with the searched drug that can be shared */ if (drugInformationResults != null) { drugsInfoView.visibility = View.VISIBLE val drugInfoList = drugInformationResults.results // Get the list of drugs that interact with the searched drug /* * Build a map of the manufacturer (mfr) drug names to the drug interactions * and nest it within a map of the generic drug names. * This helps condense the search results, since many manufacturers make the same drug. * */ val drugInteractionsMap = mutableMapOf<String, MutableMap<String, String>>() // Iterate through the list of drugs that interact with the searched drug drugInfoList.forEach { drugInfo -> drugInfo.openFDA?.genericName?.forEach { genericName -> val mfrToInteractionsMap = drugInteractionsMap.getOrPut(genericName) { mutableMapOf() } drugInfo.openFDA.manufacturerName?.forEach { mfrName -> val interactionsString = drugInfo.drugInteractionsString?.joinToString( separator = "; " ) ?: "No interactions found" mfrToInteractionsMap[mfrName] = interactionsString } } } // ****** Logging logic for debugging and not necessary for app functionality ****** var totalMfrCount = 0 drugInteractionsMap.forEach { (_, mfrMap) -> totalMfrCount += mfrMap.size } val genericCount = drugInteractionsMap.size val avgMfrsPerGeneric = if (genericCount > 0) totalMfrCount.toDouble() / genericCount else 0.0 Log.d("InteractingDrugsListFragment", "Total Generic Names: $genericCount") Log.d("InteractingDrugsListFragment", "Total Mfr Names: $totalMfrCount") Log.d( "InteractingDrugsListFragment", "Avg Mfr name per Generic Name: $avgMfrsPerGeneric" ) // ********************************************************************************* // Convert the nested map into nested data classes // so the adapter can more easily work with it val displayList = drugInteractionsMap.map { (genericName, mfrMap) -> DrugInteractionsDisplay( genericName = genericName, manufacturers = mfrMap.map { (mfrName, interactions) -> Manufacturer(mfrName, interactions) } ) } // Send the new nested data classes to the adapter adapter.updateDrugInteractionsList(displayList) searchResultsListRV.visibility = View.VISIBLE searchResultsListRV.scrollToPosition(0) displayListCache = displayList } } } //Set up observer for loading status of API query viewModel.loading.observe(viewLifecycleOwner) { loading -> if (loading) { drugsInfoView.visibility = View.INVISIBLE loadingIndicator.visibility = View.VISIBLE } else { loadingIndicator.visibility = View.INVISIBLE } } //Set up observer for error status of API query viewModel.error.observe(viewLifecycleOwner) { error -> if (error != null) { drugsInfoView.visibility = View.INVISIBLE errorMessages.visibility = View.VISIBLE errorMessages.text = getString(R.string.error_message, error) } } val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider( object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.interacting_drugs_list_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.action_share -> { // Prep and share the list of drugs if(displayListCache.isNotEmpty()) { val shareText = buildDrugListShareString(searchedDrugName, displayListCache) val intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, shareText) type = "text/plain" } startActivity(Intent.createChooser(intent, null)) } true } else -> false } } }, viewLifecycleOwner, Lifecycle.State.STARTED ) } /** * The function to handle when a drug is clicked * * This function will handle when a drug is clicked. * It will navigate to the ManufacturersListFragment with the drug that was clicked. * * @param drugInfo DrugInteractionsDisplay * The drug that was clicked */ private fun onDrugInfoItemClick(drugInfo: DrugInteractionsDisplay) { Log.d("InteractingDrugsListFragment", "Item clicked: $drugInfo") Log.d("InteractingDrugsListFragment", "Clicked Drug Generic Name: ${drugInfo.genericName}") Log.d("InteractingDrugsListFragment", "Clicked Drug Manufacturer: ${drugInfo.manufacturers}") val directions = InteractingDrugsListFragmentDirections.navigateToManufacturersList(drugInfo, searchedDrugName) findNavController().navigate(directions) } /* * Takes a list of DrugInfo objects from the API results and builds a string from them * that can be incorporated in a ShareSheet. * */ private fun buildDrugListShareString(searchedDrug: String, drugList: List<DrugInteractionsDisplay>) : String { var interactionsString: String = "" for(drug in drugList){ val drugName = drug.genericName interactionsString += "\n${drugName}; " } return getString(R.string.share_text, searchedDrug, interactionsString.dropLast(2)) } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/ui/InteractingDrugsListFragment.kt
670780381
package com.example.cs492_finalproject_rxwatch.utils /* * This enum maps the values from their API values 1-6 to more readable * and understandable names, hopefully creating more readable and understandable * code. */ enum class OutcomesEnum(val value: Int) { RECOVERED_RESOLVED(1), RECOVERING_RESOLVING(2), NOT_RECOVERED_OR_RESOLVED(3), RECOVERED_WITH_LONG_TERM_ISSUES(4), FATAL(5), UNKNOWN(6) }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/utils/OutcomesEnum.kt
1471886347
package com.example.cs492_finalproject_rxwatch.data import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /* * Represents top-level information that is returned by API * which is split into meta info and results */ @JsonClass(generateAdapter = true) data class Outcomes( @Json(name = "meta") val meta: Meta, @Json(name = "results") val results: List<Counts> ) /* * This represents the fields in the meta section */ @JsonClass(generateAdapter = true) data class Meta( @Json(name = "last_updated") val lastUpdated: String, @Json(name = "results") val drugCounts: DrugCounts? ) /* * This represents the individual counts for each outcome * that you would see in the results section. */ @JsonClass(generateAdapter = true) data class Counts( @Json(name = "term") val term: Int, @Json(name = "count") val count: Int )
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/AdverseEvents.kt
2807899418
package com.example.cs492_finalproject_rxwatch.data.database import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch class SearchedDrugViewModel(application: Application) : AndroidViewModel(application) { private val repository = SearchedDrugRepository( SearchedDrugDatabase.getInstance(application).searchedDrugDao() ) val searchedDrugs = repository.getAllSearchedDrugs().asLiveData() val mostRecentSearchedDrug = repository.getMostRecentSearchedDrug().asLiveData() fun deleteDrugByName(name: String) { viewModelScope.launch { repository.deleteSearchedDrugByName(name) } } fun addSearchedDrug(drug: SearchedDrug) { viewModelScope.launch { repository.insertSearchedDrug(drug) } } fun removeSearchedDrug(drug: SearchedDrug) { viewModelScope.launch { repository.deleteSearchedDrug(drug) } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/database/SearchedDrugViewModel.kt
746077855
package com.example.cs492_finalproject_rxwatch.data.database import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity data class SearchedDrug( @PrimaryKey val drugName: String, val timestamp: Long ) : Serializable
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/database/SearchedDrug.kt
2311405847
package com.example.cs492_finalproject_rxwatch.data.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [SearchedDrug::class], version = 1) abstract class SearchedDrugDatabase : RoomDatabase() { abstract fun searchedDrugDao(): SearchedDrugDAO companion object { const val DATABASE_NAME = "searched-drugs-db" @Volatile private var instance: SearchedDrugDatabase? = null private fun buildDatabase(context: Context) = Room.databaseBuilder( context, SearchedDrugDatabase::class.java, DATABASE_NAME ).build() fun getInstance(context: Context): SearchedDrugDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/database/SearchedDrugDatabase.kt
3023257779
package com.example.cs492_finalproject_rxwatch.data.database class SearchedDrugRepository( private val dao: SearchedDrugDAO ) { suspend fun insertSearchedDrug(drug: SearchedDrug) = dao.insert(drug) suspend fun deleteSearchedDrug(drug: SearchedDrug) = dao.delete(drug) suspend fun deleteSearchedDrugByName(name: String) = dao.deleteDrugByName(name) fun getAllSearchedDrugs() = dao.getAllSearchedDrugs() fun getMostRecentSearchedDrug() = dao.getMostRecentSearchedDrug() }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/database/SearchedDrugRepository.kt
1837206231
package com.example.cs492_finalproject_rxwatch.data.database import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface SearchedDrugDAO { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(drug: SearchedDrug) @Delete suspend fun delete(drug: SearchedDrug) @Query("DELETE FROM SearchedDrug WHERE drugName = :name") suspend fun deleteDrugByName(name: String) @Query("SELECT * FROM SearchedDrug ORDER BY timestamp DESC") fun getAllSearchedDrugs(): Flow<List<SearchedDrug>> @Query("SELECT * FROM SearchedDrug ORDER BY timestamp DESC LIMIT 1") fun getMostRecentSearchedDrug(): Flow<List<SearchedDrug>> }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/database/SearchedDrugDAO.kt
641912602
package com.example.cs492_finalproject_rxwatch.data import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /* * The DrugInformation data class is the primary data class used to * retrieve the drug name and interactions from the API label endpoint. * * Example query: * https://api.fda.gov/drug/label.json?search=(drug_interactions:($searchedDrugName))+(_exists_:openfda.generic_name) * */ @JsonClass(generateAdapter = true) data class DrugInformation ( val meta: DrugLabelMeta, val results: List<DrugInfo> ) /* * DrugLabelMeta is a simple data class to help gather the total number of results in the database. * */ @JsonClass(generateAdapter = true) data class DrugLabelMeta ( @Json(name = "last_updated") val lastUpdated: String, @Json(name = "results") val drugCounts: DrugCounts ) /* * LabelCounts gets the total number of occurrences in the FDA database that match * the query parameters without the limit, * and the limit (which should match the length of results). * */ @JsonClass(generateAdapter = true) data class DrugCounts ( val limit: Int, val total: Int ) /* * DrugInfo data class gets the two drug interactions fields from the API response: * drug_interactions: A long string * drug_interactions_table: A long string with HTML tags and syntax * Also gets the name of the drug via the openfda field * */ @JsonClass(generateAdapter = true) data class DrugInfo ( @Json(name = "drug_interactions") val drugInteractionsString: List<String>?, @Json(name = "drug_interactions_table") val drugInteractionsTable: List<String>?, @Json(name = "openfda") val openFDA: OpenFDA? ) /* * OpenFDA data class helps get the drug name fields. * The generic_name field is the primary name of interest. * */ @JsonClass(generateAdapter = true) data class OpenFDA ( @Json(name = "generic_name") val genericName : List<String>?, @Json(name = "brand_name") val brandName: List<String>?, @Json(name = "manufacturer_name") val manufacturerName: List<String>? )
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/DrugInformation.kt
498863854
package com.example.cs492_finalproject_rxwatch.data import java.io.Serializable data class DrugInteractionsDisplay( val genericName: String, val manufacturers: List<Manufacturer> ) : Serializable data class Manufacturer( val manufacturerName: String, val drugInteractions: String ) : Serializable
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/DrugInteractionsDisplay.kt
2743548870
package com.example.cs492_finalproject_rxwatch.data import com.squareup.moshi.Moshi import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET import retrofit2.http.Query interface DrugInfoService { @GET("label.json") suspend fun getDrugInformation( @Query("search") search: String, @Query("limit") limit: Int = 25 ): Response<DrugInformation> @GET("event.json") suspend fun getReactionOutcomeCount( @Query("search") search: String, @Query("count") count: String = "patient.reaction.reactionoutcome" ): Response<Outcomes> companion object { private const val BASE_URL = "https://api.fda.gov/drug/" fun create(): DrugInfoService { val moshi = Moshi.Builder().build() return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(DrugInfoService::class.java) } } }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/DrugInfoService.kt
2041672377
package com.example.cs492_finalproject_rxwatch.data import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.lang.Exception import kotlin.time.Duration.Companion.minutes import kotlin.time.TimeSource class AdverseEventsRepository( private val service: DrugInfoService, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { private var lastDrugName: String? = null private var cachedOutcomeCounts: Outcomes? = null private val cacheMaxAge = 5.minutes private val timeSource = TimeSource.Monotonic private var timestamp = timeSource.markNow() /* * Handles the API call for getting the outcome counts for a drug. If * we already have grabbed an API call for the drug it will be cached * and will be used until info for a new drug is needed or it's been * cached for more than 5 minutes */ suspend fun getReactionOutcomeCount(search: String): Result<Outcomes?> { return if(shouldFetchOutcomeCount(search)) { withContext(ioDispatcher) { try{ val response = service.getReactionOutcomeCount(search) if(response.isSuccessful) { cachedOutcomeCounts = response.body() timestamp = timeSource.markNow() lastDrugName = "test" Result.success(cachedOutcomeCounts) } else { Result.failure(Exception(response.errorBody()?.string())) } } catch(e: Exception) { Result.failure(e) } } } else { Result.success(cachedOutcomeCounts!!) } } /* * Helper function to determine whether to use cached value or not. */ private fun shouldFetchOutcomeCount(search: String): Boolean = cachedOutcomeCounts == null || !search.contains(lastDrugName.toString(), true) || (timestamp + cacheMaxAge).hasPassedNow() }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/AdverseEventsRepository.kt
3016221746
package com.example.cs492_finalproject_rxwatch.data import android.util.Log import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.lang.Exception import kotlin.time.Duration.Companion.minutes import kotlin.time.TimeSource class DrugInformationRepository( private val service: DrugInfoService, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { private var lastDrugSearched: String? = null private var cachedDrugInformation: DrugInformation? = null private val cacheMaxAge = 5.minutes private val timeSource = TimeSource.Monotonic private var timestamp = timeSource.markNow() suspend fun getDrugInformation(search: String): Result<DrugInformation?> { Log.d("DrugInformationRepository", "Search Query: $search") return if(shouldFetchOutcomeCount(search)) { withContext(ioDispatcher) { try { val response = service.getDrugInformation(search) Log.d("DrugInformationRepository", "Response: $response") if(response.isSuccessful) { cachedDrugInformation = response.body() timestamp = timeSource.markNow() lastDrugSearched = search Result.success(cachedDrugInformation) } else { Result.failure(Exception(response.errorBody()?.string())) } } catch(e: Exception) { Result.failure(e) } } } else { Result.success(cachedDrugInformation!!) } } private fun shouldFetchOutcomeCount(search: String): Boolean = cachedDrugInformation == null || !search.contains(lastDrugSearched.toString(), true) || (timestamp + cacheMaxAge).hasPassedNow() }
final-project-rxwatch/app/src/main/java/com/example/cs492_finalproject_rxwatch/data/DrugInformationRepository.kt
3195583437
package com.example.renovategradleversioncatalogdemo.serviceB import kotlin.reflect.KFunction fun main(args: Array<String>) { bar(::foo) } fun foo() {} fun bar(function: KFunction<Any>) { println(function.name) }
renovate-gradle-version-catalog-demo/serviceB/src/main/kotlin/com/example/renovategradleversioncatalogdemo/serviceB/RenovateGradleVersionCatalogDemoApplication.kt
2133159278
package com.example.renovategradleversioncatalogdemo.serviceA import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json fun main(args: Array<String>) { val obj = Data(42, "str") val json = Json.encodeToString(obj) println(json) } @Serializable data class Data(val a: Int, val b: String)
renovate-gradle-version-catalog-demo/serviceA/src/main/kotlin/com/example/renovategradleversioncatalogdemo/serviceA/RenovateGradleVersionCatalogDemoApplication.kt
3880456418
package com.anushka.tmdbclient 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.tmdbclient", appContext.packageName) } }
Android_native_exercise/TMDBClient/app/src/androidTest/java/com/anushka/tmdbclient/ExampleInstrumentedTest.kt
841223214
package com.anushka.tmdbclient import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Android_native_exercise/TMDBClient/app/src/test/java/com/anushka/tmdbclient/ExampleUnitTest.kt
1884482454
package com.anushka.tmdbclient import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.anushka.tmdbclient.databinding.FragmentMovieDetailsBinding import com.bumptech.glide.Glide class MovieDetailsFragment : Fragment() { private lateinit var binding: FragmentMovieDetailsBinding private var movieId: Int = 0 private var movieTitle: String? = "N/A" private var movieOverview: String? = "N/A" private var movieReleaseDate: String? = "N/A" private var movieVoteAverage: String? = "N/A" private var moviePosterPath: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentMovieDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Obtiene los datos del anterior fragmento arguments?.let { movieId = it.getInt("movieId") movieOverview = it.getString("movieOverview") movieTitle = it.getString("movieTitle") movieReleaseDate = it.getString("movieReleaseDate") movieVoteAverage = it.getString("movieVoteAverage") moviePosterPath = it.getString("moviePosterPath") } // Ahora puedes usar los argumentos en tu lógica de fragmento binding.textViewTitle.text = movieTitle binding.textViewRating.text = movieVoteAverage binding.textViewSynopsis.text = movieOverview binding.textViewReleaseDate.text = movieReleaseDate // La imagen se carga diferente a los otros parametros val posterURL = "https://image.tmdb.org/t/p/w185$moviePosterPath" Glide.with(binding.imageViewPoster.context) .load(posterURL) .into(binding.imageViewPoster) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/MovieDetailsFragment.kt
3120338595
package com.anushka.tmdbclient import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.anushka.tmdbclient.databinding.ActivityMainBinding import com.anushka.tmdbclient.presentation.movie.MovieActivity import com.anushka.tmdbclient.presentation.topRateMovie.TopRateMovieActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val PREFS_NAME = "MyPrefsFile" private val PREF_FIRST_LAUNCH = "isFirstLaunch" private lateinit var sharedPreferences: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) val isFirstLaunch = sharedPreferences.getBoolean(PREF_FIRST_LAUNCH, true) if (isFirstLaunch) { // La aplicación se está ejecutando por primera vez, muestra la actividad val intent = Intent(this, LanguageActivity::class.java) startActivity(intent) // Establece la bandera de primera ejecución a false val editor = sharedPreferences.edit() editor.putBoolean(PREF_FIRST_LAUNCH, false) editor.apply() } binding.popularButton1.setOnClickListener { val intent = Intent(this, MovieActivity::class.java) startActivity(intent) } binding.ratedButton2.setOnClickListener { val intent = Intent(this, TopRateMovieActivity::class.java) startActivity(intent) } } override fun onResume() { super.onResume() // Evita volver atrás con gestos window.decorView.setOnTouchListener { _, _ -> true } } @SuppressLint("MissingSuperCall") override fun onBackPressed() { // No hagas nada para ignorar el evento de retroceso finish() } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/MainActivity.kt
3527493887
package com.anushka.tmdbclient 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.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.anushka.tmdbclient.databinding.FragmentTopRateMovieListBinding import com.anushka.tmdbclient.presentation.topRateMovie.TopRateMovieAdapter import com.anushka.tmdbclient.presentation.topRateMovie.TopRateMovieViewModel import com.anushka.tmdbclient.presentation.topRateMovie.TopRateMovieViewModelFactory import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class TopRateMovieListFragment : Fragment() { @Inject lateinit var factory: TopRateMovieViewModelFactory private lateinit var topRateMovieViewModel: TopRateMovieViewModel private lateinit var binding: FragmentTopRateMovieListBinding private lateinit var adapter: TopRateMovieAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentTopRateMovieListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) topRateMovieViewModel = ViewModelProvider(this, factory) .get(TopRateMovieViewModel::class.java) val responseLiveData = topRateMovieViewModel.getTopRateMovies() responseLiveData.observe(viewLifecycleOwner, Observer { Log.i("MYTAG", it.toString()) }) initRecyclerView() } private fun initRecyclerView() { binding.movieRecyclerView.layoutManager = GridLayoutManager(context,2) // Obtener NavController val navController = findNavController() adapter = TopRateMovieAdapter(navController) binding.movieRecyclerView.adapter = adapter displayTopRateMovies() } private fun displayTopRateMovies() { binding.movieProgressBar.visibility = View.VISIBLE val responseLiveData = topRateMovieViewModel.getTopRateMovies() responseLiveData.observe(viewLifecycleOwner, Observer { if (it != null) { adapter.setList(it) adapter.notifyDataSetChanged() binding.movieProgressBar.visibility = View.GONE } else { binding.movieProgressBar.visibility = View.GONE Toast.makeText(context, "No data available", Toast.LENGTH_LONG).show() } }) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/TopRateMovieListFragment.kt
3773322092
package com.anushka.tmdbclient import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.anushka.tmdbclient.databinding.ActivityLanguageBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LanguageActivity : AppCompatActivity() { private lateinit var binding: ActivityLanguageBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLanguageBinding.inflate(layoutInflater) setContentView(binding.root) // Segun el boton presionado, es el idioma que se escogera binding.enButton1.setOnClickListener { setLanguageInSharedPreferences("en-Us") val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } binding.esButton2.setOnClickListener { setLanguageInSharedPreferences("es") val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } } // Guarda la preferencia del idioma private fun setLanguageInSharedPreferences(language: String) { val sharedPreferences = applicationContext.getSharedPreferences("my_preferences", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putString("language", language) editor.apply() } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/LanguageActivity.kt
532395748
package com.anushka.tmdbclient 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.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.anushka.tmdbclient.databinding.FragmentMovieListBinding import com.anushka.tmdbclient.presentation.movie.MovieAdapter import com.anushka.tmdbclient.presentation.movie.MovieViewModel import com.anushka.tmdbclient.presentation.movie.MovieViewModelFactory import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MovieListFragment : Fragment() { @Inject lateinit var factory: MovieViewModelFactory private lateinit var movieViewModel: MovieViewModel private lateinit var binding: FragmentMovieListBinding private lateinit var adapter: MovieAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMovieListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) movieViewModel = ViewModelProvider(this, factory) .get(MovieViewModel::class.java) val responseLiveData = movieViewModel.getMovies() responseLiveData.observe(viewLifecycleOwner, Observer { Log.i("MYTAG", it.toString()) }) initRecyclerView() } private fun initRecyclerView() { binding.movieRecyclerView.layoutManager = GridLayoutManager(context,2) // Obtener NavController val navController = findNavController() adapter = MovieAdapter(navController) binding.movieRecyclerView.adapter = adapter displayPopularMovies() } private fun displayPopularMovies() { binding.movieProgressBar.visibility = View.VISIBLE val responseLiveData = movieViewModel.getMovies() responseLiveData.observe(viewLifecycleOwner, Observer { if (it != null) { adapter.setList(it) adapter.notifyDataSetChanged() binding.movieProgressBar.visibility = View.GONE } else { binding.movieProgressBar.visibility = View.GONE Toast.makeText(context, "No data available", Toast.LENGTH_LONG).show() } }) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/MovieListFragment.kt
1760081567
package com.anushka.tmdbclient import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.anushka.tmdbclient.databinding.FragmentTopRateMovieDetailsBinding import com.bumptech.glide.Glide class TopRateMovieDetailsFragment : Fragment() { private lateinit var binding: FragmentTopRateMovieDetailsBinding private var movieId: Int = 0 private var movieTitle: String? = "N/A" private var movieOverview: String? = "N/A" private var movieReleaseDate: String? = "N/A" private var movieVoteAverage: String? = "N/A" private var moviePosterPath: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentTopRateMovieDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { movieId = it.getInt("movieId") movieOverview = it.getString("movieOverview") movieTitle = it.getString("movieTitle") movieReleaseDate = it.getString("movieReleaseDate") movieVoteAverage = it.getString("movieVoteAverage") moviePosterPath = it.getString("moviePosterPath") } // Ahora puedes usar los argumentos en tu lógica de fragmento binding.textViewTitle.text = movieTitle binding.textViewRating.text = movieVoteAverage binding.textViewSynopsis.text = movieOverview binding.textViewReleaseDate.text = movieReleaseDate // La imagen se carga diferente a los otros parametros val posterURL = "https://image.tmdb.org/t/p/w185$moviePosterPath" Glide.with(binding.imageViewPoster.context) .load(posterURL) .into(binding.imageViewPoster) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/TopRateMovieDetailsFragment.kt
3110464164
package com.anushka.tmdbclient.data.repository.movie.datasource import com.anushka.tmdbclient.data.model.movie.Movie interface MovieLocalDataSource { suspend fun getMoviesFromDB():List<Movie> suspend fun saveMoviesToDB(movies:List<Movie>) suspend fun clearAll() }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasource/MovieLocalDataSource.kt
447655438
package com.anushka.tmdbclient.data.repository.movie.datasource import com.anushka.tmdbclient.data.model.movie.MovieList import retrofit2.Response interface MovieRemoteDatasource { suspend fun getMovies(): Response<MovieList> }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasource/MovieRemoteDatasource.kt
4090502265
package com.anushka.tmdbclient.data.repository.movie.datasource import com.anushka.tmdbclient.data.model.movie.Movie interface MovieCacheDataSource { suspend fun getMoviesFromCache():List<Movie> suspend fun saveMoviesToCache(movies:List<Movie>) }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasource/MovieCacheDataSource.kt
3057519315
package com.anushka.tmdbclient.data.repository.movie import android.util.Log import com.anushka.tmdbclient.data.model.movie.Movie import com.anushka.tmdbclient.data.repository.movie.datasource.MovieCacheDataSource import com.anushka.tmdbclient.data.repository.movie.datasource.MovieLocalDataSource import com.anushka.tmdbclient.data.repository.movie.datasource.MovieRemoteDatasource import com.anushka.tmdbclient.domain.repository.MovieRepository import java.lang.Exception class MovieRepositoryImpl( private val movieRemoteDatasource: MovieRemoteDatasource, private val movieLocalDataSource: MovieLocalDataSource, private val movieCacheDataSource: MovieCacheDataSource ) : MovieRepository { override suspend fun getMovies(): List<Movie>? { return getMoviesFromCache() } override suspend fun updateMovies(): List<Movie>? { val newListOfMovies = getMoviesFromAPI() movieLocalDataSource.clearAll() movieLocalDataSource.saveMoviesToDB(newListOfMovies) movieCacheDataSource.saveMoviesToCache(newListOfMovies) return newListOfMovies } suspend fun getMoviesFromAPI(): List<Movie> { lateinit var movieList: List<Movie> try { val response = movieRemoteDatasource.getMovies() val body = response.body() if(body!=null){ movieList = body.movies } } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } return movieList } suspend fun getMoviesFromDB():List<Movie>{ lateinit var movieList: List<Movie> try { movieList = movieLocalDataSource.getMoviesFromDB() } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } if(movieList.size>0){ return movieList }else{ movieList=getMoviesFromAPI() movieLocalDataSource.saveMoviesToDB(movieList) } return movieList } suspend fun getMoviesFromCache():List<Movie>{ lateinit var movieList: List<Movie> try { movieList =movieCacheDataSource.getMoviesFromCache() } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } if(movieList.size>0){ return movieList }else{ movieList=getMoviesFromDB() movieCacheDataSource.saveMoviesToCache(movieList) } return movieList } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/MovieRepositoryImpl.kt
556216011
package com.anushka.tmdbclient.data.repository.movie.datasourceImpl import com.anushka.tmdbclient.data.api.TMDBService import com.anushka.tmdbclient.data.model.movie.MovieList import com.anushka.tmdbclient.data.repository.movie.datasource.MovieRemoteDatasource import retrofit2.Response class MovieRemoteDataSourceImpl( private val tmdbService: TMDBService, private val apiKey:String, private var language: String ): MovieRemoteDatasource { override suspend fun getMovies(): Response<MovieList> = tmdbService.getPopularMovies(apiKey,language) }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasourceImpl/MovieRemoteDataSourceImpl.kt
1514445226
package com.anushka.tmdbclient.data.repository.movie.datasourceImpl import com.anushka.tmdbclient.data.db.MovieDao import com.anushka.tmdbclient.data.model.movie.Movie import com.anushka.tmdbclient.data.repository.movie.datasource.MovieLocalDataSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MovieLocalDataSourceImpl(private val movieDao:MovieDao): MovieLocalDataSource { override suspend fun getMoviesFromDB(): List<Movie> { return movieDao.getMovies() } override suspend fun saveMoviesToDB(movies: List<Movie>) { CoroutineScope(Dispatchers.IO).launch { movieDao.saveMovies(movies) } } override suspend fun clearAll() { CoroutineScope(Dispatchers.IO).launch { movieDao.deleteAllMovies() } } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasourceImpl/MovieLocalDataSourceImpl.kt
448470144
package com.anushka.tmdbclient.data.repository.movie.datasourceImpl import com.anushka.tmdbclient.data.model.movie.Movie import com.anushka.tmdbclient.data.repository.movie.datasource.MovieCacheDataSource class MovieCacheDataSourceImpl : MovieCacheDataSource { private var movieList = ArrayList<Movie>() override suspend fun getMoviesFromCache(): List<Movie> { return movieList } override suspend fun saveMoviesToCache(movies: List<Movie>) { movieList.clear() movieList = ArrayList(movies) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/movie/datasourceImpl/MovieCacheDataSourceImpl.kt
3678732431
package com.anushka.tmdbclient.data.repository.topRateMovie.datasource import com.anushka.tmdbclient.data.model.movie.TopRateMovie interface TopRateMovieCacheDataSource { suspend fun getTopRateMoviesFromCache():List<TopRateMovie> suspend fun saveTopRateMoviesToCache(topRateMovies:List<TopRateMovie>) }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasource/TopRateMovieCacheDataSource.kt
245646665
package com.anushka.tmdbclient.data.repository.topRateMovie.datasource import com.anushka.tmdbclient.data.model.movie.TopRateMoviesList import retrofit2.Response interface TopRateMovieRemoteDatasource { suspend fun getTopRateMovies(): Response<TopRateMoviesList> }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasource/TopRateMovieRemoteDatasource.kt
2049791413
package com.anushka.tmdbclient.data.repository.topRateMovie.datasource import com.anushka.tmdbclient.data.model.movie.TopRateMovie interface TopRateMovieLocalDataSource { suspend fun getTopRateMoviesFromDB():List<TopRateMovie> suspend fun saveTopRateMoviesToDB(topRateMovies:List<TopRateMovie>) suspend fun clearAll() }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasource/TopRateMovieLocalDataSource.kt
1971585443
package com.anushka.tmdbclient.data.repository.topRateMovie.datasourceImpl import com.anushka.tmdbclient.data.db.TopRateMovieDao import com.anushka.tmdbclient.data.model.movie.TopRateMovie import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieLocalDataSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TopRateMovieLocalDataSourceImpl(private val topRateMovieDao: TopRateMovieDao) : TopRateMovieLocalDataSource { override suspend fun getTopRateMoviesFromDB(): List<TopRateMovie> { return topRateMovieDao.getTopRateMovies() } // Usamos I/O para no bloquear el hilo principal override suspend fun saveTopRateMoviesToDB(topRateMovies: List<TopRateMovie>) { CoroutineScope(Dispatchers.IO).launch { topRateMovieDao.saveTopRateMovies(topRateMovies) } } override suspend fun clearAll() { CoroutineScope(Dispatchers.IO).launch { topRateMovieDao.deleteAllTopRateMovies() } } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasourceImpl/TopRateMovieLocalDataSourceImpl.kt
2450044294
package com.anushka.tmdbclient.data.repository.topRateMovie.datasourceImpl import com.anushka.tmdbclient.data.model.movie.TopRateMovie import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieCacheDataSource class TopRateMovieCacheDataSourceImpl : TopRateMovieCacheDataSource { private var topRateMovieList = ArrayList<TopRateMovie>() override suspend fun getTopRateMoviesFromCache(): List<TopRateMovie> { return topRateMovieList } override suspend fun saveTopRateMoviesToCache(topRateMovies: List<TopRateMovie>) { topRateMovieList.clear() topRateMovieList = ArrayList(topRateMovies) } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasourceImpl/TopRateMovieCacheDataSourceImpl.kt
731679133
package com.anushka.tmdbclient.data.repository.topRateMovie.datasourceImpl import com.anushka.tmdbclient.data.api.TMDBService import com.anushka.tmdbclient.data.model.movie.TopRateMoviesList import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieRemoteDatasource import retrofit2.Response class TopRateMovieRemoteDataSourceImpl( private val tmdbService: TMDBService, private val apiKey:String, private var language: String ) : TopRateMovieRemoteDatasource { override suspend fun getTopRateMovies(): Response<TopRateMoviesList> = tmdbService.getTopRatedMovies(apiKey, language) }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/datasourceImpl/TopRateMovieRemoteDataSourceImpl.kt
3074286305
package com.anushka.tmdbclient.data.repository.topRateMovie import android.util.Log import com.anushka.tmdbclient.data.model.movie.TopRateMovie import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieCacheDataSource import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieLocalDataSource import com.anushka.tmdbclient.data.repository.topRateMovie.datasource.TopRateMovieRemoteDatasource import com.anushka.tmdbclient.domain.repository.TopRateMovieRepository import java.lang.Exception class TopRateMovieRepositoryImpl( private val topRateMovieRemoteDatasource: TopRateMovieRemoteDatasource, private val topRateMovieLocalDataSource: TopRateMovieLocalDataSource, private val topRateMovieCacheDataSource: TopRateMovieCacheDataSource ) : TopRateMovieRepository { override suspend fun getTopRateMovies(): List<TopRateMovie>? { return getTopRateMoviesFromCache() } override suspend fun updateTopRateMovies(): List<TopRateMovie>? { val newListOfTopRateMovies = getTopRateMoviesFromAPI() topRateMovieLocalDataSource.clearAll() topRateMovieLocalDataSource.saveTopRateMoviesToDB(newListOfTopRateMovies) topRateMovieCacheDataSource.saveTopRateMoviesToCache(newListOfTopRateMovies) return newListOfTopRateMovies } suspend fun getTopRateMoviesFromAPI(): List<TopRateMovie> { lateinit var topRateMovieList: List<TopRateMovie> try { val response = topRateMovieRemoteDatasource.getTopRateMovies() val body = response.body() if(body!=null){ topRateMovieList = body.topRateMovies } } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } return topRateMovieList } suspend fun getTopRateMoviesFromDB():List<TopRateMovie>{ lateinit var topRateMovieList: List<TopRateMovie> try { topRateMovieList = topRateMovieLocalDataSource.getTopRateMoviesFromDB() } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } if(topRateMovieList.size>0){ return topRateMovieList }else{ topRateMovieList=getTopRateMoviesFromAPI() topRateMovieLocalDataSource.saveTopRateMoviesToDB(topRateMovieList) } return topRateMovieList } suspend fun getTopRateMoviesFromCache():List<TopRateMovie>{ lateinit var topRateMovieList: List<TopRateMovie> try { topRateMovieList =topRateMovieCacheDataSource.getTopRateMoviesFromCache() } catch (exception: Exception) { Log.i("MyTag", exception.message.toString()) } if(topRateMovieList.size>0){ return topRateMovieList }else{ topRateMovieList=getTopRateMoviesFromDB() topRateMovieCacheDataSource.saveTopRateMoviesToCache(topRateMovieList) } return topRateMovieList } }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/repository/topRateMovie/TopRateMovieRepositoryImpl.kt
1254818472
package com.anushka.tmdbclient.data.model.movie import com.anushka.tmdbclient.data.model.movie.Movie import com.google.gson.annotations.SerializedName // lista de películas (movies) obtenidas de una respuesta data class MovieList( @SerializedName("results") val movies: List<Movie> )
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/model/movie/MovieList.kt
899187654
package com.anushka.tmdbclient.data.model.movie import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName // Modelo de la clase Movie @Entity(tableName = "popular_movies") data class Movie( @PrimaryKey @SerializedName("id") val id: Int, @SerializedName("overview") val overview: String, @SerializedName("poster_path") val posterPath: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("title") val title: String, @SerializedName("vote_average") val voteAverage: String, )
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/model/movie/Movie.kt
2915886956
package com.anushka.tmdbclient.data.model.movie import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "top_rate_movies") data class TopRateMovie( @PrimaryKey @SerializedName("id") val id: Int, @SerializedName("overview") val overview: String, @SerializedName("poster_path") val posterPath: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("title") val title: String, @SerializedName("vote_average") val voteAverage: String, )
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/model/movie/TopRateMovie.kt
3008956859
package com.anushka.tmdbclient.data.model.movie import com.google.gson.annotations.SerializedName data class TopRateMoviesList( @SerializedName("results") val topRateMovies: List<TopRateMovie> )
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/model/movie/TopRateMoviesList.kt
2355900071
package com.anushka.tmdbclient.data.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.anushka.tmdbclient.data.model.movie.Movie //Proporciona métodos para realizar consultas personalizadas @Dao interface MovieDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveMovies(movies: List<Movie>) @Query("DELETE FROM popular_movies") suspend fun deleteAllMovies() @Query("SELECT * FROM popular_movies") suspend fun getMovies(): List<Movie> }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/db/MovieDao.kt
823121882
package com.anushka.tmdbclient.data.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.anushka.tmdbclient.data.model.movie.TopRateMovie //Proporciona métodos para realizar consultas personalizadas @Dao interface TopRateMovieDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveTopRateMovies(topRateMovies: List<TopRateMovie>) @Query("DELETE FROM top_rate_movies") suspend fun deleteAllTopRateMovies() @Query("SELECT * FROM top_rate_movies") suspend fun getTopRateMovies(): List<TopRateMovie> }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/db/TopRateMovieDao.kt
1603727633
package com.anushka.tmdbclient.data.db import androidx.room.Database import androidx.room.RoomDatabase import com.anushka.tmdbclient.data.model.movie.Movie import com.anushka.tmdbclient.data.model.movie.TopRateMovie // Proporciona un punto de acceso principal para interactuar con la base de datos SQLite @Database(entities = [Movie::class,TopRateMovie::class], version = 1, exportSchema = false ) abstract class TMDBDatabase : RoomDatabase(){ abstract fun movieDao(): MovieDao abstract fun topRateMovieDao(): TopRateMovieDao }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/db/TMDBDatabase.kt
2812729500
package com.anushka.tmdbclient.data.api import com.anushka.tmdbclient.data.model.movie.MovieList import com.anushka.tmdbclient.data.model.movie.TopRateMoviesList import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query // Se encarga de obtener el endpoint de la app interface TMDBService { @GET("movie/popular") suspend fun getPopularMovies( @Query("api_key") apiKey: String, @Query("language") language: String // Parámetro para el idioma ): Response<MovieList> @GET("movie/top_rated") suspend fun getTopRatedMovies( @Query("api_key") apiKey: String, @Query("language") language: String // Parámetro para el idioma ): Response<TopRateMoviesList> }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/data/api/TMDBService.kt
2456413935
package com.anushka.tmdbclient.domain.repository import com.anushka.tmdbclient.data.model.movie.TopRateMovie interface TopRateMovieRepository { suspend fun getTopRateMovies():List<TopRateMovie>? suspend fun updateTopRateMovies():List<TopRateMovie>? }
Android_native_exercise/TMDBClient/app/src/main/java/com/anushka/tmdbclient/domain/repository/TopRateMovieRepository.kt
356245253