content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.projectmanagment
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import java.io.File
// FilesGridAdapter.kt
class FilesGridAdapter(private val context: Context, private val files: List<File>) : BaseAdapter() {
override fun getCount(): Int {
return files.size
}
override fun getItem(position: Int): Any {
return files[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View
val holder: ViewHolder
if (convertView == null) {
view = LayoutInflater.from(context).inflate(R.layout.grid_layout, parent, false)
holder = ViewHolder(view)
view.tag = holder
} else {
view = convertView
holder = convertView.tag as ViewHolder
}
val file = files[position]
// Bind data to views
holder.fileNameTextView.text = file.name
val filetype: String = getFileType(file.name)
// Set appropriate icon based on file type
holder.iconImageView.setImageResource(getFileTypeIcon(filetype))
return view
}
private fun getFileTypeIcon(fileType: String): Int {
when(fileType) {
"PDF" -> return R.drawable.ic_pdf
"Image" -> return R.drawable.ic_pdf
"Video" -> return R.drawable.ic_pdf
"Text" -> return R.drawable.ic_pdf
else -> return R.drawable.ic_pdf
}
}
private fun getFileType(fileName: String): String {
val extension = fileName.substringAfterLast('.')
return when (extension.toLowerCase()) {
"pdf" -> "PDF"
"png", "jpg", "jpeg" -> "Image"
"mp4", "avi", "mov" -> "Video"
"txt" -> "Text"
else -> "Unknown"
}
}
private class ViewHolder(view: View) {
val iconImageView: ImageView = view.findViewById(R.id.iconImageView)
val fileNameTextView: TextView = view.findViewById(R.id.fileNameTextView)
}
}
| Project_Management/app/src/main/java/com/example/projectmanagment/FilesGridAdapter.kt | 4004244066 |
package com.example.projectmanagment.Storage
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.GridView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.Conference.Meet
import com.example.projectmanagment.FilesGridAdapter
import com.example.projectmanagment.R
import com.example.projectmanagment.Todo
import com.example.projectmanagment.databinding.ActivitySharedDataBinding
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationBarView
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.io.File
class SharedData : AppCompatActivity() {
lateinit var binding: ActivitySharedDataBinding
val FILE_REQUEST_CODE = 100 // Request code for file selection
lateinit var uri: Uri
lateinit var mStorage: StorageReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivitySharedDataBinding.inflate(layoutInflater)
setContentView(binding.root)
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
}
mStorage = FirebaseStorage.getInstance().getReference("Uploads")
val selectFileBtn=binding.selectFileBtn
selectFileBtn.setOnClickListener {
selectFile()
}
retrieveFiles()
binding.bottomNavigation.selectedItemId = R.id.item_1
binding.bottomNavigation.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.item_1 -> {
Toast.makeText(this, "Item 1", Toast.LENGTH_SHORT).show()
true
}
R.id.item_2 -> {
startActivity(Intent(this, Meet::class.java))
finish()
true
}
R.id.item_3 -> {
startActivity(Intent(this, Todo::class.java))
finish()
true
}
else -> false
}
}
}
private fun selectFile() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*" // Accept all file types
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == FILE_REQUEST_CODE) {
// File selected successfully
uri = data?.data ?: return
val uriTxt = findViewById<TextView>(R.id.uriTxt)
uriTxt.text = uri.toString()
uploadFile()
}
}
private fun uploadFile() {
val fileName = uri.lastPathSegment ?: return
// Get SharedPreferences instance
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", MODE_PRIVATE)
val location = sharedPreferences.getString("projCode", "default_value")
val fileReference = location?.let { mStorage.child(it).child(fileName) }
try {
if (fileReference != null) {
fileReference.putFile(uri).addOnSuccessListener { taskSnapshot ->
val downloadUrl = uri.toString()
val dwnTxt = findViewById<TextView>(R.id.dwnTxt)
dwnTxt.text = downloadUrl.toString()
Toast.makeText(this, "Successfully Uploaded :)", Toast.LENGTH_LONG).show()
}
}
} catch (e: Exception) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
}
}
private fun retrieveFiles() {
// Get SharedPreferences instance
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", MODE_PRIVATE)
val location = sharedPreferences.getString("projCode", "default_value")
if (location != null) {
val folderReference = mStorage.child(location)
folderReference.listAll().addOnSuccessListener { listResult ->
val filesList1 = ArrayList<String>()
for (item in listResult.items) {
val fileName = item.name // Get file name
filesList1.add(fileName)
}
// Populate grid view with file names
// Assuming you have a GridView with id filesGridView in your layout
val gridView = findViewById<GridView>(R.id.gridView)
// Sample list of files (you need to replace it with your actual data)
val filesList = listOf<File>(File("file1.pdf"), File("file2.png"), File("file3.txt"))
val adapter = FilesGridAdapter(this, filesList)
gridView.adapter = adapter
}.addOnFailureListener { exception ->
// Handle any errors that may occur during retrieval
Toast.makeText(this, "Failed to retrieve files: ${exception.message}", Toast.LENGTH_SHORT).show()
}
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/Storage/SharedData.kt | 3748425101 |
package com.example.projectmanagment.SplashScreen
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.TextView
import com.example.projectmanagment.R
import com.example.projectmanagment.UserData.Welcome
class SplashFragment_2 : Fragment(R.layout.fragment_splash_2) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val buttonToActivity = view.findViewById<TextView>(R.id.btn_splsh_second)
buttonToActivity.setOnClickListener {
val intent = Intent(context, Welcome::class.java)
startActivity(intent)
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/SplashScreen/SplashFragment_2.kt | 2749624792 |
package com.example.projectmanagment.SplashScreen
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.R
class SplashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_splash_screen)
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
}
val splashFragment1 = SplashFragment_1() // Initialize SplashFragment_1
supportFragmentManager.beginTransaction()
.replace(R.id.splash_fragment_container, splashFragment1)
.commit()
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/SplashScreen/SplashScreen.kt | 2134276096 |
package com.example.projectmanagment.SplashScreen
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import com.example.projectmanagment.R
class SplashFragment_1 : Fragment(R.layout.fragment_splash_1) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btn_splsh_first : View = view.findViewById(R.id.btn_splsh_first)
btn_splsh_first.setOnClickListener {
val fragmentTwo = SplashFragment_2()
val transaction = requireActivity().supportFragmentManager.beginTransaction()
transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
transaction.replace(R.id.splash_fragment_container, fragmentTwo)
transaction.addToBackStack(null)
transaction.commit()
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/SplashScreen/SplashFragment_1.kt | 1042162165 |
package com.example.projectmanagment
object GlobalData {
var projectCode = 0
} | Project_Management/app/src/main/java/com/example/projectmanagment/GlobalData.kt | 1868796212 |
package com.example.projectmanagment.UserData
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.Projects.MainActivity
import com.example.projectmanagment.R
import com.example.projectmanagment.databinding.ActivityLoginBinding
import com.google.firebase.auth.FirebaseAuth
class Login : AppCompatActivity() {
lateinit var binding: ActivityLoginBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
enableEdgeToEdge()
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
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, R.color.secondary)
}
firebaseAuth=FirebaseAuth.getInstance()
binding.btnLogin.setOnClickListener {
val email = binding.etEmail.text.toString()
val pass = binding.etPassword.text.toString()
login(email,pass)
}
binding.btnRegister.setOnClickListener {
val intent = Intent(this, Register::class.java)
startActivity(intent)
finish()
}
}
private fun login(email: String, pass: String) {
if(email.isNotEmpty() && pass.isNotEmpty()){
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener {
if (it.isSuccessful){
val userID = firebaseAuth.currentUser!!.uid
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("userID",userID)
val intent =Intent(this, MainActivity::class.java)
startActivity(intent)
}else{
Toast.makeText(this,it.exception.toString(),Toast.LENGTH_SHORT).show()
}
}
}else{
Toast.makeText(this,"Please fill the information", Toast.LENGTH_SHORT).show()
}
}
public override fun onStart() {
super.onStart()
val currentUser = firebaseAuth.currentUser
if (currentUser != null){
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/UserData/Login.kt | 1363637642 |
package com.example.projectmanagment.UserData
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.Projects.MainActivity
import com.example.projectmanagment.R
import com.example.projectmanagment.databinding.ActivityWelcomeBinding
import com.google.firebase.auth.FirebaseAuth
class Welcome : AppCompatActivity() {
lateinit var binding: ActivityWelcomeBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityWelcomeBinding.inflate(layoutInflater)
setContentView(binding.root)
enableEdgeToEdge()
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
}
// Set the status bar color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, R.color.dark)
}
firebaseAuth=FirebaseAuth.getInstance()
binding.btnLogin.setOnClickListener{
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
binding.btnRegister.setOnClickListener{
val intent = Intent(this, Register::class.java)
startActivity(intent)
}
}
public override fun onStart() {
super.onStart()
val currentUser = firebaseAuth.currentUser
if (currentUser != null){
val userID = firebaseAuth.currentUser!!.uid
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("userID",userID)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/UserData/Welcome.kt | 2499350146 |
package com.example.projectmanagment.UserData
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.Projects.MainActivity
import com.example.projectmanagment.R
import com.example.projectmanagment.databinding.ActivityRegisterBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import kotlin.random.Random
class Register : AppCompatActivity() {
private lateinit var binding: ActivityRegisterBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var database : DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterBinding.inflate(layoutInflater)
setContentView(binding.root)
enableEdgeToEdge()
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
}
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
firebaseAuth=FirebaseAuth.getInstance()
binding.btnSignin.setOnClickListener {
startActivity(Intent(this, Login::class.java))
finish()
}
binding.btnRegister.setOnClickListener {
val email = binding.edEmail.text.toString()
val username = binding.edUsername.text.toString()
val password = binding.edPassword.text.toString()
val confirmpassword = binding.edConfirmPassword.text.toString()
register(email,username,password,confirmpassword,editor)
}
}
private fun register(email: String, username: String, password: String, confirmpassword: String, editor: SharedPreferences.Editor?) {
if(email.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty() && confirmpassword.isNotEmpty()){
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnSuccessListener {
editor!!.putString("username",username)
editor.putString("email",email)
editor.putString("password",password)
editor.putString("userID", Random.nextInt(1000,9999).toString())
editor.apply()
startActivity(Intent(this, MainActivity::class.java))
}
.addOnFailureListener {
Toast.makeText(this,"Registration Failed",Toast.LENGTH_SHORT).show()
}
}
else{
Toast.makeText(this,"Please all the Information", Toast.LENGTH_SHORT).show()
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/UserData/Register.kt | 181185338 |
package com.ga.labo1
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.ga.labo1", appContext.packageName)
}
} | labo1_movil/app/src/androidTest/java/com/ga/labo1/ExampleInstrumentedTest.kt | 3786650799 |
package com.ga.labo1
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)
}
} | labo1_movil/app/src/test/java/com/ga/labo1/ExampleUnitTest.kt | 3250556432 |
package com.ga.labo1.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) | labo1_movil/app/src/main/java/com/ga/labo1/ui/theme/Color.kt | 2189703961 |
package com.ga.labo1.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 Labo1Theme(
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
)
} | labo1_movil/app/src/main/java/com/ga/labo1/ui/theme/Theme.kt | 185940780 |
package com.ga.labo1.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
)
*/
) | labo1_movil/app/src/main/java/com/ga/labo1/ui/theme/Type.kt | 3278595532 |
package com.ga.labo1
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.ga.labo1.ui.theme.Labo1Theme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Labo1Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Ronald Rivas")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "bienvenido $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Labo1Theme {
Greeting("Ronald Rivas")
}
} | labo1_movil/app/src/main/java/com/ga/labo1/MainActivity.kt | 1785945855 |
package com.task.manager.api
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class KotlinTaskManagerApiApplicationTests {
@Test
fun contextLoads() {
}
}
| spring-boot-kotlin-task-manager-api/src/test/kotlin/com/task/manager/api/KotlinTaskManagerApiApplicationTests.kt | 903807754 |
package com.task.manager.api
import org.springframework.web.bind.annotation.*
import java.util.concurrent.atomic.AtomicLong
@RestController
@RequestMapping("/tasks")
class TaskController {
private val tasks = mutableListOf<Task>()
private val taskIdCounter = AtomicLong()
@PostMapping
fun createTask(@RequestBody taskRequest: TaskRequest): Task {
val taskId = taskIdCounter.incrementAndGet()
val newTask = Task(taskId, taskRequest.title, taskRequest.description, taskRequest.dueDate)
tasks.add(newTask)
return newTask
}
@GetMapping
fun getAllTasks(): List<Task> {
return tasks
}
@GetMapping("/{taskId}")
fun getTaskById(@PathVariable taskId: Long): Task? {
return tasks.find { it.id == taskId }
}
@PutMapping("/{taskId}")
fun updateTask(@PathVariable taskId: Long, @RequestBody updatedTask: TaskRequest): Task? {
val existingTask = tasks.find { it.id == taskId }
if (existingTask != null) {
existingTask.title = updatedTask.title
existingTask.description = updatedTask.description
existingTask.dueDate = updatedTask.dueDate
}
return existingTask
}
@DeleteMapping("/{taskId}")
fun deleteTask(@PathVariable taskId: Long): Boolean {
return tasks.removeIf { it.id == taskId }
}
}
data class Task(val id: Long, var title: String, var description: String, var dueDate: String)
data class TaskRequest(val title: String, val description: String, val dueDate: String)
| spring-boot-kotlin-task-manager-api/src/main/kotlin/com/task/manager/api/TaskController.kt | 3501339294 |
package com.task.manager.api
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class KotlinTaskManagerApiApplication
fun main(args: Array<String>) {
runApplication<KotlinTaskManagerApiApplication>(*args)
}
| spring-boot-kotlin-task-manager-api/src/main/kotlin/com/task/manager/api/KotlinTaskManagerApiApplication.kt | 2500665065 |
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
fun main() {
val myStudentsArray: Array<String> = arrayOf("Peter", "Vasya", "Tolyan", "Lyokha")
myStudentsArray[0] = "Anna"
println("First cockroach: ${myStudentsArray[0]}")
println("Second cockroach:${myStudentsArray[1]}")
println("Third cockroach: ${myStudentsArray[2]}")
println("Fourth cockroach: ${myStudentsArray[3]}")
val myArray: Array<Array<Int>> = arrayOf(
arrayOf( 1, 2 , 3, 4, 5),
arrayOf(6, 7, 8, 9, 10),
arrayOf(11, 12, 13, 14, 15)
)
println(myArray[0][4])
println(myArray[2][4])
}
| new-project2/new-folder27.03/cockroach-names/src/main/kotlin/Main.kt | 2703405967 |
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
} | oh-my-algorithm/src/main/kotlin/Main.kt | 3350697704 |
package com.example.medicalemergencycardapp
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.medicalemergencycardapp", appContext.packageName)
}
} | Medical_Emergency_Card_App/medicalEmergencyCardApp/app/src/androidTest/java/com/example/medicalemergencycardapp/ExampleInstrumentedTest.kt | 252035611 |
package com.example.medicalemergencycardapp
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)
}
} | Medical_Emergency_Card_App/medicalEmergencyCardApp/app/src/test/java/com/example/medicalemergencycardapp/ExampleUnitTest.kt | 3842005198 |
package com.example.medicalemergencycardapp
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.view.isVisible
import com.example.medicalemergencycardapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.inputValueButton.setOnClickListener {
val intent = Intent(this, EditActivity::class.java)
startActivity(intent)
}
binding.delteValueButton.setOnClickListener {
deleteInformation()
}
binding.warningValueTextView.isVisible = binding.warningCheckBox.isChecked
binding.warningCheckBox.setOnCheckedChangeListener { _, isChecked ->
binding.warningValueTextView.isVisible = isChecked
}
}
override fun onResume() {
super.onResume()
getDataAndUiUpdate()
}
private fun getDataAndUiUpdate(){
with(getSharedPreferences(USER_INFORMATION, Context.MODE_PRIVATE)){
binding.nameValueTextView.text = getString(NAME,"미정")
binding.birthdateValueTextView.text = getString(BIRTHDATE, "미정")
binding.bloodTypeValueTextView.text = getString(BLOOD_TYPE, "미정")
binding.emergencyContactValueTextView.text = getString(EMERGENCY_CONTACT, "미정")
val warning = getString(WARNING,"")
binding.warningCheckBox.isVisible = warning.isNullOrEmpty().not()
binding.warningCheckBox.isChecked = warning.isNullOrEmpty().not()
binding.warningValueTextView.isVisible = warning.isNullOrEmpty().not()
binding.warningTextView.isVisible = warning.isNullOrEmpty().not()
if (warning.isNullOrEmpty().not()){
binding.warningValueTextView.text = warning
}
}
}
private fun deleteInformation(){
with(getSharedPreferences(USER_INFORMATION,Context.MODE_PRIVATE).edit()){
clear()
apply()
getDataAndUiUpdate()
}
Toast.makeText(this,"정보가 초기화되었습니다.",Toast.LENGTH_SHORT).show()
}
} | Medical_Emergency_Card_App/medicalEmergencyCardApp/app/src/main/java/com/example/medicalemergencycardapp/MainActivity.kt | 2354653981 |
package com.example.medicalemergencycardapp
const val USER_INFORMATION ="userInformation"
const val NAME = "name"
const val BIRTHDATE = "brithdate"
const val BLOOD_TYPE = "bloodType"
const val EMERGENCY_CONTACT = "emergencyContact"
const val WARNING = "warning" | Medical_Emergency_Card_App/medicalEmergencyCardApp/app/src/main/java/com/example/medicalemergencycardapp/Const.kt | 1783267897 |
package com.example.medicalemergencycardapp
import android.app.DatePickerDialog
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.view.isVisible
import com.example.medicalemergencycardapp.databinding.ActivityEditBinding
class EditActivity : AppCompatActivity() {
private lateinit var binding: ActivityEditBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.bloodTypeSpinner.adapter = ArrayAdapter.createFromResource(
this,
R.array.blood_types,
android.R.layout.simple_spinner_item
)
binding.birthdateLayer.setOnClickListener {
val listener = DatePickerDialog.OnDateSetListener { _, year, month, dateOfMonth ->
binding.birthdateValueTextView.text = "$year-${month+1}-$dateOfMonth"
}
DatePickerDialog(this, listener,2000,0,1).show()
}
binding.warningCheckBox.setOnCheckedChangeListener { _, isChecked ->
binding.warningValueEditText.isVisible = isChecked
}
binding.saveButton.setOnClickListener {
saveData()
finish()
}
}
private fun saveData(){
with(getSharedPreferences(USER_INFORMATION, Context.MODE_PRIVATE).edit()){
putString(NAME,binding.nameValueEditText.text.toString())
putString(BLOOD_TYPE,getBloodType())
putString(EMERGENCY_CONTACT, binding.emergencyContactValueEditText.text.toString())
putString(BIRTHDATE, binding.birthdateValueTextView.text.toString())
putString(WARNING, getWarning())
apply()
}
Toast.makeText(this,"정보가 저장되었습니다", Toast.LENGTH_SHORT).show()
}
private fun getBloodType(): String{
val bloodAlphabet = binding.bloodTypeSpinner.selectedItem.toString()
val bloodSigh = if (binding.bloodTypePlus.isChecked) "RH+" else "RH-"
return "$bloodSigh ${bloodAlphabet}형"
}
private fun getWarning():String{
return if (binding.warningCheckBox.isChecked) binding.warningValueEditText.text.toString() else ""
}
} | Medical_Emergency_Card_App/medicalEmergencyCardApp/app/src/main/java/com/example/medicalemergencycardapp/EditActivity.kt | 681226299 |
import androidx.compose.ui.window.ComposeUIViewController
fun MainViewController() = ComposeUIViewController { App() }
| Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/iosMain/kotlin/MainViewController.kt | 3500059733 |
import platform.UIKit.UIDevice
class IOSPlatform: Platform {
override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
actual fun getPlatform(): Platform = IOSPlatform() | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/iosMain/kotlin/Platform.ios.kt | 110407275 |
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
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.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
@OptIn(ExperimentalResourceApi::class)
@Composable
fun App() {
MaterialTheme {
var name: String by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(8.dp))
TextField(
value = name,
onValueChange = { name = it }
)
Spacer(modifier = Modifier.height(38.dp))
AnimatedVisibility(name.isNotEmpty()) {
if (name.lowercase() == "aristidevs") {
Text("SUSCRIBETE!!!", fontSize = 36.sp, fontWeight = FontWeight.Bold)
} else {
Text("Hola $name", fontSize = 24.sp)
}
}
}
}
} | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/commonMain/kotlin/App.kt | 2871182946 |
interface Platform {
val name: String
}
expect fun getPlatform(): Platform | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/commonMain/kotlin/Platform.kt | 960794953 |
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
} | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/commonMain/kotlin/Greeting.kt | 2562376394 |
class JVMPlatform: Platform {
override val name: String = "Java ${System.getProperty("java.version")}"
}
actual fun getPlatform(): Platform = JVMPlatform() | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/desktopMain/kotlin/Platform.jvm.kt | 1652497929 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
App()
}
}
@Preview
@Composable
fun AppDesktopPreview() {
App()
} | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/desktopMain/kotlin/main.kt | 4273132414 |
import android.os.Build
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform() | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/androidMain/kotlin/Platform.android.kt | 3472575554 |
package com.aristidevs.hellowordkmp
import App
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App()
}
}
}
@Preview
@Composable
fun AppAndroidPreview() {
App()
} | Curso-Kotlin-Multiplatform/HelloWorld/composeApp/src/androidMain/kotlin/com/aristidevs/hellowordkmp/MainActivity.kt | 3122068058 |
import androidx.compose.ui.window.ComposeUIViewController
fun MainViewController() = ComposeUIViewController { App() }
| Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/iosMain/kotlin/MainViewController.kt | 3500059733 |
import platform.UIKit.UIDevice
class IOSPlatform: Platform {
override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
actual fun getPlatform(): Platform = IOSPlatform() | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/iosMain/kotlin/Platform.ios.kt | 110407275 |
package settings
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.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.text.font.FontWeight
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.russhwolf.settings.Settings
import settings.ProfileScreen.Companion.KEY_NAME
import settings.ProfileScreen.Companion.KEY_VIP
class ProfileResultScreen : Screen {
private val settings: Settings = Settings()
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val isVip = settings.getBoolean(KEY_VIP, false)
val backgroundColor = if (isVip) {
Color.Yellow
} else {
Color.White
}
Column(
modifier = Modifier.fillMaxSize().background(backgroundColor),
horizontalAlignment = Alignment.CenterHorizontally
) {
val name = settings.getString(KEY_NAME, "")
Text("Bienvenid@ $name", fontSize = 26.sp, fontWeight = FontWeight.Bold)
Button(onClick = {
// settings.remove(KEY_NAME)
// settings.remove(KEY_VIP)
settings.clear()
navigator.pop()
}) {
Text("Volver y borrar datos")
}
}
}
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/settings/ProfileResultScreen.kt | 525804200 |
package settings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.Checkbox
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.russhwolf.settings.Settings
import com.russhwolf.settings.get
import com.russhwolf.settings.set
class ProfileScreen : Screen {
private val settings: Settings = Settings()
companion object{
const val KEY_NAME = "NAME"
const val KEY_VIP = "VIP"
}
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
var name by remember { mutableStateOf("") }
var isVip by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(Modifier.weight(1f))
OutlinedTextField(value = name, onValueChange = { name = it })
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = isVip, onCheckedChange = { isVip = it })
Text("Eres VIP?")
}
Spacer(Modifier.weight(1f))
Button(onClick = {
// settings.putString("NAME", name)
settings[KEY_NAME] = name
settings[KEY_VIP] = isVip
navigator.push(ProfileResultScreen())
}, enabled = name.isNotEmpty()) {
Text("Guardar perfil")
}
Spacer(Modifier.weight(0.3f))
}
}
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/settings/ProfileScreen.kt | 2758082122 |
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.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.unit.dp
import androidx.compose.ui.unit.sp
import bottombar.BottomBarScreen
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.Navigator
import cafe.adriel.voyager.navigator.currentOrThrow
import cafe.adriel.voyager.transitions.FadeTransition
import cafe.adriel.voyager.transitions.ScaleTransition
import cafe.adriel.voyager.transitions.SlideTransition
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import settings.ProfileScreen
@Composable
fun App() {
MaterialTheme {
Navigator(screen = MainScreen())
{navigator ->
SlideTransition(navigator)
// FadeTransition(navigator)
// ScaleTransition(navigator)
}
}
}
class MainScreen : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = {
navigator.push(SecondScreen())
}) {
Text("Navegación básica")
}
Spacer(Modifier.height(18.dp))
Button(onClick = {
navigator.push(BottomBarScreen())
}) {
Text("BottomBar")
}
Spacer(Modifier.height(18.dp))
Button(onClick = {
navigator.push(ProfileScreen())
}) {
Text("Navegación con persistencia")
}
}
}
}
class SecondScreen : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
Column(
modifier = Modifier.fillMaxSize().background(Color.Blue),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Segunda Pantalla", fontSize = 26.sp, color = Color.White)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { navigator.pop() }) { Text("Volver") }
}
}
}
| Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/App.kt | 3729857481 |
interface Platform {
val name: String
}
expect fun getPlatform(): Platform | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/Platform.kt | 960794953 |
package bottombar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabOptions
object HomeTab : Tab {
override val options: TabOptions
@Composable
get() {
val icon = rememberVectorPainter(Icons.Default.Home)
return remember {
TabOptions(
index = 0u,
title = "Home",
icon = icon
)
}
}
@Composable
override fun Content() {
Box(Modifier.fillMaxSize().background(Color.Green), contentAlignment = Alignment.Center) {
Text("HomeScreen", fontSize = 22.sp, color = Color.Black)
}
}
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/bottombar/HomeTab.kt | 3362294198 |
package bottombar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabOptions
object ProfileTab : Tab {
override val options: TabOptions
@Composable
get() {
val icon = rememberVectorPainter(Icons.Default.Menu)
return remember {
TabOptions(
index = 2u,
title = "Profile",
icon = icon
)
}
}
@Composable
override fun Content() {
Box(Modifier.fillMaxSize().background(Color.Gray), contentAlignment = Alignment.Center) {
Text("ProfileScreen", fontSize = 22.sp, color = Color.White)
}
}
}
| Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/bottombar/ProfileTab.kt | 2921095188 |
package bottombar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabOptions
object FavTab : Tab {
override val options: TabOptions
@Composable
get() {
val icon = rememberVectorPainter(Icons.Default.Favorite)
return remember {
TabOptions(
index = 1u,
title = "Fav",
icon = icon
)
}
}
@Composable
override fun Content() {
Box(Modifier.fillMaxSize().background(Color.Yellow), contentAlignment = Alignment.Center) {
Text("FavScreen", fontSize = 22.sp, color = Color.Black)
}
}
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/bottombar/FavTab.kt | 1836914828 |
package bottombar
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import cafe.adriel.voyager.core.annotation.ExperimentalVoyagerApi
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.tab.CurrentTab
import cafe.adriel.voyager.navigator.tab.LocalTabNavigator
import cafe.adriel.voyager.navigator.tab.TabDisposable
import cafe.adriel.voyager.navigator.tab.TabNavigator
class BottomBarScreen : Screen {
@OptIn(ExperimentalVoyagerApi::class)
@Composable
override fun Content() {
TabNavigator(
HomeTab,
tabDisposable = {
TabDisposable(
it,
listOf(HomeTab, FavTab, ProfileTab)
)
}
) {
Scaffold(
topBar = {
TopAppBar(title = { Text(it.current.options.title) })
},
bottomBar = {
BottomNavigation {
val tabNavigator = LocalTabNavigator.current
BottomNavigationItem(
selected = tabNavigator.current.key == HomeTab.key,
label = { Text(HomeTab.options.title) },
icon = {
Icon(
painter = HomeTab.options.icon!!,
contentDescription = null
)
},
onClick = { tabNavigator.current = HomeTab }
)
BottomNavigationItem(
selected = tabNavigator.current.key == FavTab.key,
label = { Text(FavTab.options.title) },
icon = {
Icon(
painter = FavTab.options.icon!!,
contentDescription = null
)
},
onClick = { tabNavigator.current = FavTab }
)
BottomNavigationItem(
selected = tabNavigator.current.key == ProfileTab.key,
label = { Text(ProfileTab.options.title) },
icon = {
Icon(
painter = ProfileTab.options.icon!!,
contentDescription = null
)
},
onClick = { tabNavigator.current = ProfileTab }
)
}
},
content = { CurrentTab() }
)
}
}
}
| Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/bottombar/BottomBarScreen.kt | 1890256426 |
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/commonMain/kotlin/Greeting.kt | 2562376394 |
class JVMPlatform: Platform {
override val name: String = "Java ${System.getProperty("java.version")}"
}
actual fun getPlatform(): Platform = JVMPlatform() | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/desktopMain/kotlin/Platform.jvm.kt | 1652497929 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
App()
}
}
@Preview
@Composable
fun AppDesktopPreview() {
App()
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/desktopMain/kotlin/main.kt | 4273132414 |
import android.os.Build
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform() | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/androidMain/kotlin/Platform.android.kt | 3472575554 |
package com.aristidevs.navigator
import App
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App()
}
}
}
@Preview
@Composable
fun AppAndroidPreview() {
App()
} | Curso-Kotlin-Multiplatform/NavigationExampleKMP/composeApp/src/androidMain/kotlin/com/aristidevs/navigator/MainActivity.kt | 3909709696 |
import androidx.compose.ui.window.ComposeUIViewController
fun MainViewController() = ComposeUIViewController { App() } | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/iosMain/kotlin/MainViewController.kt | 4056994505 |
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
actual class GetDeviceInformation {
actual fun getDeviceInfo(): String {
return "Soy un cacaiOS"
}
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/iosMain/kotlin/GetDeviceInformation.kt | 596275625 |
import platform.UIKit.UIDevice
class IOSPlatform: Platform {
override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
actual fun getPlatform(): Platform = IOSPlatform() | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/iosMain/kotlin/Platform.ios.kt | 110407275 |
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.ui.tooling.preview.Preview
import actualexpected.composeapp.generated.resources.Res
import actualexpected.composeapp.generated.resources.compose_multiplatform
@OptIn(ExperimentalResourceApi::class)
@Composable
@Preview
fun App() {
MaterialTheme {
var showContent by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
val response = GetDeviceInformation().getDeviceInfo()
Button(onClick = { showContent = !showContent }) {
Text("Click me! $response")
}
AnimatedVisibility(showContent) {
val greeting = remember { Greeting().greet() }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Image(painterResource(Res.drawable.compose_multiplatform), null)
Text("Compose: $greeting")
}
}
}
}
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/commonMain/kotlin/App.kt | 2153796737 |
interface Platform {
val name: String
}
expect fun getPlatform(): Platform | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/commonMain/kotlin/Platform.kt | 960794953 |
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
expect class GetDeviceInformation() {
fun getDeviceInfo():String
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/commonMain/kotlin/GetDeviceInformation.kt | 3774202472 |
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/commonMain/kotlin/Greeting.kt | 2562376394 |
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
actual class GetDeviceInformation {
actual fun getDeviceInfo(): String {
return "Soy un Android molón"
}
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/androidMain/kotlin/GetDeviceInformation.kt | 2039460435 |
import android.os.Build
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform() | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/androidMain/kotlin/Platform.android.kt | 3472575554 |
package com.aristidevs.actualexpected
import App
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App()
}
}
}
@Preview
@Composable
fun AppAndroidPreview() {
App()
} | Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/androidMain/kotlin/com/aristidevs/actualexpected/MainActivity.kt | 3648249597 |
package com.example.toDoMariem
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | todoRepository/app/src/androidTest/java/com/example/toDoMariem/ExampleInstrumentedTest.kt | 988230763 |
package com.example.toDoMariem
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | todoRepository/app/src/test/java/com/example/toDoMariem/ExampleUnitTest.kt | 2815499486 |
package com.example.toDoMariem
import android.os.Parcel
import android.os.Parcelable
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Task(
@SerialName("id")
val id: String?,
@SerialName("content")
val title: String?,
@SerialName("description")
val description: String?
) : Parcelable{
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(id)
parcel.writeString(title)
parcel.writeString(description)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Task> {
override fun createFromParcel(parcel: Parcel): Task {
return Task(parcel)
}
override fun newArray(size: Int): Array<Task?> {
return arrayOfNulls(size)
}
}
}
| todoRepository/app/src/main/java/com/example/toDoMariem/dataTask.kt | 3415064789 |
package com.example.toDoMariem
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| todoRepository/app/src/main/java/com/example/toDoMariem/MainActivity.kt | 1977621301 |
package com.example.toDoMariem.user
import android.Manifest
import android.content.ContentResolver
import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.toDoMariem.data.Api
import com.example.toDoMariem.data.UserViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.io.FileNotFoundException
import kotlin.reflect.KFunction1
class UserActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val userViewModel: UserViewModel = viewModel()
userViewModel.fetchUser()
UserContent(userViewModel, this::pickPhotoWithPermission)
}
}
@RequiresApi(Build.VERSION_CODES.M)
private fun pickPhotoWithPermission(photoPickerLauncher: () -> Unit) {
val storagePermission = Manifest.permission.READ_EXTERNAL_STORAGE
when {
ContextCompat.checkSelfPermission(this, storagePermission) == PackageManager.PERMISSION_GRANTED ->
photoPickerLauncher()
shouldShowRequestPermissionRationale(storagePermission) ->
showMessage("Permission needed to pick photos.")
else ->
requestPermissionLauncher.launch(storagePermission)
}
}
private fun showMessage(message: String) {
// Utilisez un Snackbar ou une autre méthode pour afficher un message
Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show()
}
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
} else {
}
}
}
@Composable
fun UserContent(userViewModel: UserViewModel, onPickPhoto: KFunction1<() -> Unit, Unit>) {
val userWebService = Api.userWebService
val viewModelScope = rememberCoroutineScope()
val context = LocalContext.current
val captureUri by lazy {
val contentValues = ContentValues()
context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
}
val takePicture = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success ->
if (success) {
captureUri?.let { uri ->
val multipartImage = uri.toRequestBody(context.contentResolver)
viewModelScope.launch {
try {
userWebService.updateAvatar(multipartImage)
} catch (e: Exception) {
}
}
}
}
}
val photoPicker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let { selectedUri ->
val multipartImage = selectedUri.toRequestBody(context.contentResolver)
viewModelScope.launch {
try {
val response = userWebService.updateAvatar(multipartImage)
} catch (e: Exception) {
}
}
}
}
val requestPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
photoPicker.launch("image/*")
} else {
}
}
val user by userViewModel.userStateFlow.collectAsState()
var newName by remember { mutableStateOf("") }
Column {
Text(text = "Nom actuel : ${user?.name ?: "Non défini"}")
// Champ pour modifier le nom
TextField(
value = newName,
onValueChange = { newName = it },
label = { Text("Modifier le nom") }
)
Button(onClick = {
userViewModel.updateUserName(newName)
}) {
Text("Mettre à jour le nom")
}
Button(onClick = { takePicture.launch(captureUri) }) {
Text("Take Picture")
}
Button(onClick = { onPickPhoto { photoPicker.launch("image/*") } }) {
Text("Pick Photo")
}
}
}
private fun Bitmap.toRequestBody(): MultipartBody.Part {
val tmpFile = File.createTempFile("avatar", "jpg")
tmpFile.outputStream().use {
this.compress(Bitmap.CompressFormat.JPEG, 100, it)
}
return MultipartBody.Part.createFormData(
name = "avatar",
filename = "avatar.jpg",
body = tmpFile.readBytes().toRequestBody()
)
}
private fun Uri.toRequestBody(contentResolver: ContentResolver): MultipartBody.Part {
val fileInputStream = contentResolver.openInputStream(this) ?: throw FileNotFoundException("File not found")
val fileBody = fileInputStream.readBytes().toRequestBody()
return MultipartBody.Part.createFormData(
name = "avatar",
filename = "avatar.jpg",
body = fileBody
)
}
| todoRepository/app/src/main/java/com/example/toDoMariem/user/UserActivity.kt | 3464709043 |
package com.example.toDoMariem.data
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class UserViewModel : ViewModel() {
val userStateFlow = MutableStateFlow<User?>(null)
private val userWebService = Api.userWebService
fun fetchUser() {
viewModelScope.launch {
try {
val response = userWebService.fetchUser()
if (response.isSuccessful) {
userStateFlow.value = response.body()
} else {
Log.e("UserViewModel", "Error fetching user: ${response.errorBody()?.string()}")
}
} catch (e: Exception) {
Log.e("UserViewModel", "Exception when fetching user", e)
}
}
}
fun updateUserName(newName: String) {
viewModelScope.launch {
val userUpdate = UserUpdate(newName)
val response = userWebService.update(userUpdate)
if (response.isSuccessful) {
fetchUser() // Re-fetch user data to get updated info
} else {
Log.e("UserViewModel", "Error updating user: ${response.errorBody()}")
}
}
}
}
| todoRepository/app/src/main/java/com/example/toDoMariem/user/UserViewModel.kt | 3363711480 |
package com.example.toDoMariem.detail
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.*
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.toDoMariem.Task
import java.util.*
class DetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
val taskToEdit = intent.getParcelableExtra<Task>("TASK_TO_EDIT")
Detail(onValidate = { newTask ->
val returnIntent = Intent()
returnIntent.putExtra("task", newTask)
setResult(Activity.RESULT_OK, returnIntent)
finish()
}, initialTask = taskToEdit)
}
}
}
}
@Composable
fun Detail(onValidate: (Task) -> Unit, initialTask: Task?) {
var taskInitialized= Task(
id = UUID.randomUUID().toString(),
title = "New Task !",
description = "Describe your task..."
)
var task by remember {mutableStateOf(initialTask ?: taskInitialized)}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = "Task Detail",
style = MaterialTheme.typography.h1,
modifier = Modifier.padding(bottom = 16.dp)
)
OutlinedTextField(
value = task.title ?: "",
onValueChange = { task = task.copy(title = it) },
label = { Text("Title") },
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = task.description ?: "",
onValueChange = { task = task.copy(description = it) },
label = { Text("Description") },
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
onValidate(task)
},
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterHorizontally)
) {
Text("Save")
}
}
}
@Preview
@Composable
fun DetailPreview() {
Detail(onValidate= {}, initialTask = null)
}
| todoRepository/app/src/main/java/com/example/toDoMariem/detail/DetailActivity.kt | 3095393607 |
package com.example.toDoMariem.list
import com.example.toDoMariem.Task
interface TaskListListener {
fun onClickDelete(task: Task)
fun onClickEdit(task:Task)
} | todoRepository/app/src/main/java/com/example/toDoMariem/list/TaskListListener.kt | 2100363240 |
package com.example.toDoMariem.list
import TaskListAdapter
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.toDoMariem.R
import com.example.toDoMariem.Task
import com.example.toDoMariem.data.Api
import com.example.toDoMariem.data.TasksListViewModel
import com.example.toDoMariem.data.User
import com.example.toDoMariem.data.UserViewModel
import com.example.toDoMariem.detail.DetailActivity
import com.example.toDoMariem.user.UserActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class TaskListFragment : Fragment(R.layout.fragment_task_list) {
private var user: User? = null
private val userModel: UserViewModel by viewModels()
private val viewModel: TasksListViewModel by viewModels()
private lateinit var userTextView: TextView
private val adapterListener: TaskListListener = object : TaskListListener {
override fun onClickDelete(task: Task) {
viewModel.delete(task)
}
override fun onClickEdit(task: Task) {
val intent = Intent(requireContext(), DetailActivity::class.java)
intent.putExtra("TASK_TO_EDIT", task)
editTask.launch(intent)
}
}
private lateinit var createTask: ActivityResultLauncher<Intent>
private lateinit var editTask: ActivityResultLauncher<Intent>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerViewTasks)
val adapter = TaskListAdapter(adapterListener)
recyclerView.adapter = adapter
userTextView = view.findViewById(R.id.textViewHeader)
// Récupérez le bouton d'ajout de tâche et gérez son clic
val btnAddTask = view.findViewById<FloatingActionButton>(R.id.fabAddTask)
btnAddTask.setOnClickListener {
val intent = Intent(requireActivity(), DetailActivity::class.java)
createTask.launch(intent)
}
createTask = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
val task = result.data?.getParcelableExtra("task") as? Task
task?.let {
viewModel.add(task)
}
}
lifecycleScope.launch {
user = fetchUser()
userTextView.text = user?.name
viewModel.tasksStateFlow.collect { tasks ->
adapter.submitList(tasks)
}
}
editTask = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val editedTask = result.data?.getParcelableExtra<Task>("task")
editedTask?.let { task ->
viewModel.update(task)
}
}
}
val avatarImageView = view.findViewById<ImageView>(R.id.imageViewAvatar)
avatarImageView.setOnClickListener {
val intent = Intent(requireContext(), UserActivity::class.java)
startActivity(intent)
}
}
override fun onResume() {
val avatarImageView = view?.findViewById<ImageView?>(R.id.imageViewAvatar)
avatarImageView?.load(user?.avatar) {
error(R.drawable.ic_baseline_person_24) // image par défaut en cas d'erreur
}
super.onResume()
viewModel.refresh()
}
private suspend fun fetchUser(): User {
return withContext(Dispatchers.IO) {
Api.userWebService.fetchUser().body() !!
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
return inflater.inflate(R.layout.fragment_task_list, container, false)
}
}
| todoRepository/app/src/main/java/com/example/toDoMariem/list/TaskListFragment.kt | 554463294 |
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.toDoMariem.R
import com.example.toDoMariem.Task
import com.example.toDoMariem.list.TaskListFragment
import com.example.toDoMariem.list.TaskListListener
object TaskDiffCallback : DiffUtil.ItemCallback<Task>() {
override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem == newItem
}
}
class TaskListAdapter(var listener: TaskListListener) : ListAdapter<Task, TaskListAdapter.TaskViewHolder>(TaskDiffCallback) {
inner class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val taskTitleTextView: TextView = itemView.findViewById(R.id.task_title)
private val taskDescriptionTextView: TextView = itemView.findViewById(R.id.task_description)
fun bind(task: Task) {
taskTitleTextView.text = task.title
taskDescriptionTextView.text = task.description ?: "No description"
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val itemView =
LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false)
return TaskViewHolder(itemView)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val currentTask = getItem(position)
holder.bind(currentTask)
// Gestionnaire de clic pour le bouton de suppression
holder.itemView.findViewById<ImageButton>(R.id.delete_task_button).setOnClickListener {
// Appel de la lambda onClickDelete avec la tâche actuelle
listener.onClickDelete(currentTask)
}
holder.itemView.findViewById<ImageButton>(R.id.edit_task_button).setOnClickListener {
// Appel de la lambda onClickDelete avec la tâche actuelle
listener.onClickEdit(currentTask)
}
}
}
| todoRepository/app/src/main/java/com/example/toDoMariem/list/TaskListAdapter.kt | 2781305812 |
package com.example.toDoMariem.data
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
object Api {
private const val TOKEN = "6a4aa7f546e7db84f52dd7c57577f33ef06b6b34"
private val retrofit by lazy {
// client HTTP
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.addInterceptor { chain ->
// intercepteur qui ajoute le `header` d'authentification avec votre token:
val newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $TOKEN")
.build()
chain.proceed(newRequest)
}
.build()
// transforme le JSON en objets kotlin et inversement
val jsonSerializer = Json {
ignoreUnknownKeys = true
coerceInputValues = true
}
// instance retrofit pour implémenter les webServices:
Retrofit.Builder()
.baseUrl("https://api.todoist.com/")
.client(okHttpClient)
.addConverterFactory(jsonSerializer.asConverterFactory("application/json".toMediaType()))
.build()
}
val userWebService : UserWebService by lazy {
retrofit.create(UserWebService::class.java)
}
val tasksWebService : TasksWebService by lazy {
retrofit.create(TasksWebService::class.java)
}
} | todoRepository/app/src/main/java/com/example/toDoMariem/data/Api.kt | 4013179133 |
package com.example.toDoMariem.data
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.toDoMariem.Task
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.util.Collections.emptyList
class TasksListViewModel : ViewModel() {
private val webService = Api.tasksWebService
public val tasksStateFlow = MutableStateFlow<List<Task>>(emptyList())
fun refresh() {
viewModelScope.launch {
val response = webService.fetchTasks() // Call HTTP (opération longue)
if (!response.isSuccessful) { // à cette ligne, on a reçu la réponse de l'API
Log.e("Network", "Error: ${response.message()}")
return@launch
}
val fetchedTasks = response.body()!!
tasksStateFlow.value = fetchedTasks // on modifie le flow, ce qui déclenche ses observer
}
}
fun update(task: Task) {
viewModelScope.launch {
val response = webService.update(task)
if (!response.isSuccessful) {
Log.e("Network", "Error: ${response.raw()}")
return@launch
}
val updatedTask = response.body()!!
val updatedList = tasksStateFlow.value.map {
if (it.id == updatedTask.id) updatedTask else it
}
tasksStateFlow.value = updatedList
}
}
// Suppression d'une tâche sur le serveur
fun delete(task: Task) {
viewModelScope.launch {
val response = task?.id?.let { webService.delete(it) }
if (!response?.isSuccessful!!) {
// Gestion des erreurs
return@launch
}
val updatedList = tasksStateFlow.value.filterNot { it.id == task.id }
tasksStateFlow.value = updatedList
}
}
// Ajout d'une nouvelle tâche sur le serveur
fun add(task: Task) {
viewModelScope.launch {
val response = webService.create(task)
if (!response.isSuccessful) {
return@launch
}
val createdTask = response.body() ?: return@launch
val updatedList = tasksStateFlow.value + createdTask
tasksStateFlow.value = updatedList
}
}
} | todoRepository/app/src/main/java/com/example/toDoMariem/data/TasksListViewModel.kt | 2255631671 |
package com.example.toDoMariem.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import okhttp3.MultipartBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Multipart
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.Part
interface UserWebService {
@Multipart
@POST("sync/v9/update_avatar")
suspend fun updateAvatar(@Part avatar: MultipartBody.Part): Response<User>
@GET("/sync/v9/user/")
suspend fun fetchUser(): Response<User>
@PATCH("sync/v9/sync")
suspend fun update(@Body userUpdate: UserUpdate): Response<Unit>
}
@Serializable
data class UserUpdate(
@SerialName("full_name") val name: String)
| todoRepository/app/src/main/java/com/example/toDoMariem/data/UserWebService.kt | 2680205789 |
package com.example.toDoMariem.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class User(
@SerialName("email")
val email: String,
@SerialName("full_name")
var name: String,
@SerialName("avatar_medium")
val avatar: String? = null
)
| todoRepository/app/src/main/java/com/example/toDoMariem/data/User.kt | 2436657421 |
package com.example.toDoMariem.data
import com.example.toDoMariem.Task
import retrofit2.Response
import retrofit2.http.*
interface TasksWebService {
@GET("/rest/v2/tasks/")
suspend fun fetchTasks(): Response<List<Task>>
@POST("/rest/v2/tasks/")
suspend fun create(@Body task: Task): Response<Task>
@POST("/rest/v2/tasks/{id}")
suspend fun update(@Body task: Task, @Path("id") id: String? = task.id): Response<Task>
@DELETE("/rest/v2/tasks/{id}")
suspend fun delete(@Path("id") id: String): Response<Unit>
} | todoRepository/app/src/main/java/com/example/toDoMariem/data/TasksWebService.kt | 4111207129 |
package com.example.myapplication
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.myapplication", appContext.packageName)
}
} | MobileAppsProject/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
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)
}
} | MobileAppsProject/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.repository.CountryRepository
import com.example.myapplication.repository.UiState
import com.example.myapplication.repository.model.CountryResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
private val countryRepository = CountryRepository()
private val mutableCountriesData = MutableLiveData<UiState<List<CountryResponse>>>()
val immutableCountriesData: LiveData<UiState<List<CountryResponse>>> = mutableCountriesData
fun getData() {
viewModelScope.launch(Dispatchers.IO) {
try {
val request = countryRepository.getCountryResponse()
Log.d("com.example.myapplication.MainViewModel", "request: ${request.raw()}")
if(request.isSuccessful){
request.message()
val countries = request.body()
Log.d("com.example.myapplication.MainViewModel", "Request body: $countries")
mutableCountriesData.postValue(UiState(countries))
}
} catch (e: Exception) {
Log.e("com.example.myapplication.MainViewModel", "Operacja nie powiodla sie $e", e)
}
}
}
}
| MobileAppsProject/app/src/main/java/com/example/myapplication/MainViewModel.kt | 2461412795 |
package com.example.myapplication.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) | MobileAppsProject/app/src/main/java/com/example/myapplication/ui/theme/Color.kt | 2513741509 |
package com.example.myapplication.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 MyApplicationTheme(
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
)
} | MobileAppsProject/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt | 1455779958 |
package com.example.myapplication.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
)
*/
) | MobileAppsProject/app/src/main/java/com/example/myapplication/ui/theme/Type.kt | 3144575447 |
package com.example.myapplication.repository
data class UiState<T>(
val data: T? = null,
val isLoading: Boolean = false,
val error: String? = null
) | MobileAppsProject/app/src/main/java/com/example/myapplication/repository/UiState.kt | 2224021807 |
package com.example.myapplication.repository
import com.example.myapplication.repository.model.Country
import com.example.myapplication.repository.model.CountryResponse
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
interface CountryService {
@GET("all")
suspend fun getCountryResponse(): Response<List<CountryResponse>>
@GET("name/{name}")
suspend fun getCountryDetailsResponse(@Path("name") name: String): Response<List<Country>>
companion object {
private const val COUNTRIES_URL = "https://restcountries.com/v3.1/"
private val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(COUNTRIES_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val countryService: CountryService by lazy {
retrofit.create(CountryService::class.java)
}
}
} | MobileAppsProject/app/src/main/java/com/example/myapplication/repository/CountryService.kt | 1217765943 |
package com.example.myapplication.repository.model
data class Country(
val name: Name,
val region: String,
val area: Int,
val flags: Flag
)
data class Name(
val common: String,
val official: String
)
| MobileAppsProject/app/src/main/java/com/example/myapplication/repository/model/Country.kt | 3605774902 |
package com.example.myapplication.repository.model
data class CountryResponse(
val name: Name,
val independent: String,
val unMember: String,
val capital: List<String>,
val flags: Flag
)
data class Flag(
val png: String
)
| MobileAppsProject/app/src/main/java/com/example/myapplication/repository/model/CountryResponse.kt | 1663954910 |
package com.example.myapplication.repository
import com.example.myapplication.repository.model.Country
import com.example.myapplication.repository.model.CountryResponse
import retrofit2.Response
import retrofit2.http.Path
class CountryRepository {
suspend fun getCountryResponse(): Response<List<CountryResponse>> =
CountryService.countryService.getCountryResponse()
suspend fun getCountryDetailsResponse(name: String): Response<List<Country>> =
CountryService.countryService.getCountryDetailsResponse(name)
} | MobileAppsProject/app/src/main/java/com/example/myapplication/repository/CountryRepository.kt | 3960894763 |
package com.example.myapplication
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.example.myapplication.repository.UiState
import com.example.myapplication.repository.model.CountryResponse
import com.example.myapplication.repository.model.Flag
import com.example.myapplication.repository.model.Name
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
viewModel.getData()
MainView(viewModel = viewModel, onClick = {name -> navigateToCountryDetailsActivity(name)})
}
}
private fun navigateToCountryDetailsActivity(name: String) {
val detailsIntent = Intent(this, CountryDetailsActivity::class.java)
detailsIntent.putExtra("CUSTOM_NAME", name)
startActivity(detailsIntent)
}
}
@Composable
fun MainView(viewModel: MainViewModel, onClick: (String) -> Unit) {
val uiState by viewModel.immutableCountriesData.observeAsState(UiState())
when {
uiState.isLoading -> { MyLoadingView() }
uiState.error != null -> { MyErrorView() }
uiState.data != null -> { uiState.data?.let { MyListView(countries = it, onClick) } }
}
}
@Composable
fun CountryView(name: Name, independent: String, flag: Flag, capital: List<String>, onClick: (String) -> Unit) {
Column (modifier=Modifier
.padding(10.dp)
.background(Color(87, 163, 235), RoundedCornerShape(15.dp))
.border(BorderStroke(1.dp, Color.Transparent), RoundedCornerShape(15.dp))
.clickable { onClick.invoke(name.common) }
){
Text(text = name.common, fontSize = 20.sp, fontWeight = FontWeight(1000),
modifier = Modifier.offset(10.dp), color = Color(255, 255, 255))
Row(modifier = Modifier.padding(15.dp).fillMaxWidth()
, horizontalArrangement = Arrangement.SpaceBetween) {
Column {
Text(text = "Capital: ${capital[0]}", fontWeight = FontWeight(500), color = Color(255, 255, 255))
Text(text = "Independence: $independent", fontWeight = FontWeight(500), color = Color(255, 255, 255))
}
AsyncImage(
model = flag.png,
contentDescription = "Flaga ${name.common}"
)
}
}
}
@Composable
fun MyErrorView() {
Log.d("Country", "ERROR")
}
@Composable
fun MyLoadingView() {
Text(text = "Loading")
}
@Composable
fun MyListView(countries: List<CountryResponse>, onClick: (String) -> Unit) {
Column (modifier = Modifier.background(Color(232,244,253))){
LazyColumn{
items(countries) { country ->
CountryView(name = country.name, independent = country.independent, flag = country.flags, capital = country.capital, onClick = {name -> onClick.invoke(name)})
}
}
}
}
| MobileAppsProject/app/src/main/java/com/example/myapplication/MainActivity.kt | 2105415883 |
package com.example.myapplication
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.repository.CountryRepository
import com.example.myapplication.repository.UiState
import com.example.myapplication.repository.model.Country
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class CountryDetailsViewModel : ViewModel() {
private val countryRepository = CountryRepository()
private val mutableCountryDetailsData = MutableLiveData<UiState<Country>>()
val immutableCountryDetailsData: LiveData<UiState<Country>> = mutableCountryDetailsData
fun getData(name: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
val request = countryRepository.getCountryDetailsResponse(name)
if(request.isSuccessful){
request.message()
val countryDetails = request.body()
mutableCountryDetailsData.postValue(UiState(countryDetails?.get(0)))
}
} catch (e: Exception) {
Log.e("CountryDetailsViewModel", "Operacja nie powiodla sie $e", e)
}
}
}
} | MobileAppsProject/app/src/main/java/com/example/myapplication/CountryDetailsViewModel.kt | 1393633133 |
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.myapplication.repository.UiState
import com.example.myapplication.repository.model.Country
class CountryDetailsActivity : ComponentActivity() {
private val viewModel: CountryDetailsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val name = intent.getStringExtra("CUSTOM_NAME")
setContent {
viewModel.getData("$name")
CountryDetailsView(viewModel = viewModel)
}
}
}
@Composable
fun CountryDetailsView(viewModel: CountryDetailsViewModel) {
val uiState by viewModel.immutableCountryDetailsData.observeAsState(UiState())
when {
uiState.isLoading -> { MyLoadingView() }
uiState.error != null -> { MyErrorView() }
uiState.data != null -> { uiState.data?.let { CountryView(country = it) } }
}
}
@Composable
fun CountryView(country: Country) {
Column (horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(top = 10.dp)
.background(Color(232,244,253))
){
AsyncImage(
model = country.flags.png,
contentDescription = "Flaga ${country.name.common}",
modifier = Modifier.wrapContentSize(Alignment.TopEnd)
)
CountryDetailsRow("Country (Official Name)", country.name.official)
CountryDetailsRow("Country (Common Name)", country.name.common)
CountryDetailsRow("Region", country.region)
CountryDetailsRow("Area", "${country.area}")
}
}
@Composable
fun CountryDetailsRow(textDescription: String, data: String){
Row(modifier = Modifier
.padding(15.dp)
.border(BorderStroke(1.dp, Color.Transparent), RoundedCornerShape(12.dp))
.fillMaxWidth()
.background(Color(87, 163, 235), RoundedCornerShape(15.dp))
.padding(15.dp)
) {
Text(text = "$textDescription: $data", color = Color(255, 255, 255))
}
}
| MobileAppsProject/app/src/main/java/com/example/myapplication/CountryDetailsActivity.kt | 3402663746 |
package com.example.basiclogin
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.basiclogin", appContext.packageName)
}
} | Proyecto1prueba/app/src/androidTest/java/com/example/basiclogin/ExampleInstrumentedTest.kt | 856507566 |
package com.example.basiclogin
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)
}
} | Proyecto1prueba/app/src/test/java/com/example/basiclogin/ExampleUnitTest.kt | 868780210 |
package com.example.basiclogin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class Activity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_2)
val tv_welcome = findViewById<TextView>(R.id.tv_wel)
val userName = intent.getStringExtra("user")
val sharedPref = this.getSharedPreferences("MySharedPrefer", MODE_PRIVATE)
val nickname = sharedPref.getString("nickname", "")
tv_welcome.append(" " + nickname)
}
} | Proyecto1prueba/app/src/main/java/com/example/basiclogin/Activity2.kt | 2359282589 |
package com.example.basiclogin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnIS = findViewById<Button>(R.id.buttonIS)
val ptUser = findViewById<EditText>(R.id.pt_user)
val ptPassword = findViewById<EditText>(R.id.pt_password)
val ptNickname = findViewById<EditText>(R.id.pt_nickname)
btnIS.setOnClickListener {
val user = ptUser.text.toString()
val password = ptPassword.text.toString()
val nickname = ptNickname.text.toString()
if (user == "Eduardo") {
if (password == "1234") {
val intent = Intent(this, Activity2::class.java)
intent.putExtra("user", user)
val sharedPref = this.getSharedPreferences("MySharedPrefer", MODE_PRIVATE)
with (sharedPref.edit()) {
putString("nickname", nickname)
apply()
}
startActivity(intent)
} else {
Toast.makeText(this, "Contraseña incorrecta", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Nombre incorrecto", Toast.LENGTH_SHORT).show()
}
}
}
} | Proyecto1prueba/app/src/main/java/com/example/basiclogin/MainActivity.kt | 3565961394 |
package com.ralugan.raluganplus
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.ralugan.raluganplus", appContext.packageName)
}
} | raluganplus/app/src/androidTest/java/com/ralugan/raluganplus/ExampleInstrumentedTest.kt | 674876908 |
package com.ralugan.raluganplus
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)
}
} | raluganplus/app/src/test/java/com/ralugan/raluganplus/ExampleUnitTest.kt | 2248270684 |
package com.ralugan.raluganplus.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
} | raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/home/HomeViewModel.kt | 3250516857 |
package com.ralugan.raluganplus.ui.home
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.ralugan.raluganplus.ui.details.DetailsActivity
import com.ralugan.raluganplus.R
import com.ralugan.raluganplus.api.ApiClient
import com.ralugan.raluganplus.api.WikidataApi
import com.ralugan.raluganplus.databinding.FragmentStarwarsBinding
import com.ralugan.raluganplus.dataclass.RaluganPlus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Response
class StarWarsFragment : Fragment() {
private var _binding: FragmentStarwarsBinding? = null
private val binding get() = _binding!!
private lateinit var auth: FirebaseAuth
private val wikidataApi: WikidataApi = ApiClient.getWikidataApi()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentStarwarsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
auth = FirebaseAuth.getInstance()
super.onViewCreated(view, savedInstanceState)
val sparqlQuery = """
SELECT ?itemLabel ?pic
WHERE {
{
?filmItem wdt:P1476 ?itemLabel. # Title
?filmItem wdt:P31 wd:Q11424. # Film
?filmItem wdt:P750 wd:Q54958752. # Platform = Disney+
?filmItem wdt:P272 wd:Q242446. # LucasFilm
OPTIONAL {
?filmItem wdt:P154 ?pic.
}
}
UNION
{
?seriesItem wdt:P1476 ?itemLabel. # Title
?seriesItem wdt:P31 wd:Q5398426. # Television series
?seriesItem wdt:P750 wd:Q54958752. # Platform = Disney+
?seriesItem wdt:P272 wd:Q242446. # LucasFilm
OPTIONAL {
?seriesItem wdt:P154 ?pic.
}
}
}
ORDER BY DESC (?pic)
""".trimIndent()
// Appel de l'API dans une coroutine
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
activity?.runOnUiThread {
handleApiResponse(response)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
binding.textSearch.setOnClickListener {
val clickedTitle = binding.textSearch.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
private fun handleApiResponse(response: Response<ResponseBody>) {
val linearLayout = binding.linearLayout
// Effacer les résultats précédents
linearLayout.removeAllViews()
if (response.isSuccessful) {
try {
val jsonResult = JSONObject(response.body()?.string())
if (jsonResult.has("results")) {
val results = jsonResult.getJSONObject("results")
val bindings = results.getJSONArray("bindings")
if (bindings.length() > 0) {
for (i in 0 until bindings.length()) {
val binding = bindings.getJSONObject(i)
val itemLabel = binding.getJSONObject("itemLabel").getString("value")
// Créer un TextView pour le titre
val titleTextView = TextView(requireContext())
titleTextView.text = itemLabel
val imageView = ImageView(requireContext())
// Créer un ImageView pour l'image
if (binding.has("pic")) {
val imageUrl = binding.getJSONObject("pic").getString("value").replace("http://", "https://")
// Utiliser Glide pour charger l'image dans l'ImageView
Glide.with(this)
.load(imageUrl)
.error(R.drawable.ralugan)
.into(imageView)
// Ajouter le TextView et ImageView au LinearLayout
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
val heartButton = ImageButton(requireContext())
heartButton.setImageResource(R.drawable.ic_coeur) // Remplacez "ic_coeur" par le nom de votre image de cœur
heartButton.setOnClickListener {
// Ajouter le film à la liste des favoris de l'utilisateur
addMovieToFavorites(auth.currentUser?.uid, itemLabel, imageUrl)
}
linearLayout.addView(heartButton)
} else {
Glide.with(this)
.load(R.drawable.ralugan)
.into(imageView)
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
}
// Set an ID for the TextView to capture click event
titleTextView.id = View.generateViewId()
// Set click listener for the TextView
titleTextView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
imageView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} catch (e: JSONException) {
linearLayout.addView(createTextView("Erreur de traitement JSON"))
Log.e("SearchFragment", "JSON parsing error: ${e.message}")
}
} else {
linearLayout.addView(createTextView("Erreur de chargement des données"))
Log.e("SearchFragment", "API call failed with code: ${response.code()}")
// ... (rest of the error handling)
}
}
private fun createTextView(text: String): TextView {
val textView = TextView(requireContext())
textView.text = text
textView.isClickable = true
textView.isFocusable = true
return textView
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun addMovieToFavorites(uid: String?, movieTitle: String, movieImageUrl: String) {
if (uid != null) {
// Vérifier si le film est déjà dans la liste des favoris
isMovieInFavorites(uid, movieTitle) { isAlreadyInFavorites ->
if (isAlreadyInFavorites) {
Log.d("star wars", "$isAlreadyInFavorites")
// Afficher un message indiquant que le film est déjà dans les favoris
Toast.makeText(
requireContext(),
"Le film est déjà dans la liste des favoris",
Toast.LENGTH_SHORT
).show()
} else {
// Ajouter le film à la liste des favoris
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
val newFavorite = RaluganPlus(movieTitle, movieImageUrl)
usersRef.push().setValue(newFavorite)
.addOnCompleteListener { dbTask ->
if (dbTask.isSuccessful) {
// Succès de l'ajout du film aux favoris
Toast.makeText(
requireContext(),
"Film ajouté aux favoris avec succès",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
requireContext(),
"Erreur lors de l'ajout du film aux favoris",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
private fun isMovieInFavorites(uid: String?, movieTitle: String, onComplete: (Boolean) -> Unit) {
if (uid != null) {
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
usersRef.orderByChild("title").equalTo(movieTitle)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
onComplete(dataSnapshot.exists())
}
override fun onCancelled(databaseError: DatabaseError) {
// Gérer l'erreur
onComplete(false)
}
})
} else {
onComplete(false)
}
}
} | raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/home/StarWarsFragment.kt | 819978116 |
package com.ralugan.raluganplus.ui.home
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.ralugan.raluganplus.ui.details.DetailsActivity
import com.ralugan.raluganplus.R
import com.ralugan.raluganplus.api.ApiClient
import com.ralugan.raluganplus.api.WikidataApi
import com.ralugan.raluganplus.databinding.FragmentMarvelBinding
import com.ralugan.raluganplus.dataclass.RaluganPlus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Response
class MarvelFragment : Fragment() {
private var _binding: FragmentMarvelBinding? = null
private val binding get() = _binding!!
private lateinit var auth: FirebaseAuth
private val wikidataApi: WikidataApi = ApiClient.getWikidataApi()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMarvelBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
auth = FirebaseAuth.getInstance()
super.onViewCreated(view, savedInstanceState)
val sparqlQuery = """
SELECT ?itemLabel ?pic
WHERE {
{
?filmItem wdt:P1476 ?itemLabel. # Title
?filmItem wdt:P31 wd:Q11424. # Film
?filmItem wdt:P750 wd:Q54958752. # Platform = Disney+
?filmItem wdt:P272 wd:Q367466. # Marvel Studios
OPTIONAL {
?filmItem wdt:P154 ?pic.
}
}
UNION
{
?seriesItem wdt:P1476 ?itemLabel. # Title
?seriesItem wdt:P31 wd:Q5398426. # Television series
?seriesItem wdt:P750 wd:Q54958752. # Platform = Disney+
?seriesItem wdt:P272 wd:Q367466. # Marvel Studios
OPTIONAL {
?seriesItem wdt:P154 ?pic.
}
}
}
ORDER BY DESC (?pic)
""".trimIndent()
// Appel de l'API dans une coroutine
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
activity?.runOnUiThread {
handleApiResponse(response)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
binding.textSearch.setOnClickListener {
val clickedTitle = binding.textSearch.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
private fun handleApiResponse(response: Response<ResponseBody>) {
val linearLayout = binding.linearLayout
// Effacer les résultats précédents
linearLayout.removeAllViews()
if (response.isSuccessful) {
try {
val jsonResult = JSONObject(response.body()?.string())
if (jsonResult.has("results")) {
val results = jsonResult.getJSONObject("results")
val bindings = results.getJSONArray("bindings")
if (bindings.length() > 0) {
for (i in 0 until bindings.length()) {
val binding = bindings.getJSONObject(i)
val itemLabel = binding.getJSONObject("itemLabel").getString("value")
// Créer un TextView pour le titre
val titleTextView = TextView(requireContext())
titleTextView.text = itemLabel
val imageView = ImageView(requireContext())
// Créer un ImageView pour l'image
if (binding.has("pic")) {
val imageUrl = binding.getJSONObject("pic").getString("value").replace("http://", "https://")
// Utiliser Glide pour charger l'image dans l'ImageView
Glide.with(this)
.load(imageUrl)
.error(R.drawable.ralugan)
.into(imageView)
// Ajouter le TextView et ImageView au LinearLayout
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
val heartButton = ImageButton(requireContext())
heartButton.setImageResource(R.drawable.ic_coeur) // Remplacez "ic_coeur" par le nom de votre image de cœur
heartButton.setOnClickListener {
// Ajouter le film à la liste des favoris de l'utilisateur
addMovieToFavorites(auth.currentUser?.uid, itemLabel, imageUrl)
}
linearLayout.addView(heartButton)
} else {
Glide.with(this)
.load(R.drawable.ralugan)
.into(imageView)
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
}
// Set an ID for the TextView to capture click event
titleTextView.id = View.generateViewId()
// Set click listener for the TextView
titleTextView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
imageView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} catch (e: JSONException) {
linearLayout.addView(createTextView("Erreur de traitement JSON"))
Log.e("SearchFragment", "JSON parsing error: ${e.message}")
}
} else {
linearLayout.addView(createTextView("Erreur de chargement des données"))
Log.e("SearchFragment", "API call failed with code: ${response.code()}")
// ... (rest of the error handling)
}
}
private fun createTextView(text: String): TextView {
val textView = TextView(requireContext())
textView.text = text
textView.isClickable = true
textView.isFocusable = true
return textView
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun addMovieToFavorites(uid: String?, movieTitle: String, movieImageUrl: String) {
if (uid != null) {
// Vérifier si le film est déjà dans la liste des favoris
isMovieInFavorites(uid, movieTitle) { isAlreadyInFavorites ->
if (isAlreadyInFavorites) {
Log.d("star wars", "$isAlreadyInFavorites")
// Afficher un message indiquant que le film est déjà dans les favoris
Toast.makeText(
requireContext(),
"Le film est déjà dans la liste des favoris",
Toast.LENGTH_SHORT
).show()
} else {
// Ajouter le film à la liste des favoris
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
val newFavorite = RaluganPlus(movieTitle, movieImageUrl)
usersRef.push().setValue(newFavorite)
.addOnCompleteListener { dbTask ->
if (dbTask.isSuccessful) {
// Succès de l'ajout du film aux favoris
Toast.makeText(
requireContext(),
"Film ajouté aux favoris avec succès",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
requireContext(),
"Erreur lors de l'ajout du film aux favoris",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
private fun isMovieInFavorites(uid: String?, movieTitle: String, onComplete: (Boolean) -> Unit) {
if (uid != null) {
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
usersRef.orderByChild("title").equalTo(movieTitle)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
onComplete(dataSnapshot.exists())
}
override fun onCancelled(databaseError: DatabaseError) {
// Gérer l'erreur
onComplete(false)
}
})
} else {
onComplete(false)
}
}
} | raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/home/MarvelFragment.kt | 2228340069 |
package com.ralugan.raluganplus.ui.home
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.ralugan.raluganplus.R
import com.ralugan.raluganplus.api.ApiClient
import com.ralugan.raluganplus.api.WikidataApi
import com.ralugan.raluganplus.databinding.FragmentHomeBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Response
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.ralugan.raluganplus.ui.details.DetailsActivity
import kotlinx.coroutines.withContext
import org.json.JSONException
import org.json.JSONObject
import androidx.viewpager2.widget.ViewPager2
class HomeFragment<YourResponseType : Any?> : Fragment() {
private var _binding: FragmentHomeBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
private val wikidataApi: WikidataApi = ApiClient.getWikidataApi()
private lateinit var horizontalLinearLayout: LinearLayout
private lateinit var horizontalLinearLayout2: LinearLayout
private lateinit var horizontalLinearLayout3: LinearLayout
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_home, container, false)
horizontalLinearLayout = rootView.findViewById(R.id.horizontalLinearLayout)
horizontalLinearLayout2 = rootView.findViewById(R.id.horizontalLinearLayout2)
horizontalLinearLayout3 = rootView.findViewById(R.id.horizontalLinearLayout3)
nouveauSurRaluganPlus()
Drama()
Crime()
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val disneyButton = view.findViewById<ImageButton>(R.id.customButtonDisney)
val marvelButton = view.findViewById<ImageButton>(R.id.customButtonMarvel)
val starWarsButton = view.findViewById<ImageButton>(R.id.customButton4)
val pixarButton = view.findViewById<ImageButton>(R.id.customButton2)
val natGeoButton = view.findViewById<ImageButton>(R.id.customButton7)
val starplusButton = view.findViewById<ImageButton>(R.id.customButtonStar)
disneyButton.setOnClickListener {
findNavController().navigate(R.id.navigation_disney)
}
marvelButton.setOnClickListener {
findNavController().navigate(R.id.navigation_marvel)
}
starWarsButton.setOnClickListener {
findNavController().navigate(R.id.navigation_starwars)
}
pixarButton.setOnClickListener {
showUnderConstructionDialog()
}
natGeoButton.setOnClickListener {
showUnderConstructionDialog()
}
starplusButton.setOnClickListener {
showUnderConstructionDialog()
}
nouveauSurRaluganPlus()
}
private fun nouveauSurRaluganPlus() {
val sparqlQuery = """
SELECT ?itemLabel ?pic ?date
WHERE {
?item wdt:P1476 ?itemLabel. # Title
?item wdt:P580 ?date.
#?item wdt:P31 wd:Q11424. # Film
?item wdt:P31 wd:Q5398426. # Television series
?item wdt:P750 wd:Q54958752. # Platform = Disney+
OPTIONAL{
?item wdt:P154 ?pic.
}
}
ORDER BY DESC(BOUND(?pic)) DESC(?date)
LIMIT 14
""".trimIndent()
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
withContext(Dispatchers.Main) {
handleApiResponse(response, horizontalLinearLayout)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
}
private fun Drama() {
val sparqlQuery = """
SELECT ?itemLabel ?pic
WHERE {
?item wdt:P1476 ?itemLabel. # Title
?item wdt:P136 wd:Q1366112. # GenreDrama
#?item wdt:P31 wd:Q11424. # Film
?item wdt:P31 wd:Q5398426. # Television series
?item wdt:P750 wd:Q54958752. # Platform = Disney+
OPTIONAL{
?item wdt:P154 ?pic.
}
}
ORDER BY DESC (?pic)
LIMIT 15
""".trimIndent()
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
withContext(Dispatchers.Main) {
handleApiResponse(response, horizontalLinearLayout2)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
}
private fun Crime() {
val sparqlQuery = """
SELECT ?itemLabel ?pic
WHERE {
?item wdt:P1476 ?itemLabel. # Title
?item wdt:P136 wd:Q9335577. # GenreDrama
#?item wdt:P31 wd:Q11424. # Film
?item wdt:P31 wd:Q5398426. # Television series
?item wdt:P750 wd:Q54958752. # Platform = Disney+
OPTIONAL{
?item wdt:P154 ?pic.
}
}
ORDER BY DESC (?pic)
LIMIT 30
""".trimIndent()
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
withContext(Dispatchers.Main) {
handleApiResponse(response, horizontalLinearLayout3)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
}
private fun handleApiResponse(response: Response<ResponseBody>, horizontalLinearLayout: LinearLayout) {
// Effacer les résultats précédents
horizontalLinearLayout.removeAllViews()
if (response.isSuccessful) {
try {
val jsonResult = JSONObject(response.body()?.string())
if (jsonResult.has("results")) {
val results = jsonResult.getJSONObject("results")
val bindings = results.getJSONArray("bindings")
if (bindings.length() > 0) {
for (i in 0 until bindings.length()) {
val binding = bindings.getJSONObject(i)
val itemLabel = binding.getJSONObject("itemLabel").getString("value")
// Créer un TextView pour le titre
val titleTextView = TextView(requireContext())
titleTextView.text = itemLabel
val imageView = ImageView(requireContext())
// Créer un ImageView pour l'image
if (binding.has("pic")) {
val imageUrl = binding.getJSONObject("pic").getString("value").replace("http://", "https://")
// Utiliser Glide pour charger l'image dans l'ImageView
Glide.with(requireContext())
.load(imageUrl)
.override(500, 500) // Remplacez 300 par la taille souhaitée en pixels
.into(imageView)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.rightMargin = 10 // Ajustez cette valeur en fonction de l'espace souhaité
// Ajouter le TextView et ImageView à la disposition horizontale avec les marges
horizontalLinearLayout.addView(imageView, params)
}
// Set an ID for the TextView to capture click event
titleTextView.id = View.generateViewId()
// Set click listener for the TextView
titleTextView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
imageView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
} else {
horizontalLinearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} else {
horizontalLinearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} catch (e: JSONException) {
horizontalLinearLayout.addView(createTextView("Erreur de traitement JSON"))
Log.e("SearchFragment", "JSON parsing error: ${e.message}")
}
} else {
horizontalLinearLayout.addView(createTextView("Erreur de chargement des données"))
Log.e("SearchFragment", "API call failed with code: ${response.code()}")
// ... (rest of the error handling)
}
}
private fun createTextView(text: String): TextView {
val textView = TextView(requireContext())
textView.text = text
textView.isClickable = true
textView.isFocusable = true
return textView
}
private fun showUnderConstructionDialog() {
// Créez une boîte de dialogue (AlertDialog) pour afficher le message "En construction"
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("En cours de construction")
builder.setMessage("Nous travaillons sur cette fonctionnalité. Revenez bientôt pour les dernières mises à jour !")
builder.setPositiveButton("OK") { dialog, _ ->
dialog.dismiss()
}
// Affichez la boîte de dialogue
val dialog = builder.create()
dialog.show()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/home/HomeFragment.kt | 529956398 |
package com.ralugan.raluganplus.ui.home
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.ralugan.raluganplus.ui.details.DetailsActivity
import com.ralugan.raluganplus.R
import com.ralugan.raluganplus.api.ApiClient
import com.ralugan.raluganplus.api.WikidataApi
import com.ralugan.raluganplus.databinding.FragmentDisneyBinding
import com.ralugan.raluganplus.dataclass.RaluganPlus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Response
class DisneyFragment : Fragment() {
private var _binding: FragmentDisneyBinding? = null
private val binding get() = _binding!!
private lateinit var auth: FirebaseAuth
private val wikidataApi: WikidataApi = ApiClient.getWikidataApi()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentDisneyBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
auth = FirebaseAuth.getInstance()
super.onViewCreated(view, savedInstanceState)
val sparqlQuery = """
SELECT ?itemLabel ?pic
WHERE {
{
?filmItem wdt:P1476 ?itemLabel. # Title
?filmItem wdt:P31 wd:Q11424. # Film
?filmItem wdt:P750 wd:Q54958752. # Platform = Disney+
?filmItem wdt:P272 wd:Q191224. # Disney
OPTIONAL {
?filmItem wdt:P154 ?pic.
}
}
UNION
{
?seriesItem wdt:P1476 ?itemLabel. # Title
?seriesItem wdt:P31 wd:Q5398426. # Television series
?seriesItem wdt:P750 wd:Q54958752. # Platform = Disney+
?seriesItem wdt:P272 wd:Q191224. # Disney
OPTIONAL {
?seriesItem wdt:P154 ?pic.
}
}
}
ORDER BY DESC (?pic)
""".trimIndent()
// Appel de l'API dans une coroutine
CoroutineScope(Dispatchers.IO).launch {
try {
val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute()
activity?.runOnUiThread {
handleApiResponse(response)
}
} catch (e: Exception) {
// Gérer l'exception
}
}
binding.textSearch.setOnClickListener {
val clickedTitle = binding.textSearch.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
private fun handleApiResponse(response: Response<ResponseBody>) {
val linearLayout = binding.linearLayout
// Effacer les résultats précédents
linearLayout.removeAllViews()
if (response.isSuccessful) {
try {
val jsonResult = JSONObject(response.body()?.string())
if (jsonResult.has("results")) {
val results = jsonResult.getJSONObject("results")
val bindings = results.getJSONArray("bindings")
if (bindings.length() > 0) {
for (i in 0 until bindings.length()) {
val binding = bindings.getJSONObject(i)
val itemLabel = binding.getJSONObject("itemLabel").getString("value")
// Créer un TextView pour le titre
val titleTextView = TextView(requireContext())
titleTextView.text = itemLabel
val imageView = ImageView(requireContext())
// Créer un ImageView pour l'image
if (binding.has("pic")) {
val imageUrl = binding.getJSONObject("pic").getString("value").replace("http://", "https://")
// Utiliser Glide pour charger l'image dans l'ImageView
Glide.with(this)
.load(imageUrl)
.error(R.drawable.ralugan)
.into(imageView)
// Ajouter le TextView et ImageView au LinearLayout
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
val heartButton = ImageButton(requireContext())
heartButton.setImageResource(R.drawable.ic_coeur) // Remplacez "ic_coeur" par le nom de votre image de cœur
heartButton.setOnClickListener {
// Ajouter le film à la liste des favoris de l'utilisateur
addMovieToFavorites(auth.currentUser?.uid, itemLabel, imageUrl)
}
linearLayout.addView(heartButton)
} else {
// Si "pic" n'existe pas, ajouter seulement le TextView
Glide.with(this)
.load(R.drawable.ralugan)
.into(imageView)
linearLayout.addView(titleTextView)
linearLayout.addView(imageView)
}
// Set an ID for the TextView to capture click event
titleTextView.id = View.generateViewId()
// Set click listener for the TextView
titleTextView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
imageView.setOnClickListener {
val clickedTitle = titleTextView.text.toString()
// Create an Intent to start the new activity
val intent = Intent(requireContext(), DetailsActivity::class.java)
intent.putExtra("TITLE", clickedTitle)
// Start the activity
startActivity(intent)
}
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} else {
linearLayout.addView(createTextView("Aucun résultat trouvé"))
}
} catch (e: JSONException) {
linearLayout.addView(createTextView("Erreur de traitement JSON"))
Log.e("SearchFragment", "JSON parsing error: ${e.message}")
}
} else {
linearLayout.addView(createTextView("Erreur de chargement des données"))
Log.e("SearchFragment", "API call failed with code: ${response.code()}")
// ... (rest of the error handling)
}
}
private fun createTextView(text: String): TextView {
val textView = TextView(requireContext())
textView.text = text
textView.isClickable = true
textView.isFocusable = true
return textView
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun addMovieToFavorites(uid: String?, movieTitle: String, movieImageUrl: String) {
if (uid != null) {
// Vérifier si le film est déjà dans la liste des favoris
isMovieInFavorites(uid, movieTitle) { isAlreadyInFavorites ->
if (isAlreadyInFavorites) {
Log.d("star wars", "$isAlreadyInFavorites")
// Afficher un message indiquant que le film est déjà dans les favoris
Toast.makeText(
requireContext(),
"Le film est déjà dans la liste des favoris",
Toast.LENGTH_SHORT
).show()
} else {
// Ajouter le film à la liste des favoris
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
val newFavorite = RaluganPlus(movieTitle, movieImageUrl)
usersRef.push().setValue(newFavorite)
.addOnCompleteListener { dbTask ->
if (dbTask.isSuccessful) {
// Succès de l'ajout du film aux favoris
Toast.makeText(
requireContext(),
"Film ajouté aux favoris avec succès",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
requireContext(),
"Erreur lors de l'ajout du film aux favoris",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
private fun isMovieInFavorites(uid: String?, movieTitle: String, onComplete: (Boolean) -> Unit) {
if (uid != null) {
val database = FirebaseDatabase.getInstance()
val usersRef = database.getReference("users").child(uid).child("listFavorite")
usersRef.orderByChild("title").equalTo(movieTitle)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
onComplete(dataSnapshot.exists())
}
override fun onCancelled(databaseError: DatabaseError) {
// Gérer l'erreur
onComplete(false)
}
})
} else {
onComplete(false)
}
}
} | raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/home/DisneyFragment.kt | 407744775 |
package com.ralugan.raluganplus.ui.details
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ralugan.raluganplus.R
class DetailsActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: DetailsAdapter
private lateinit var viewModel: DetailsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
// Récupérer le titre depuis l'Intent
val title = intent.getStringExtra("TITLE")
// Maintenant, vous pouvez utiliser le titre comme nécessaire dans votre DetailsActivity
Log.d("DetailsActivity", "Received title: $title")
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter = DetailsAdapter(emptyList())
recyclerView.adapter = adapter
val viewModelFactory = DetailsViewModelFactory(title ?: "")
viewModel = ViewModelProvider(this, viewModelFactory).get(DetailsViewModel::class.java)
viewModel.detailsItemList.observe(this, Observer {
adapter.updateData(it)
})
viewModel.fetchDetails()
}
}
| raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/details/DetailsActivity.kt | 2650039204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.