content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.jettodo.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/ui/theme/Color.kt | 1957149236 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun JetToDoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/ui/theme/Theme.kt | 2880959256 |
package com.example.jettodo.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/ui/theme/Type.kt | 3646947797 |
package com.example.jettodo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application() {
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/App.kt | 3361042148 |
package com.example.jettodo
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.jettodo.components.*
import com.example.jettodo.ui.theme.JetToDoTheme
import dagger.hilt.android.AndroidEntryPoint
import java.time.DayOfWeek
import java.time.Year
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetToDoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Row(
modifier = Modifier.padding(5.dp),
verticalAlignment = Alignment.Top,
) {
// Tab
StudyReportScreen()
}
}
}
}
}
}
@Composable
fun StudyReportScreen(viewModel: MainViewModel = hiltViewModel()) {
Column {
TabRow(
selectedTabIndex = viewModel.tabSelected.ordinal,
backgroundColor = Color.LightGray,
contentColor = Color.Red,
) {
Screen.values().map { it.name }.forEachIndexed { index, title ->
Tab(
text = { Text(text = title) },
selected = viewModel.tabSelected.ordinal == index,
onClick = { viewModel.tabSelected = Screen.values()[index] },
unselectedContentColor = Color.Blue
)
}
}
when (viewModel.tabSelected) {
Screen.DAY -> DayScreen()
Screen.WEEK -> WeekScreen()
Screen.MONTH -> MonthScreen()
Screen.YEAR -> YaerScreen()
}
}
}
enum class Screen {
DAY, WEEK, MONTH, YEAR
}
@Composable
fun DayScreen() {
MainContent()
}
@Composable
fun WeekScreen() {
MainContent()
}
@Composable
fun MonthScreen() {
MainContent()
}
@Composable
fun YaerScreen() {
MainContent()
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainContent(viewModel: MainViewModel = hiltViewModel()) {
if (viewModel.isShowDialog) {
EditDialog()
}
Scaffold(floatingActionButton = {
FloatingActionButton(onClick = { viewModel.isShowDialog = true }) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Create new")
}
}) {
val tasks by viewModel.tasks.collectAsState(initial = emptyList())
val tasksWeek by viewModel.tasksWeek.collectAsState(initial = emptyList())
val tasksMonth by viewModel.tasksMonth.collectAsState(initial = emptyList())
val tasksYear by viewModel.tasksYear.collectAsState(initial = emptyList())
if (viewModel.tabSelected == Screen.DAY) {
TaskList(
tasks = tasks,
onClickRow = {
viewModel.setEditingTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteTask(it) },
)
} else if (viewModel.tabSelected == Screen.WEEK) {
WeekTaskList(
tasks = tasksWeek,
onClickRow = {
viewModel.setEditingWeekTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteWeekTask(it) },
)
} else if (viewModel.tabSelected == Screen.MONTH) {
MonthTaskList(
tasks = tasksMonth,
onClickRow = {
viewModel.setEditingMonthTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteMonthTask(it) },
)
} else {
YearTaskList(
tasks = tasksYear,
onClickRow = {
viewModel.setEditingYearTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteYearTask(it) },
)
}
}
}
| Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/MainActivity.kt | 1309948671 |
package com.example.jettodo
import android.content.Context
import androidx.room.Room
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@dagger.Module
@InstallIn(SingletonComponent::class)
object Module {
@Provides
fun provideDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabase::class.java, "task_database").build()
@Provides
fun provideWeekDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabaseWeek::class.java, "week_task_database").build()
@Provides
fun provideMonthDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabaseMonth::class.java, "month_task_database").build()
@Provides
fun provideYearDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabaseYear::class.java, "year_task_database").build()
@Provides
fun provideDao(db: AppDatabase) = db.taskDao()
@Provides
fun provideWeekDao(db: AppDatabaseWeek) = db.weekTaskDao()
@Provides
fun provideMonthDao(db: AppDatabaseMonth) = db.monthTaskDao()
@Provides
fun provideYearDao(db: AppDatabaseYear) = db.yearTaskDao()
}
| Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/Module.kt | 3674393327 |
package com.example.jettodo.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import com.example.jettodo.MonthTask
import com.example.jettodo.Task
import com.example.jettodo.WeekTask
import com.example.jettodo.YearTask
@Composable
fun TaskList(
tasks:List<Task>,
onClickRow:(Task) -> Unit,
onClickDelete:(Task) -> Unit,
){
LazyColumn {
items(tasks) { task ->
TaskRow(
task = task,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
}
@Composable
fun WeekTaskList(
tasks:List<WeekTask>,
onClickRow:(WeekTask) -> Unit,
onClickDelete:(WeekTask) -> Unit,
){
LazyColumn {
items(tasks) { WeekTask ->
WeekTaskRow(
task = WeekTask,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
}
@Composable
fun MonthTaskList(
tasks:List<MonthTask>,
onClickRow:(MonthTask) -> Unit,
onClickDelete:(MonthTask) -> Unit,
){
LazyColumn {
items(tasks) { MonthTask ->
MonthTaskRow(
task = MonthTask,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
}
@Composable
fun YearTaskList(
tasks:List<YearTask>,
onClickRow:(YearTask) -> Unit,
onClickDelete:(YearTask) -> Unit,
){
LazyColumn {
items(tasks) { YearTask ->
YearTaskRow(
task = YearTask,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
}
| Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/components/TaskList.kt | 392937029 |
package com.example.jettodo.components
import androidx.compose.foundation.layout.*
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.MainViewModel
import com.example.jettodo.Screen
@Composable
fun EditDialog(viewModel: MainViewModel = hiltViewModel(), ){
DisposableEffect(Unit)
{
// Called when the dialog is closed
onDispose {
if (viewModel.tabSelected == Screen.DAY) {
viewModel.resetProperties()
}else if (viewModel.tabSelected == Screen.WEEK) {
viewModel.resetPropertiesWeek()
}else if (viewModel.tabSelected == Screen.MONTH) {
viewModel.resetPropertiesMonth()
}else if (viewModel.tabSelected == Screen.YEAR) {
viewModel.resetPropertiesYear()
}
}
}
AlertDialog(
// Tap outside the screen
onDismissRequest = {viewModel.isShowDialog = false},
title = { Text(text =
if(
(viewModel.isEditing && viewModel.tabSelected == Screen.DAY) ||
(viewModel.isEditingWeek && viewModel.tabSelected == Screen.WEEK) ||
(viewModel.isEditingMonth && viewModel.tabSelected == Screen.MONTH)||
(viewModel.isEditingYear&& viewModel.tabSelected == Screen.YEAR)
){
GetEditText("update")
} else { GetEditText("create") })},
text = {
Column {
Text(text = "Title")
TextField(
value = viewModel.title,
onValueChange = {viewModel.title = it}
)
Text(text = "Detail")
TextField(
value = viewModel.description,
onValueChange = {viewModel.description = it}
)
}
},
buttons = {
Row(
modifier = Modifier.padding(8.dp),
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {viewModel.isShowDialog = false}
){
Text(text = "Cancel")
}
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {
viewModel.isShowDialog = false
if (viewModel.tabSelected == Screen.DAY) {
if (viewModel.isEditing) {
viewModel.updateTask()
} else {
viewModel.createTask()
}
}else if (viewModel.tabSelected == Screen.WEEK) {
if (viewModel.isEditingWeek) {
viewModel.updateWeekTask()
} else {
viewModel.createWeekTask()
}
}else if (viewModel.tabSelected == Screen.MONTH) {
if (viewModel.isEditingMonth) {
viewModel.updateMonthTask()
} else {
viewModel.createMonthTask()
}
}else if (viewModel.tabSelected == Screen.YEAR) {
if (viewModel.isEditingYear) {
viewModel.updateYearTask()
} else {
viewModel.createYearTask()
}
}
}
){
Text(text = if (
(viewModel.isEditing && viewModel.tabSelected == Screen.DAY) ||
(viewModel.isEditingWeek && viewModel.tabSelected == Screen.WEEK) ||
(viewModel.isEditingMonth && viewModel.tabSelected == Screen.MONTH)||
(viewModel.isEditingYear&& viewModel.tabSelected == Screen.YEAR)
) "Update" else "Create")
}
}
},
)
}
@Composable
fun GetEditText(
kind : String,
viewModel: MainViewModel = hiltViewModel()): String{
var text : String
if (viewModel.tabSelected == Screen.DAY) {
text = "Day task"
} else if (viewModel.tabSelected == Screen.WEEK) {
text = "Week task"
} else if (viewModel.tabSelected == Screen.MONTH) {
text = "Month task"
} else {
text = "Year task"
}
return text + " " + kind
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/components/EditDialog.kt | 3209865645 |
package com.example.jettodo.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jettodo.MonthTask
import com.example.jettodo.Task
import com.example.jettodo.WeekTask
import com.example.jettodo.YearTask
@Composable
fun TaskRow(
task: Task,
onClickRow: (Task) -> Unit,
onClickDelete: (Task) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Composable
fun WeekTaskRow(
task: WeekTask,
onClickRow: (WeekTask) -> Unit,
onClickDelete: (WeekTask) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Composable
fun MonthTaskRow(
task: MonthTask,
onClickRow: (MonthTask) -> Unit,
onClickDelete: (MonthTask) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Composable
fun YearTaskRow(
task: YearTask,
onClickRow: (YearTask) -> Unit,
onClickDelete: (YearTask) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Preview
@Composable
fun TaskRowPreview(){
TaskRow(
task = Task(title = "preview", description = ""),
onClickRow = {},
) {}
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/components/TaskRow.kt | 1884251223 |
package com.example.jettodo
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
}
@Database(entities = [WeekTask::class], version = 1, exportSchema = false)
abstract class AppDatabaseWeek : RoomDatabase() {
abstract fun weekTaskDao(): WeekTaskDao
}
@Database(entities = [MonthTask::class], version = 1, exportSchema = false)
abstract class AppDatabaseMonth : RoomDatabase() {
abstract fun monthTaskDao(): MonthTaskDao
}
@Database(entities = [YearTask::class], version = 1, exportSchema = false)
abstract class AppDatabaseYear : RoomDatabase() {
abstract fun yearTaskDao(): YearTaskDao
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/AppDatabase.kt | 40161410 |
package com.example.jettodo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Task(
// DataEntity is an object for operating sqlite
// Table structure
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
)
@Entity
data class WeekTask(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
)
@Entity
data class MonthTask(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
)
@Entity
data class YearTask(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
)
| Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/Task.kt | 873970918 |
package com.example.jettodo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface TaskDao {
// suspend is an asynchronous process
// Defined by annotation
@Insert
suspend fun insertTask(task: Task)
@Query("SELECT * FROM Task")
fun loadAllTask(): Flow<List<Task>>
@Update
suspend fun updateTask(task: Task)
@Delete
suspend fun deleteTask(task: Task)
}
@Dao
interface WeekTaskDao {
@Insert
suspend fun insertTask(task: WeekTask)
@Query("SELECT * FROM WeekTask")
fun loadAllTask(): Flow<List<WeekTask>>
@Update
suspend fun updateTask(task: WeekTask)
@Delete
suspend fun deleteTask(task: WeekTask)
}
@Dao
interface MonthTaskDao {
@Insert
suspend fun insertTask(task: MonthTask)
@Query("SELECT * FROM MonthTask")
fun loadAllTask(): Flow<List<MonthTask>>
@Update
suspend fun updateTask(task: MonthTask)
@Delete
suspend fun deleteTask(task: MonthTask)
}
@Dao
interface YearTaskDao {
@Insert
suspend fun insertTask(task: YearTask)
@Query("SELECT * FROM YearTask")
fun loadAllTask(): Flow<List<YearTask>>
@Update
suspend fun updateTask(task: YearTask)
@Delete
suspend fun deleteTask(task: YearTask)
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/TaskDao.kt | 1265869067 |
import java.util.logging.Handler
import kotlin.math.round
fun main(args: Array<String>) {
val dice = Dice(10)
val fighter = Fighter("David Buchtela", 20, 8, 5, dice)
val enemy = Fighter("Spongebob", 27, 8, 5, dice)
println("Bojovnรญk jednaaaa jeeeee: $fighter!!!!")
println("ลฝivot: ${fighter.healthBar()}")
Thread.sleep(1000)
println("A na druhรฉ stranฤ... neskrotnรฝ.... neodolatelnรฝ.... ลฝLUTร.... $enemy!!!!!!")
println("ลฝivot: ${enemy.healthBar()}\n\n")
while(fighter.isAlive() && enemy.isAlive())
{
fighter.doAttack(enemy)
println(fighter.lastNotify())
Thread.sleep(1000)
println(enemy.lastNotify() + "\n" + enemy.healthBar() + "\n")
if(!enemy.isAlive()){
break
}
enemy.doAttack(fighter)
Thread.sleep(1000)
println(enemy.lastNotify())
Thread.sleep(1000)
println(fighter.lastNotify() + "\n" + fighter.healthBar() + "\n")
Thread.sleep(1000)
}
}
class Dice(setWallsNum: Int) {
val wallsNum: Int
init {
wallsNum = setWallsNum
}
constructor(): this(6)
fun diceThrow(): Int {
return (1..wallsNum).shuffled().first()
}
override fun toString(): String {
return "Kostka s $wallsNum stฤnami"
}
}
class Fighter(private val name: String, private var health: Int, private val attack: Int,
private val defense: Int, private val dice: Dice)
{
private var notify = ""
private val maxHealth: Int = health
override fun toString(): String {
return name
}
private fun setNotify(notify: String)
{
this.notify = notify
}
fun lastNotify(): String
{
return notify
}
fun isAlive(): Boolean
{
return health > 0
}
fun healthBar(): String
{
var s = "["
val total = 20
var calcul = round((health.toDouble()/maxHealth) * total).toInt()
if((calcul == 0) && (isAlive()))
calcul = 1
s = s.padEnd(calcul + s.length, '#')
s = s.padEnd(total - calcul + s.length, ' ')
s += "]"
return s
}
fun defend(hit: Int)
{
val hurt = hit - (defense + dice.diceThrow())
if(hurt > 0)
{
health -= hurt
notify = "$name dostal poskozeni $hurt"
if (health < 0)
{
health = 0
notify += " a tรญm pรกdem umลel X-X"
}
}
else notify = "$name Vyhnul se B)"
setNotify(notify)
}
fun doAttack(enemy: Fighter)
{
val hit = attack + dice.diceThrow()
setNotify("$name รบtoฤรญ s รบtokem $hit")
enemy.defend(hit)
}
} | Kotlin_beggining/Boj/src/main/kotlin/Main.kt | 1529327677 |
object Hamming {
fun compute(leftStrand: String, rightStrand: String): String {
var difference: Int = 0
if(leftStrand.length == rightStrand.length)
{
for (i in leftStrand.indices)
{
if (leftStrand[i] != rightStrand[i])
{
difference++
}
}
return difference.toString()
}
else return "left and right strands must be of equal length"
}
}
fun main() {
println(Hamming.compute("Honza","Honza"))
} | Kotlin_beggining/Hamming_kotlin/src/main/kotlin/Hamming.kt | 424814550 |
class Dice(setWallsNum: Int) {
val wallsNum: Int
init {
wallsNum = setWallsNum
}
constructor(): this(6)
fun diceThrow(): Int {
return (1..wallsNum).shuffled().first()
}
override fun toString(): String {
return "Kostka s $wallsNum stฤnami"
}
}
fun main(args: Array<String>) {
val dice = Dice(10)
println(dice.wallsNum)
println(dice)
for(i in 0..9){
print(dice.diceThrow().toString() + " ")
}
} | Kotlin_beggining/Dice/src/main/kotlin/Main.kt | 3558101592 |
package com.example.basiccalculator
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.basiccalculator", appContext.packageName)
}
} | basic-calculator/app/src/androidTest/java/com/example/basiccalculator/ExampleInstrumentedTest.kt | 1578538396 |
package com.example.basiccalculator
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)
}
} | basic-calculator/app/src/test/java/com/example/basiccalculator/ExampleUnitTest.kt | 3912703438 |
package com.example.basiccalculator
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.basiccalculator.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
var number1: Double? = null
var number2: Double? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
enableEdgeToEdge()
val view = binding.root
setContentView(view)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
fun toplama(view: View) {
if(binding.editText1.text.isNotEmpty() && binding.editText2.text.isNotEmpty()) {
val num: Number = binding.editText1.text.toString().toInt() + binding.editText2.text.toString().toInt()
binding.textView.text = "Result: ${num}"
} else {
binding.textView.text = "Please enter number!"
}
}
fun cikarma(view: View) {
if(binding.editText1.text.isNotEmpty() && binding.editText2.text.isNotEmpty()) {
val num: Number = binding.editText1.text.toString().toInt() - binding.editText2.text.toString().toInt()
binding.textView.text = "Result: ${num}"
} else {
binding.textView.text = "Please enter number!"
}
}
fun carpma(view: View) {
if(binding.editText1.text.isNotEmpty() && binding.editText2.text.isNotEmpty()) {
val num: Number = binding.editText1.text.toString().toInt() * binding.editText2.text.toString().toInt()
binding.textView.text = "Result: ${num}"
} else {
binding.textView.text = "Please enter number!"
}
}
fun bolme(view: View) {
if(binding.editText1.text.isNotEmpty() && binding.editText2.text.isNotEmpty()) {
val num: Number = binding.editText1.text.toString().toInt() / binding.editText2.text.toString().toInt()
binding.textView.text = "Result: ${num}"
} else {
binding.textView.text = "Please enter number!"
}
}
} | basic-calculator/app/src/main/java/com/example/basiccalculator/MainActivity.kt | 782215984 |
package com.example.sudokugame
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
/**
* Aqui usuamos el View para crear un tablero de sudoku, con las lineas y celdas correspondientes.
* Ademas, se definen los colores y estilos de las celdas, lineas y numeros.
* Se implementa la interfaz OnTouchListener para manejar los eventos de toque en el tablero.
*/
class SudokuBoardView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) {
private var boardSize = 9 // Tamaรฑo del tablero
private var sqrtSize = 3 // Tamaรฑo de la raiz cuadrada del tablero
private var cellSizePixels = 0 // Tamaรฑo de las celdas del tablero
private var selectedRow = -1 // Fila seleccionada
private var selectedColumn = -1 // Columna seleccionada
private var boardNumbers = ArrayList<Pair<Int, Int>?>() // Lista de numeros en el tablero
internal var onTouchListener: OnTouchListener? = null // Listener para los eventos de toque en el tablero
private val thickLinePaint = Paint().apply { // Paint para las lineas gruesas del tablero
style = Paint.Style.STROKE
color = Color.BLACK
strokeWidth = 4F
}
private val thinLinePaint = Paint().apply { // Paint para las lineas delgadas del tablero
style = Paint.Style.STROKE
color = Color.BLACK
strokeWidth = 2F
}
private val selectedCellPaint = Paint().apply { // Paint para la celda seleccionada en el tablero
style = Paint.Style.FILL_AND_STROKE
color = Color.rgb(173, 216, 230)
}
private val conflictingCellPaint = Paint().apply { // Paint para las celdas conflictivas en el tablero
// conflictivas son las que tienen el mismo numero en la misma fila, columna o cuadrante, ademas de la seleccionada
style = Paint.Style.FILL_AND_STROKE
color = Color.LTGRAY
}
private val textPaint = Paint().apply {// Paint para los numeros en las celdas del tablero
color = Color.BLACK
textSize = 35f
}
private val preDefinedCellPaint = Paint().apply { // Paint para las celdas predefinidas en el tablero
style = Paint.Style.FILL_AND_STROKE
color = Color.rgb(235, 235, 235)
}
private val checkedCellPaint = Paint().apply { // Paint para las celdas verificadas en el tablero
style = Paint.Style.FILL_AND_STROKE
color = Color.rgb(255, 255, 204)
}
private val correctCellPaint = Paint().apply { // Paint para las celdas correctas en el tablero
style = Paint.Style.FILL_AND_STROKE
color = Color.GREEN
}
private val wrongCellPaint = Paint().apply {// verifica si la celda es incorrecta
style = Paint.Style.FILL_AND_STROKE
color = Color.RED
}
/**
* mide el tamaรฑo de la celda y lo ajusta al tamaรฑo del tablero
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val sizePixels = widthMeasureSpec.coerceAtMost(heightMeasureSpec)
setMeasuredDimension(sizePixels, sizePixels)
}
/**
* Dibuja el tablero en todo el canvas o el lienzo.
*/
override fun onDraw(canvas: Canvas) {
cellSizePixels = (width / boardSize)
fillCells(canvas)
drawLines(canvas)
}
private fun fillCells(canvas: Canvas) {
if (selectedRow == -1 || selectedColumn == -1) return // valida si la celda seleccionada es valida
// si es valida recorre las celdas del tablero y las pinta segun su estado
for (row in 0 until boardSize) {
for (column in 0 until boardSize) { // recorre las columnas y filas del tablero y verifica si hay conflictos
var conflict = false
if (row == selectedRow && column == selectedColumn) {
fillCell(canvas, row, column, selectedCellPaint)
conflict = true
} else if (row == selectedRow || column == selectedColumn || (row / sqrtSize == selectedRow / sqrtSize && column / sqrtSize == selectedColumn / sqrtSize)) {
fillCell(canvas, row, column, conflictingCellPaint)
conflict = true
}
if (boardNumbers[row * boardSize + column] != null) { // si no hay conflictos pinta la celda segun su estado
val text = boardNumbers[row * boardSize + column]!!.first.toString()
val textX = column * cellSizePixels + (cellSizePixels - textPaint.measureText(text)) / 2
val textY = row * cellSizePixels + (cellSizePixels + textPaint.textSize) / 2
if (!conflict) {
when (boardNumbers[row * boardSize + column]!!.second) {
0 -> fillCell(canvas, row, column, preDefinedCellPaint)
2 -> fillCell(canvas, row, column, checkedCellPaint)
3 -> fillCell(canvas, row, column, correctCellPaint)
4 -> fillCell(canvas, row, column, wrongCellPaint)
}
}
canvas.drawText(text, textX, textY, textPaint) // pinta el numero en la celda
}
}
}
}
// determina el color de la celda segun su estado
private fun fillCell(canvas: Canvas, row: Int, column: Int, paint: Paint) {
val rect = Rect(column * cellSizePixels, row * cellSizePixels, (column + 1) * cellSizePixels, (row + 1) * cellSizePixels)
canvas.drawRect(rect, paint)
}
private fun drawLines(canvas: Canvas) { // dibuja las lineas del tablero
canvas.drawRect(0F, 0F, width.toFloat(), height.toFloat(), thickLinePaint)
for (i in 1 until boardSize) {
val paint = when (i % sqrtSize) {
0 -> thickLinePaint
else -> thinLinePaint
}
canvas.drawLine(
i * cellSizePixels.toFloat(),
0F,
i * cellSizePixels.toFloat(),
height.toFloat(),
paint
)
canvas.drawLine(
0F,
i * cellSizePixels.toFloat(),
width.toFloat(),
i * cellSizePixels.toFloat(),
paint
)
}
}
/**
* Manejador de eventos de toque en el tablero.
*/
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
return when (event.action) {
MotionEvent.ACTION_DOWN -> {
handleTouchEvent(event.x, event.y)
true
}
else -> false
}
}
private fun handleTouchEvent(x: Float, y: Float) {
val selectedRow = (y / cellSizePixels).toInt()
val selectedColumn = (x / cellSizePixels).toInt()
onTouchListener?.onTouch(selectedRow, selectedColumn)
}
/**
* Actualiza la celda seleccionada en el tablero.
*/
fun updateSelectedCell(row: Int, column: Int) {
selectedRow = row
selectedColumn = column
invalidate()
}
/**
* Actualiza los numeros en el tablero segun lo seleccionado en el teclado.
*/
fun updateBoardNumbers(boardNumbers: List<Pair<Int, Int>?>) {
this.boardNumbers = boardNumbers as ArrayList<Pair<Int, Int>?>
selectedRow = 10
selectedColumn = 10
invalidate()
}
/**
* Para manjejar los eventos de toque en el tablero.
* se tuvo que usar una interfaz para poder implementar el metodo onTouch en el tablero.
* se implementa el metodo onTouch de la interfaz OnTouchListener.
*
*/
interface OnTouchListener {
/**
* Cada vez que se toca una celda en el tablero se llama a este metodo.
* por medio de la interfaz se implementa el metodo onTouch.
*/
fun onTouch(row: Int, column: Int)
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/SudokuBoardView.kt | 1087045187 |
package com.example.sudokugame
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
configureButtons()
}
/**
* Aqui estamos configurando los botones de la actividad principal.
*/
private fun configureButtons() {
findViewById<Button>(R.id.easyButton).setOnClickListener {
startClassicGameActivity(1)
}
findViewById<Button>(R.id.mediumButton).setOnClickListener {
startClassicGameActivity(2)
}
findViewById<Button>(R.id.hardButton).setOnClickListener {
startClassicGameActivity(3)
}
}
/**
* Comienza la actividad del juego clasico. Dependiendo del modo, se inicia el juego con un nivel de dificultad diferente.
*
* @param mode El juego tiene 3 niveles o dificultades: 1 facil, 2 medio, 3 dificil .
*/
private fun startClassicGameActivity(mode: Int) {
val intent = Intent(this, ClassicGameActivity::class.java).apply {
putExtra("mode", mode)
}
startActivity(intent)
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/MainActivity.kt | 374801364 |
package com.example.sudokugame
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
/**
* Activity cuando el juego ha terminado.
*/
class GameFinishedActivity : AppCompatActivity() {
private var mode = 1
private lateinit var activity : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game_finished)
// Optiene el tipo de actividad
activity = intent.getStringExtra("activity")!!
// Configura variables de la actividad anterior en base al tiempo que duro el juego y los errores cometidos
val textView = findViewById<TextView>(R.id.time)
var text = ""
when (activity) {
"classic" -> {
val mistakes = intent.getIntExtra("contadorErrores", 0)
val minutes = intent.getIntExtra("Minutos", 0)
val seconds = intent.getIntExtra("Segundos", 0)
mode = intent.getIntExtra("mode", 1)
text = "has terminado el juego en \n$minutes "
text += if (minutes == 1) "Minutos"
else "minutos"
text += " y $seconds "
text += if (seconds == 1) "Segundos"
else "segundos"
text += ".\nHas tenido $mistakes "
text += if (mistakes == 1) "Error."
else "Errores."
if(mistakes==0){
text += "\nHas ganado el juego. Felicidades."
}else{
text += "\nHas perdido el juego. ยกVuelve a intentarlo!"
}
}
"twoPlayers" -> {
text = intent.getStringExtra("type")!!
}
}
textView.text = text
}
/**
* llama de nuevo a la actividad principal. cuando el boton de menu es presionado.
*/
fun menu(view: View) {
val intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
this.finish()
}
/**
* Llama de nuevo a la actividad del juego. cuando el boton de jugar de nuevo es presionado.
*/
fun again(view: View) {
when(activity) {
"classic" -> {
val intent = Intent(this, ClassicGameActivity::class.java)
intent.putExtra("mode", mode)
this.startActivity(intent) // Inicia la actividad del juego clasico de la misma dificultad
this.finish()
}
}
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/GameFinishedActivity.kt | 2716046330 |
package com.example.sudokugame
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
///Clase de fรกbrica para crear instancias de [SudokuViewModel].
//@param parameter Un parรกmetro entero utilizado para personalizar la instancia del ViewModel.
class ViewModelFactory(private val parameter: Int) : ViewModelProvider.Factory {
//Crea una nueva instancia de la clase de ViewModel solicitada.
//modelClass es la clase del viewModel a crear
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass == SudokuViewModel::class.java) {
//retorna una nueva instancia de la clase de ViewModel solicitada.
return SudokuViewModel(parameter) as T
}
//manejo de errores por si la clase de ViewModel solicitada es desconocida
throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.canonicalName}")
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/ViewModelFactory.kt | 3449085132 |
package com.example.sudokugame
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.*
import kotlin.collections.ArrayList
import kotlin.random.Random
//ViewModel para la creaciรณn del sudoku
class SudokuViewModel(mode: Int) : ViewModel() {
var selectedCell = MutableLiveData<Pair<Int, Int>>()
var boardNumbers = MutableLiveData<List<Pair<Int, Int>?>>()
var minutes = MutableLiveData<Int>()
var seconds = MutableLiveData<Int>()
private var timer: Timer? = null
private var elapsedTimeInSeconds = 0
private var solution = ArrayList<Int>()
var mistakes = 0
private var finished = false
init {
selectedCell.postValue(Pair(10, 10))
createSolution()
when (mode) {
1 -> makeBoard(30)
2 -> makeBoard(40)
else -> makeBoard(45)
}
startTimer()
}
//se realiza la soluciรณn del sudoku
private fun createSolution() {
val numbers = (1..9).shuffled(Random).toList()
solution.addAll(numbers)
var shiftedNumbers = numbers
repeat(2) {
shiftedNumbers = shiftedNumbers.subList(3, shiftedNumbers.size) + shiftedNumbers.subList(0, 3)
solution.addAll(shiftedNumbers)
}
repeat(2) {
shiftedNumbers = shiftedNumbers.subList(1, shiftedNumbers.size) + shiftedNumbers.subList(0, 1)
solution.addAll(shiftedNumbers)
repeat(2) {
shiftedNumbers = shiftedNumbers.subList(3, shiftedNumbers.size) + shiftedNumbers.subList(0, 3)
solution.addAll(shiftedNumbers)
}
}
}
//Funciรณn que genera el tablero de juego
private fun makeBoard(number: Int) {
var reps = number
val array = ArrayList<Pair<Int, Int>?>()
for (i in 0 until solution.size) {
array.add(Pair(solution[i], 0))
}
while (reps != 0) {
val randomNumber = Random.nextInt(0, 81)
if (array[randomNumber] != null) {
array[randomNumber] = null
reps--
}
}
boardNumbers.postValue(array.toList())
}
//actualiza la celda seleccionada en el tablero
fun updateSelectedCell(row: Int, column: Int) {
if (finished) return
if (boardNumbers.value!!.toMutableList()[row * 9 + column] == null ||
(boardNumbers.value!!.toMutableList()[row * 9 + column]!!.second != 0 &&
boardNumbers.value!!.toMutableList()[row * 9 + column]!!.second != 3)
) {
selectedCell.postValue(Pair(row, column))
}
}
//Inserta los numeros de la lista actual al tablero de juego
fun numberInput(number: Int) {
if (selectedCell.value!!.first == 10 || finished) return
val currentList = boardNumbers.value?.toMutableList()
currentList?.set(selectedCell.value!!.first * 9 + selectedCell.value!!.second, Pair(number, 1))
selectedCell.value = Pair(10, 10)
boardNumbers.value = currentList
}
//almacena un numero en la celda seleccionada y valida si es correcto
fun numberInputWithCheck(number: Int): Int {
if (selectedCell.value!!.first == 10 || finished) return 0
val row = selectedCell.value!!.first
val column = selectedCell.value!!.second
numberInput(number)
if (checkCell(row, column)) {
return 1
}
return -1
}
//acepta la inserciรณn del numero seleccionado en la celda
fun acceptNumber() {
if (selectedCell.value!!.first == 10 || finished) return
val currentList = boardNumbers.value?.toMutableList()
if (currentList!![selectedCell.value!!.first * 9 + selectedCell.value!!.second] == null) return
currentList[selectedCell.value!!.first * 9 + selectedCell.value!!.second] =
Pair(currentList[selectedCell.value!!.first * 9 + selectedCell.value!!.second]!!.first, 2)
selectedCell.value = Pair(10, 10)
boardNumbers.value = currentList
}
//Elimina un numero en una celda
fun removeNumber() {
if (selectedCell.value!!.first == 10 || finished) return
val currentList = boardNumbers.value?.toMutableList()
if (currentList!![selectedCell.value!!.first * 9 + selectedCell.value!!.second] == null) return
currentList[selectedCell.value!!.first * 9 + selectedCell.value!!.second] = null
selectedCell.value = Pair(10, 10)
boardNumbers.value = currentList
}
//termina el juego del sudoku y valida las celdas correctas e incorrectas
fun finish(): Boolean {
if (finished) return false
boardNumbers.value?.toMutableList()?.forEach { pair ->
if (pair == null) return false
}
stopTimer()
for (row in 0 until 9) {
for (column in 0 until 9) {
if (!checkCell(row, column)) {
mistakes++
}
}
}
finished = true
return true
}
//valida si una celda esta posicionada correctamente en la columna y fila seleccionada
private fun checkCell(row: Int, column: Int): Boolean {
val currentList = boardNumbers.value?.toMutableList()
return if (currentList?.get(row * 9 + column)!!.first == solution[row * 9 + column]) {
currentList[row * 9 + column] = Pair(currentList[row * 9 + column]!!.first, 3)
boardNumbers.value = currentList
true
} else {
currentList[row * 9 + column] = Pair(currentList[row * 9 + column]!!.first, 4)
boardNumbers.value = currentList
false
}
}
//comienza el temporizador
private fun startTimer() {
timer = Timer()
timer?.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
updateTime()
}
}, 0L, 1000L)
}
//se detiene el temporizador
private fun stopTimer() {
timer?.cancel()
timer = null
}
//Actualiza el tiempo transcurrido
private fun updateTime() {
elapsedTimeInSeconds++
val minutes = elapsedTimeInSeconds / 60
val seconds = elapsedTimeInSeconds % 60
this.minutes.postValue(minutes)
this.seconds.postValue(seconds)
}
//libera recursos no usados en la aplicaciรณn
override fun onCleared() {
super.onCleared()
stopTimer()
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/SudokuViewModel.kt | 3718695536 |
package com.example.sudokugame
import android.content.Intent
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
class ClassicGameActivity : AppCompatActivity() {
private lateinit var mediaPlayer: MediaPlayer
private lateinit var viewModel: SudokuViewModel
private var mode = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_classic_game)
mediaPlayer = MediaPlayer.create(this, R.raw.ding)
// una vez cambiamos de actividad, configuramos la vista del tablero y la mostramos en el activity-classic-game.xml
val boardView = findViewById<SudokuBoardView>(R.id.sudokuBoardView)
boardView.onTouchListener = object : SudokuBoardView.OnTouchListener {
override fun onTouch(row: Int, column: Int) {
onCellTouched(row, column)
}
}
// Usando el intent, obtenemos el modo de dificultad del juego como un int
mode = intent.getIntExtra("mode", 1)
// ViewModel
val viewModelFactory = ViewModelFactory(mode)
viewModel = ViewModelProvider(this, viewModelFactory)[SudokuViewModel::class.java]
viewModel.selectedCell.observe(this) { updateSelectedCell(it) }
viewModel.boardNumbers.observe(this) { updateBoardNumbers(it) }
viewModel.seconds.observe(this) { updateTime(it) }
// Teckado de numeros del 1 al 9
val buttonList = listOf(
findViewById(R.id.oneButton),
findViewById(R.id.twoButton),
findViewById(R.id.threeButton),
findViewById(R.id.fourButton),
findViewById(R.id.fiveButton),
findViewById(R.id.sixButton),
findViewById(R.id.sevenButton),
findViewById(R.id.eightButton),
findViewById<Button>(R.id.nineButton)
)
buttonList.forEachIndexed { index, button ->
button.setOnClickListener { viewModel.numberInput(index + 1)
mediaPlayer.seekTo(100)
mediaPlayer.start()} // le sumamos 1 porque los indices empiezan en 0
}
// aceptar button
val acceptButton = findViewById<Button>(R.id.acceptButton)
acceptButton.setOnClickListener { viewModel.acceptNumber() }
// eliminar button
val removeButton = findViewById<Button>(R.id.backButton)
removeButton.setOnClickListener { viewModel.removeNumber() }
// Terminar button
val finishButton = findViewById<Button>(R.id.finishButton)
finishButton.setOnClickListener {
if (viewModel.finish()) end()
}
}
/**
* Actualiza la celda seleccionada en el tablero del Sudoku.
* Cuando se toca una celda, se actualiza la celda seleccionada en el tablero
* y se muestra en la vista usando coordenadas de fila y columna.
*/
private fun updateSelectedCell(cell: Pair<Int, Int>?) = cell?.let { // cell para la celda seleccionada y recibe un par de enteros fila o columna
val boardView = findViewById<SudokuBoardView>(R.id.sudokuBoardView) // obtenemos la vista del tablero
boardView.updateSelectedCell(cell.first, cell.second) // actualizamos la celda seleccionada en la vista del tablero
}
/**
* Actualiza los nรบmeros en el tablero del Sudoku.
* dibuja los numeros en el tablero del sudoku y la actualiza segun la celda seleccionada.
*/
private fun updateBoardNumbers(boardNumbers: List<Pair<Int, Int>?>) {
val boardView = findViewById<SudokuBoardView>(R.id.sudokuBoardView)
boardView.updateBoardNumbers(boardNumbers)
}
/**
* Esta funcion actualiza el tiempo en la vista del tablero.
* muestra el tiempo en el formato MM:SS
*/
private fun updateTime(seconds: Int) {
var text = viewModel.minutes.value.toString() + ":"
if (viewModel.minutes.value!! < 10) { // si los minutos son menores a 10, se agrega un 0 al inicio
text = "0$text"
}
if (seconds < 10) { // si los segundos son menores a 10, se agrega un 0 al inicio
text += "0$seconds"
} else {
text += seconds
}
val timeTextView = findViewById<TextView>(R.id.time) // obtenemos el textview del tiempo
timeTextView.text = text // actualizamos el tiempo en la vista
}
/**
* Aqui se maneja el evento de tocar una celda en el tablero.
* nuevamente cuando se toca la celda se actualiza la celda seleccionada en el tablero
* y se muestra en la vista usando coordenadas de fila y columna.
*/
fun onCellTouched(row: Int, column: Int) {
viewModel.updateSelectedCell(row, column)
}
/**
* Cuando el juego termina, se inicia la actividad de juego terminado.
*/
private fun end() {
val handler = Handler() // maneja las variables de tiempoy errores en un hilo que va a gamefinishedactivity
val startNewActivityRunnable = Runnable {
val intent = Intent(this, GameFinishedActivity::class.java)
intent.putExtra("activity", "classic")
intent.putExtra("contadorErrores", viewModel.mistakes)
intent.putExtra("Minutos", viewModel.minutes.value)
intent.putExtra("Segundos", viewModel.seconds.value)
intent.putExtra("Mode", mode)
startActivity(intent)
this.finish()
}
handler.postDelayed(startNewActivityRunnable, 2000)
}
}
| SudokuGame/app/src/main/java/com/example/sudokugame/ClassicGameActivity.kt | 922423572 |
package com.example.togglevpn
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.togglevpn", appContext.packageName)
}
} | togglevpn/app/src/androidTest/java/com/example/togglevpn/ExampleInstrumentedTest.kt | 1101705809 |
package com.example.togglevpn
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)
}
} | togglevpn/app/src/test/java/com/example/togglevpn/ExampleUnitTest.kt | 2841298974 |
package com.example.togglevpn.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) | togglevpn/app/src/main/java/com/example/togglevpn/ui/theme/Color.kt | 3070685128 |
package com.example.togglevpn.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 ToggleVPNTheme(
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
)
} | togglevpn/app/src/main/java/com/example/togglevpn/ui/theme/Theme.kt | 1573838919 |
package com.example.togglevpn.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
)
*/
) | togglevpn/app/src/main/java/com/example/togglevpn/ui/theme/Type.kt | 2419627840 |
package com.example.togglevpn
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import com.example.togglevpn.ui.theme.ToggleVPNTheme
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ToggleVPNTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting()
}
}
}
}
}
@Composable
fun Greeting() {
val context = LocalContext.current
var isConnected by remember {
mutableStateOf(false)
}
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(Unit) {
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
//execute network request here
//set isConnected status
isConnected = true
}
}
Column(modifier = Modifier.fillMaxSize().background(if (isConnected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally){
var IP = "192.168.1.224"
var port = "8081"
TextField(
value = "192.168.1.224",
onValueChange = { IP = it },
label = { Text("IP") }
)
TextField(
value = "8081",
onValueChange = { IP = it },
label = { Text("IP") }
)
Button(onClick = {
val url = "http://$IP:$port/"
val request = Request.Builder()
.url(url + "on")
.build()
OkHttpClient().newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()/
}
override fun onResponse(call: Call, response: Response) {
response.use {
Handler(Looper.getMainLooper()).post {
Toast.makeText(
context,
if (response.isSuccessful) "Turned on!" else "Already turned on!",
Toast.LENGTH_SHORT
).show()
}
}
}
})
},
modifier = Modifier.fillMaxWidth()) {
Text("On")
}
Button(onClick = {
val url = "http://$IP:$port/"
val request = Request.Builder()
.url(url + "off")
.build()
OkHttpClient().newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {}
})
},
modifier = Modifier.fillMaxWidth()) {
Text("Off")
}
}
} | togglevpn/app/src/main/java/com/example/togglevpn/MainActivity.kt | 7374707 |
package com.example.ez006
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.ez006", appContext.packageName)
}
} | EZ006/app/src/androidTest/java/com/example/ez006/ExampleInstrumentedTest.kt | 735080504 |
package com.example.ez006
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)
}
} | EZ006/app/src/test/java/com/example/ez006/ExampleUnitTest.kt | 2110000704 |
package com.example.ez006
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | EZ006/app/src/main/java/com/example/ez006/MainActivity.kt | 1011275200 |
package com.example.ez006
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(private val context: Context):
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION){
companion object{
private const val DATABASE_NAME = "UserDatabase.db"
private const val DATABASE_VERSION = 1
private const val TABLE_NAME = "data"
private const val COLUMN_ID = "id"
private const val COLUMU_USERNAME = "username"
private const val COLUMU_PASSWORD = "password"
}
override fun onCreate(db: SQLiteDatabase?) {
val createTableQuery = ("CREATE TABLE $TABLE_NAME (" +
"$COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"$COLUMU_USERNAME TEXT, " +
"$COLUMU_PASSWORD TEXT)")
db?.execSQL(createTableQuery)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
val dropTableQuery = "DROP TABLE IF EXISTS $TABLE_NAME"
db?.execSQL(dropTableQuery)
onCreate(db)
}
fun insertUser(username: String, password: String): Long {
val values = ContentValues().apply {
put(COLUMU_USERNAME, username)
put(COLUMU_PASSWORD, password)
}
val db = writableDatabase
return db.insert(TABLE_NAME, null, values)
}
fun readUser(username: String, password: String): Boolean {
val db = readableDatabase
val selection = "$COLUMU_USERNAME = ? AND $COLUMU_PASSWORD = ?"
val selectionArgs = arrayOf(username, password)
val cursor = db.query(TABLE_NAME, null, selection, selectionArgs, null, null, null)
val userExists = cursor.count > 0
cursor.close()
return userExists
}
} | EZ006/app/src/main/java/com/example/ez006/DatabaseHelper.kt | 4209621708 |
package com.example.ez006
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.ez006.databinding.ActivitySignupBinding
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignupBinding
private lateinit var databaseHelper: DatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignupBinding.inflate(layoutInflater)
setContentView(binding.root)
databaseHelper = DatabaseHelper(this)
binding.loginButton
val loginUsername = binding.loginUsername.text.toString()
val loginPassword = binding.loginPassword.text.toString()
loginDatabase(loginUsername, loginPassword)
}
binding.loginRedirect.setOnClickListener {
val intent = Intent(this, SignupActivity::class.java)
startActivity(intent)
finish()
}
}
private fun loginDatabase(username: String, password: String){
val userExists = databaseHelper.readUser(username, password)
if (userExists){
Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show()
}
}
} | EZ006/app/src/main/java/com/example/ez006/LoginActivity.kt | 3637188840 |
package com.example.ez006
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.ez006.databinding.ActivitySignupBinding
class SignupActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignupBinding
private lateinit var databaseHelper: DatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignupBinding.inflate(layoutInflater)
setContentView(binding.root)
databaseHelper = DatabaseHelper(this)
binding.signupButton.setOnClickListener {
val signupUsername = binding.signupUsername.text.toString()
val signupPassword = binding.signupPassword.text.toString()
signupDatabase(signupUsername, signupPassword)
}
binding.loginRedirect.setOnClickListener {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun signupDatabase(username: String, password: String) {
val insertedrowId = databaseHelper.insertUser(username, password)
if (insertedrowId != -1L) {
Toast.makeText(this, "Signup Successful", Toast.LENGTH_SHORT).show()
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "signup Failed", Toast.LENGTH_SHORT).show()
}
}
} | EZ006/app/src/main/java/com/example/ez006/SignupActivity.kt | 1597469832 |
package com.example.navigationdemo
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.navigationdemo", appContext.packageName)
}
} | navigation_demo_jetpackcompose/app/src/androidTest/java/com/example/navigationdemo/ExampleInstrumentedTest.kt | 2824860725 |
package com.example.navigationdemo
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)
}
} | navigation_demo_jetpackcompose/app/src/test/java/com/example/navigationdemo/ExampleUnitTest.kt | 3320178159 |
package com.example.navigationdemo.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) | navigation_demo_jetpackcompose/app/src/main/java/com/example/navigationdemo/ui/theme/Color.kt | 2429308687 |
package com.example.navigationdemo.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 NavigationDemoTheme(
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
)
} | navigation_demo_jetpackcompose/app/src/main/java/com/example/navigationdemo/ui/theme/Theme.kt | 661715598 |
package com.example.navigationdemo.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
)
*/
) | navigation_demo_jetpackcompose/app/src/main/java/com/example/navigationdemo/ui/theme/Type.kt | 1847961832 |
@file:OptIn(ExperimentalMaterial3Api::class)
package com.example.navigationdemo
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
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.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
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.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.navigationdemo.ui.theme.NavigationDemoTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NavigationDemoTheme {
ContentView()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContentView() {
val navController = rememberNavController()
var canNavigateBack by remember { mutableStateOf(false) }
navController.addOnDestinationChangedListener{ controller, _, _ ->
canNavigateBack = controller.previousBackStackEntry != null
}
// val backStackEntry by navController.currentBackStackEntryAsState()
//
// val currentScreen = Route.valueOf(
// backStackEntry?.destination?.route ?: Route.Start.name
// )
// val currentScreenTitle = currentScreen.title
val onItemSelect:(Int) -> Unit = {
val routeName = when(it) {
1 -> Route.First.name
2 -> "${Route.Second.name}/1"
3 -> Route.Third.name
4 -> "${Route.Third.name}?index=1"
5 -> "${Route.Third.name}?index=2"
else -> Route.First.name
}
navController.navigate(route = routeName)
}
Log.d("test", (navController.previousBackStackEntry).toString())
Scaffold(
topBar = {
TopBar(
title = "some title",
canNavigateBack = canNavigateBack,
onBackButtonPress = {
// navController.navigateUp()
navController.popBackStack(
destinationId = navController.graph.findStartDestination().id,
inclusive = false
)
})
}
) {padding->
NavHost(
navController = navController,
startDestination = Route.Start.name,
modifier = Modifier
.padding(padding)
) {
composable(route = Route.Start.name) {
StartScreen(onItemSelect = onItemSelect)
}
composable(route = Route.First.name) {
FirstScreen(
title = "first"
)
}
composable(
route = "${Route.Second.name}/{index}",
arguments = listOf(
navArgument("index") {
type = NavType.IntType
nullable = false
defaultValue = 1
}
)
) {entry->
val index = entry.arguments?.getInt("index")
SecondScreen(
index = index ?: 1
)
}
composable(route = "${Route.Third.name}?index={index}",
arguments = listOf(
navArgument("index") {
defaultValue = 123
})
) { entry->
val index = entry.arguments?.getInt("index")
ThirdScreen(
index = index ?: 1
)
}
}
}
}
@Composable
fun StartScreen(onItemSelect: (Int) -> Unit) {
val itemList = listOf<String>(
"To first screen",
"To second screen",
"To third screen",
"To 3-1",
"To 3-2"
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
itemList.forEachIndexed { index, item ->
if (index != 0) {
Divider(modifier = Modifier, thickness = 1.dp, color = Color.Black)
}
Text(
text = item,
textAlign = TextAlign.Center,
modifier = Modifier
.background(Color.LightGray)
.padding(10.dp)
.fillMaxWidth()
.clickable { onItemSelect(index + 1) }
)
}
}
}
@Composable
fun TopBar(title: String, canNavigateBack: Boolean, onBackButtonPress: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.padding(15.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
if (canNavigateBack) {
Text(
text = "<",
modifier = Modifier
.clickable { onBackButtonPress() }
)
} else {
Spacer(modifier = Modifier)
}
Text(
text = title,
)
Spacer(modifier = Modifier)
}
}
@Composable
fun FirstScreen(title:String) {
Text(text = "first screen")
}
@Composable
fun SecondScreen(index: Int) {
Text(text = "2-${index}")
}
@Composable
fun ThirdScreen(index: Int) {
Text(text = "3-${index}")
}
enum class Route(val title: String) {
Start(title = "Start Screen Title"),
First(title = "First Screen Title"),
Second(title = "Second Screen Title"),
Third(title = "Third Screen Title"),
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
NavigationDemoTheme {
ContentView()
}
} | navigation_demo_jetpackcompose/app/src/main/java/com/example/navigationdemo/MainActivity.kt | 2206469143 |
package com.zanahtech.jccomponents
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.zanahtech.jccomponents", appContext.packageName)
}
} | jc-components/app/src/androidTest/java/com/zanahtech/jccomponents/ExampleInstrumentedTest.kt | 1675161546 |
package com.zanahtech.jccomponents
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)
}
} | jc-components/app/src/test/java/com/zanahtech/jccomponents/ExampleUnitTest.kt | 1308967844 |
package com.zanahtech.jccomponents.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)
val GreenJC = Color(0xFF3FDC85) | jc-components/app/src/main/java/com/zanahtech/jccomponents/ui/theme/Color.kt | 156914665 |
package com.zanahtech.jccomponents.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 = GreenJC,
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 JccomponentsTheme(
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 = GreenJC.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/ui/theme/Theme.kt | 3183564709 |
package com.zanahtech.jccomponents.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
)
*/
) | jc-components/app/src/main/java/com/zanahtech/jccomponents/ui/theme/Type.kt | 3035225482 |
package com.zanahtech.jccomponents
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
@Composable
fun Search(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Search", fontSize = 30.sp, color = GreenJC)
}
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Search.kt | 3959197763 |
package com.zanahtech.jccomponents
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
@Composable
fun Settings(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Settings", fontSize = 30.sp, color = GreenJC)
}
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Settings.kt | 3192705308 |
package com.zanahtech.jccomponents
import android.annotation.SuppressLint
import android.graphics.drawable.Icon
import android.os.Bundle
import android.service.controls.actions.FloatAction
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.MailOutline
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.rounded.Menu
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.zanahtech.jccomponents.ui.theme.GreenJC
import com.zanahtech.jccomponents.ui.theme.JccomponentsTheme
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
setContent {
JccomponentsTheme {
// A surface container using the 'background' color from the theme
Surface(
// modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
// contentAlignment = Alignment.CenterStart
) {
// LearnTopAppBar()
// LearnState()
// LearnNavDrawer()
MyBottomAppBar()
}
}
}
}
}
//@Composable
//fun LearnTextAndModifiers(){
//
// val clickOnText = {}
//
// Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
//
//// Text(text = stringResource(id = R.string.hello_text),
//// color = Color.Blue,
//// fontSize = 32.sp,
//// fontStyle = FontStyle.Italic,
//// modifier = Modifier
//// .padding(22.dp)
//// .background(Color.Black)
//// .clickable(onClick = clickOnText)
//// )
//// Text(text = "Hello Column 1")
//// Text(text = "Hello Column 2")
////}
////
//// Row (verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {
//// Text(text = stringResource(id = R.string.hello_text),
//// color = Color.Blue,
//// fontSize = 32.sp,
//// fontStyle = FontStyle.Italic,
//// modifier = Modifier
//// .padding(22.dp)
//// .background(Color.Black)
//// .clickable(onClick = clickOnText)
//// )
//// Text(text = "Hello Column 1")
//// Text(text = "Hello Column 2")
////
//// }
//
// Box(modifier = Modifier
// .fillMaxSize()
// .background(Color.Gray), contentAlignment = Alignment.Center){
// Box(modifier = Modifier.height(300.dp).width(300.dp).background(Color.Blue) ){
//
// Text(text = stringResource(id = R.string.hello_text),
// color = Color.White,
// fontSize = 30.sp,
// fontStyle = FontStyle.Italic,
// modifier = Modifier
// .align(Alignment.Center)
// .padding(22.dp)
// .background(Color.Black)
// .clickable(onClick = clickOnText)
// )
//
//
// }
//
//
//
//
// }
// }
//
//
//
//
//}
//Alignment = Cross Axis (Row = Vertical, Column = Horizontal)
//Arrangement = Main Axis (Row = Horizontal, Column = Vertical)
//@Composable
//fun LearnAlignmentArrangement(){
//
// //RowAlignment: Top, CenterVertically, Bottom
// //RowArrangement: Start, Center, End, SpaceBetween, SpaceAround, SpaceEvenly,
// //Absolute.Left, Absolute.Right, Absolute.Center
// //Absolute.SpaceBetween, Absolute.SpaceAround, Absolute.SpaceEvenly
//// Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center){
//// Text(text = "Row Alignment Arrangement")
//// }
//
// Box(contentAlignment = Alignment.BottomCenter){
// Text(text = "text", modifier = Modifier.align(Alignment.Center))
// Text(text = "text 2", modifier = Modifier.align(Alignment.TopCenter))
// Text(text = "text3", modifier = Modifier.align(Alignment.TopEnd))
// Text(text = "text4", modifier = Modifier.align(Alignment.TopStart))
// Text(text = "text5", modifier = Modifier.align(Alignment.BottomEnd))
// Text(text = "text6", modifier = Modifier.align(Alignment.CenterStart))
// Text(text = "text8", modifier = Modifier.align(Alignment.CenterEnd))
// Text(text = "text9", modifier = Modifier.align(Alignment.BottomStart))
//
// }
//}
//
//
//@Composable
//fun LearnButton(){
//
// val context = LocalContext.current.applicationContext
//
// Column (verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
// Button(onClick = { Toast.makeText(context, "Login successful", Toast.LENGTH_SHORT).show()},
//
// shape = RoundedCornerShape(size = 16.dp), colors = ButtonDefaults.buttonColors(containerColor = Color.Cyan)
// ) {
// Text(text = "Login")
//
// }
// }
//}
//
//@Composable
//fun LearnImage(){
// val context = LocalContext.current.applicationContext
//
// Column (verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
// Image(painter = painterResource(id = R.drawable.work), contentDescription = "work in progress" )
//
// Button(onClick = { Toast.makeText(context, "Login successful", Toast.LENGTH_SHORT).show()},
//
// shape = RoundedCornerShape(size = 16.dp), colors = ButtonDefaults.buttonColors(containerColor = Color.Cyan)
// ) {
// Text(text = "Login")
//
// }
//
// }
//
//}
//
//@Composable
//fun LearnState(){
//// var age = 0
// var age by remember {
// mutableStateOf(0)
// }
//
//
// Column (verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally){
// Button(onClick = { age++
// Log.v("TAG", "age"+age)}) {
// Text(text = "I am $age years old")
//
//
// }
// }
//}
//
//@OptIn(ExperimentalMaterial3Api::class)
//@Composable
//fun LearnTopAppBar(){
//
// val context = LocalContext.current.applicationContext
// TopAppBar(title = { Text(text = "WhatsApp")},
// navigationIcon = {
// IconButton(onClick = {Toast.makeText(context, "Whatsapp", Toast.LENGTH_SHORT).show()}) {
// Icon(painter = painterResource(id = R.drawable.splash), contentDescription = "whatsapp icon")
//
// }
// }, colors = TopAppBarDefaults.topAppBarColors(
// containerColor = GreenJC,
// titleContentColor = Color.White,
// navigationIconContentColor = Color.White
// ), actions = {
// IconButton(onClick = { Toast.makeText(context, "Profile", Toast.LENGTH_SHORT).show() }) {
// Icon(imageVector = Icons.Filled.Person, contentDescription = "Profile", tint= Color.White)
//
// }
// IconButton(onClick = { Toast.makeText(context, "Search", Toast.LENGTH_SHORT).show() }) {
// Icon(imageVector = Icons.Filled.Search, contentDescription = "Profile", tint= Color.White)
//
// }
// IconButton(onClick = { Toast.makeText(context, "Menu", Toast.LENGTH_SHORT).show() }) {
// Icon(imageVector = Icons.Filled.MoreVert, contentDescription = "Profile", tint= Color.White)
//
// }
// }
// )
//
//}
//
//@Preview
//@Composable
//fun TopAppBarPreview(){
// LearnTopAppBar()
//}
//@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
//@OptIn(ExperimentalMaterial3Api::class)
//@Composable
//fun LearnNavDrawer(){
// val navigationController = rememberNavController()
// val coroutineScope = rememberCoroutineScope()
// val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
// val context = LocalContext.current.applicationContext
//
// ModalNavigationDrawer(
// drawerState = drawerState,
// gesturesEnabled = true,
// drawerContent = {
// ModalDrawerSheet {
// Box(modifier = Modifier
// .background(GreenJC)
// .fillMaxWidth()
// .height(150.dp))
// {
// Text(text = "")
// }
//
// Divider()
// NavigationDrawerItem(label = { Text(text = "Home", color = GreenJC) },
// selected = false,
// icon = { Icon(imageVector = Icons.Default.Home, contentDescription = "Home", tint= GreenJC)},
// onClick = {
// coroutineScope.launch {
// drawerState.close()
// }
// navigationController.navigate(Screens.Home.screen){
// popUpTo(0)
// }
// })
//
// NavigationDrawerItem(label = { Text(text = "Profile", color = GreenJC) },
// selected = false,
// icon = { Icon(imageVector = Icons.Default.AccountBox, contentDescription = "Profile", tint= GreenJC)},
// onClick = {
// coroutineScope.launch {
// drawerState.close()
// }
// navigationController.navigate(Screens.Profile.screen){
// popUpTo(0)
// }
// })
//
//
// NavigationDrawerItem(label = { Text(text = "Settings", color = GreenJC) },
// selected = false,
// icon = { Icon(imageVector = Icons.Default.Settings, contentDescription = "Settings", tint= GreenJC)},
// onClick = {
// coroutineScope.launch {
// drawerState.close()
// }
// navigationController.navigate(Screens.Settings.screen){
// popUpTo(0)
// }
// })
//
// NavigationDrawerItem(label = { Text(text = "Logout", color = GreenJC) },
// selected = false,
// icon = { Icon(imageVector = Icons.Default.ExitToApp, contentDescription = "Logout", tint= GreenJC)},
// onClick = {
// coroutineScope.launch {
// drawerState.close()
// }
// Toast.makeText(context, "Logout", Toast.LENGTH_SHORT).show()
// })
//
//
// }
// }) {
// Scaffold (
// topBar = {
// val coroutineScope = rememberCoroutineScope()
// TopAppBar(title = { Text(text = "WhatsApp")},
// colors = TopAppBarDefaults.topAppBarColors(
// containerColor = GreenJC,
// titleContentColor = Color.White,
// navigationIconContentColor = Color.White
// ),
// navigationIcon = {
// IconButton(onClick = {
// coroutineScope.launch {
// drawerState.open()
// }
// }) {
// Icon(
// Icons.Rounded.Menu, contentDescription = "MenuButton"
// )
// }
// },
// )
//
// }
// ) {
// NavHost(navController = navigationController,
// startDestination = Screens.Home.screen ){
// composable(Screens.Home.screen){ Home() }
// composable(Screens.Profile.screen){ Profile() }
// composable(Screens.Settings.screen){ Settings() }
//
//
// }
//
// }
//
//
// }
//}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyBottomAppBar(){
val navigationController = rememberNavController()
val context = LocalContext.current.applicationContext
val selected = remember {
mutableStateOf(Icons.Default.Home)
}
val sheetState = rememberModalBottomSheetState()
var showBottomSheet by remember {
mutableStateOf(false)
}
Scaffold(
bottomBar = {
BottomAppBar(
containerColor = GreenJC
){
IconButton(onClick = { selected.value = Icons.Default.Home
navigationController.navigate(Screens.Home.screen){
popUpTo(0)
}
},
modifier = Modifier.weight(1f)) {
Icon(Icons.Default.Home, contentDescription = null, modifier = Modifier.size(26.dp),
tint = if (selected.value == Icons.Default.Home) Color.White else Color.DarkGray
)
}
IconButton(onClick = { selected.value = Icons.Default.Search
navigationController.navigate(Screens.Search.screen){
popUpTo(0)
}
},
modifier = Modifier.weight(1f)) {
Icon(Icons.Default.Search, contentDescription = null, modifier = Modifier.size(26.dp),
tint = if (selected.value == Icons.Default.Search) Color.White else Color.DarkGray
)
}
Box(modifier = Modifier
.weight(1f)
.padding(16.dp),
contentAlignment = Alignment.Center
){
FloatingActionButton(onClick = { showBottomSheet = true }) {
Icon(Icons.Default.Add, contentDescription = null, tint = GreenJC )
}
}
IconButton(onClick = { selected.value = Icons.Default.MailOutline
navigationController.navigate(Screens.Notification.screen){
popUpTo(0)
}
},
modifier = Modifier.weight(1f)) {
Icon(Icons.Default.MailOutline, contentDescription = null, modifier = Modifier.size(26.dp),
tint = if (selected.value == Icons.Default.MailOutline) Color.White else Color.DarkGray
)
}
IconButton(onClick = { selected.value = Icons.Default.Person
navigationController.navigate(Screens.Profile.screen){
popUpTo(0)
}
},
modifier = Modifier.weight(1f)) {
Icon(Icons.Default.Person, contentDescription = null, modifier = Modifier.size(26.dp),
tint = if (selected.value == Icons.Default.Person) Color.White else Color.DarkGray
)
}
}
},
) { paddingValues ->
NavHost(navController = navigationController,
startDestination = Screens.Home.screen,
modifier = Modifier.padding(paddingValues)){
composable(Screens.Home.screen){Home ()}
composable(Screens.Search.screen){ Search () }
composable(Screens.Notification.screen){ Notification () }
composable(Screens.Profile.screen){ Profile () }
composable(Screens.Post.screen){ Post()}
}
}
if (showBottomSheet){
ModalBottomSheet(onDismissRequest = { showBottomSheet = false },
sheetState = sheetState
) {
Column(modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
BottomSheetItem(icon = Icons.Default.ThumbUp, title = "Create a Post") {
showBottomSheet = false
navigationController.navigate(Screens.Post.screen){
popUpTo(0)
}
}
BottomSheetItem(icon = Icons.Default.Star, title = "Add a story") {
Toast.makeText(context, "Story", Toast.LENGTH_SHORT).show()
}
BottomSheetItem(icon = Icons.Default.PlayArrow, title = "Create a reel") {
Toast.makeText(context, "Reel", Toast.LENGTH_SHORT).show()
}
BottomSheetItem(icon = Icons.Default.Favorite, title = "Go Live") {
Toast.makeText(context, "Go Live", Toast.LENGTH_SHORT).show()
}
}
}
}
}
@Composable
fun BottomSheetItem(icon: ImageVector, title: String, onClick: () -> Unit){
Row (verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.clickable { onClick() }
){
Icon(icon, contentDescription = null, tint = GreenJC)
Text(text = title, color = GreenJC, fontSize = 22.sp)
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/MainActivity.kt | 2125134778 |
package com.zanahtech.jccomponents
sealed class Screens (val screen: String){
data object Home: Screens("home")
data object Profile: Screens("profile")
data object Settings: Screens("settings")
data object Search: Screens("search")
data object Notification: Screens("notification")
data object Post: Screens("post")
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Screens.kt | 2318932126 |
package com.zanahtech.jccomponents
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
import com.zanahtech.jccomponents.ui.theme.JccomponentsTheme
@Composable
fun Home(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Home", fontSize = 30.sp, color = GreenJC)
}
}
}
@Preview
@Composable
fun HomePreview(){
JccomponentsTheme{
Home()
}
}
| jc-components/app/src/main/java/com/zanahtech/jccomponents/Home.kt | 879786513 |
package com.zanahtech.jccomponents
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
@Composable
fun Post(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Post", fontSize = 30.sp, color = GreenJC)
}
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Post.kt | 3497130875 |
package com.zanahtech.jccomponents
import android.app.Notification
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
@Composable
fun Notification(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Notification", fontSize = 30.sp, color = GreenJC)
}
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Notification.kt | 472702031 |
package com.zanahtech.jccomponents
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.zanahtech.jccomponents.ui.theme.GreenJC
@Composable
fun Profile(){
Box(modifier = Modifier.fillMaxSize()){
Column(modifier = Modifier
.fillMaxSize()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Profile", fontSize = 30.sp, color = GreenJC)
}
}
} | jc-components/app/src/main/java/com/zanahtech/jccomponents/Profile.kt | 852113540 |
package com.example.animationapplication
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.animationapplication", appContext.packageName)
}
}
| Animation-Application-Android/app/src/androidTest/java/com/example/animationapplication/ExampleInstrumentedTest.kt | 3236367093 |
package com.example.animationapplication
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)
}
}
| Animation-Application-Android/app/src/test/java/com/example/animationapplication/ExampleUnitTest.kt | 302422246 |
package com.example.animationapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fb = findViewById<ImageView>(R.id.fb)
val player = findViewById<ImageView>(R.id.pl)
val goalbox = findViewById<ImageView>(R.id.goalbox)
val msg = findViewById<TextView>(R.id.msg)
fb.bringToFront()
val an = AnimationUtils.loadAnimation(this,R.anim.football)
val banim = AnimationUtils.loadAnimation(this,R.anim.ballrotate)
val animationset = AnimationSet(false)
animationset.addAnimation(banim)
animationset.addAnimation(an)
startbtn.setOnClickListener {
val pan = AnimationUtils.loadAnimation(this,R.anim.player)
player.startAnimation(pan)
fb.startAnimation(animationset)
an.setAnimationListener(object :Animation.AnimationListener {
override fun onAnimationRepeat(p0: Animation?) {
}
override fun onAnimationStart(p0: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
msg.isVisible = true
}
})
}
}
}
| Animation-Application-Android/app/src/main/java/com/example/animationapplication/MainActivity.kt | 3283215856 |
package com.example.tictactoe
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.tictactoe", appContext.packageName)
}
} | TicTac/app/src/androidTest/java/com/example/tictactoe/ExampleInstrumentedTest.kt | 1726577991 |
package com.example.tictactoe
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)
}
} | TicTac/app/src/test/java/com/example/tictactoe/ExampleUnitTest.kt | 821878711 |
package com.example.tictactoe
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.children
import androidx.lifecycle.lifecycleScope
import com.example.tictactoe.databinding.ActivityMainBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding:ActivityMainBinding
private var flag=0
private var counter=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding =ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
//reset click listener
btnReset.setOnClickListener {
//Resetting the score of both players
newScore(TAG_RESET)
//clearing the titles again
newGame()
}
}
}
fun oxClick(view: View)
{
val btn = view as ImageView
binding.apply {
if (btn.drawable == null)
{
//one move
counter++
//assigning the turn to the player
when(flag)
{
0 -> {
//turn of the first player
btn.setImageResource(R.drawable.ic_o)
btn.tag= TAG_O
card0.strokeWidth =0
cardX.strokeWidth =2
//changing the turn
flag=1
}
1 -> {
//turn of the second player
btn.setImageResource(R.drawable.ic_x)
btn.tag = TAG_X
cardX.strokeWidth =0
cardX.strokeWidth =2
//changing the turn
flag=0
}
}
//using a lifecycle method to introduce a delay
lifecycleScope.launch {
//checking the pre-defined conditions for winning the XO game
if(iv1.tag==iv2.tag && iv2.tag==iv3.tag && iv3.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv1.tag.toString())
withAnimation(iv1,iv2,iv3)
}
else if(iv4.tag==iv5.tag && iv5.tag==iv6.tag && iv6.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv4.tag.toString())
withAnimation(iv4,iv5,iv6)
}
else if(iv7.tag==iv8.tag && iv8.tag==iv9.tag && iv9.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv7.tag.toString())
withAnimation(iv7,iv8,iv9)
}
else if(iv1.tag==iv5.tag && iv5.tag==iv9.tag && iv9.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv1.tag.toString())
withAnimation(iv1,iv5,iv9)
}
else if(iv3.tag==iv5.tag && iv5.tag==iv7.tag && iv7.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv3.tag.toString())
withAnimation(iv3,iv5,iv7)
}
else if(iv1.tag==iv4.tag && iv4.tag==iv7.tag && iv7.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv1.tag.toString())
withAnimation(iv1,iv4,iv7)
}
else if(iv3.tag==iv6.tag && iv6.tag==iv9.tag && iv9.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv3.tag.toString())
withAnimation(iv3,iv6,iv9)
}
else if(iv2.tag==iv5.tag && iv5.tag==iv8.tag && iv8.tag!=null) {
//find the winner of the game through the selected image view tag
newScore(iv2.tag.toString())
withAnimation(iv2,iv5,iv8)
}
else if(counter==9){
//if all the tiles are filled and there is no winner we empty the tiles
Toast.makeText(this@MainActivity, "No clear winner", Toast.LENGTH_SHORT).show()
newGame()
}
}
}
}
}
private suspend fun withAnimation(viewOne:View, viewTwo:View, viewThree:View){
//changing the color of the correct tiles to green one by one
viewOne.setBackgroundResource(R.drawable.board_back_green)
delay(200)
viewTwo.setBackgroundResource(R.drawable.board_back_green)
delay(200)
viewThree.setBackgroundResource(R.drawable.board_back_green)
delay(200)
newGame()
}
private fun newScore(tag:String){
when(tag)
{
TAG_X-> {
//Current score of user x
val xPoint= binding.boardXCount.text.toString().toInt()
binding.boardXCount.text =(xPoint +1).toString()
}
TAG_O -> {
//Current score of user 0
val oPoint= binding.board0Count.text.toString().toInt()
binding.board0Count.text =(oPoint +1).toString()
}
TAG_RESET -> {
//Resetting the whole board
binding.board0Count.text="0"
binding.boardXCount.text="0"
}
}
}
private fun newGame(){
//change the turn
flag=0
//resetting the number of moves
counter=0
//fina all image views and clear all the tags and views of the drawables from it
binding.gridLayout.children.filterIsInstance<ImageView>().forEach { iv->
iv.setImageDrawable(null)
iv.tag = null
iv.setBackgroundResource(R.drawable.board_back)
//adding a green border to the user whose turn it is to play
binding.card0.strokeWidth = 2
binding.cardX.strokeWidth = 0
}
}
} | TicTac/app/src/main/java/com/example/tictactoe/MainActivity.kt | 2285663392 |
package com.example.tictactoe
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.tictactoe.databinding.ActivityStartActiivityBinding
class StartActivity : AppCompatActivity() {
private lateinit var binding: ActivityStartActiivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityStartActiivityBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.playBtn.setOnClickListener {
startActivity(Intent(this@StartActivity,MainActivity::class.java))
finish()
}
}
} | TicTac/app/src/main/java/com/example/tictactoe/StartActivity.kt | 1155655503 |
package com.example.tictactoe
const val TAG_X ="X"
const val TAG_O ="O"
const val TAG_RESET ="reset" | TicTac/app/src/main/java/com/example/tictactoe/Constants.kt | 1723693794 |
package com.senai.vsconnect_kotlin
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.senai.vsconnect_kotlin", appContext.packageName)
}
} | MobileFuncional/app/src/androidTest/java/com/senai/vsconnect_kotlin/ExampleInstrumentedTest.kt | 4187008903 |
package com.senai.vsconnect_kotlin
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)
}
} | MobileFuncional/app/src/test/java/com/senai/vsconnect_kotlin/ExampleUnitTest.kt | 3288985430 |
package com.senai.vsconnect_kotlin.apis
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RetrofitConfig {
companion object {
fun obterInstanciaRetrofit(url: String = "http://172.16.52.129:8080/"): Retrofit {
return Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/apis/RetrofitConfig.kt | 1530418255 |
package com.senai.vsconnect_kotlin.apis
import com.google.gson.JsonObject
import com.senai.vsconnect_kotlin.models.Login
import com.senai.vsconnect_kotlin.models.Alerta
import com.senai.vsconnect_kotlin.models.Erro
import com.senai.vsconnect_kotlin.models.Estrategia
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface EndpointInterface {
@GET("alertas")
fun listarAlertas() : Call<List<Alerta>>
@GET("erro")
fun listarErros() : Call<List<Erro>>
@GET("estrategias")
fun listarEstrategias() : Call<List<Estrategia>>
@POST("login")
fun login(@Body usuario: Login) :Call<JsonObject>
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/apis/EndpointInterface.kt | 1808328999 |
package com.senai.vsconnect_kotlin
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import com.senai.vsconnect_kotlin.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
//desabilita a exibiรงao do titulo do nome da tela atual
supportActionBar?.setDisplayShowTitleEnabled(false)
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_editar_imagem, R.id.nav_servicos, R.id.nav_sair
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
navView.menu.findItem(R.id.nav_sair).setOnMenuItemClickListener { menu ->
val mainIntent = Intent(
this@MainActivity,
LoginActivity::class.java)
startActivity(mainIntent)
finish()
true
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/MainActivity.kt | 669782060 |
package com.senai.vsconnect_kotlin.models
class Estrategia
( val id : String )
{
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/models/Estrategia.kt | 3217686851 |
package com.senai.vsconnect_kotlin.models
class Erro(
val nomeerro: String,
val status_erro : String // ativo ou nao ativo (com erro)
) {
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/models/Erro.kt | 2078477128 |
package com.senai.vsconnect_kotlin.models
class Login(
val email: String,
val senha: String
) | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/models/Login.kt | 1989988890 |
package com.senai.vsconnect_kotlin.models
import java.util.UUID
class Alerta (
val id_erro : String,
val nivel_criticidade : String,
val data_alerta: String,
val status_alerta: String,
val descricao_alerta: String,
val erro : Erro
) | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/models/Alerta.kt | 506908717 |
package com.senai.vsconnect_kotlin.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.senai.vsconnect_kotlin.R
import com.senai.vsconnect_kotlin.models.Alerta
import org.w3c.dom.Text
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class ListaAlertaAdapter(
private val context: Context,
private val listaAlerta: List<Alerta>
) : RecyclerView.Adapter<ListaAlertaAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
//Essa funcao e responsavel por chamar e atribuir valores para as views do item da Recyclerview
fun VincularDadosNoItem(alerta: Alerta) {
val txtErro = itemView.findViewById<TextView>(R.id.codigoErro)
txtErro.text = alerta.erro.nomeerro
val txtDescricao = itemView.findViewById<TextView>(R.id.descricaoAlerta)
txtDescricao.text = alerta.descricao_alerta
val txtData = itemView.findViewById<TextView>(R.id.dataAlerta)
val localDateTime: LocalDateTime = LocalDateTime.parse( "${alerta.data_alerta}T00:00:00")
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val output: String = formatter.format(localDateTime)
txtData.text = output
val txtStatus = itemView.findViewById<TextView>( R.id.statusAlerta)
txtStatus.text = alerta.status_alerta
val txtCriticidade = itemView.findViewById<TextView>(R.id.criticidadeAlerta)
txtCriticidade.text = alerta.nivel_criticidade
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListaAlertaAdapter.ViewHolder {
val inflater = LayoutInflater.from(context);
val view = inflater.inflate(R.layout.fragment_alerta, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ListaAlertaAdapter.ViewHolder, position: Int) {
val itemServico = listaAlerta[position]
holder.VincularDadosNoItem(itemServico)
}
override fun getItemCount(): Int {
return listaAlerta.size
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/adapters/ListaAlertaAdapter.kt | 2765044648 |
package com.senai.vsconnect_kotlin.components
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.senai.vsconnect_kotlin.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ServicoFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ServicoFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_alerta, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ServicoFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ServicoFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/components/ServicoFragment.kt | 2318839097 |
package com.senai.vsconnect_kotlin
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.google.gson.JsonObject
import com.senai.vsconnect_kotlin.apis.EndpointInterface
import com.senai.vsconnect_kotlin.apis.RetrofitConfig
import com.senai.vsconnect_kotlin.databinding.ActivityLoginBinding
import com.senai.vsconnect_kotlin.models.Login
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.nio.charset.StandardCharsets
import java.util.Base64
class LoginActivity : AppCompatActivity() {
//ร uma propriedade privada como o nome binding do tipo ActivityLoginBinding
private lateinit var binding: ActivityLoginBinding
private val clientRetrofit = RetrofitConfig.obterInstanciaRetrofit()
private val endpoints = clientRetrofit.create(EndpointInterface::class.java)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Atribui ร variรกvel binding um objeto que contรฉm referรชncias (propriedades) aos elementos definidos no layout
binding = ActivityLoginBinding.inflate(layoutInflater)
val sharedPreferences = getSharedPreferences("idUsuario", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.remove("idUsuario")
editor.apply()
//setOnClickListener รฉ um ouvinte de clique
//Ou seja, quando clicar no botรฃo entrar irรก cair nesse bloco
binding.btnEntrar.setOnClickListener {
autenticarUsuario()
}
setContentView(binding.root)
}
private fun autenticarUsuario(){
val root: View = binding.root
val idEmail = root.findViewById<EditText>(R.id.campo_email)
val idSenha = root.findViewById<EditText>(R.id.campo_senha)
val emailDigitado = idEmail.text.toString()
val senhaDigitado = idSenha.text.toString()
val usuario = Login(emailDigitado, senhaDigitado)
endpoints.login(usuario).enqueue(object : Callback<JsonObject>{
override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
when(response.code()){
200 -> {
val idUsuario = decodificarToken(response.body().toString())
val sharedPreferences = getSharedPreferences("idUsuario", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("idUsuario", idUsuario.toString())
editor.apply()
//direcionando o usuario para tela lista de servicos
val mainIntent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(mainIntent)
finish()
}
403 -> { tratarFalhaNaAutenticacao(mensagemErro = "E-mail e/ou senha invalidos.") }
else -> { tratarFalhaNaAutenticacao(mensagemErro = "falha ao se logar!") }
}
}
override fun onFailure(call: Call<JsonObject>, t: Throwable) {
tratarFalhaNaAutenticacao(mensagemErro = "Falha ao tentar se logar!")
}
})
}
private fun tratarFalhaNaAutenticacao(mensagemErro: String){
Toast.makeText(this, mensagemErro, Toast.LENGTH_SHORT).show()
}
private fun decodificarToken(token: String): Any {
val partes = token.split(".")
val payloadBase64 = partes[1]
val payloadBytes = Base64.getUrlDecoder().decode(payloadBase64)
val payloadJson = String(payloadBytes, StandardCharsets.UTF_8)
val json = JSONObject(payloadJson)
return json["idUsuario"].toString()
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/LoginActivity.kt | 3227874180 |
package com.senai.vsconnect_kotlin.views
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.google.gson.JsonObject
import com.senai.vsconnect_kotlin.R
import com.senai.vsconnect_kotlin.adapters.ListaAlertaAdapter
import com.senai.vsconnect_kotlin.apis.EndpointInterface
import com.senai.vsconnect_kotlin.apis.RetrofitConfig
import com.senai.vsconnect_kotlin.databinding.FragmentEditarImagemBinding
import com.senai.vsconnect_kotlin.models.Alerta
import com.senai.vsconnect_kotlin.models.Erro
import com.senai.vsconnect_kotlin.models.Estrategia
import com.squareup.picasso.Picasso
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
class EditarImagemFragment : Fragment() {
private var _binding: FragmentEditarImagemBinding? = null
private val bindings get() = _binding!!
private val clientRetrofit = RetrofitConfig.obterInstanciaRetrofit()
private val endpoints = clientRetrofit.create(EndpointInterface::class.java)
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentEditarImagemBinding.inflate(inflater, container, false)
val root: View = binding.root
val sharedPreferences = requireContext().getSharedPreferences("idUsuario", Context.MODE_PRIVATE)
val idUsuario = sharedPreferences.getString("idUsuario", "")
// buscarUsuarioPorID(idUsuario.toString())
endpoints.listarAlertas().enqueue(object : Callback<List<Alerta>> {
override fun onResponse(call: Call<List<Alerta>>, response:
Response<List<Alerta>>
) {
val response = response.body()
val alertas = root.findViewById<TextView>(R.id.txtAlertaValor)
alertas.text = if (response?.size == null) "0" else response.size.toString()
}
override fun onFailure(call: Call<List<Alerta>>, t: Throwable) {
println("Falha na requisicao: ${t.message}")
}
})
endpoints.listarErros().enqueue(object : Callback<List<Erro>> {
override fun onResponse(call: Call<List<Erro>>, response: Response<List<Erro>>) {
val response = response.body()
var errosCount = 0
var errosCorrigidosCount = 0
if (response != null) {
for ((index, model) in response.withIndex()) {
if (model.status_erro == "Ativo"){
errosCount += 1
}else{
errosCorrigidosCount += 1
}
}
}
val erros = root.findViewById<TextView>(R.id.txtErroValor)
erros.text = errosCount.toString()
val errosCorrigidos = root.findViewById<TextView>(R.id.txtErroCorrigidoValor)
errosCorrigidos.text = errosCorrigidosCount.toString()
}
override fun onFailure(call: Call<List<Erro>>, t: Throwable) {
println("Falha na requisicao: ${t.message}")
}
})
endpoints.listarEstrategias().enqueue(object : Callback<List<Estrategia>> {
override fun onResponse(call: Call<List<Estrategia>>, response:
Response<List<Estrategia>>
) {
val response = response.body()
val estrategia = root.findViewById<TextView>(R.id.txtEstrategiaValor)
estrategia.text = if (response?.size == null) "0" else response.size.toString()
}
override fun onFailure(call: Call<List<Estrategia>>, t: Throwable) {
println("Falha na requisicao: ${t.message}")
}
})
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/views/EditarImagemFragment.kt | 2895662092 |
package com.senai.vsconnect_kotlin.views
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.senai.vsconnect_kotlin.adapters.ListaAlertaAdapter
import com.senai.vsconnect_kotlin.apis.EndpointInterface
import com.senai.vsconnect_kotlin.apis.RetrofitConfig
import com.senai.vsconnect_kotlin.databinding.FragmentListaServicosBinding
import com.senai.vsconnect_kotlin.models.Alerta
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ListaServicosFragment : Fragment() {
private val clientRetrofit = RetrofitConfig.obterInstanciaRetrofit()
private val endpoints = clientRetrofit.create(EndpointInterface::class.java)
private var _binding: FragmentListaServicosBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentListaServicosBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.recyclerServicos.layoutManager = LinearLayoutManager(requireContext())
endpoints.listarAlertas().enqueue(object : Callback<List<Alerta>> {
override fun onResponse(call: Call<List<Alerta>>, response:
Response<List<Alerta>>
) {
val servicos = response.body()
binding.recyclerServicos.adapter = servicos?.let { ListaAlertaAdapter(requireContext(), it) }
}
override fun onFailure(call: Call<List<Alerta>>, t: Throwable) {
println("Falha na requisicao: ${t.message}")
}
})
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | MobileFuncional/app/src/main/java/com/senai/vsconnect_kotlin/views/ListaServicosFragment.kt | 1643932563 |
package com.example.echo
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.echo", appContext.packageName)
}
} | Echo/app/src/androidTest/java/com/example/echo/ExampleInstrumentedTest.kt | 3483201039 |
package com.example.echo
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)
}
} | Echo/app/src/test/java/com/example/echo/ExampleUnitTest.kt | 3930706310 |
package com.example.echo.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) | Echo/app/src/main/java/com/example/echo/ui/theme/Color.kt | 1564479677 |
package com.example.echo.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 EchoTheme(
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
)
} | Echo/app/src/main/java/com/example/echo/ui/theme/Theme.kt | 3624884329 |
package com.example.echo.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
)
*/
) | Echo/app/src/main/java/com/example/echo/ui/theme/Type.kt | 2129655039 |
package com.example.echo
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Mic
import androidx.compose.material3.IconButton
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.runtime.mutableStateOf
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.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.echo.components.Header
import com.example.echo.ui.theme.EchoTheme
import java.util.Locale
class MainActivity : ComponentActivity() {
private lateinit var startForResult: ActivityResultLauncher<Intent>
private var speakText by
mutableStateOf("")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK && it.data != null) {
val resultData = it.data
val resultArray =
resultData?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
speakText = resultArray?.get(0).toString()
}
}
setContent {
EchoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
SpeechToTextApp()
}
}
}
}
@Composable
fun SpeechToTextApp() {
Header()
Box(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
IconButton(onClick = {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Now...")
startForResult.launch(intent)
}) {
androidx.compose.material3.Icon(
Icons.Rounded.Mic,
contentDescription = "Mic-Icon"
)
}
Text(text = "Tap mic to transcribe.",
color = Color.White)
if (speakText.isBlank()) {
Text(
text = "Speech To Text using Google Voice Engine.",
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.background(
color = MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(8.dp)
)
.border(
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
.padding(16.dp)
)
} else {
SelectionContainer(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.background(
color = MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(8.dp)
)
.border(
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
.padding(16.dp)
) {
Text(
text = speakText,
fontWeight = FontWeight.SemiBold,
fontSize = 18.sp
)
}
}
}
}
}
@Preview
@Composable
fun SpeechToTextAppPreview() {
SpeechToTextApp()
}
}
| Echo/app/src/main/java/com/example/echo/MainActivity.kt | 3220279949 |
package com.example.echo.components
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun Header() {
Box(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = 10.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Echo",
fontWeight = FontWeight.Bold,
fontSize = 35.sp,
modifier = Modifier.background(color = MaterialTheme.colorScheme.background)
)
}
}
} | Echo/app/src/main/java/com/example/echo/components/Header.kt | 1435073911 |
package com.example.sluchnum
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.sluchnum", appContext.packageName)
}
} | lab_9/app/src/androidTest/java/com/example/sluchnum/ExampleInstrumentedTest.kt | 2840654970 |
package com.example.sluchnum
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)
}
} | lab_9/app/src/test/java/com/example/sluchnum/ExampleUnitTest.kt | 2012414063 |
package com.example.sluchnum
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun nextactivity(view: View){
val randomIntent = Intent(this,SluchNum2:: class.java)
startActivity(randomIntent)
}
} | lab_9/app/src/main/java/com/example/sluchnum/MainActivity.kt | 2793610302 |
package com.example.sluchnum
import android.os.Bundle
import android.widget.TextView
import kotlin.random.Random
import androidx.appcompat.app.AppCompatActivity
class SluchNum2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_s2)
val random = Random.nextInt(0,1000)
val randomInt = Random.nextInt(0,random)
val textViewRandom : TextView = findViewById(R.id.textView_random2)
val textViewLabel : TextView = findViewById(R.id.textView_label)
textViewRandom.text= randomInt.toString()
textViewLabel.text= getString(R.string.textRandom2,random)
}
} | lab_9/app/src/main/java/com/example/sluchnum/SluchNum2.kt | 2240088052 |
package com.example.myapplication
import android.media.Image import android.os.Bundle
import androidx.activity.ComponentActivity import
androidx.activity.compose.setContent import
androidx.compose.foundation.Image import
androidx.compose.foundation.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.material3.MaterialTheme import
androidx.compose.material3.Surface import
androidx.compose.material3.Text import
androidx.compose.runtime.Composable import
androidx.compose.ui.Alignment import
androidx.compose.ui.Modifier import
androidx.compose.ui.graphics.Color import
androidx.compose.ui.layout.ContentScale import
androidx.compose.ui.res.painterResource 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
androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
import java.time.format.TextStyle
class MainActivity : ComponentActivity() { override
fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GreetingiImage(message1 =
stringResource(R.string.jetpack_compose_tutorial),message2= stringResource(
R.string.ssecond_string
),message3= stringResource(R.string.third_string)
)
}
}
}
}
}
@Composable
fun GreetingiImage(message1:String,message2:String,message3:String, modifier: Modifier =
Modifier) {
val image= painterResource(R.drawable.bg_compose_background)
Column(
verticalArrangement = Arrangement.Bottom,
modifier = modifier
) {
Image(
painter=image,
contentDescription=null,
)
Surface(color = Color.White) {
Column(
verticalArrangement = Arrangement.Bottom,
modifier = modifier
) {
Text(
text = message1,
fontSize = 24.sp,
modifier = Modifier.padding(16.dp)
)
Text(
text = message2,
textAlign = TextAlign.Justify,
modifier = Modifier.padding(16.dp)
)
Text(
text = message3,
textAlign = TextAlign.Justify,
modifier = Modifier.padding(16.dp)
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
GreetingiImage(message1 = stringResource(R.string.jetpack_compose_tutorial),message2=
stringResource(
R.string.ssecond_string
),message3= stringResource(R.string.third_string)
)
}
}
| Jetpack-Tutorial-Content/MainActivity.kt | 2666293293 |
package com.hm.hyeonminshinlottospring.support
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoRank
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.TotalMatchResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.WinningLottoMatchResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.WinningLottoRoundResponse
const val TEST_WINNINGLOTTO_ID = 2001L
const val TEST_OTHER_WINNINGLOTTO_ID = 2002L
const val TEST_INVALID_WINNINGLOTTO_ID = -1L
fun createWinningLotto(
lotto: Lotto,
round: Int = TEST_ROUND,
id: Long = TEST_WINNINGLOTTO_ID,
) = WinningLotto(
lotto = lotto,
round = round,
id = id,
)
fun createWinningLottoRoundResponse(winningLotto: WinningLotto) = WinningLottoRoundResponse.from(winningLotto)
fun createWinningLottoMatchResponse(
lotto: Lotto,
matched: List<Int>,
rank: LottoRank,
) = WinningLottoMatchResponse.from(lotto, matched, rank)
fun createListWinningLottoMatchResponse() =
listOf(
createWinningLottoMatchResponse(
lotto = createLotto(createUser(), numbers = listOf(1, 2, 3, 4, 5, 6)),
matched = listOf(1, 2, 3),
rank = LottoRank.getRank(3),
),
createWinningLottoMatchResponse(
lotto = createOtherLotto(createUser(), numbers = listOf(10, 11, 12, 13, 14, 15)),
matched = listOf(11, 12, 13, 14),
rank = LottoRank.getRank(4),
),
)
fun createTotalMatchResponse() = TotalMatchResponse.from(createListWinningLottoMatchResponse())
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/WinningLottoFixtures.kt | 859187033 |
package com.hm.hyeonminshinlottospring.support.test
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockHttpServletRequestDsl
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
class ControllerTestHelper {
companion object {
private val objectMapper = jacksonObjectMapper().apply { registerModule(JavaTimeModule()) }
fun MockHttpServletRequestDsl.jsonContent(value: Any) {
content = objectToString(value)
contentType = MediaType.APPLICATION_JSON
}
fun MockHttpServletRequestBuilder.jsonContent(value: Any): MockHttpServletRequestBuilder =
apply {
content(objectToString(value))
contentType(MediaType.APPLICATION_JSON)
}
fun jsonContent(value: Any): String = objectToString(value)
private fun objectToString(value: Any): String = objectMapper.writeValueAsString(value)
}
}
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/test/ControllerTestHelper.kt | 1473954409 |
package com.hm.hyeonminshinlottospring.support.test
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.EXAMPLE
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.field
import org.springframework.restdocs.RestDocumentationContextProvider
import org.springframework.restdocs.headers.HeaderDescriptor
import org.springframework.restdocs.headers.HeaderDocumentation
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler
import org.springframework.restdocs.operation.preprocess.Preprocessors
import org.springframework.restdocs.payload.FieldDescriptor
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.payload.PayloadDocumentation
import org.springframework.restdocs.payload.RequestFieldsSnippet
import org.springframework.restdocs.payload.ResponseFieldsSnippet
import org.springframework.restdocs.request.ParameterDescriptor
import org.springframework.restdocs.request.RequestDocumentation
import org.springframework.restdocs.request.RequestPartDescriptor
import org.springframework.restdocs.snippet.Attributes.Attribute
import org.springframework.restdocs.snippet.Snippet
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.MockMvcResultHandlersDsl
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.filter.CharacterEncodingFilter
private const val EXAMPLE_NULL = "null"
class RestDocsHelper {
companion object {
const val EXAMPLE = "example"
fun generateRestDocMockMvc(
webApplicationContext: WebApplicationContext,
restDocumentationContextProvider: RestDocumentationContextProvider,
): MockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter<DefaultMockMvcBuilder>(CharacterEncodingFilter("UTF-8", true))
.alwaysDo<DefaultMockMvcBuilder>(MockMvcResultHandlers.print())
.apply<DefaultMockMvcBuilder>(
MockMvcRestDocumentation.documentationConfiguration(restDocumentationContextProvider)
.operationPreprocessors()
.withRequestDefaults(Preprocessors.prettyPrint())
.withResponseDefaults(Preprocessors.prettyPrint()),
)
.build()
fun requestBody(vararg fields: RestDocsField): RequestFieldsSnippet =
PayloadDocumentation.requestFields(fields.map { it.descriptor })
fun responseBody(vararg fields: RestDocsField): ResponseFieldsSnippet =
PayloadDocumentation.responseFields(fields.map { it.descriptor })
fun field(key: String, value: String?): Attribute {
return Attribute(key, value)
}
fun MockMvcResultHandlersDsl.createDocument(identifier: String, vararg snippets: Snippet) {
return handle(MockMvcRestDocumentation.document("{class-name}/$identifier", *snippets))
}
fun createPathDocument(value: Any, vararg snippets: Snippet): RestDocumentationResultHandler =
MockMvcRestDocumentation.document("{class-name}/$value", *snippets)
}
}
infix fun String.type(
type: JsonFieldType,
): RestDocsField = createField(this, type)
private fun createField(
path: String,
type: JsonFieldType,
): RestDocsField = RestDocsField(PayloadDocumentation.fieldWithPath(path).type(type))
class RestDocsField(
val descriptor: FieldDescriptor,
) {
infix fun isOptional(value: Boolean): RestDocsField {
if (value) descriptor.optional()
return this
}
infix fun description(value: String): RestDocsField {
descriptor.description(value)
return this
}
infix fun example(value: Any?): RestDocsField {
descriptor.attributes(field(EXAMPLE, if (value is String) value else value?.toString() ?: EXAMPLE_NULL))
return this
}
}
infix fun String.headerDescription(value: String): HeaderDescriptor {
return HeaderDocumentation.headerWithName(this).description(value)
}
infix fun String.pathDescription(value: String): ParameterDescriptor {
return RequestDocumentation.parameterWithName(this).description(value)
}
infix fun String.parameterDescription(value: String): ParameterDescriptor {
return RequestDocumentation.parameterWithName(this).description(value)
}
infix fun String.requestPartDescription(value: String): RequestPartDescriptor {
return RequestDocumentation.partWithName(this).description(value)
}
infix fun ParameterDescriptor.example(value: Any): ParameterDescriptor {
return this.attributes(
field(
EXAMPLE,
if (value is String) {
value
} else if (value is Array<*>) {
value.joinToString()
} else {
value.toString()
},
),
)
}
infix fun ParameterDescriptor.isOptional(value: Boolean): ParameterDescriptor {
if (value) this.optional()
return this
}
infix fun RequestPartDescriptor.isOptional(value: Boolean): RequestPartDescriptor {
if (value) this.optional()
return this
}
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/test/RestDocsHelpler.kt | 3172964089 |
package com.hm.hyeonminshinlottospring.support.test
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
fun TestEntityManager.flushAndClear() {
flush()
clear()
}
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/test/TestEntityManager.kt | 2148815042 |
package com.hm.hyeonminshinlottospring.support.test
import com.hm.hyeonminshinlottospring.global.config.JpaAuditingConfig
import com.hm.hyeonminshinlottospring.global.config.SchedulingConfig
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.annotation.Import
import org.springframework.restdocs.RestDocumentationExtension
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.TestConstructor
class BaseTests {
@ActiveProfiles("test")
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
annotation class TestEnvironment
@TestEnvironment
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@Import(JpaAuditingConfig::class)
@DataJpaTest(properties = ["spring.jpa.hibernate.ddl-auto=none"])
annotation class RepositoryTest
@TestEnvironment
@AutoConfigureRestDocs
@Import(SchedulingConfig::class)
@ExtendWith(RestDocumentationExtension::class)
annotation class UnitControllerTestEnvironment
@TestEnvironment
@SpringBootTest
annotation class IntegrationTest
}
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/test/BaseTests.kt | 3662116899 |
package com.hm.hyeonminshinlottospring.support.config
import io.kotest.core.config.AbstractProjectConfig
import io.kotest.core.extensions.Extension
import io.kotest.extensions.spring.SpringTestExtension
import io.kotest.extensions.spring.SpringTestLifecycleMode
/**
* [https://effortguy.tistory.com/475]
*
* # KotestConfig
*
* kotest๋ฅผ ์ฌ์ฉํด์ spring์ @Transactional ์ ๋
ธํ
์ด์
์ ์ฌ์ฉํ ๋,
* ๋กค๋ฐฑ(rollback)์ด ์ ๋๋ก ๋์ง ์์ ์ฌ์ฉํ๋ ์ค์ .
*
* ํด๋น ์ค์ ์ ์ฌ์ฉํ๊ฒ ๋๋ฉด `SpringTestLifecycleMode.Test`,
* ์ฆ ๊ฐ์ฅ ์๋์ nested๊ฐ ์๋๋ผ ํฐ ๋จ์(์. DescribeSpec์์ describe) ๊ธฐ์ค์ผ๋ก ๋ฌถ์ฌ์
* ํธ๋์ญ์
์ด ๋ฐ์ํ๋ค.
*
* ๊ฒฐ๊ตญ ์ด ์ค์ ์ ํ
์คํธ๋ง๋ค ํธ๋์ญ์
๋กค๋ฐฑ์ ์ ์ฉ์ํค๋ ค ํ๋ ๊ฒ์ด๋ค.
*
* ## ์ฃผ์์ฌํญ
*
* ์ ๋ด์ฉ์ ์ดํดํ๋ค๋ฉด ํด๋น ํ
์คํธ ๋ด์์ ์ฌ์ฉํ ๊ฐ ์ ์ญ ๋ณ์๋ค์ ์ด๊ธฐํ๋ฅผ ๋กค๋ฐฑํ๊ธฐ ์ํด์๋
* `val`์ ํตํด ์ ์ธํ ๊ฒ ์๋๋ผ `lateinit var`๋ก ์ค์ ํ ๋ค `beforeEach` ํจ์ ๋ด์์ ์ด๊ธฐํํด์ฃผ์ด์ผ ํ๋ค!
*/
class KotestConfig : AbstractProjectConfig() {
// ํธ๋์ญ์
๋กค๋ฐฑ ๋จ์ ์ค์
override fun extensions(): List<Extension> = listOf(SpringTestExtension(SpringTestLifecycleMode.Root))
// coroutine ํ
์คํธ ํ๊ฒฝ ๋ฐ ๋๋ฒ๊ทธ ์ค์
override val coroutineTestScope = true
override val coroutineDebugProbes = true
}
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/config/KotestConfig.kt | 3488313157 |
package com.hm.hyeonminshinlottospring.support
import com.hm.hyeonminshinlottospring.domain.lotto.domain.GenerateMode
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateRequest
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateResponse
import com.hm.hyeonminshinlottospring.domain.lotto.dto.SliceLottoNumberResponse
import com.hm.hyeonminshinlottospring.domain.user.domain.User
const val TEST_LOTTO_ID = 12L
const val TEST_OTHER_LOTTO_ID = 13L
const val TEST_ANOTHER_LOTTO_ID = 14L
const val TEST_NOT_EXIST_LOTTO_ID = 1000L
const val TEST_INVALID_LOTTO_ID = -1L
const val TEST_ROUND = 1001
const val TEST_OTHER_ROUND = 1002
const val TEST_ANOTHER_ROUND = 1003
const val TEST_NOT_EXIST_ROUND = 4
const val TEST_INVALID_ROUND = -1
const val TEST_GENERATE_COUNT_2 = 2
const val TEST_GENERATE_COUNT_10 = 10
val TEST_NUMBER =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS)
val TEST_NUMBER_2 =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS)
val TEST_OTHER_NUMBER =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS)
val TEST_NUMBER_NODUP_BUT_OVERSIZE =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS + 1)
val TEST_NUMBER_NODUP_BUT_UNDERSIZE =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS - 1)
val TEST_NUMBER_NORMALSIZE_BUT_DUP =
(LottoNumbers.LOTTO_MIN_NUMBER..<LottoNumbers.LOTTO_MAX_NUMBER)
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS - 2) + LottoNumbers.LOTTO_MAX_NUMBER + LottoNumbers.LOTTO_MAX_NUMBER
fun createLotto(
user: User,
round: Int = TEST_ROUND,
numbers: Collection<Int> = TEST_NUMBER,
) = Lotto(
round = round,
numbers = numbers,
user = user,
)
fun createOtherLotto(
user: User,
round: Int = TEST_ROUND,
numbers: Collection<Int> = TEST_OTHER_NUMBER,
) = Lotto(
round = round,
numbers = numbers,
user = user,
)
fun createCustomLotto(
round: Int,
numbers: Collection<Int>,
user: User,
) = Lotto(
round = round,
numbers = numbers,
user = user,
)
fun createLottoNumber(list: Collection<Int> = TEST_NUMBER) = LottoNumbers(list)
fun createLottoNumbers(count: Int = 1): List<List<Int>> {
val mutableList = mutableListOf<List<Int>>()
repeat(count) {
mutableList.add(
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS),
)
}
return mutableList.toList()
}
fun createAllLotto(user: User) = listOf(createLotto(user), createLotto(user, numbers = TEST_NUMBER_2))
fun createLottoCreateRequest(
userId: Long = TEST_USER_ID,
insertedMoney: Int = TEST_MONEY_10,
numbers: List<List<Int>>? = null,
mode: GenerateMode = GenerateMode.RANDOM,
) = LottoCreateRequest(
userId = userId,
mode = mode,
insertedMoney = insertedMoney,
numbers = numbers,
)
fun createLottoCreateResponse(
userId: Long = TEST_USER_ID,
round: Int = TEST_ROUND,
createdLottoCount: Int = TEST_GENERATE_COUNT_10,
) = LottoCreateResponse(
userId = userId,
round = round,
createdLottoCount = createdLottoCount,
)
fun createSliceLottoNumberResponse(
userId: Long? = TEST_USER_ID,
round: Int? = TEST_ROUND,
hasNext: Boolean = true,
numberOfElements: Int = TEST_GENERATE_COUNT_2,
numberList: List<String>? = null,
) = SliceLottoNumberResponse(
userId = userId,
round = round,
hasNext = hasNext,
numberOfElements = numberOfElements,
numberList = numberList ?: createLottoNumbers(numberOfElements).map { it.joinToString() },
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/LottoFixtures.kt | 1947214669 |
package com.hm.hyeonminshinlottospring.support
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import com.hm.hyeonminshinlottospring.domain.user.dto.UserCreateRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserMoneyPatchRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserResponse
const val TEST_USER_ID = 1001L
const val TEST_OTHER_USER_ID = 1002L
const val TEST_ANOTHER_USER_ID = 1003L
const val TEST_ADMIN_USER_ID = 1004L
const val TEST_NOT_EXIST_USER_ID = 1005L
const val TEST_INVALID_USER_ID = -1L
const val TEST_USERNAME = "testUsername"
const val TEST_OTHER_USERNAME = "testOtherUsername"
const val TEST_ADMIN_USERNAME = "testAdmin"
const val TEST_NOT_EXIST_USERNAME = "testNotExist"
const val TEST_MONEY_ZERO = 0
const val TEST_MONEY_10 = 10
const val TEST_INVALID_MONEY = -1
val TEST_USER_ROLE_USER = UserRole.ROLE_USER
val TEST_USER_ROLE_ADMIN = UserRole.ROLE_ADMIN
fun createUser(
userName: String = TEST_USERNAME,
userRole: UserRole = TEST_USER_ROLE_USER,
money: Int = TEST_MONEY_10,
) = User(
userName = userName,
userRole = userRole,
money = money,
)
fun createOtherUser(
userName: String = TEST_OTHER_USERNAME,
userRole: UserRole = TEST_USER_ROLE_USER,
money: Int = TEST_MONEY_10,
) = User(
userName = userName,
userRole = userRole,
money = money,
)
fun createAdmin(
userName: String = TEST_ADMIN_USERNAME,
userRole: UserRole = TEST_USER_ROLE_ADMIN,
money: Int = TEST_MONEY_10,
) = User(
userName = userName,
userRole = userRole,
money = money,
)
fun createUserCreateRequest(user: User) =
UserCreateRequest(
userName = user.userName,
money = user.money,
userRole = user.userRole,
)
fun createUserMoneyPatchRequest(
userId: Long = TEST_USER_ID,
money: Int = TEST_MONEY_10,
) = UserMoneyPatchRequest(
userId = userId,
money = money,
)
fun createUserResponse(user: User) = UserResponse.from(user)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/UserFixtures.kt | 2332334314 |
package com.hm.hyeonminshinlottospring.support
import org.springframework.data.domain.PageRequest
const val USER_ID_PARAM = "userId"
const val CHARGE_PARAM = "charge"
const val ROUND_PARAM = "round"
const val PAGE_PARAM = "page"
const val SIZE_PARAM = "size"
const val TEST_DEFAULT_PAGE = 0
const val TEST_DEFAULT_SIZE = 20
const val TEST_PAGE = 1
const val TEST_SIZE = 1
const val TEST_INVALID_SIZE: Int = -1
val TEST_PAGEABLE = PageRequest.of(TEST_PAGE, TEST_SIZE)
val TEST_DEFAULT_PAGEABLE = PageRequest.of(TEST_DEFAULT_PAGE, TEST_DEFAULT_SIZE)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/support/ParamFixtures.kt | 2883967977 |
package com.hm.hyeonminshinlottospring.domain.user.repository
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_NOT_EXIST_USERNAME
import com.hm.hyeonminshinlottospring.support.createUser
import com.hm.hyeonminshinlottospring.support.test.BaseTests.RepositoryTest
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.core.spec.style.ExpectSpec
import io.kotest.matchers.shouldBe
@RepositoryTest
class UserRepositoryTest(
private val userRepository: UserRepository,
) : ExpectSpec(
{
val user1 = userRepository.save(createUser())
afterSpec {
userRepository.deleteAll()
}
context("์ ์ ID ์กฐํ") {
expect("์ ์ ID์ ์ผ์นํ๋ ์ ์ ์กฐํ") {
val result = userRepository.findByUserId(user1.id)
result.userName shouldBe user1.userName
}
expect("์ ์ ID๊ฐ ์กด์ฌํ ๋") {
val result = userRepository.existsById(user1.id)
result shouldBe true
}
expect("์ ์ ID๊ฐ ์กด์ฌํ์ง ์์ ๋") {
val result = userRepository.existsById(TEST_INVALID_USER_ID)
result shouldBe false
}
}
context("์ ์ ์ด๋ฆ ์กฐํ") {
expect("์ ์ ์ด๋ฆ๊ณผ ์ผ์นํ๋ ์ ์ ์กฐํ") {
shouldNotThrowAny { userRepository.findByUserName(user1.userName) }
}
expect("์ ์ ์ด๋ฆ์ด ์กด์ฌํ ๋") {
val result = userRepository.existsByUserName(user1.userName)
result shouldBe true
}
expect("์ ์ ์ด๋ฆ์ด ์กด์ฌํ์ง ์์ ๋") {
val result = userRepository.existsByUserName(TEST_NOT_EXIST_USERNAME)
result shouldBe false
}
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/user/repository/UserRepositoryTest.kt | 658873881 |
package com.hm.hyeonminshinlottospring.domain.user.controller
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoPrice
import com.hm.hyeonminshinlottospring.domain.user.service.UserService
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_MONEY
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_MONEY_10
import com.hm.hyeonminshinlottospring.support.TEST_USER_ID
import com.hm.hyeonminshinlottospring.support.createUser
import com.hm.hyeonminshinlottospring.support.createUserCreateRequest
import com.hm.hyeonminshinlottospring.support.createUserMoneyPatchRequest
import com.hm.hyeonminshinlottospring.support.createUserResponse
import com.hm.hyeonminshinlottospring.support.test.BaseTests.UnitControllerTestEnvironment
import com.hm.hyeonminshinlottospring.support.test.ControllerTestHelper.Companion.jsonContent
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.createDocument
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.createPathDocument
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.requestBody
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.responseBody
import com.hm.hyeonminshinlottospring.support.test.example
import com.hm.hyeonminshinlottospring.support.test.pathDescription
import com.hm.hyeonminshinlottospring.support.test.type
import com.ninjasquad.springmockk.MockkBean
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.every
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.restdocs.ManualRestDocumentation
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.request.RequestDocumentation.pathParameters
import org.springframework.test.web.servlet.patch
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.context.WebApplicationContext
@UnitControllerTestEnvironment
@WebMvcTest(UserController::class)
class UserControllerTest(
private val context: WebApplicationContext,
@MockkBean private val userService: UserService,
) : DescribeSpec(
{
val restDocumentation = ManualRestDocumentation()
val restDocMockMvc = RestDocsHelper.generateRestDocMockMvc(context, restDocumentation)
beforeEach {
restDocumentation.beforeTest(javaClass, it.name.testName)
}
describe("POST /api/v1/user") {
val targetUri = "/api/v1/user"
context("์ ํจํ ์์ฒญ์ธ ๊ฒฝ์ฐ") {
val user = createUser()
val request = createUserCreateRequest(user)
every { userService.createUser(request) } returns user.id
it("201 ์๋ตํ๋ค.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isCreated() }
}.andDo {
createDocument(
"create-user-success",
requestBody(
"userName" type JsonFieldType.STRING description "์ ์ ์ด๋ฆ" example request.userName,
"money" type JsonFieldType.NUMBER description "์ถฉ์ ํ ๋" example request.money,
"userRole" type JsonFieldType.STRING description "์ ์ ์ญํ " example request.userRole,
),
)
}
}
}
context("์ ์ ์ด๋ฆ์ด ์ ํจํ์ง ์์ ๊ฒฝ์ฐ") {
val user = createUser(userName = " ")
val request = createUserCreateRequest(user)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"create-user-fail-user-name-blank",
requestBody(
"userName" type JsonFieldType.STRING description "๊ณต๋ฐฑ์ธ ์ ์ ์ด๋ฆ" example " ",
"money" type JsonFieldType.NUMBER description "์ถฉ์ ํ ๋" example request.money,
"userRole" type JsonFieldType.STRING description "์ ์ ์ญํ " example request.userRole,
),
)
}
}
}
context("๋์ด ์์๋ก ๋ค์ด์จ ๊ฒฝ์ฐ") {
val user = createUser(money = TEST_INVALID_MONEY)
val request = createUserCreateRequest(user)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"create-user-fail-money-negative",
requestBody(
"userName" type JsonFieldType.STRING description "์ ์ ์ด๋ฆ" example request.userName,
"money" type JsonFieldType.NUMBER description "0 ์ดํ์ ์์๋ก ์ฃผ์ด์ง ์ถฉ์ ํ ๋" example TEST_INVALID_MONEY,
"userRole" type JsonFieldType.STRING description "์ ์ ์ญํ " example request.userRole,
),
)
}
}
}
}
describe("GET /api/v1/user/{userId}") {
val targetUri = "/api/v1/user/{userId}"
context("์ ํจํ ์ ์ ID๊ฐ ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val user = createUser()
val response = createUserResponse(user)
every { userService.getUserInformation(TEST_USER_ID) } returns response
it("200 ์๋ตํ๋ค.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_USER_ID),
).andExpect(
status().isOk,
).andDo(
createPathDocument(
"get-user-information-success",
pathParameters(
"userId" pathDescription "์กฐํํ ์ ์ ID" example TEST_USER_ID,
),
responseBody(
"userName" type JsonFieldType.STRING description "์ ์ ์ด๋ฆ" example response.userName,
"userRole" type JsonFieldType.STRING description "์ ์ ์ญํ " example response.userRole,
"money" type JsonFieldType.NUMBER description "์์งํ ๊ธ์ก" example response.money,
),
),
)
}
}
context("์ ์ ID๊ฐ ์์๋ก ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_INVALID_USER_ID),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-user-information-fail-user-id-negative",
pathParameters(
"userId" pathDescription "์์์ ์ ์ ID" example TEST_INVALID_USER_ID,
),
),
)
}
}
context("์ ์ ID๊ฐ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ") {
every { userService.getUserInformation(TEST_USER_ID) } throws NoSuchElementException("${TEST_USER_ID}: ์ฌ์ฉ์๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.")
it("404 ์๋ตํ๋ค.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_USER_ID),
).andExpect(
status().isNotFound,
).andDo(
createPathDocument(
"get-user-information-fail-user-id-not-exist",
pathParameters(
"userId" pathDescription "์กด์ฌํ์ง ์๋ ์ ์ ID" example TEST_USER_ID,
),
),
)
}
}
}
describe("PATCH /api/v1/user/addMoney") {
val targetUri = "/api/v1/user/addMoney"
context("์ ํจํ ๋ฐ์ดํฐ๊ฐ ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest()
every { userService.addUserMoney(request) } returns TEST_MONEY_10
it("204 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isNoContent() }
}.andDo {
createDocument(
"add-user-money-success",
requestBody(
"userId" type JsonFieldType.NUMBER description "์ถฉ์ ํ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถฉ์ ํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ ์ ID๊ฐ ์์๋ก ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(userId = TEST_INVALID_USER_ID)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"add-user-money-fail-user-id-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "์์์ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถฉ์ ํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ ์ ID๊ฐ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(userId = TEST_USER_ID)
every { userService.addUserMoney(request) } throws NoSuchElementException("$TEST_USER_ID: ์ฌ์ฉ์๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.")
it("404 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isNotFound() }
}.andDo {
createDocument(
"add-user-money-fail-user-id-not-exist",
requestBody(
"userId" type JsonFieldType.NUMBER description "์กด์ฌํ์ง ์๋ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถฉ์ ํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ถฉ์ ํ ๋์ด ์์๋ก ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(money = TEST_INVALID_MONEY)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"add-user-money-fail-charge-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์์์ ์ถฉ์ ํ ๊ธ์ก" example request.money,
),
)
}
}
}
}
describe("PATCH /api/v1/user/withdrawMoney") {
val targetUri = "/api/v1/user/withdrawMoney"
context("์ ํจํ ๋ฐ์ดํฐ๊ฐ ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest()
every { userService.withdrawUserMoney(request) } returns TEST_MONEY_10
it("204 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isNoContent() }
}.andDo {
createDocument(
"withdraw-user-money-success",
requestBody(
"userId" type JsonFieldType.NUMBER description "์ถ๊ธํ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถ๊ธํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ ์ ID๊ฐ ์์๋ก ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(userId = TEST_INVALID_USER_ID)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"withdraw-user-money-fail-user-id-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "์์์ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถ๊ธํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ ์ ID๊ฐ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(userId = TEST_USER_ID)
every { userService.withdrawUserMoney(request) } throws NoSuchElementException("$TEST_USER_ID: ์ฌ์ฉ์๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.")
it("404 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isNotFound() }
}.andDo {
createDocument(
"withdraw-user-money-fail-user-id-not-exist",
requestBody(
"userId" type JsonFieldType.NUMBER description "์กด์ฌํ์ง ์๋ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์ถ๊ธํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ถํ ๋์ด ์์๋ก ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(money = TEST_INVALID_MONEY)
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"withdraw-user-money-fail-charge-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "์ถ๊ธํ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "์์์ ์ถ๊ธํ ๊ธ์ก" example request.money,
),
)
}
}
}
context("์ถ๊ธํ ๋์ด ์์งํ ๊ธ์ก๋ณด๋ค ํฌ๊ฒ ์ฃผ์ด์ง ๊ฒฝ์ฐ") {
val request = createUserMoneyPatchRequest(money = TEST_MONEY_10 + 1)
every { userService.withdrawUserMoney(request) } throws IllegalArgumentException("$TEST_USER_ID: ํ์ฌ ์์งํ ๊ธ์ก($TEST_MONEY_10${LottoPrice.UNIT})๋ณด๋ค ์ ์ ๊ธ์ก์ ์
๋ ฅํด์ฃผ์ธ์.")
it("400 ์๋ตํ๋ค.") {
restDocMockMvc.patch(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"withdraw-user-money-fail-charge-bigger-than-having",
requestBody(
"userId" type JsonFieldType.NUMBER description "์ถ๊ธํ ์ ์ ID" example request.userId,
"money" type JsonFieldType.NUMBER description "๊ฐ์ง ๊ธ์ก๋ณด๋ค ํฐ ์ถ๊ธํ ๊ธ์ก" example request.money,
),
)
}
}
}
}
afterTest {
restDocumentation.afterTest()
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/user/controller/UserControllerTest.kt | 2868996828 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.