content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.kcb import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Person import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource 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.input.PasswordVisualTransformation 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.kcb.ui.theme.KCBTheme import androidx.compose.runtime.mutableStateOf as mutableStateOf1 class formactivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Forms() } } } @Composable fun Forms() { Column( modifier = Modifier .fillMaxSize() .paint( painterResource(id = R.drawable.background), contentScale = ContentScale.FillBounds ) .verticalScroll(rememberScrollState()) ) { val mContext = LocalContext.current var firstname by remember { mutableStateOf("") } var lastname by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var contact by remember { mutableStateOf("") } var location by remember { mutableStateOf("") } Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = R.drawable.register1), contentDescription = "register", modifier = Modifier.size(200.dp) ) } androidx.compose.material3.Text( text = "Create an account", fontSize = 24.sp, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, textDecoration = TextDecoration.Underline, color = Color.White ) Spacer(modifier = Modifier.height(20.dp)) TextField( value = firstname, onValueChange = { firstname = it }, placeholder = { androidx.compose.material3.Text(text = "Firstname") }, leadingIcon = { Icon( imageVector = Icons.Default.Person, contentDescription = "person" ) }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text) ) Spacer(modifier = Modifier.height(20.dp)) TextField( value = lastname, onValueChange = { lastname = it }, placeholder = { androidx.compose.material3.Text(text = "Lastname") }, leadingIcon = { Icon( imageVector = Icons.Default.Person, contentDescription = "person" ) }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text) ) Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(20.dp)) TextField( value = email, onValueChange = { email = it }, placeholder = { androidx.compose.material3.Text(text = "Email") }, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "email") }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) ) Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(20.dp)) TextField( value = password, onValueChange = { password = it }, placeholder = { androidx.compose.material3.Text(text = "Password") }, leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "lock") }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(20.dp)) TextField( value = contact, onValueChange = { contact = it }, placeholder = { androidx.compose.material3.Text(text = "Phone number") }, leadingIcon = { Icon(imageVector = Icons.Default.Call, contentDescription = "call") }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = location, onValueChange = { location = it }, placeholder = { androidx.compose.material3.Text(text = "Location") }, leadingIcon = { Icon( imageVector = Icons.Default.LocationOn, contentDescription = "location" ) }, modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(10.dp)) Box( modifier = Modifier .fillMaxWidth(), contentAlignment = Alignment.Center ) { Button( onClick = {}, shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors(Color.DarkGray), modifier = Modifier .fillMaxWidth() .padding(start = 60.dp, end = 60.dp) ) { Text( text = "Sign up", color = Color.Black ) } Spacer(modifier = Modifier.height(30.dp)) } androidx.compose.material3.Text( text = "Already have an account?Log in.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth() .clickable { mContext.startActivity(Intent(mContext,LoginActivity::class.java)) }, textAlign = TextAlign.Center, textDecoration = TextDecoration.Underline, color = Color.White ) } } @Preview(showBackground = true) @Composable fun FormsPreview() { Forms() }
KCB-Android/app/src/main/java/com/example/kcb/formactivity.kt
1375008004
package com.example.kcb import android.content.Intent import android.graphics.drawable.Icon import android.os.Bundle import android.provider.MediaStore import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Share import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource 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.core.net.toUri import com.example.kcb.ui.theme.KCBTheme class IntentActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyIntents() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MyIntents(){ Column(modifier = Modifier .fillMaxSize() .paint(painterResource(id = R.drawable.background), contentScale = ContentScale.FillBounds) ) { val mContext = LocalContext.current TopAppBar(title = { Text(text = "Intents", color = Color.Gray) }, colors = TopAppBarDefaults.mediumTopAppBarColors(Color.Black), navigationIcon = { IconButton(onClick = { mContext.startActivity(Intent(mContext, Layoutactivity::class.java)) }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "arrowback" , tint = Color.DarkGray) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Default.Add, contentDescription = "add", tint = Color.White) } IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon(imageVector = Icons.Default.Settings, contentDescription = "settings", tint = Color.White) } }) //End of TopAppBar Spacer(modifier = Modifier.height(5.dp)) //STK OutlinedButton(onClick = { val simToolKitLaunchIntent = mContext.packageManager.getLaunchIntentForPackage("com.android.stk") simToolKitLaunchIntent?.let { mContext.startActivity(it) } }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "M-pesa", color = Color.White) } Spacer(modifier = Modifier.height(5.dp)) //Email OutlinedButton(onClick = { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Mansory Car Expo") shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, the Expo is scheduled for 22nd to 26th July 2024.") mContext.startActivity(shareIntent) }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "Email", color = Color.White) } Spacer(modifier = Modifier.height(5.dp)) //SMS OutlinedButton(onClick = { val smsIntent=Intent(Intent.ACTION_SENDTO) smsIntent.data="smsto:0741690058".toUri() smsIntent.putExtra("sms_body","Hello Sherly,how was your day?") mContext.startActivity(smsIntent) }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "SMS", color = Color.White) } //Call Spacer(modifier = Modifier.height(5.dp)) OutlinedButton(onClick = { val callIntent=Intent(Intent.ACTION_DIAL) callIntent.data="tel:0741690058".toUri() mContext.startActivity(callIntent) }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "Call", color = Color.White) } //Camera Spacer(modifier = Modifier.height(5.dp)) OutlinedButton(onClick = { val cameraIntent=Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (cameraIntent.resolveActivity(mContext.packageManager)!=null){ mContext.startActivity(cameraIntent) }else{ println("Camera app is not available") } }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "Camera", color = Color.White) } //Share Spacer(modifier = Modifier.height(5.dp)) OutlinedButton(onClick = { val shareIntent=Intent(Intent.ACTION_SEND) shareIntent.type="text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out this is a cool content") mContext.startActivity(Intent.createChooser(shareIntent, "Share")) }, modifier = Modifier .fillMaxWidth() .padding(start = 85.dp, end = 85.dp), shape = RoundedCornerShape(10.dp), border = BorderStroke(2.dp, Color.Gray) ) { androidx.compose.material3.Text( text = "Share", color = Color.White) } androidx.compose.material3.Text( text = "Don't have an aacount? Register.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth() .clickable { mContext.startActivity(Intent(mContext,formactivity::class.java)) }, textAlign = TextAlign.Center, textDecoration = TextDecoration.Underline, color = Color.White ) } } @Preview(showBackground = true) @Composable fun MyIntentsPreview(){ MyIntents() }
KCB-Android/app/src/main/java/com/example/kcb/IntentActivity.kt
1696172942
package com.example.kcb import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext 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.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.example.kcb.ui.theme.KCBTheme class LottieActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyLottie() } } } @Composable fun MyLottie(){ Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { val mContext = LocalContext.current //Lottie Animation val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.music)) val progress by animateLottieCompositionAsState(composition) LottieAnimation(composition, progress, modifier = Modifier.size(300.dp) ) Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Explore...", fontWeight = FontWeight.ExtraBold, fontSize = 30.sp, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = Color.Black ) Spacer(modifier = Modifier.height(20.dp)) Button( onClick = { mContext.startActivity(Intent(mContext,SplashScreenActivity::class.java)) }, shape = RoundedCornerShape(22.dp), colors = ButtonDefaults.buttonColors(Color.Black), modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp) ) { Text(text = "Continue ", fontSize = 22.sp) Spacer(modifier = Modifier.height(20.dp)) } } } @Preview(showBackground = true) @Composable fun MyLottiePreview(){ MyLottie() }
KCB-Android/app/src/main/java/com/example/kcb/LottieActivity.kt
3003138678
package com.example.kcb import android.content.Intent import android.os.Bundle import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Notifications import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Star import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import com.example.kcb.ui.theme.KCBTheme class DiscoverActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Discover() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Discover() { Column( modifier = Modifier .fillMaxSize() ) { val mContext = LocalContext.current TopAppBar(title = { Text(text = "Cities", color = Color.Black) }, colors = TopAppBarDefaults.mediumTopAppBarColors(Color.White), navigationIcon = { IconButton(onClick = { mContext.startActivity(Intent(mContext, Layoutactivity::class.java)) }) { Icon( imageVector = Icons.Default.Menu, contentDescription = "menu", tint = Color.Black ) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Default.Share, contentDescription = "share", tint = Color.Black ) } IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon( imageVector = Icons.Default.Search, contentDescription = "search", tint = Color.Black ) } //end of topappbar IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon( imageVector = Icons.Default.Notifications, contentDescription = "search", tint = Color.Black ) } }) Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { androidx.compose.material3.Text( text = "Tickets", fontSize = 40.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Cursive, modifier = Modifier.padding(start = 10.dp) ) } Spacer(modifier = Modifier.height(10.dp)) //Column 1 Card( modifier = Modifier .height(150.dp) .width(150.dp) ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Spacer(modifier = Modifier.width(10.dp)) Image( painter = painterResource(id = R.drawable.nairobi), contentDescription = "nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds ) Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = "favourite", tint = Color.White, modifier = Modifier .align(Alignment.TopEnd) .padding(15.dp) ) } } Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Nairobi", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) Row { Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) } Spacer(modifier = Modifier.height(3.dp)) androidx.compose.material3.Text( text = "512 Reviews", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(3.dp)) androidx.compose.material3.Text( text = "Ksh.47,000", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, color = Color.Blue ) Spacer(modifier = Modifier.height(6.dp)) Row { OutlinedButton(onClick = { val callIntent = Intent(Intent.ACTION_DIAL) callIntent.data = "tel:0741690058".toUri() mContext.startActivity(callIntent) }) { androidx.compose.material3.Text(text = "Call") } Spacer(modifier = Modifier.width(4.dp)) OutlinedButton(onClick = { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Destination Booking") shareIntent.putExtra( Intent.EXTRA_TEXT, "Hello,welcome to our ticket booking site ." ) mContext.startActivity(shareIntent) }) { androidx.compose.material3.Text(text = "Email") } } } //End of Column } @Preview(showBackground = true) @Composable fun DiscoverPreview(){ Discover() }
KCB-Android/app/src/main/java/com/example/kcb/DiscoverActivity.kt
2339201659
package com.example.kcb import android.content.Intent import android.os.Bundle import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.kcb.ui.theme.KCBTheme class DestinationActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Destination() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Destination(){ Column( modifier = Modifier .fillMaxSize() ) { val mContext = LocalContext.current TopAppBar(title = { Text(text = "Destination", color = Color.Gray) }, colors = TopAppBarDefaults.mediumTopAppBarColors(Color.Black), navigationIcon = { IconButton(onClick = { mContext.startActivity(Intent(mContext, Layoutactivity::class.java)) }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "arrowback" , tint = Color.DarkGray) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon(imageVector = Icons.Default.Add, contentDescription = "add", tint = Color.White) } IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon(imageVector = Icons.Default.Settings, contentDescription = "settings", tint = Color.White) //end of topappbar } }) Box (modifier = Modifier .fillMaxWidth() .height(250.dp), contentAlignment = Alignment.Center){ Image(painter = painterResource(id = R.drawable.nairobi), contentDescription ="nairobi" , modifier =Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) androidx.compose.material3.Text( text ="Let's plan your next vacation", fontSize = 28.sp, fontWeight = FontWeight.Bold, color = Color.White, textAlign = TextAlign.Center) } //End of box Spacer(modifier = Modifier.height(20.dp)) var search by remember{ mutableStateOf("") } OutlinedTextField( value =search , onValueChange ={search = it}, modifier = Modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp), placeholder ={ androidx.compose.material3.Text(text = "What's your next destination?") }, leadingIcon = { Icon(imageVector = Icons.Default.Search, contentDescription = "search")}) //End of search bar Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text(text ="Recently viewed..." , fontSize = 20.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.SansSerif, modifier = Modifier.padding(20.dp, end = 20.dp)) Spacer(modifier = Modifier.height(7.dp)) Row(modifier = Modifier.horizontalScroll(rememberScrollState())) { Card (modifier = Modifier .height(250.dp) .width(200.dp)){ Column { Box(modifier = Modifier .fillMaxWidth() .height(150.dp), contentAlignment = Alignment.Center) { Image(painter = painterResource(id = R.drawable.nairobi), contentDescription ="nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Spacer(modifier = Modifier.height(10.dp)) //card 1 androidx.compose.material3.Text( text = "Kianda.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Center) } } //End of Card 1 Spacer(modifier = Modifier.width(5.dp)) Card (modifier = Modifier .height(250.dp) .width(200.dp)){ Column { Box(modifier = Modifier .fillMaxWidth() .height(150.dp), contentAlignment = Alignment.Center) { Image(painter = painterResource(id = R.drawable.nairobi), contentDescription ="nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Spacer(modifier = Modifier.height(10.dp)) //card 1 androidx.compose.material3.Text( text = "Nairobi.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Center) } } //End of Card 1 Spacer(modifier = Modifier.width(5.dp)) Card (modifier = Modifier .height(250.dp) .width(200.dp)){ Column { Box(modifier = Modifier .fillMaxWidth() .height(150.dp), contentAlignment = Alignment.Center) { Image(painter = painterResource(id = R.drawable.nairobi), contentDescription ="nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Spacer(modifier = Modifier.height(10.dp)) //card 1 androidx.compose.material3.Text( text = "Gachie.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Center) } } //End of Card 1 Spacer(modifier = Modifier.width(5.dp)) Card (modifier = Modifier .height(250.dp) .width(200.dp)){ Column { Box(modifier = Modifier .fillMaxWidth() .height(150.dp), contentAlignment = Alignment.Center) { Image(painter = painterResource(id = R.drawable.nairobi), contentDescription ="nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Spacer(modifier = Modifier.height(10.dp)) //card 1 androidx.compose.material3.Text( text = "Thindigwa.", fontSize = 16.sp, modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Center) } } //End of Card 1 Spacer(modifier = Modifier.width(5.dp)) } //End of row 1 } } @Preview(showBackground = true) @Composable fun DestinationPreview(){ Destination() }
KCB-Android/app/src/main/java/com/example/kcb/DestinationActivity.kt
3639375257
package com.example.kcb import android.content.Intent import android.os.Bundle import android.widget.Space import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Lock import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation 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.kcb.ui.theme.Brown import com.example.kcb.ui.theme.KCBTheme class LoginActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Login() } } } @Composable fun Login() { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState(),) ) { val mContext = LocalContext.current var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = R.drawable.login), contentDescription = "login", modifier = Modifier.size(150.dp) ) } androidx.compose.material3.Text( text = "Log in", fontWeight = FontWeight.Bold, fontSize = 30.sp, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, textDecoration = TextDecoration.Underline, color = Brown ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = email, onValueChange = { email = it }, placeholder = { androidx.compose.material3.Text(text = "Email") }, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "email") }, modifier = Modifier .fillMaxWidth() .padding(start = 35.dp, end = 35.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, placeholder = { androidx.compose.material3.Text(text = "Password") }, leadingIcon = { Icon( imageVector = Icons.Default.Lock, contentDescription = "password" ) }, modifier = Modifier .fillMaxWidth() .padding(start = 35.dp, end = 35.dp), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email), visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Forgot password?", fontSize = 20.sp, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline, color = Color.Black ) Spacer(modifier = Modifier.height(30.dp)) Button( onClick = { mContext.startActivity(Intent(mContext,LottieActivity::class.java)) }, shape = RoundedCornerShape(22.dp), colors = ButtonDefaults.buttonColors(Color.Black), modifier = Modifier .fillMaxWidth() .padding(start = 30.dp, end = 30.dp) ) { androidx.compose.material3.Text(text = "Log in ", fontSize = 22.sp) Spacer(modifier = Modifier) } } } @Preview(showBackground = true) @Composable fun LoginPreview(){ Login() }
KCB-Android/app/src/main/java/com/example/kcb/LoginActivity.kt
4200902776
package com.example.kcb import android.content.Intent import android.os.Bundle import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Notifications import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Star import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import com.example.kcb.ui.theme.KCBTheme class ExploreActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Explore() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Explore() { Column( modifier = Modifier .fillMaxSize() ) { val mContext = LocalContext.current TopAppBar(title = { Text(text = "Cities", color = Color.Black) }, colors = TopAppBarDefaults.mediumTopAppBarColors(Color.White), navigationIcon = { IconButton(onClick = { mContext.startActivity(Intent(mContext, Layoutactivity::class.java)) }) { Icon( imageVector = Icons.Default.Menu, contentDescription = "menu", tint = Color.Black ) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Default.Share, contentDescription = "share", tint = Color.Black ) } IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon( imageVector = Icons.Default.Search, contentDescription = "search", tint = Color.Black ) } //end of topappbar IconButton(onClick = { val settingsIntent = Intent(Settings.ACTION_SETTINGS) mContext.startActivity(settingsIntent) }) { Icon( imageVector = Icons.Default.Notifications, contentDescription = "search", tint = Color.Black ) } }) Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { androidx.compose.material3.Text( text = "Tickets", fontSize = 40.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Cursive, modifier = Modifier.padding(start = 10.dp) ) } Spacer(modifier = Modifier.height(10.dp)) //Column 1 Card( modifier = Modifier .height(150.dp) .width(150.dp) ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Spacer(modifier = Modifier.width(10.dp)) Image( painter = painterResource(id = R.drawable.nairobi), contentDescription = "nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds ) Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = "favourite", tint = Color.White, modifier = Modifier .align(Alignment.TopEnd) .padding(15.dp) ) } } Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Nairobi", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) Row { Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) Icon( imageVector = Icons.Default.Star, contentDescription = "star", tint = Color.Blue ) } Spacer(modifier = Modifier.height(3.dp)) androidx.compose.material3.Text( text = "512 Reviews", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(3.dp)) androidx.compose.material3.Text( text = "Ksh.47,000", fontSize = 15.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, color = Color.Blue ) Spacer(modifier = Modifier.height(6.dp)) Row { OutlinedButton(onClick = { val callIntent = Intent(Intent.ACTION_DIAL) callIntent.data = "tel:0741690058".toUri() mContext.startActivity(callIntent) }) { androidx.compose.material3.Text(text = "Call") } Spacer(modifier = Modifier.width(4.dp)) OutlinedButton(onClick = { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Destination Booking") shareIntent.putExtra( Intent.EXTRA_TEXT, "Hello,welcome to our ticket booking site ." ) mContext.startActivity(shareIntent) }) { androidx.compose.material3.Text(text = "Email") } } } //End of Column } @Preview(showBackground = true) @Composable fun ExplorePreview(){ Explore() }
KCB-Android/app/src/main/java/com/example/kcb/ExploreActivity.kt
3730834033
package com.example.kcb import android.content.Intent import android.os.Bundle import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.kcb.ui.theme.Grey import com.example.kcb.ui.theme.KCBTheme class ChairsActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Chairs() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Chairs() { Column( modifier = Modifier .fillMaxSize() .background(Grey) ) { val mContext = LocalContext.current TopAppBar(title = { Text(text = "", color = Color.Gray) }, colors = TopAppBarDefaults.mediumTopAppBarColors(Grey), navigationIcon = { IconButton(onClick = { mContext.startActivity( Intent( mContext, Layoutactivity::class.java ) ) }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "arrowback", tint = Color.Black ) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Default.Lock, contentDescription = "lock", tint = Color.Black ) } IconButton(onClick = { }) { Icon( imageVector = Icons.Default.Menu, contentDescription = "menu", tint = Color.Black ) } }) //End of TopAppBar Row(modifier = Modifier.horizontalScroll(rememberScrollState())) { androidx.compose.material3.Text( text = "Chairs", fontSize = 30.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.width(15.dp)) androidx.compose.material3.Text( text = "Tables", fontSize = 30.sp, fontWeight = FontWeight.Normal, fontFamily = FontFamily.Serif, color = Color.Gray ) Spacer(modifier = Modifier.width(15.dp)) androidx.compose.material3.Text( text = "Sofa", fontSize = 30.sp, fontWeight = FontWeight.Normal, fontFamily = FontFamily.Serif, color = Color.Gray ) Spacer(modifier = Modifier.width(15.dp)) androidx.compose.material3.Text( text = "Beds", fontSize = 30.sp, fontWeight = FontWeight.Normal, fontFamily = FontFamily.Serif, color = Color.Gray ) } Spacer(modifier = Modifier.height(10.dp)) Row { androidx.compose.material3.Text( text = "120 products", fontSize = 15.sp, fontWeight = FontWeight.Normal, fontFamily = FontFamily.Serif, color = Color.Gray ) androidx.compose.material3.Text( text = " Popular", fontSize = 15.sp, fontWeight = FontWeight.Normal, modifier = Modifier.padding(start = 210.dp), fontFamily = FontFamily.Serif, color = Color.Black ) IconButton(onClick = { }) { Icon( imageVector = Icons.Default.ArrowDropDown, contentDescription = "dropdown", tint = Color.Black ) } } Spacer(modifier = Modifier.height(3.dp)) //Column 1 Column { Row { Spacer(modifier = Modifier.width(20.dp)) Card { Card( modifier = Modifier .height(150.dp) .width(150.dp) ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Spacer(modifier = Modifier.width(10.dp)) Image( painter = painterResource(id = R.drawable.chair2), contentDescription = "nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds ) } } Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Amos Chair", fontSize = 25.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) androidx.compose.material3.Text( text = "A wooden chair an", fontSize = 15.sp, fontFamily = FontFamily.Serif, ) androidx.compose.material3.Text( text = " amazing design ", fontSize = 15.sp, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) Row { androidx.compose.material3.Text( text = " $ 680 ", fontSize = 20.sp, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = { }) { Icon( imageVector = Icons.Default.Lock, contentDescription = "lock", tint = Color.DarkGray ) } } //End of column 1 } Spacer(modifier = Modifier.width(20.dp)) Card { Card( modifier = Modifier .height(150.dp) .width(150.dp) ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Spacer(modifier = Modifier.width(10.dp)) Image( painter = painterResource(id = R.drawable.chair1), contentDescription = "nairobi", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds ) } } Spacer(modifier = Modifier.height(20.dp)) androidx.compose.material3.Text( text = "Amos Chair", fontSize = 25.sp, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) androidx.compose.material3.Text( text = "A wooden chair an", fontSize = 15.sp, fontFamily = FontFamily.Serif, ) androidx.compose.material3.Text( text = " amazing design ", fontSize = 15.sp, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.height(5.dp)) Row { androidx.compose.material3.Text( text = " $ 680 ", fontSize = 20.sp, fontFamily = FontFamily.Serif, ) Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = { }) { Icon( imageVector = Icons.Default.Lock, contentDescription = "lock", tint = Color.DarkGray ) } } //End of column 1 } } // end of row one } } } @Preview(showBackground = true, showSystemUi = true) @Composable fun ChairsPreview(){ Chairs() }
KCB-Android/app/src/main/java/com/example/kcb/ChairsActivity.kt
1461017402
package com.example.mysqlitedatabaseapp 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.mysqlitedatabaseapp", appContext.packageName) } }
MySqliteDatabaseapp/app/src/androidTest/java/com/example/mysqlitedatabaseapp/ExampleInstrumentedTest.kt
3150110565
package com.example.mysqlitedatabaseapp 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) } }
MySqliteDatabaseapp/app/src/test/java/com/example/mysqlitedatabaseapp/ExampleUnitTest.kt
14696255
package com.example.mysqlitedatabaseapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/ui/theme/Color.kt
316305665
package com.example.mysqlitedatabaseapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MySqliteDatabaseAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/ui/theme/Theme.kt
4249531641
package com.example.mysqlitedatabaseapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/ui/theme/Type.kt
1881119650
package com.example.mysqlitedatabaseapp.ui.theme import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DBHandler // creating a constructor for our database handler. (context: Context?) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { // below method is for creating a database by running a sqlite query override fun onCreate(db: SQLiteDatabase) { // on below line we are creating an sqlite query and we are // setting our column names along with their data types. val query = ("CREATE TABLE " + TABLE_NAME + " (" + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_COL + " TEXT," + EMAIL_COL + " TEXT," + ID_NO_COL + " TEXT)") // at last we are calling a exec sql method to execute above sql query db.execSQL(query) } // this method is use to add new users to our sqlite database. fun addNewUser( name: String?, email: String?, idNumber: String?, ) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. val db = this.writableDatabase // on below line we are creating a // variable for content values. val values = ContentValues() // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, name) values.put(EMAIL_COL, email) values.put(ID_NO_COL, idNumber) // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values) // at last we are closing our // database after adding database. db.close() } fun getDatabase() = this.writableDatabase override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // this method is called to check if the table exists already. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) onCreate(db) } companion object { // creating a constant variables for our database. // below variable is for our database name. private const val DB_NAME = "emobilis_db" // below int is our database version private const val DB_VERSION = 1 // below variable is for our table name. private const val TABLE_NAME = "users" // below variable is for our id column. private const val ID_COL = "id" // below variable is for our course name column private const val NAME_COL = "jina" // below variable id for our course email column. private const val EMAIL_COL = "arafa" // below variable for our course id_no column. private const val ID_NO_COL = "id_no" } }
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/ui/theme/Dbhandler.kt
1096247845
package com.example.mysqlitedatabaseapp import android.app.AlertDialog import android.content.Context import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mysqlitedatabaseapp.models.DBHandler import com.example.mysqlitedatabaseapp.ui.theme.MySqliteDatabaseAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MySqliteDatabaseAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { HomeScreen() } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeScreen() { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Welcome to our App", color = Color.Red, fontSize = 40.sp, fontFamily = FontFamily.Cursive ) Spacer(modifier = Modifier.height(20.dp)) var name by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } var idNumber by remember { mutableStateOf("") } OutlinedTextField( value = name, onValueChange = {name = it}, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text ), label = { Text(text = "Enter name")} ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = email, onValueChange = {email = it}, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email ), label = { Text(text = "Enter email")} ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = idNumber, onValueChange = {idNumber = it}, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number ), label = { Text(text = "Enter id number")} ) Spacer(modifier = Modifier.height(20.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { val context = LocalContext.current var dbHandler = DBHandler(context) // Access the db from the handler var db = dbHandler.getDatabase() Button(onClick = { if (name.isEmpty() || email.isEmpty() || idNumber.isEmpty()){ messages("EMPTY FIELDS", "Please fill all inputs!!!", context) }else{ // Proceed to save the data dbHandler.addNewUser(name, email, idNumber) messages("SUCCESS!!!","User saved successfully", context) db.close() } }) { Text(text = "Save") } Button(onClick = { // Select data from the database val data = db.rawQuery("SELECT * FROM users", null) if (data.count == 0){ messages("NO DATA!!","Sorry, there's no data", context) }else{ val buffer = StringBuffer() while (data.moveToNext()){ buffer.append(data.getString(0)+"\n") buffer.append(data.getString(1)+"\n") buffer.append(data.getString(2)+"\n") buffer.append(data.getString(3)+"\n\n") } messages("USERS!!!", buffer.toString(),context) db.close() } }) { Text(text = "View") } Button(onClick = { if (idNumber.isEmpty()){ messages("EMPTY FIELD","Please enter id no", context) }else{ // Proceed to delete var users = db.rawQuery("SELECT * FROM users WHERE id_no='"+idNumber+"'",null) if (users.count == 0){ messages("NO USERS","Sorry, no users found", context) }else{ // Finally delete the data db.execSQL("DELETE FROM users WHERE id_no='"+idNumber+"'") messages("SUCCESS","User deleted successfully",context) } } }) { Text(text = "Delete") } } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MySqliteDatabaseAppTheme { HomeScreen() } } fun messages(title:String, message: String, context:Context){ var alertDialog = AlertDialog.Builder(context) alertDialog.setTitle(title) alertDialog.setMessage(message) alertDialog.create().show() }
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/MainActivity.kt
4120720109
package com.example.mysqlitedatabaseapp.models import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DBHandler // creating a constructor for our database handler. (context: Context?) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { // below method is for creating a database by running a sqlite query override fun onCreate(db: SQLiteDatabase) { // on below line we are creating an sqlite query and we are // setting our column names along with their data types. val query = ("CREATE TABLE " + TABLE_NAME + " (" + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_COL + " TEXT," + EMAIL_COL + " TEXT," + ID_NO_COL + " TEXT)") // at last we are calling a exec sql method to execute above sql query db.execSQL(query) } // this method is use to add new users to our sqlite database. fun addNewUser( name: String?, email: String?, idNumber: String?, ) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. val db = this.writableDatabase // on below line we are creating a // variable for content values. val values = ContentValues() // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, name) values.put(EMAIL_COL, email) values.put(ID_NO_COL, idNumber) // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values) // at last we are closing our // database after adding database. db.close() } fun getDatabase() = this.writableDatabase override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // this method is called to check if the table exists already. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) onCreate(db) } companion object { // creating a constant variables for our database. // below variable is for our database name. private const val DB_NAME = "emobilis_db" // below int is our database version private const val DB_VERSION = 1 // below variable is for our table name. private const val TABLE_NAME = "users" // below variable is for our id column. private const val ID_COL = "id" // below variable is for our course name column private const val NAME_COL = "jina" // below variable id for our course email column. private const val EMAIL_COL = "arafa" // below variable for our course id_no column. private const val ID_NO_COL = "id_no" } }
MySqliteDatabaseapp/app/src/main/java/com/example/mysqlitedatabaseapp/models/DBHandler.kt
2411986913
package com.example.insta 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.insta", appContext.packageName) } }
NewsFeedApp/Insta 6/app/src/androidTest/java/com/example/insta/ExampleInstrumentedTest.kt
3875414812
package com.example.insta 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) } }
NewsFeedApp/Insta 6/app/src/test/java/com/example/insta/ExampleUnitTest.kt
3955938511
// MainActivity.kt package com.example.insta import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider class MainActivity : AppCompatActivity() { private lateinit var viewModel: PostViewModel private lateinit var postsTextView: TextView private var currentIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProvider(this, PostViewModelFactory(application)).get(PostViewModel::class.java) postsTextView = findViewById(R.id.postsTextView) val nextButton = findViewById<Button>(R.id.nextButton) nextButton.setOnClickListener { showNextPost() } val shareButton = findViewById<Button>(R.id.shareButton) shareButton.setOnClickListener { sharePostDetails() } val aboutButton = findViewById<Button>(R.id.aboutButton) aboutButton.setOnClickListener { startActivity(Intent(this, AboutActivity::class.java)) } viewModel.postsData.observe(this, { posts -> if (posts != null && posts.isNotEmpty()) { updatePostDetails(posts[currentIndex]) } else { postsTextView.text = "Failed to fetch posts." } }) viewModel.fetchPosts() } private fun showNextPost() { currentIndex++ // Handle looping back to the first post if currentIndex exceeds the number of posts if (currentIndex >= viewModel.postsData.value?.size ?: 0) { currentIndex = 0 } viewModel.postsData.value?.get(currentIndex)?.let { updatePostDetails(it) } } private fun updatePostDetails(post: Post) { val postText = "Title: ${post.title}\n\nBody: ${post.body}" postsTextView.text = postText } private fun sharePostDetails() { // Get the post details from the text view val postDetails = postsTextView.text.toString() // Start the EmailActivity and pass the post details as an extra val intent = Intent(this@MainActivity, EmailActivity::class.java) intent.putExtra("postDetails", postDetails) startActivity(intent) } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/MainActivity.kt
625648508
// EmailActivity.kt package com.example.insta import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity class EmailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_email) val emailEditText = findViewById<EditText>(R.id.emailEditText) val sendButton = findViewById<Button>(R.id.sendButton) sendButton.setOnClickListener { val email = emailEditText.text.toString().trim() val postDetails = intent.getStringExtra("postDetails") sendEmail(email, postDetails) } val backButton = findViewById<Button>(R.id.backButton) backButton.setOnClickListener { finish() } } private fun sendEmail(email: String, postDetails: String?) { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email)) intent.putExtra(Intent.EXTRA_SUBJECT, "Post Details") intent.putExtra(Intent.EXTRA_TEXT, postDetails) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } else { } } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/EmailActivity.kt
1243399595
package com.example.insta import retrofit2.Call // Import the retrofit2 Call class import retrofit2.http.GET import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory interface JsonPlaceholderApiService { @GET("posts") fun getPosts(): Call<List<Post>> companion object { const val BASE_URL = "https://jsonplaceholder.typicode.com/" fun create(): JsonPlaceholderApiService { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(JsonPlaceholderApiService::class.java) } } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/JsonPlaceholderApiService.kt
2621168006
package com.example.insta import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import retrofit2.Call import retrofit2.Callback import retrofit2.Response class PostViewModel(private val jsonPlaceholderApiService: JsonPlaceholderApiService) : ViewModel() { private val _postsData = MutableLiveData<List<Post>?>() val postsData: LiveData<List<Post>?> get() = _postsData fun fetchPosts() { jsonPlaceholderApiService.getPosts().enqueue(object : Callback<List<Post>> { override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) { if (response.isSuccessful) { _postsData.postValue(response.body()) } else { _postsData.postValue(null) } } override fun onFailure(call: Call<List<Post>>, t: Throwable) { _postsData.postValue(null) } }) } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/PostViewModel.kt
1393419406
package com.example.insta import retrofit2.Call import retrofit2.Callback import retrofit2.Response class PostRepository(private val apiService: JsonPlaceholderApiService) { fun getPosts(onPostsFetched: (List<Post>?) -> Unit) { apiService.getPosts().enqueue(object : Callback<List<Post>> { override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) { if (response.isSuccessful) { val posts = response.body() onPostsFetched(posts) } else { onPostsFetched(null) } } override fun onFailure(call: Call<List<Post>>, t: Throwable) { onPostsFetched(null) } }) } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/PostRepository.kt
3389210836
// AboutActivity.kt package com.example.insta import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity class AboutActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) val backButton = findViewById<Button>(R.id.backButton) backButton.setOnClickListener { finish() } } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/AboutActivity.kt
1726042125
package com.example.insta data class Post( val userId: Int, val id: Int, val title: String, val body: String )
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/Post.kt
979430430
package com.example.insta import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class PostViewModelFactory(private val application: Application) : ViewModelProvider.Factory { private fun createJsonPlaceholderApiService(): JsonPlaceholderApiService { val retrofit = Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") // Base URL of your API .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(JsonPlaceholderApiService::class.java) } @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(PostViewModel::class.java)) { val apiService = createJsonPlaceholderApiService() return PostViewModel(apiService) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/PostViewModelFactory.kt
751661809
package com.example.insta import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.os.Handler; class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash2) Handler().postDelayed({ val intent = Intent(this@SplashActivity, MainActivity::class.java) startActivity(intent) finish() }, 3000) } }
NewsFeedApp/Insta 6/app/src/main/java/com/example/insta/SplashActivity.kt
3830951907
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Article import androidx.compose.material.icons.filled.Inbox import androidx.compose.material.icons.filled.People import androidx.compose.material.icons.outlined.ChatBubbleOutline import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import com.example.reply.R @Composable fun ReplyApp( replyHomeUIState: ReplyHomeUIState, closeDetailScreen: () -> Unit = {}, navigateToDetail: (Long) -> Unit = {} ) { ReplyAppContent( replyHomeUIState = replyHomeUIState, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail ) } @Composable fun ReplyAppContent( modifier: Modifier = Modifier, replyHomeUIState: ReplyHomeUIState, closeDetailScreen: () -> Unit, navigateToDetail: (Long) -> Unit, ) { val selectedDestination = remember { mutableStateOf(ReplyRoute.INBOX) } Column( modifier = modifier .fillMaxSize() ) { if (selectedDestination.value == ReplyRoute.INBOX) { ReplyInboxScreen( replyHomeUIState = replyHomeUIState, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail, modifier = Modifier.weight(1f) ) } else { EmptyComingSoon(modifier = Modifier.weight(1f)) } NavigationBar(modifier = Modifier.fillMaxWidth()) { TOP_LEVEL_DESTINATIONS.forEach { replyDestination -> NavigationBarItem( selected = selectedDestination.value == replyDestination.route, onClick = { selectedDestination.value = replyDestination.route }, icon = { Icon( imageVector = replyDestination.selectedIcon, contentDescription = stringResource(id = replyDestination.iconTextId) ) } ) } } } } object ReplyRoute { const val INBOX = "Inbox" const val ARTICLES = "Articles" const val DM = "DirectMessages" const val GROUPS = "Groups" } data class ReplyTopLevelDestination( val route: String, val selectedIcon: ImageVector, val unselectedIcon: ImageVector, val iconTextId: Int ) val TOP_LEVEL_DESTINATIONS = listOf( ReplyTopLevelDestination( route = ReplyRoute.INBOX, selectedIcon = Icons.Default.Inbox, unselectedIcon = Icons.Default.Inbox, iconTextId = R.string.tab_inbox ), ReplyTopLevelDestination( route = ReplyRoute.ARTICLES, selectedIcon = Icons.Default.Article, unselectedIcon = Icons.Default.Article, iconTextId = R.string.tab_article ), ReplyTopLevelDestination( route = ReplyRoute.DM, selectedIcon = Icons.Outlined.ChatBubbleOutline, unselectedIcon = Icons.Outlined.ChatBubbleOutline, iconTextId = R.string.tab_inbox ), ReplyTopLevelDestination( route = ReplyRoute.GROUPS, selectedIcon = Icons.Default.People, unselectedIcon = Icons.Default.People, iconTextId = R.string.tab_article ) )
ThemingCodelab/app/src/main/java/com/example/reply/ui/ReplyApp.kt
2351482078
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import android.content.res.Configuration.UI_MODE_NIGHT_NO import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.tooling.preview.Preview import com.example.reply.data.LocalEmailsDataProvider class MainActivity : ComponentActivity() { private val viewModel: ReplyHomeViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val uiState by viewModel.uiState.collectAsState() ReplyApp( replyHomeUIState = uiState, closeDetailScreen = { viewModel.closeDetailScreen() }, navigateToDetail = { emailId -> viewModel.setSelectedEmail(emailId) } ) } } } @Preview( uiMode = UI_MODE_NIGHT_YES, name = "DefaultPreviewDark" ) @Preview( uiMode = UI_MODE_NIGHT_NO, name = "DefaultPreviewLight" ) @Composable fun ReplyAppPreviewLight() { ReplyApp( replyHomeUIState = ReplyHomeUIState( emails = LocalEmailsDataProvider.allEmails ) ) }
ThemingCodelab/app/src/main/java/com/example/reply/ui/MainActivity.kt
3265129744
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.Icon import androidx.compose.material3.LargeFloatingActionButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.reply.R import com.example.reply.data.Email import com.example.reply.ui.components.EmailDetailAppBar import com.example.reply.ui.components.ReplyEmailListItem import com.example.reply.ui.components.ReplyEmailThreadItem import com.example.reply.ui.components.ReplySearchBar @Composable fun ReplyInboxScreen( replyHomeUIState: ReplyHomeUIState, closeDetailScreen: () -> Unit, navigateToDetail: (Long) -> Unit, modifier: Modifier = Modifier ) { val emailLazyListState = rememberLazyListState() Box(modifier = modifier.fillMaxSize()) { ReplyEmailListContent( replyHomeUIState = replyHomeUIState, emailLazyListState = emailLazyListState, modifier = Modifier.fillMaxSize(), closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail ) LargeFloatingActionButton( onClick = { /*Click Implementation*/ }, modifier = Modifier .align(Alignment.BottomEnd) .padding(16.dp), ) { Icon( imageVector = Icons.Default.Edit, contentDescription = stringResource(id = R.string.edit), modifier = Modifier.size(28.dp) ) } } } @Composable fun ReplyEmailListContent( replyHomeUIState: ReplyHomeUIState, emailLazyListState: LazyListState, modifier: Modifier = Modifier, closeDetailScreen: () -> Unit, navigateToDetail: (Long) -> Unit ) { if (replyHomeUIState.selectedEmail != null && replyHomeUIState.isDetailOnlyOpen) { BackHandler { closeDetailScreen() } ReplyEmailDetail(email = replyHomeUIState.selectedEmail) { closeDetailScreen() } } else { ReplyEmailList( emails = replyHomeUIState.emails, emailLazyListState = emailLazyListState, modifier = modifier, navigateToDetail = navigateToDetail ) } } @Composable fun ReplyEmailList( emails: List<Email>, emailLazyListState: LazyListState, selectedEmail: Email? = null, modifier: Modifier = Modifier, navigateToDetail: (Long) -> Unit ) { LazyColumn(modifier = modifier, state = emailLazyListState) { item { ReplySearchBar(modifier = Modifier.fillMaxWidth()) } items(items = emails, key = { it.id }) { email -> ReplyEmailListItem( email = email, isSelected = email.id == selectedEmail?.id ) { emailId -> navigateToDetail(emailId) } } } } @Composable fun ReplyEmailDetail( email: Email, isFullScreen: Boolean = true, modifier: Modifier = Modifier.fillMaxSize(), onBackPressed: () -> Unit = {} ) { LazyColumn( modifier = modifier .padding(top = 16.dp) ) { item { EmailDetailAppBar(email, isFullScreen) { onBackPressed() } } items(items = email.threads, key = { it.id }) { email -> ReplyEmailThreadItem(email = email) } } }
ThemingCodelab/app/src/main/java/com/example/reply/ui/ReplyListContent.kt
3882090952
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.reply.data.Email import com.example.reply.data.LocalEmailsDataProvider import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class ReplyHomeViewModel : ViewModel() { // UI state exposed to the UI private val _uiState = MutableStateFlow(ReplyHomeUIState(loading = true)) val uiState: StateFlow<ReplyHomeUIState> = _uiState init { initEmailList() } private fun initEmailList() { val emails = LocalEmailsDataProvider.allEmails _uiState.value = ReplyHomeUIState( emails = emails, selectedEmail = emails.first() ) } fun setSelectedEmail(emailId: Long) { /** * We only set isDetailOnlyOpen to true when it's only single pane layout */ val email = uiState.value.emails.find { it.id == emailId } _uiState.value = _uiState.value.copy( selectedEmail = email, isDetailOnlyOpen = true ) } fun closeDetailScreen() { _uiState.value = _uiState .value.copy( isDetailOnlyOpen = false, selectedEmail = _uiState.value.emails.first() ) } } data class ReplyHomeUIState( val emails: List<Email> = emptyList(), val selectedEmail: Email? = null, val isDetailOnlyOpen: Boolean = false, val loading: Boolean = false, val error: String? = null )
ThemingCodelab/app/src/main/java/com/example/reply/ui/ReplyHomeViewModel.kt
1787778086
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Search import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.reply.R import com.example.reply.data.Email @Composable fun ReplySearchBar(modifier: Modifier = Modifier) { Row( modifier = modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Default.Search, contentDescription = stringResource(id = R.string.search), modifier = Modifier.padding(start = 16.dp), ) Text( text = stringResource(id = R.string.search_replies), modifier = Modifier .weight(1f) .padding(16.dp), style = MaterialTheme.typography.bodyMedium, ) ReplyProfileImage( drawableResource = R.drawable.avatar_6, description = stringResource(id = R.string.profile), modifier = Modifier .padding(12.dp) .size(32.dp) ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun EmailDetailAppBar( email: Email, isFullScreen: Boolean, modifier: Modifier = Modifier, onBackPressed: () -> Unit ) { TopAppBar( modifier = modifier, title = { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = if (isFullScreen) Alignment.CenterHorizontally else Alignment.Start ) { Text( text = email.subject, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) Text( modifier = Modifier.padding(top = 4.dp), text = "${email.threads.size} ${stringResource(id = R.string.messages)}", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline ) } }, navigationIcon = { if (isFullScreen) { FilledIconButton( onClick = onBackPressed, modifier = Modifier.padding(8.dp), colors = IconButtonDefaults.filledIconButtonColors( containerColor = MaterialTheme.colorScheme.surface, contentColor = MaterialTheme.colorScheme.onSurface ) ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.back_button), modifier = Modifier.size(14.dp) ) } } }, actions = { IconButton( onClick = { /*Click Implementation*/ }, ) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.more_options_button), tint = MaterialTheme.colorScheme.onSurfaceVariant ) } } ) }
ThemingCodelab/app/src/main/java/com/example/reply/ui/components/ReplyAppBars.kt
1376723498
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp @Composable fun ReplyProfileImage( drawableResource: Int, description: String, modifier: Modifier = Modifier ) { Image( modifier = modifier .size(40.dp) .clip(CircleShape), painter = painterResource(id = drawableResource), contentDescription = description, ) }
ThemingCodelab/app/src/main/java/com/example/reply/ui/components/ReplyProfileImage.kt
3036193327
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.StarBorder import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.reply.R import com.example.reply.data.Email @Composable fun ReplyEmailThreadItem( email: Email, modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxWidth() .padding(16.dp) .padding(20.dp) ) { Row(modifier = Modifier.fillMaxWidth()) { ReplyProfileImage( drawableResource = email.sender.avatar, description = email.sender.fullName, ) Column( modifier = Modifier .weight(1f) .padding(horizontal = 12.dp, vertical = 4.dp), verticalArrangement = Arrangement.Center ) { Text( text = email.sender.firstName, ) Text( text = stringResource(id = R.string.twenty_mins_ago), ) } IconButton( onClick = { /*Click Implementation*/ }, modifier = Modifier .clip(CircleShape) ) { Icon( imageVector = if (email.isStarred) Icons.Default.Star else Icons.Default.StarBorder, contentDescription = stringResource(id = R.string.description_favorite), tint = if (email.isStarred) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.outline ) } } Text( text = email.subject, modifier = Modifier.padding(top = 12.dp, bottom = 8.dp), ) Text( text = email.body, ) Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), ) { Button( onClick = { /*Click Implementation*/ }, modifier = Modifier.weight(1f), ) { Text( text = stringResource(id = R.string.reply), ) } Button( onClick = { /*Click Implementation*/ }, modifier = Modifier.weight(1f), ) { Text( text = stringResource(id = R.string.reply_all), ) } } } }
ThemingCodelab/app/src/main/java/com/example/reply/ui/components/ReplyEmailThreadItem.kt
3192881017
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.StarBorder import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.example.reply.R import com.example.reply.data.Email @Composable fun ReplyEmailListItem( email: Email, isSelected: Boolean = false, modifier: Modifier = Modifier, navigateToDetail: (Long) -> Unit ) { Card( modifier = modifier .padding(horizontal = 16.dp, vertical = 4.dp) .semantics { selected = isSelected } .clickable { navigateToDetail(email.id) }, ) { Column( modifier = Modifier .fillMaxWidth() .padding(20.dp) ) { Row(modifier = Modifier.fillMaxWidth()) { ReplyProfileImage( drawableResource = email.sender.avatar, description = email.sender.fullName, ) Column( modifier = Modifier .weight(1f) .padding(horizontal = 12.dp, vertical = 4.dp), verticalArrangement = Arrangement.Center ) { Text( text = email.sender.firstName, ) Text( text = email.createdAt, ) } IconButton( onClick = { /*Click Implementation*/ }, modifier = Modifier .clip(CircleShape) ) { Icon( imageVector = Icons.Default.StarBorder, contentDescription = stringResource(id = R.string.description_favorite), ) } } Text( text = email.subject, modifier = Modifier.padding(top = 12.dp, bottom = 8.dp), ) Text( text = email.body, maxLines = 2, overflow = TextOverflow.Ellipsis ) } } }
ThemingCodelab/app/src/main/java/com/example/reply/ui/components/ReplyEmailListItem.kt
2079498356
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.theme import androidx.compose.ui.graphics.Color // Generate them via theme builder // https://material-foundation.github.io/material-theme-builder/#/custom val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
ThemingCodelab/app/src/main/java/com/example/reply/ui/theme/Color.kt
1208605450
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable // Material 3 color schemes private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 ) @Composable fun ReplyTheme( darkTheme: Boolean = false, content: @Composable () -> Unit ) { val replyColorScheme = when { darkTheme -> DarkColorScheme else -> LightColorScheme } MaterialTheme( colorScheme = replyColorScheme, content = content ) }
ThemingCodelab/app/src/main/java/com/example/reply/ui/theme/Theme.kt
3973420913
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Material 3 typography // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
ThemingCodelab/app/src/main/java/com/example/reply/ui/theme/Type.kt
1659205222
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.reply.R @Composable fun EmptyComingSoon( modifier: Modifier = Modifier ) { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( modifier = Modifier.padding(8.dp), text = stringResource(id = R.string.empty_screen_title), style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.primary ) Text( modifier = Modifier.padding(horizontal = 8.dp), text = stringResource(id = R.string.empty_screen_subtitle), style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.outline ) } } @Preview @Composable fun ComingSoonPreview() { EmptyComingSoon() }
ThemingCodelab/app/src/main/java/com/example/reply/ui/EmptyComingSoon.kt
1374729761
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data import androidx.annotation.DrawableRes /** * A simple data class to represent an Email. */ data class Email( val id: Long, val sender: Account, val recipients: List<Account> = emptyList(), val subject: String, val body: String, val attachments: List<EmailAttachment> = emptyList(), var isImportant: Boolean = false, var isStarred: Boolean = false, var mailbox: MailboxType = MailboxType.INBOX, val createdAt: String, val threads: List<Email> = emptyList() ) enum class MailboxType { INBOX, DRAFTS, SENT, SPAM, TRASH } data class EmailAttachment( @DrawableRes val resId: Int, val contentDesc: String )
ThemingCodelab/app/src/main/java/com/example/reply/data/Email.kt
2196920346
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data import androidx.annotation.DrawableRes /** * An object which represents an account which can belong to a user. A single user can have * multiple accounts. */ data class Account( val id: Long, val uid: Long, val firstName: String, val lastName: String, val email: String, val altEmail: String, @DrawableRes val avatar: Int, var isCurrentAccount: Boolean = false ) { val fullName: String = "$firstName $lastName" }
ThemingCodelab/app/src/main/java/com/example/reply/data/Account.kt
3385183363
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data import com.example.reply.R /** * A static data store of [Email]s. */ object LocalEmailsDataProvider { private val threads = listOf( Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Your update on Google Play Store is live!", body = """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), isStarred = true, mailbox = MailboxType.TRASH, createdAt = "3 hours ago", ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Update to Your Itinerary", body = "", createdAt = "2 hours ago", ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createdAt = "2 hours ago", isStarred = true, mailbox = MailboxType.SENT ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Delivered", body = "Your shoes should be waiting for you at home!", isStarred = true, createdAt = "2 hours ago", ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "(No subject)", body = """ Hey, Wanted to email and see what you thought of """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.DRAFTS ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountByUid(6L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Brunch this weekend?", body = """ I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever. If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico. Talk to you soon, Ali """.trimIndent(), isStarred = true, createdAt = "40 mins ago", ), Email( id = 2L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Bonjour from Paris", body = "Here are some great shots from my trip...", attachments = listOf( EmailAttachment(R.drawable.paris_1, "Bridge in Paris"), EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"), EmailAttachment(R.drawable.paris_3, "City street in Paris"), EmailAttachment(R.drawable.paris_4, "Street with bike in Paris") ), isImportant = true, isStarred = true, createdAt = "1 hour ago", ), ) val allEmails = listOf( Email( id = 0L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Package shipped!", body = """ Cucumber Mask Facial has shipped. Keep an eye out for a package to arrive between this Thursday and next Tuesday. If for any reason you don't receive your package before the end of next week, please reach out to us for details on your shipment. As always, thank you for shopping with us and we hope you love our specially formulated Cucumber Mask! """.trimIndent(), createdAt = "20 mins ago", isImportant = true, isStarred = true, threads = threads, ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountByUid(6L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Brunch this weekend?", body = """ I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever. If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico. Talk to you soon, Ali """.trimIndent(), createdAt = "40 mins ago", threads = threads.shuffled(), ), Email( 2L, LocalAccountsDataProvider.getContactAccountByUid(5L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Bonjour from Paris", "Here are some great shots from my trip...", listOf( EmailAttachment(R.drawable.paris_1, "Bridge in Paris"), EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"), EmailAttachment(R.drawable.paris_3, "City street in Paris"), EmailAttachment(R.drawable.paris_4, "Street with bike in Paris") ), createdAt = "1 hour ago", threads = threads.shuffled(), ), Email( 3L, LocalAccountsDataProvider.getContactAccountByUid(8L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "High school reunion?", """ Hi friends, I was at the grocery store on Sunday night.. when I ran into Genie Williams! I almost didn't recognize her afer 20 years! Anyway, it turns out she is on the organizing committee for the high school reunion this fall. I don't know if you were planning on going or not, but she could definitely use our help in trying to track down lots of missing alums. If you can make it, we're doing a little phone-tree party at her place next Saturday, hoping that if we can find one person, thee more will... """.trimIndent(), createdAt = "2 hours ago", mailbox = MailboxType.SENT, threads = threads.shuffled(), ), Email( id = 4L, sender = LocalAccountsDataProvider.getContactAccountByUid(11L), recipients = listOf( LocalAccountsDataProvider.getDefaultUserAccount(), LocalAccountsDataProvider.getContactAccountByUid(8L), LocalAccountsDataProvider.getContactAccountByUid(5L) ), subject = "Brazil trip", body = """ Thought we might be able to go over some details about our upcoming vacation. I've been doing a bit of research and have come across a few paces in Northern Brazil that I think we should check out. One, the north has some of the most predictable wind on the planet. I'd love to get out on the ocean and kitesurf for a couple of days if we're going to be anywhere near or around Taiba. I hear it's beautiful there and if you're up for it, I'd love to go. Other than that, I haven't spent too much time looking into places along our road trip route. I'm assuming we can find places to stay and things to do as we drive and find places we think look interesting. But... I know you're more of a planner, so if you have ideas or places in mind, lets jot some ideas down! Maybe we can jump on the phone later today if you have a second. """.trimIndent(), createdAt = "2 hours ago", isStarred = true, threads = threads.shuffled(), ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Update to Your Itinerary", body = "", createdAt = "2 hours ago", threads = threads.shuffled() ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createdAt = "2 hours ago", mailbox = MailboxType.SENT, threads = threads.shuffled() ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Delivered", body = "Your shoes should be waiting for you at home!", createdAt = "2 hours ago", threads = threads.shuffled() ), Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Your update on Google Play Store is live!", body = """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), mailbox = MailboxType.TRASH, createdAt = "3 hours ago", threads = threads.shuffled(), ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "(No subject)", body = """ Hey, Wanted to email and see what you thought of """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.DRAFTS, threads = threads.shuffled(), ), Email( id = 10L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Try a free TrailGo account", body = """ Looking for the best hiking trails in your area? TrailGo gets you on the path to the outdoors faster than you can pack a sandwich. Whether you're an experienced hiker or just looking to get outside for the afternoon, there's a segment that suits you. """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.TRASH, threads = threads.shuffled(), ), Email( id = 11L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Free money", body = """ You've been selected as a winner in our latest raffle! To claim your prize, click on the link. """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.SPAM, threads = threads.shuffled(), ) ) /** * Get an [Email] with the given [id]. */ fun get(id: Long): Email? { return allEmails.firstOrNull { it.id == id } } /** * Create a new, blank [Email]. */ fun create(): Email { return Email( System.nanoTime(), // Unique ID generation. LocalAccountsDataProvider.getDefaultUserAccount(), createdAt = "Just now", subject = "Monthly hosting party", body = "I would like to invite everyone to our monthly event hosting party" ) } /** * Create a new [Email] that is a reply to the email with the given [replyToId]. */ fun createReplyTo(replyToId: Long): Email { val replyTo = get(replyToId) ?: return create() return Email( id = System.nanoTime(), sender = replyTo.recipients.firstOrNull() ?: LocalAccountsDataProvider.getDefaultUserAccount(), recipients = listOf(replyTo.sender) + replyTo.recipients, subject = replyTo.subject, isStarred = replyTo.isStarred, isImportant = replyTo.isImportant, createdAt = "Just now", body = "Responding to the above conversation." ) } /** * Get a list of [EmailFolder]s by which [Email]s can be categorized. */ fun getAllFolders() = listOf( "Receipts", "Pine Elementary", "Taxes", "Vacation", "Mortgage", "Grocery coupons" ) }
ThemingCodelab/app/src/main/java/com/example/reply/data/LocalEmailsDataProvider.kt
4280409563
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data import com.example.reply.R /** * An static data store of [Account]s. This includes both [Account]s owned by the current user and * all [Account]s of the current user's contacts. */ object LocalAccountsDataProvider { private val allUserAccounts = listOf( Account( id = 1L, uid = 0L, firstName = "Jeff", lastName = "Hansen", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_10, isCurrentAccount = true ), Account( id = 2L, uid = 0L, firstName = "Jeff", lastName = "H", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_2 ), Account( id = 3L, uid = 0L, firstName = "Jeff", lastName = "Hansen", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_9 ) ) private val allUserContactAccounts = listOf( Account( id = 4L, uid = 1L, firstName = "Tracy", lastName = "Alvarez", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_1 ), Account( id = 5L, uid = 2L, firstName = "Allison", lastName = "Trabucco", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_3 ), Account( id = 6L, uid = 3L, firstName = "Ali", lastName = "Connors", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_5 ), Account( id = 7L, uid = 4L, firstName = "Alberto", lastName = "Williams", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_0 ), Account( id = 8L, uid = 5L, firstName = "Kim", lastName = "Alen", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_7 ), Account( id = 9L, uid = 6L, firstName = "Google", lastName = "Express", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_express ), Account( id = 10L, uid = 7L, firstName = "Sandra", lastName = "Adams", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_2 ), Account( id = 11L, uid = 8L, firstName = "Trevor", lastName = "Hansen", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_8 ), Account( id = 12L, uid = 9L, firstName = "Sean", lastName = "Holt", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_6 ), Account( id = 13L, uid = 10L, firstName = "Frank", lastName = "Hawkins", email = "[email protected]", altEmail = "[email protected]", avatar = R.drawable.avatar_4 ) ) /** * Get the current user's default account. */ fun getDefaultUserAccount() = allUserAccounts.first() /** * Whether or not the given [Account.id] uid is an account owned by the current user. */ fun isUserAccount(uid: Long): Boolean = allUserAccounts.any { it.uid == uid } /** * Get the contact of the current user with the given [accountId]. */ fun getContactAccountByUid(accountId: Long): Account { return allUserContactAccounts.first { it.id == accountId } } }
ThemingCodelab/app/src/main/java/com/example/reply/data/LocalAccountsDataProvider.kt
1896818507
/* * Copyright $YEAR The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
ThemingCodelab/spotless/copyright.kt
2813624007
package com.mftjc.spesa import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.mftjc.spesa", appContext.packageName) } }
Grocery-App/app/src/androidTest/java/com/mftjc/spesa/ExampleInstrumentedTest.kt
3116437518
package com.mftjc.spesa import org.junit.Assert.assertEquals import org.junit.Test /** * 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) } }
Grocery-App/app/src/test/java/com/mftjc/spesa/ExampleUnitTest.kt
4087103432
package com.mftjc.spesa.viewmodel import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mftjc.spesa.db.ProductDb import com.mftjc.spesa.model.Product import com.mftjc.spesa.repository.ProductRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch class ProductVm(context: Context) : ViewModel() { private val db = ProductDb.getInstance(context) private val dao = db.productDao() private val repository = ProductRepository(dao) fun getAllProducts(): Flow<List<Product>> { return repository.products } fun getProduct(id: Int): Flow<Product>{ return repository.getProduct(id) } fun insertOrUpdateProduct(product: Product){ viewModelScope.launch { repository.insertOrUpdateProduct(product) } } fun deleteProduct(product: Product){ viewModelScope.launch { repository.deleteProduct(product) } } fun deleteAllProducts(){ viewModelScope.launch { repository.deleteAllProducts() } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/viewmodel/ProductVm.kt
1960047030
package com.mftjc.spesa.ui.theme import androidx.compose.ui.graphics.Color val Green = Color(0xFFA5DD9B) val LightWhite = Color(0xFFFEFDED) val LightGreen = Color(0xFFC5EBAA) val Green2 = Color(0xFF79AC78) val LightWhite2 = LightWhite val LightGreen2 = Color(0xFFB0D9B1)
Grocery-App/app/src/main/java/com/mftjc/spesa/ui/theme/Color.kt
1844506951
package com.mftjc.spesa.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Green, secondary = LightWhite, tertiary = LightGreen ) private val LightColorScheme = lightColorScheme( primary = Green2, secondary = LightWhite2, tertiary = LightGreen2 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun SpesaTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Grocery-App/app/src/main/java/com/mftjc/spesa/ui/theme/Theme.kt
254927733
package com.mftjc.spesa.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Grocery-App/app/src/main/java/com/mftjc/spesa/ui/theme/Type.kt
449147210
package com.mftjc.spesa.repository import com.mftjc.spesa.dao.ProductDao import com.mftjc.spesa.model.Product import kotlinx.coroutines.flow.Flow class ProductRepository(private val dao: ProductDao){ val products = dao.getAllProducts() fun getProduct(id: Int): Flow<Product> { return dao.getProduct(id) } suspend fun insertOrUpdateProduct(product: Product){ dao.insertOrUpdateProduct(product) } suspend fun deleteProduct(product: Product){ dao.deleteProduct(product) } suspend fun deleteAllProducts(){ dao.deleteAllProducts() } }
Grocery-App/app/src/main/java/com/mftjc/spesa/repository/ProductRepository.kt
560540835
package com.mftjc.spesa import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.mftjc.spesa.navigation.SetupNavGraph import com.mftjc.spesa.viewmodel.ProductVm class MainActivity : ComponentActivity() { private lateinit var vm: ProductVm private lateinit var navHostController: NavHostController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) vm = ProductVm(this) setContent { navHostController = rememberNavController() SetupNavGraph(navHostController = navHostController, productVm = vm, context = this) } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/MainActivity.kt
431459044
package com.mftjc.spesa.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import com.mftjc.spesa.model.Product import kotlinx.coroutines.flow.Flow @Dao interface ProductDao { @Query("SELECT * FROM products") fun getAllProducts(): Flow<List<Product>> @Query("SELECT * FROM products WHERE id = :id") fun getProduct(id: Int): Flow<Product> @Upsert suspend fun insertOrUpdateProduct(product: Product) @Delete suspend fun deleteProduct(product: Product) @Query("DELETE FROM products") suspend fun deleteAllProducts() }
Grocery-App/app/src/main/java/com/mftjc/spesa/dao/ProductDao.kt
523093414
package com.mftjc.spesa.navigation import android.content.Context import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.mftjc.spesa.view.AddOrUpdateProductView import com.mftjc.spesa.view.HomeView import com.mftjc.spesa.viewmodel.ProductVm @Composable fun SetupNavGraph( navHostController: NavHostController, productVm: ProductVm, context: Context ){ NavHost( navHostController, startDestination = Screen.HomeScreen.route ){ composable( route = Screen.HomeScreen.route ){ HomeView(vm = productVm, navHostController, context) } composable( route = Screen.AddOrUpdateProductScreen.route, arguments = listOf(navArgument("id"){ type = NavType.IntType }) ){ AddOrUpdateProductView(vm = productVm, navHostController = navHostController, id = it.arguments!!.getInt("id"), context) } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/navigation/SetupNavGraph.kt
1216924475
package com.mftjc.spesa.navigation sealed class Screen(val route: String) { object HomeScreen: Screen(route = "home_screen") object AddOrUpdateProductScreen: Screen(route = "add_or_update_product_screen/{id}"){ fun passId(id: Int): String{ return "add_or_update_product_screen/$id" } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/navigation/Screen.kt
1103778756
package com.mftjc.spesa.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "products") data class Product( @PrimaryKey(autoGenerate = true) var id: Int = 0, var name: String = "", var quantity: String = "" )
Grocery-App/app/src/main/java/com/mftjc/spesa/model/Product.kt
2397294414
package com.mftjc.spesa.view import android.content.Context import android.widget.Toast import android.widget.Toast.LENGTH_SHORT import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.navigation.NavHostController import com.mftjc.spesa.model.Product import com.mftjc.spesa.ui.theme.Green import com.mftjc.spesa.ui.theme.LightGreen import com.mftjc.spesa.ui.theme.LightWhite import com.mftjc.spesa.viewmodel.ProductVm @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddOrUpdateProductView(vm: ProductVm, navHostController: NavHostController, id: Int, context: Context){ var product = vm.getProduct(id).collectAsState(initial = Product()).value var name by remember { mutableStateOf("") } var quantity by remember { mutableStateOf("") } var title by remember { mutableStateOf("Inserisci Prodotto") } var nameButton by remember { mutableStateOf("Inserisci") } if (id != 0) { name = product.name quantity = product.quantity title = "Modifica Prodotto" nameButton = "Modifica" } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text(text = title) }, navigationIcon = { IconButton(onClick = { navHostController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, contentDescription = "Go back to HomeView") } }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors(Green) ) } ) { Box(modifier = Modifier .fillMaxSize() .padding(it) .background(LightWhite) ){ Column( modifier = Modifier .fillMaxSize(), Arrangement.SpaceAround, Alignment.CenterHorizontally ) { TextField( value = name, onValueChange = { name = it }, label = { Text( text = "Nome Prodotto" ) }, keyboardOptions = KeyboardOptions(KeyboardCapitalization.Sentences), colors = TextFieldDefaults.colors( focusedContainerColor = Green, unfocusedContainerColor = LightGreen ) ) TextField( value = quantity, onValueChange = { quantity = it }, label = { Text(text = "Quantità") }, keyboardOptions = KeyboardOptions(KeyboardCapitalization.Sentences), colors = TextFieldDefaults.colors( focusedContainerColor = Green, unfocusedContainerColor = LightGreen ) ) Button( onClick = { //if no product is found, it will be null if (product != null){ product.name = name product.quantity = quantity vm.insertOrUpdateProduct(product) Toast.makeText(context, "Prodotto Modificato", LENGTH_SHORT).show() } else { product = Product(name = name, quantity = quantity) vm.insertOrUpdateProduct(product) Toast.makeText(context, "Prodotto Inserito", LENGTH_SHORT).show() } navHostController.popBackStack() }, enabled = name.isNotBlank() && quantity.isNotBlank(), colors = ButtonDefaults.buttonColors( Green, contentColor = Color.DarkGray ) ) { Text(text = nameButton) } } } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/view/AddProductView.kt
4070691140
package com.mftjc.spesa.view import android.content.Context import android.widget.Toast import android.widget.Toast.LENGTH_SHORT import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.mftjc.spesa.model.Product import com.mftjc.spesa.navigation.Screen import com.mftjc.spesa.ui.theme.Green import com.mftjc.spesa.ui.theme.LightGreen import com.mftjc.spesa.ui.theme.LightWhite import com.mftjc.spesa.viewmodel.ProductVm @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeView( vm: ProductVm, navHostController: NavHostController, context: Context ){ Scaffold( modifier = Modifier .fillMaxSize(), topBar = { CenterAlignedTopAppBar( title = { Text(text = "Spesa") }, actions = { IconButton(onClick = { vm.deleteAllProducts() Toast.makeText(context, "Tutti i prodotti sono stati eliminati", LENGTH_SHORT).show() }){ Icon(Icons.Filled.Delete, contentDescription = "Delete all products") } }, colors = TopAppBarDefaults.topAppBarColors(Green), ) } ) { Box(modifier = Modifier .fillMaxSize() .padding(it) .background(LightWhite), contentAlignment = Alignment.TopCenter ){ ShowListProducts(navHostController = navHostController, vm = vm, context = context) Box(modifier = Modifier .fillMaxSize() .padding(15.dp), contentAlignment = Alignment.BottomEnd ){ FloatingActionButton( onClick = { navHostController.navigate(Screen.AddOrUpdateProductScreen.passId(0))}, containerColor = Green ) { Icon(Icons.Filled.Add, contentDescription = "Show AddProductScreen") } } } } } @Composable private fun ShowListProducts( navHostController: NavHostController, vm: ProductVm, context: Context ){ val products by vm.getAllProducts().collectAsState(initial = emptyList()) //if there is no product if (products.isEmpty()){ Box(modifier = Modifier .fillMaxSize(), contentAlignment = Alignment.Center ){ Text( text = "La lista è vuota.", textAlign = TextAlign.Center, fontSize = 25.sp, color = Color.Gray ) } } else { LazyColumn( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { items(products){ product -> ProductCard(product = product, navHostController, vm, context) } } } } @Composable private fun ProductCard( product: Product, navHostController: NavHostController, vm: ProductVm, context: Context ){ Card( modifier = Modifier .fillMaxWidth(0.9f) .padding(10.dp) .shadow(5.dp, shape = RoundedCornerShape(5.dp)), shape = RoundedCornerShape(5.dp), colors = CardDefaults.cardColors(LightGreen) ) { Row( modifier = Modifier .fillMaxSize(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceAround ) { Box( modifier = Modifier .fillMaxHeight() .fillMaxWidth(0.5f), contentAlignment = Alignment.Center ) { Text( textAlign = TextAlign.Center, fontSize = 20.sp, text = "${product.name}: ${product.quantity}" ) } Box( modifier = Modifier .fillMaxHeight() .fillMaxWidth(0.5f), contentAlignment = Alignment.Center ){ Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ){ IconButton(onClick = { navHostController.navigate(Screen.AddOrUpdateProductScreen.passId(product.id)) }) { Icon(Icons.Filled.Edit, contentDescription = "Show UpdateScreenView") } IconButton(onClick = { vm.deleteProduct(product) Toast.makeText(context, "Prodotto Eliminato", LENGTH_SHORT).show() }) { Icon(Icons.Filled.Delete, contentDescription = "Show DeleteScreenView") } } } } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/view/HomeView.kt
442423486
package com.mftjc.spesa.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.mftjc.spesa.dao.ProductDao import com.mftjc.spesa.model.Product @Database(entities = [Product::class], version = 1, exportSchema = false) abstract class ProductDb : RoomDatabase(){ abstract fun productDao(): ProductDao companion object{ @Volatile private var instance: ProductDb? = null fun getInstance(context: Context): ProductDb { if (instance == null) { synchronized(ProductDb::class) { instance = Room.databaseBuilder( context.applicationContext, ProductDb::class.java, "spesa" ).build() } } return instance as ProductDb } } }
Grocery-App/app/src/main/java/com/mftjc/spesa/db/ProductDb.kt
1829746240
package com.example.jetpackcomposeapp 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.jetpackcomposeapp", appContext.packageName) } }
Jetpack-Compose-App/app/src/androidTest/java/com/example/jetpackcomposeapp/ExampleInstrumentedTest.kt
1454196570
package com.example.jetpackcomposeapp 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) } }
Jetpack-Compose-App/app/src/test/java/com/example/jetpackcomposeapp/ExampleUnitTest.kt
4066582670
package com.example.jetpackcomposeapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Jetpack-Compose-App/app/src/main/java/com/example/jetpackcomposeapp/ui/theme/Color.kt
2815184612
package com.example.jetpackcomposeapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun JetpackComposeAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Jetpack-Compose-App/app/src/main/java/com/example/jetpackcomposeapp/ui/theme/Theme.kt
1088655007
package com.example.jetpackcomposeapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Jetpack-Compose-App/app/src/main/java/com/example/jetpackcomposeapp/ui/theme/Type.kt
3673609461
package com.example.jetpackcomposeapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.jetpackcomposeapp.ui.theme.JetpackComposeAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposeAppTheme { var name by remember { mutableStateOf("") } var names by remember { mutableStateOf(listOf<String>()) } Column( modifier = Modifier .padding(16.dp) ) { Row { OutlinedTextField( value = name, onValueChange = { text -> name = text }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(16.dp)) Button(onClick = { if (name.isNotBlank()) { names += name name = "" } }) { Text(text = "Add") } } Spacer(modifier = Modifier.height(16.dp)) LazyColumn { items(names) { currentName -> Text( text = currentName, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) Divider() } } } } } } }
Jetpack-Compose-App/app/src/main/java/com/example/jetpackcomposeapp/MainActivity.kt
1213472430
package io.github.cotrin1208.repository import com.google.cloud.datastore.* import io.github.cotrin1208.util.PropertyName class DatastoreRepository(private val datastore: Datastore) : IDatastoreRepository { override fun createKey(kindName: String, keyName: String): Key { return datastore.newKeyFactory().setKind(kindName).newKey(keyName) } override fun createEntity(key: Key, func: Entity.Builder.() -> Unit): Entity { val entity = Entity.newBuilder(key).apply(func).build() datastore.put(entity) return entity } override fun readEntity(key: Key): Entity? { return datastore.get(key) } override fun queryEntitiesInKind(kindName: String): List<Entity> { val query = Query.newEntityQueryBuilder().setKind(kindName).build() return datastore.run(query).asSequence().toList() } override fun queryEntitiesWithPropertyName(kindName: String, propertyName: String, value: String): List<Entity> { val query = Query.newEntityQueryBuilder().apply { setKind(kindName) setFilter(StructuredQuery.PropertyFilter.eq(PropertyName.USER_ID, value)) }.build() return datastore.run(query).asSequence().toList() } override fun updateParameters(key: Key, func: Entity.Builder.() -> Unit): Entity? { val oldEntity = readEntity(key) val newEntity = Entity.newBuilder(key).apply { oldEntity?.let { oldEntity.properties.forEach { (key, value) -> set(key, value) } } }.apply(func).build() datastore.update(newEntity) return newEntity } override fun updateEntity(key: Key, func: Entity.Builder.() -> Unit): Entity? { val entity = Entity.newBuilder(key).apply(func).build() datastore.update(entity) return entity } override fun deleteEntity(key: Key) { datastore.delete(key) } }
medicine-reminder-bot/src/main/kotlin/repository/DatastoreRepository.kt
1854852961
package io.github.cotrin1208.repository import io.github.cotrin1208.model.error.ErrorResponse import io.github.cotrin1208.model.error.LineApiException import io.github.cotrin1208.model.message.PushMessage import io.github.cotrin1208.model.user.UserProfile import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.engine.apache.* import io.ktor.client.plugins.* import io.ktor.client.plugins.auth.* import io.ktor.client.plugins.auth.providers.* import io.ktor.client.plugins.contentnegotiation.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.serialization.kotlinx.json.* import kotlinx.serialization.json.Json class LineApiRepository : ILineApiRepository { private val client = HttpClient(Apache) { install(ContentNegotiation) { json(Json { encodeDefaults = true }) } install(DefaultRequest) { url("https://api.line.me/v2/bot/") } install(Auth) { bearer { loadTokens { BearerTokens(System.getenv("CHANNEL_ACCESS_TOKEN") ?: "", "") } } } } override suspend fun getUserProfile(userId: String): UserProfile { val response = client.get("profile/$userId") return when (response.status) { HttpStatusCode.OK -> response.body<UserProfile>() else -> throw LineApiException(response.body<ErrorResponse>().message) } } override suspend fun sendPushMessage(message: PushMessage) { val response = client.post("message/push") { header(HttpHeaders.ContentType, ContentType.Application.Json) setBody(message) } if (response.status != HttpStatusCode.OK) { println(response.body<ErrorResponse>().toString()) } } }
medicine-reminder-bot/src/main/kotlin/repository/LineApiRepository.kt
2450723637
package io.github.cotrin1208.repository import com.google.cloud.datastore.Entity import com.google.cloud.datastore.Key interface IDatastoreRepository { fun createKey(kindName: String, keyName: String): Key fun createEntity(key: Key, func: Entity.Builder.() -> Unit): Entity fun readEntity(key: Key): Entity? fun queryEntitiesInKind(kindName: String): List<Entity> fun queryEntitiesWithPropertyName(kindName: String, propertyName: String, value: String): List<Entity> fun updateParameters(key: Key, func: Entity.Builder.() -> Unit): Entity? fun updateEntity(key: Key, func: Entity.Builder.() -> Unit): Entity? fun deleteEntity(key: Key) }
medicine-reminder-bot/src/main/kotlin/repository/IDatastoreRepository.kt
1680895740
package io.github.cotrin1208.repository import io.github.cotrin1208.model.message.PushMessage import io.github.cotrin1208.model.user.UserProfile interface ILineApiRepository { suspend fun getUserProfile(userId: String): UserProfile suspend fun sendPushMessage(message: PushMessage) }
medicine-reminder-bot/src/main/kotlin/repository/ILineApiRepository.kt
250417224
package io.github.cotrin1208.util import io.ktor.http.* val HttpHeaders.LineSignature: String get() = "X-Line-Signature" fun <T> T.asList() = listOf(this)
medicine-reminder-bot/src/main/kotlin/util/Extension.kt
1009018006
package io.github.cotrin1208.util import io.github.cotrin1208.model.message.Message object Stickers { private val stickers = listOf( Message.Sticker(packageId = "789", stickerId = "10856"), Message.Sticker(packageId = "789", stickerId = "10858"), Message.Sticker(packageId = "789", stickerId = "10871"), Message.Sticker(packageId = "6136", stickerId = "10551378"), Message.Sticker(packageId = "6136", stickerId = "10551394"), Message.Sticker(packageId = "6136", stickerId = "10551398"), Message.Sticker(packageId = "6325", stickerId = "10979904"), Message.Sticker(packageId = "6325", stickerId = "10979908"), Message.Sticker(packageId = "6325", stickerId = "10979913"), Message.Sticker(packageId = "6325", stickerId = "10979914"), Message.Sticker(packageId = "6325", stickerId = "10979918"), Message.Sticker(packageId = "6325", stickerId = "10979919"), Message.Sticker(packageId = "6325", stickerId = "10979924"), Message.Sticker(packageId = "8515", stickerId = "16581242"), Message.Sticker(packageId = "8515", stickerId = "16581245"), Message.Sticker(packageId = "8515", stickerId = "16581249"), Message.Sticker(packageId = "8515", stickerId = "16581254"), Message.Sticker(packageId = "8515", stickerId = "16581252"), Message.Sticker(packageId = "8515", stickerId = "16581265"), Message.Sticker(packageId = "8515", stickerId = "16581265"), Message.Sticker(packageId = "11537", stickerId = "52002735"), Message.Sticker(packageId = "11537", stickerId = "52002742"), Message.Sticker(packageId = "11537", stickerId = "52002743"), Message.Sticker(packageId = "11538", stickerId = "51626500"), Message.Sticker(packageId = "11538", stickerId = "51626501"), Message.Sticker(packageId = "11539", stickerId = "52114110"), Message.Sticker(packageId = "11539", stickerId = "52114111"), Message.Sticker(packageId = "11539", stickerId = "52114113"), Message.Sticker(packageId = "11539", stickerId = "52114117"), Message.Sticker(packageId = "11539", stickerId = "52114118"), Message.Sticker(packageId = "11539", stickerId = "52114123"), ) fun random() = stickers.random() }
medicine-reminder-bot/src/main/kotlin/util/Stickers.kt
1251034843
package io.github.cotrin1208.util object PropertyName { const val FRIDAY_MORNING_RESPONDED = "FridayMorningResponseReceived" const val FRIDAY_EVENING_RESPONDED = "FridayEveningResponseReceived" const val SUNDAY_MORNING_RESPONDED = "SundayMorningResponseReceived" const val USER_ID = "UserId" } object KindName { const val USER_KIND = "User" }
medicine-reminder-bot/src/main/kotlin/util/DatastoreIdentifier.kt
2829141363
package io.github.cotrin1208.util object ActionData { const val FRIDAY_MORNING_RESPONDED = "fridayMorningResponded" const val FRIDAY_EVENING_RESPONDED = "fridayEveningResponded" const val SUNDAY_MORNING_RESPONDED = "sundayMorningResponded" }
medicine-reminder-bot/src/main/kotlin/util/ActionData.kt
3263413761
package io.github.cotrin1208.plugin import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.* fun Application.configureSerialization() { install(ContentNegotiation) { json() } }
medicine-reminder-bot/src/main/kotlin/plugin/Serialization.kt
524663521
package io.github.cotrin1208.plugin import com.google.cloud.datastore.DatastoreOptions import io.github.cotrin1208.repository.DatastoreRepository import io.github.cotrin1208.repository.IDatastoreRepository import io.github.cotrin1208.repository.ILineApiRepository import io.github.cotrin1208.repository.LineApiRepository import io.github.cotrin1208.service.IMessageService import io.github.cotrin1208.service.IWebhookService import io.github.cotrin1208.service.MessageService import io.github.cotrin1208.service.WebhookService import io.ktor.server.application.* import org.koin.core.module.dsl.singleOf import org.koin.dsl.bind import org.koin.dsl.module import org.koin.ktor.plugin.Koin fun Application.configureKoin() { install(Koin) { modules( repositoryModule, serviceModule ) } } val repositoryModule = module { single { DatastoreOptions.getDefaultInstance().service } singleOf(::DatastoreRepository) bind IDatastoreRepository::class singleOf(::LineApiRepository) bind ILineApiRepository::class } val serviceModule = module { singleOf(::WebhookService) bind IWebhookService::class singleOf(::MessageService) bind IMessageService::class }
medicine-reminder-bot/src/main/kotlin/plugin/Koin.kt
203857812
package io.github.cotrin1208.plugin.routing import io.ktor.server.application.* import io.ktor.server.routing.* fun Application.configureRoute() { routing { lineBotRoute() pushMessageRoute() } }
medicine-reminder-bot/src/main/kotlin/plugin/routing/Routing.kt
3023640559
package io.github.cotrin1208.plugin.routing import io.github.cotrin1208.service.IMessageService import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.inject fun Route.pushMessageRoute() { val messageService: IMessageService by inject() route("notify") { post("friday-morning") { messageService.sendFridayMorningReminder() call.respond(HttpStatusCode.OK) } post("friday-evening") { messageService.sendFridayEveningReminder() call.respond(HttpStatusCode.OK) } post("sunday-morning") { messageService.sendSundayMorningReminder() call.respond(HttpStatusCode.OK) } } route("check") { post("friday-morning") { messageService.sendFridayMorningReminderAgain() call.respond(HttpStatusCode.OK) } post("friday-evening") { messageService.sendFridayEveningReminderAgain() call.respond(HttpStatusCode.OK) } post("sunday-morning") { messageService.sendSundayMorningReminderAgain() call.respond(HttpStatusCode.OK) } } }
medicine-reminder-bot/src/main/kotlin/plugin/routing/PushMessageRoute.kt
2124951170
package io.github.cotrin1208.plugin.routing import io.github.cotrin1208.feature.LineSignatureVerification import io.github.cotrin1208.model.webhook.Webhook import io.github.cotrin1208.model.webhook.WebhookEvent import io.github.cotrin1208.service.IWebhookService import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.doublereceive.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.pipeline.* import org.koin.ktor.ext.inject fun Route.lineBotRoute() { val webhookHandleService: IWebhookService by inject() webhook("webhook") { val requestBody = call.receive<Webhook>() requestBody.events.forEach { when (it) { is WebhookEvent.Follow -> webhookHandleService.onFollowEvent(it) is WebhookEvent.Postback -> webhookHandleService.onPostbackEvent(it) } } call.respond(HttpStatusCode.OK) } } fun Route.webhook( path: String = "callback", body: suspend PipelineContext<Unit, ApplicationCall>.(Unit) -> Unit, ) { route(path) { install(DoubleReceive) install(LineSignatureVerification) { channelSecret = System.getenv("CHANNEL_SECRET") ?: "" } post(body) } }
medicine-reminder-bot/src/main/kotlin/plugin/routing/WebhookRoute.kt
1219238770
package io.github.cotrin1208.plugin import com.google.cloud.datastore.DatastoreException import io.github.cotrin1208.model.error.LineApiException import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun Application.configureStatusPages() { install(StatusPages) { exception<DatastoreException> { call, _ -> call.respond(HttpStatusCode.InternalServerError) } exception<LineApiException> { call, _ -> call.respond(HttpStatusCode.BadGateway) } } }
medicine-reminder-bot/src/main/kotlin/plugin/StatusPages.kt
3803242096
package io.github.cotrin1208 import io.github.cotrin1208.plugin.configureKoin import io.github.cotrin1208.plugin.configureSerialization import io.github.cotrin1208.plugin.configureStatusPages import io.github.cotrin1208.plugin.routing.configureRoute import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0") { module() }.start(wait = true) } fun Application.module() { configureSerialization() configureStatusPages() configureRoute() configureKoin() }
medicine-reminder-bot/src/main/kotlin/Main.kt
41391919
package io.github.cotrin1208.model.webhook import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed interface Source { val userId: String? @Serializable @SerialName("user") data class User( override val userId: String, ) : Source @Serializable @SerialName("group") data class Group( val groupId: String, override val userId: String?, ) : Source @Serializable @SerialName("room") data class Room( val roomId: String, override val userId: String?, ) : Source }
medicine-reminder-bot/src/main/kotlin/model/webhook/Source.kt
3738660299
package io.github.cotrin1208.model.webhook import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Webhook( val destination: String, val events: List<WebhookEvent>, ) @Serializable sealed interface WebhookEvent { val mode: String val timestamp: Long val source: Source val webhookEventId: String val deliveryContext: DeliveryContext @Serializable @SerialName("follow") data class Follow( override val mode: String, override val timestamp: Long, override val source: Source, override val webhookEventId: String, override val deliveryContext: DeliveryContext, val replyToken: String, val follow: FollowType, ) : WebhookEvent @Serializable @SerialName("postback") data class Postback( override val mode: String, override val timestamp: Long, override val source: Source, override val webhookEventId: String, override val deliveryContext: DeliveryContext, val replyToken: String, val postback: PostbackObject, ) : WebhookEvent } @Serializable data class DeliveryContext( val isRedelivery: Boolean, ) @Serializable data class FollowType( val isUnblocked: Boolean, ) @Serializable data class PostbackObject( val data: String, val params: PostbackParams? = null, ) @Serializable sealed interface PostbackParams { @Serializable @SerialName("date_select") data class DateSelect( val date: String? = null, val time: String? = null, val datetime: String? = null, ) : PostbackParams }
medicine-reminder-bot/src/main/kotlin/model/webhook/Webhook.kt
775014668
package io.github.cotrin1208.model.message import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed interface TemplateObject { @Serializable @SerialName("confirm") data class Confirm( val text: String, val actions: List<Action>, ) : TemplateObject }
medicine-reminder-bot/src/main/kotlin/model/message/TemplateObject.kt
3151059765
package io.github.cotrin1208.model.message import kotlinx.serialization.Serializable @Serializable data class QuickReplyItem( val type: String = "action", val imageUrl: String? = null, val action: Action, )
medicine-reminder-bot/src/main/kotlin/model/message/QuickReplyItem.kt
2112627586
package io.github.cotrin1208.model.message import kotlinx.serialization.Serializable @Serializable data class PushMessage( val to: String, val messages: List<Message>, val notificationDisabled: Boolean? = null, )
medicine-reminder-bot/src/main/kotlin/model/message/PushMessage.kt
4020634943
package io.github.cotrin1208.model.message import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed interface Message { val quickReply: List<QuickReplyItem>? @Serializable @SerialName("text") data class Text( override val quickReply: List<QuickReplyItem>? = null, val text: String, val emojis: List<Emoji>? = null, ) : Message @Serializable @SerialName("sticker") data class Sticker( override val quickReply: List<QuickReplyItem>? = null, val packageId: String, val stickerId: String, val quoteToken: String? = null, ) : Message @Serializable @SerialName("template") data class Template( override val quickReply: List<QuickReplyItem>? = null, val altText: String, val template: TemplateObject, ) : Message }
medicine-reminder-bot/src/main/kotlin/model/message/Message.kt
944899375
package io.github.cotrin1208.model.message import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed interface Action { @Serializable @SerialName("postback") data class PostBack( val label: String, val data: String, val displayText: String? = null, val inputOption: ActionInputOption? = null, val fillInText: String? = null, ) : Action } @Serializable sealed interface ActionInputOption { @Serializable @SerialName("closeRichMenu") data object CloseRichMenu : ActionInputOption @Serializable @SerialName("openRichMenu") data object OpenRichMenu : ActionInputOption @Serializable @SerialName("openKeyboard") data object OpenKeyboard : ActionInputOption @Serializable @SerialName("openVoice") data object OpenVoice : ActionInputOption }
medicine-reminder-bot/src/main/kotlin/model/message/Action.kt
3522762647
package io.github.cotrin1208.model.message import kotlinx.serialization.Serializable @Serializable data class Emoji( val index: Int? = null, val productId: String? = null, val emojiId: String? = null, val quoteToken: String? = null, )
medicine-reminder-bot/src/main/kotlin/model/message/Emoji.kt
4261876732
package io.github.cotrin1208.model.user import kotlinx.serialization.Serializable @Serializable data class UserProfile( val displayName: String, val userId: String, val language: String? = null, val pictureUrl: String? = null, val statusMessage: String? = null, )
medicine-reminder-bot/src/main/kotlin/model/user/UserProfile.kt
507385643
package io.github.cotrin1208.model import kotlinx.serialization.Serializable @Serializable data class ConfirmTemplate( val type: String, val altText: String, val template: Template, ) @Serializable data class Template( val type: String, val text: String, val actions: List<Action>, ) @Serializable data class Action( val type: String, val label: String, val text: String, ) @Serializable data class MessageRequest( val to: String, val messages: List<ConfirmTemplate>, )
medicine-reminder-bot/src/main/kotlin/model/ConfirmTemplate.kt
1958054190
package io.github.cotrin1208.model.remind data class MedicineInfo( val id: String, val name: String, )
medicine-reminder-bot/src/main/kotlin/model/remind/MedicineInfo.kt
2795675757
package io.github.cotrin1208.model.error class LineApiException(override val message: String?) : Exception()
medicine-reminder-bot/src/main/kotlin/model/error/LineApiException.kt
609270941
package io.github.cotrin1208.model.error import kotlinx.serialization.Serializable @Serializable data class ErrorResponse( val message: String, val details: List<Detail>? = null, ) @Serializable data class Detail( val message: String? = null, val property: String? = null, )
medicine-reminder-bot/src/main/kotlin/model/error/ErrorResponse.kt
3683717766
package io.github.cotrin1208.feature import io.github.cotrin1208.util.LineSignature import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec val LineSignatureVerification = createRouteScopedPlugin( name = "LineSignatureVerificationPlugin", createConfiguration = ::Configuration ) { suspend fun ApplicationCall.verifySignature(channelSecret: String): Boolean { val signatureFromHeader = request.header(HttpHeaders.LineSignature) ?: return false val key = SecretKeySpec(channelSecret.toByteArray(), "HmacSHA256") val mac = Mac.getInstance("HmacSHA256").apply { init(key) } val source = receiveText().toByteArray(Charsets.UTF_8) val calculatedSignature = Base64.getEncoder().encodeToString(mac.doFinal(source)) return signatureFromHeader == calculatedSignature } pluginConfig.apply { onCall { call -> if (!call.verifySignature(channelSecret)) { call.respond(HttpStatusCode.Forbidden) return@onCall } } } } class Configuration { lateinit var channelSecret: String }
medicine-reminder-bot/src/main/kotlin/feature/LineSignatureVerification.kt
3916405352
package io.github.cotrin1208.service interface IMessageService { suspend fun sendFridayMorningReminder() suspend fun sendFridayEveningReminder() suspend fun sendSundayMorningReminder() suspend fun sendFridayMorningReminderAgain() suspend fun sendFridayEveningReminderAgain() suspend fun sendSundayMorningReminderAgain() }
medicine-reminder-bot/src/main/kotlin/service/IMessageService.kt
3630935600
package io.github.cotrin1208.service import com.google.cloud.datastore.Key import io.github.cotrin1208.model.message.Action import io.github.cotrin1208.model.message.Message import io.github.cotrin1208.model.message.PushMessage import io.github.cotrin1208.model.message.TemplateObject import io.github.cotrin1208.repository.IDatastoreRepository import io.github.cotrin1208.repository.ILineApiRepository import io.github.cotrin1208.util.ActionData import io.github.cotrin1208.util.KindName import io.github.cotrin1208.util.PropertyName class MessageService( private val datastoreRepository: IDatastoreRepository, private val lineApiRepository: ILineApiRepository, ) : IMessageService { override suspend fun sendFridayMorningReminder() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { sendReminder( user.getString(PropertyName.USER_ID), "金曜日朝のお薬リマインダー", ActionData.FRIDAY_MORNING_RESPONDED ) setFridayMorningFlag(user.key) } } override suspend fun sendFridayEveningReminder() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { sendReminder( user.getString(PropertyName.USER_ID), "金曜日夜のお薬リマインダー", ActionData.FRIDAY_EVENING_RESPONDED ) setFridayEveningFlag(user.key) } } override suspend fun sendSundayMorningReminder() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { sendReminder( user.getString(PropertyName.USER_ID), "日曜日朝のお薬リマインダー", ActionData.SUNDAY_MORNING_RESPONDED ) setSundayMorningFlag(user.key) } } override suspend fun sendFridayMorningReminderAgain() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { if (user.getBoolean(PropertyName.FRIDAY_MORNING_RESPONDED)) continue sendReminder( user.getString(PropertyName.USER_ID), "金曜日朝のお薬リマインダー", ActionData.FRIDAY_MORNING_RESPONDED ) } } override suspend fun sendFridayEveningReminderAgain() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { if (user.getBoolean(PropertyName.FRIDAY_EVENING_RESPONDED)) continue sendReminder( user.getString(PropertyName.USER_ID), "金曜日夜のお薬リマインダー", ActionData.FRIDAY_EVENING_RESPONDED ) } } override suspend fun sendSundayMorningReminderAgain() { val userList = datastoreRepository.queryEntitiesInKind(KindName.USER_KIND) for (user in userList) { if (user.getBoolean(PropertyName.SUNDAY_MORNING_RESPONDED)) continue sendReminder( user.getString(PropertyName.USER_ID), "日曜日朝のお薬リマインダー", ActionData.SUNDAY_MORNING_RESPONDED ) } } private fun setFridayMorningFlag(key: Key) { datastoreRepository.updateParameters(key) { set(PropertyName.FRIDAY_MORNING_RESPONDED, false) } } private fun setFridayEveningFlag(key: Key) { datastoreRepository.updateParameters(key) { set(PropertyName.FRIDAY_EVENING_RESPONDED, false) } } private fun setSundayMorningFlag(key: Key) { datastoreRepository.updateParameters(key) { set(PropertyName.SUNDAY_MORNING_RESPONDED, false) } } private fun createConfirmTemplate(title: String, data: String): Message.Template { return Message.Template( altText = title, template = TemplateObject.Confirm( text = title, actions = listOf( Action.PostBack( label = "スキップ", data = data, ), Action.PostBack( label = "飲んだ", data = data, ) ) ) ) } private fun createPushMessage(to: String, message: Message): PushMessage { return PushMessage(to, listOf(message)) } private suspend fun sendReminder(userId: String, title: String, data: String) { val message = createPushMessage( userId, createConfirmTemplate(title, data) ) lineApiRepository.sendPushMessage(message) } }
medicine-reminder-bot/src/main/kotlin/service/MessageService.kt
978655594
package io.github.cotrin1208.service import com.google.cloud.datastore.Key import io.github.cotrin1208.model.message.PushMessage import io.github.cotrin1208.model.webhook.Source import io.github.cotrin1208.model.webhook.WebhookEvent import io.github.cotrin1208.repository.IDatastoreRepository import io.github.cotrin1208.repository.ILineApiRepository import io.github.cotrin1208.util.* class WebhookService( private val datastoreRepository: IDatastoreRepository, private val lineApiRepository: ILineApiRepository, ) : IWebhookService { override suspend fun onFollowEvent(event: WebhookEvent.Follow) { val source = event.source if (source is Source.User) { val userProfile = lineApiRepository.getUserProfile(source.userId) println(userProfile.displayName) val key = datastoreRepository.createKey(KindName.USER_KIND, userProfile.displayName) datastoreRepository.createEntity(key) { set(PropertyName.FRIDAY_MORNING_RESPONDED, false) set(PropertyName.FRIDAY_EVENING_RESPONDED, false) set(PropertyName.SUNDAY_MORNING_RESPONDED, false) set(PropertyName.USER_ID, source.userId) } } } override suspend fun onPostbackEvent(event: WebhookEvent.Postback) { val source = event.source if (source !is Source.User) return val user = datastoreRepository.queryEntitiesWithPropertyName(KindName.USER_KIND, PropertyName.USER_ID, source.userId) .first() when (event.postback.data) { ActionData.FRIDAY_MORNING_RESPONDED -> { if (user.getBoolean(PropertyName.FRIDAY_MORNING_RESPONDED)) return updateRespondedFlag(user.key, PropertyName.FRIDAY_MORNING_RESPONDED) sendRandomStickerMessage(source.userId) } ActionData.FRIDAY_EVENING_RESPONDED -> { if (user.getBoolean(PropertyName.FRIDAY_EVENING_RESPONDED)) return updateRespondedFlag(user.key, PropertyName.FRIDAY_EVENING_RESPONDED) sendRandomStickerMessage(source.userId) } ActionData.SUNDAY_MORNING_RESPONDED -> { if (user.getBoolean(PropertyName.SUNDAY_MORNING_RESPONDED)) return updateRespondedFlag(user.key, PropertyName.SUNDAY_MORNING_RESPONDED) sendRandomStickerMessage(source.userId) } } } private fun updateRespondedFlag(key: Key, flagName: String) { datastoreRepository.updateParameters(key) { set(flagName, true) } } private suspend fun sendRandomStickerMessage(to: String) { lineApiRepository.sendPushMessage( PushMessage( to = to, messages = Stickers.random().asList() ) ) } }
medicine-reminder-bot/src/main/kotlin/service/WebhookService.kt
2153255848
package io.github.cotrin1208.service import io.github.cotrin1208.model.webhook.WebhookEvent interface IWebhookService { suspend fun onFollowEvent(event: WebhookEvent.Follow) suspend fun onPostbackEvent(event: WebhookEvent.Postback) }
medicine-reminder-bot/src/main/kotlin/service/IWebhookService.kt
754454546
package com.example.quotegenerator 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.quotegenerator", appContext.packageName) } }
Quote-Generator/app/src/androidTest/java/com/example/quotegenerator/ExampleInstrumentedTest.kt
59168366
package com.example.quotegenerator 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) } }
Quote-Generator/app/src/test/java/com/example/quotegenerator/ExampleUnitTest.kt
1205723550