path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
Curso-Kotlin-Multiplatform/ActualExpected/composeApp/src/androidMain/kotlin/GetDeviceInformation.kt
2039460435
@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/Platform.android.kt
3472575554
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/com/aristidevs/actualexpected/MainActivity.kt
3648249597
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() }
todoRepository/app/src/androidTest/java/com/example/toDoMariem/ExampleInstrumentedTest.kt
988230763
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/test/java/com/example/toDoMariem/ExampleUnitTest.kt
2815499486
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/main/java/com/example/toDoMariem/dataTask.kt
3415064789
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/MainActivity.kt
1977621301
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/user/UserActivity.kt
3464709043
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/UserViewModel.kt
3363711480
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/detail/DetailActivity.kt
3095393607
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/list/TaskListListener.kt
2100363240
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/TaskListFragment.kt
554463294
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/TaskListAdapter.kt
2781305812
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/data/Api.kt
4013179133
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/TasksListViewModel.kt
2255631671
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/UserWebService.kt
2680205789
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/User.kt
2436657421
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/TasksWebService.kt
4111207129
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> }
MobileAppsProject/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
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/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
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/main/java/com/example/myapplication/MainViewModel.kt
2461412795
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/ui/theme/Color.kt
2513741509
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/Theme.kt
1455779958
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/Type.kt
3144575447
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/repository/UiState.kt
2224021807
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/CountryService.kt
1217765943
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/model/Country.kt
3605774902
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/CountryResponse.kt
1663954910
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/CountryRepository.kt
3960894763
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/MainActivity.kt
2105415883
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/CountryDetailsViewModel.kt
1393633133
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/CountryDetailsActivity.kt
3402663746
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)) } }
Proyecto1prueba/app/src/androidTest/java/com/example/basiclogin/ExampleInstrumentedTest.kt
856507566
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/test/java/com/example/basiclogin/ExampleUnitTest.kt
868780210
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/main/java/com/example/basiclogin/Activity2.kt
2359282589
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/MainActivity.kt
3565961394
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() } } } }
raluganplus/app/src/androidTest/java/com/ralugan/raluganplus/ExampleInstrumentedTest.kt
674876908
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/test/java/com/ralugan/raluganplus/ExampleUnitTest.kt
2248270684
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/main/java/com/ralugan/raluganplus/ui/home/HomeViewModel.kt
3250516857
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/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.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/MarvelFragment.kt
2228340069
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/HomeFragment.kt
529956398
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/DisneyFragment.kt
407744775
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/details/DetailsActivity.kt
2650039204
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/DetailsViewModelFactory.kt
2694700563
package com.ralugan.raluganplus.ui.details import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class DetailsViewModelFactory(private val title: String) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(DetailsViewModel::class.java)) { return DetailsViewModel(title) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/details/DetailsAdapter.kt
2097148730
package com.ralugan.raluganplus.ui.details import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.ralugan.raluganplus.R import com.ralugan.raluganplus.dataclass.DetailsItem class DetailsAdapter(private var detailsItemList: List<DetailsItem>) : RecyclerView.Adapter<DetailsAdapter.ViewHolder>() { class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val titleTextView: TextView = itemView.findViewById(R.id.titleTextView) val noteTextView: TextView = itemView.findViewById(R.id.noteTextView) val awardTextView: TextView = itemView.findViewById(R.id.awardTextView) val costTextView: TextView = itemView.findViewById(R.id.costTextView) val dateTextView: TextView = itemView.findViewById(R.id.dateTextView) val dirTextView: TextView = itemView.findViewById(R.id.dirTextView) val durationTextView: TextView = itemView.findViewById(R.id.durationTextView) val episodesTextView: TextView = itemView.findViewById(R.id.episodesTextView) val seasonsTextView: TextView = itemView.findViewById(R.id.seasonsTextView) val genreTextView: TextView = itemView.findViewById(R.id.genreTextView) val imageView: ImageView = itemView.findViewById(R.id.imageView) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.itemdetails, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val detailsItem = detailsItemList[position] holder.titleTextView.text = detailsItem.itemLabel holder.noteTextView.text = detailsItem.note holder.awardTextView.text = detailsItem.award holder.costTextView.text = detailsItem.cost holder.dateTextView.text = detailsItem.date holder.dirTextView.text = detailsItem.dir holder.durationTextView.text = detailsItem.duration holder.episodesTextView.text = detailsItem.episodes holder.seasonsTextView.text = detailsItem.seasons holder.genreTextView.text = detailsItem.genre detailsItem.pic?.let { Log.e("DetailsAdapter", it) } // Chargez l'image avec Glide (si l'URL de l'image n'est pas null) if (!detailsItem.pic.isNullOrBlank()) { Glide.with(holder.itemView.context) .load(detailsItem.pic) .error(R.drawable.ralugan) .into(holder.imageView) } else { Glide.with(holder.itemView.context) .load(R.drawable.ralugan) .into(holder.imageView) } } override fun getItemCount(): Int { return detailsItemList.size } fun updateData(newList: List<DetailsItem>) { detailsItemList = newList notifyDataSetChanged() } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/details/DetailsViewModel.kt
3045504462
package com.ralugan.raluganplus.ui.details import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.ralugan.raluganplus.api.ApiClient import com.ralugan.raluganplus.api.WikidataApi import com.ralugan.raluganplus.dataclass.DetailsItem import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.ResponseBody import org.json.JSONException import org.json.JSONObject import retrofit2.Response class DetailsViewModel(private val title: String) : ViewModel() { private val wikidataApi: WikidataApi = ApiClient.getWikidataApi() private val _detailsItemList = MutableLiveData<List<DetailsItem>>() val detailsItemList: LiveData<List<DetailsItem>> get() = _detailsItemList fun fetchDetails() { val sparqlQuery = """ SELECT ?itemLabel ?pic ?note ?award ?cost ?date ?dir ?duration ?episodes ?seasons ?genre WHERE { { ?seriesItem wdt:P1476 ?itemLabel. # Title ?seriesItem wdt:P2047 ?duration. ?seriesItem wdt:P57 ?dir. ?seriesItem wdt:P136 ?genre. ?seriesItem wdt:P31 wd:Q5398426. # Television series ?seriesItem wdt:P750 wd:Q54958752. # Platform = Disney+ FILTER(CONTAINS(UCASE(?itemLabel), UCASE('$title'))) OPTIONAL{ ?seriesItem wdt:P1113 ?episodes. # Episodes }. OPTIONAL{ ?seriesItem wdt:P2437 ?seasons. # Seasons }. OPTIONAL{ ?seriesItem wdt:P154 ?pic}. OPTIONAL{ ?seriesItem wdt:P1258 ?note}. OPTIONAL{ ?seriesItem wdt:P166 ?award}. OPTIONAL{ ?seriesItem wdt:P2130 ?cost}. OPTIONAL{ ?seriesItem wdt:P580 ?date}. } UNION { ?filmItem wdt:P1476 ?itemLabel. # Title ?filmItem wdt:P2047 ?duration. ?filmItem wdt:P57 ?dir. ?filmItem wdt:P136 ?genre. ?filmItem wdt:P31 wd:Q11424. # Film ?filmItem wdt:P750 wd:Q54958752. # Platform = Disney+ FILTER(CONTAINS(UCASE(?itemLabel), UCASE('$title'))) OPTIONAL{ ?filmItem wdt:P154 ?pic}. OPTIONAL{ ?filmItem wdt:P1258 ?note}. OPTIONAL{ ?filmItem wdt:P166 ?award}. OPTIONAL{ ?filmItem wdt:P2130 ?cost}. OPTIONAL{ ?filmItem wdt:P580 ?date}. } } ORDER BY DESC (?pic) """.trimIndent() // Appel de l'API dans une coroutine CoroutineScope(Dispatchers.IO).launch { try { val response = wikidataApi.getDisneyPlusInfo(sparqlQuery, "json").execute() // Utilisez Dispatchers.Main pour passer au thread principal withContext(Dispatchers.Main) { handleApiResponse(response) } } catch (e: Exception) { // Gérer l'exception } } } private fun handleApiResponse(response: Response<ResponseBody>) { if (response.isSuccessful) { try { val jsonResult = JSONObject(response.body()?.string()) if (jsonResult.has("results")) { val results = jsonResult.getJSONObject("results") val bindings = results.getJSONArray("bindings") val detailsItemList = mutableListOf<DetailsItem>() if (bindings.length() > 0) { val firstBinding = bindings.getJSONObject(0) // Récupérez le premier élément seulement val itemLabel = firstBinding.getJSONObject("itemLabel").optString("value", "N/A") val pic = firstBinding.optJSONObject("pic")?.optString("value", "N/A") val note = firstBinding.optJSONObject("note")?.optString("value", "N/A") val award = firstBinding.optJSONObject("award")?.optString("value", "N/A") val cost = firstBinding.optJSONObject("cost")?.optString("value", "N/A") val date = firstBinding.optJSONObject("date")?.optString("value", "N/A") val dir = firstBinding.optJSONObject("dir")?.optString("value", "N/A") val duration = firstBinding.optJSONObject("duration")?.optString("value", "N/A") val episodes = firstBinding.optJSONObject("episodes")?.optString("value", "N/A") val seasons = firstBinding.optJSONObject("seasons")?.optString("value", "N/A") val genre = firstBinding.optJSONObject("genre")?.optString("value", "N/A") val detailsItem = DetailsItem( itemLabel ?: "N/A", pic ?: "N/A", note ?: "N/A", award ?: "N/A", cost ?: "N/A", date ?: "N/A", dir ?: "N/A", duration ?: "N/A", episodes ?: "N/A", seasons ?: "N/A", genre ?: "N/A" ) detailsItemList.add(detailsItem) } _detailsItemList.postValue(detailsItemList) } } catch (e: JSONException) { // Handle JSON parsing error } } else { // Handle API call failure } } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/favorite/FavoriteViewModel.kt
2740863902
package com.ralugan.raluganplus.ui.favorite import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class FavoriteViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is favorite Fragment" } val text: LiveData<String> = _text }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/favorite/FavoriteFragment.kt
1753952921
package com.ralugan.raluganplus.ui.favorite import android.app.AlertDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.ralugan.raluganplus.R import androidx.fragment.app.Fragment 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.dataclass.RaluganPlus class FavoriteFragment : Fragment() { private lateinit var favoriteAdapter: FavoriteAdapter private lateinit var deleteFavoriteButton: ImageButton override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_favorite, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val deleteButton = view.findViewById<ImageButton>(R.id.deleteFavoriteButton) favoriteAdapter = FavoriteAdapter(emptyList()) val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.adapter = favoriteAdapter deleteButton?.setOnClickListener { showUnderConstructionDialog() } loadCurrentUserFavorites() } private fun loadCurrentUserFavorites() { val currentUser = FirebaseAuth.getInstance().currentUser // Vérifier si l'utilisateur est connecté if (currentUser != null) { val uid = currentUser.uid val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users").child(uid).child("listFavorite") usersRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val favoritesList = mutableListOf<RaluganPlus>() for (childSnapshot in snapshot.children) { val favorite = childSnapshot.getValue(RaluganPlus::class.java) favorite?.let { favoritesList.add(it) } } favoriteAdapter.updateData(favoritesList) } override fun onCancelled(error: DatabaseError) { // Gérer l'erreur } }) } } 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() } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/favorite/FavoriteAdaptater.kt
3369034900
package com.ralugan.raluganplus.ui.favorite import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.ralugan.raluganplus.R import com.ralugan.raluganplus.dataclass.RaluganPlus class FavoriteAdapter(private var favoriteMovies: List<RaluganPlus>) : RecyclerView.Adapter<FavoriteAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_item_favorite, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val movie = favoriteMovies[position] // Mettez à jour les vues de l'élément avec les données du film holder.titleTextView.text = movie.title Glide.with(holder.itemView.context) .load(movie.imageUrl) .override(3000,4000) .into(holder.imageView) } override fun getItemCount(): Int { return favoriteMovies.size } fun updateData(newData: List<RaluganPlus>) { favoriteMovies = newData notifyDataSetChanged() } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val titleTextView: TextView = itemView.findViewById(R.id.titleTextView) val imageView: ImageView = itemView.findViewById(R.id.imageView) } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/search/SearchViewModel.kt
3078700811
package com.ralugan.raluganplus.ui.search import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SearchViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is notifications Fragment" } val text: LiveData<String> = _text }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/search/SearchFragment.kt
2965380441
package com.ralugan.raluganplus.ui.search 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.ImageView import android.widget.SearchView import android.widget.TextView import androidx.fragment.app.Fragment import com.bumptech.glide.Glide 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.FragmentSearchBinding 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 SearchFragment : Fragment() { private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! private val wikidataApi: WikidataApi = ApiClient.getWikidataApi() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val searchView: SearchView = view.findViewById(R.id.searchView) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { // Appel de la méthode de recherche ici performSearch(query) return true } override fun onQueryTextChange(newText: String?): Boolean { // Mettez à jour votre liste ou effectuez d'autres actions lorsqu'il y a un changement de texte return true } }) } private fun performSearch(query: String?) { // Vous pouvez utiliser la nouvelle valeur de query pour construire votre requête SPARQL // et appeler l'API avec la nouvelle requête if (query != null) { // Remplacez votre requête SPARQL actuelle avec la nouvelle requête val sparqlQuery = """ SELECT ?itemLabel ?pic WHERE { { ?seriesItem wdt:P1476 ?itemLabel. # Title ?seriesItem wdt:P31 wd:Q5398426. # Television series ?seriesItem wdt:P750 wd:Q54958752. # Platform = Disney+ FILTER(CONTAINS(UCASE(?itemLabel), UCASE('$query'))) OPTIONAL { ?seriesItem wdt:P154 ?pic. } } UNION { ?filmItem wdt:P1476 ?itemLabel. # Title ?filmItem wdt:P31 wd:Q11424. # Film ?filmItem wdt:P750 wd:Q54958752. # Platform = Disney+ FILTER(CONTAINS(UCASE(?itemLabel), UCASE('$query'))) OPTIONAL { ?filmItem 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) } 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 } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/profile/SignupFragment.kt
2763191454
package com.ralugan.raluganplus.ui.profile import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.ralugan.raluganplus.R import com.ralugan.raluganplus.databinding.FragmentLoginBinding import com.ralugan.raluganplus.databinding.FragmentSignupBinding class SignupFragment : Fragment() { private var _binding: FragmentSignupBinding? = null private val binding get() = _binding!! private lateinit var auth: FirebaseAuth private var imageUri: Uri? = null lateinit var imageView: ImageView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSignupBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) auth = FirebaseAuth.getInstance() val firstNameEditText: EditText = binding.editTextFirstName // Ajout du champ de prénom val emailSignUpEditText = binding.editTextEmailSignUp val passwordSignUpEditText = binding.editTextPasswordSignUp val signupButton: Button = binding.signupButton val backButton: Button = binding.backButton // Initialiser l'ImageView imageView = view.findViewById(R.id.imageView) // Trouver le bouton par son ID val selectImageButton: Button = view.findViewById(R.id.selectImageButton) // Ajouter un gestionnaire de clic au bouton selectImageButton.setOnClickListener { // Code pour sélectionner une image à partir du répertoire du téléphone val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" startActivityForResult(intent, IMAGE_PICK_CODE) } signupButton.setOnClickListener { val firstName = firstNameEditText.text.toString() val emailSignUp = emailSignUpEditText.text.toString() val passwordSignUp = passwordSignUpEditText.text.toString() if (emailSignUp.isNotEmpty() && passwordSignUp.isNotEmpty() && firstName.isNotEmpty()) { signUp(emailSignUp, passwordSignUp, firstName, imageUri) } else { Toast.makeText( requireContext(), "Veuillez remplir tous les champs afin de vous inscrire", Toast.LENGTH_SHORT ).show() } } backButton.setOnClickListener { findNavController().navigate(R.id.navigation_login) } } private fun signUp(email: String, password: String, firstName: String, imageUri: Uri?) { auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(requireActivity()) { task -> if (task.isSuccessful) { // Enregistrement des données dans la base de données Realtime Firebase val user = auth.currentUser val uid = user?.uid if (uid != null) { if (imageUri != null) { uploadImageToFirebaseStorage(uid, imageUri) } val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users") val listFavorite = mutableListOf("Your initial favorite movie" ) val userMap = HashMap<String, Any>() userMap["uid"] = uid userMap["email"] = email userMap["firstName"] = firstName userMap ["listFavorite"] = listFavorite // Ajoutez l'URL de l'image à la carte si disponible if (imageUri != null) { val imageUrl = "https://firebasestorage.googleapis.com/v0/b/raluganplus.appspot.com/o/userProfile%2F${uid}.jpeg?alt=media" userMap["imageUrl"] = imageUrl } else { userMap["imageUrl"] = "" } usersRef.child(uid).setValue(userMap) .addOnCompleteListener { dbTask -> if (dbTask.isSuccessful) { // Succès de l'enregistrement dans la base de données Toast.makeText( requireContext(), "Inscription réussie", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( requireContext(), "Erreur d'enregistrement dans la base de données", Toast.LENGTH_SHORT ).show() } } } else { // L'inscription a échoué Toast.makeText( requireContext(), "Erreur d'inscription: ${task.exception?.localizedMessage}", Toast.LENGTH_SHORT ).show() } } } } // Fonction pour télécharger une image sur Firebase Storage private fun uploadImageToFirebaseStorage(uid: String, imageUri: Uri) { val storageRef = FirebaseStorage.getInstance().getReference("userProfile") val imageRef = storageRef.child("image_${System.currentTimeMillis()}.jpeg") imageRef.putFile(imageUri) .addOnSuccessListener { taskSnapshot -> // L'image a été téléchargée avec succès // Récupérez l'URL de téléchargement imageRef.downloadUrl.addOnSuccessListener { uri -> // Mettez à jour la base de données avec l'URL de l'image updateProfileImageInDatabase(uid, uri.toString()) } } .addOnFailureListener { exception -> // Une erreur s'est produite lors du téléchargement de l'image Toast.makeText( requireContext(), "Erreur de téléchargement de l'image: ${exception.localizedMessage}", Toast.LENGTH_SHORT ).show() } } private fun updateProfileImageInDatabase(uid: String, imageUrl: String) { val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users") // Mettez à jour l'URL de l'image dans la base de données usersRef.child(uid).child("imageUrl").setValue(imageUrl) .addOnCompleteListener { dbTask -> if (dbTask.isSuccessful) { // Succès de la mise à jour de l'image dans la base de données Toast.makeText( requireContext(), "Image de profil mise à jour avec succès", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( requireContext(), "Erreur de mise à jour de l'image de profil dans la base de données", Toast.LENGTH_SHORT ).show() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } // Assurez-vous de définir le code de demande IMAGE_PICK_CODE companion object { const val IMAGE_PICK_CODE = 1000 } // Gérez le résultat de la sélection d'image dans onActivityResult override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == IMAGE_PICK_CODE && resultCode == Activity.RESULT_OK && data != null) { // L'utilisateur a sélectionné une image imageUri = data.data // Mettez à jour l'ImageView avec l'image sélectionnée imageView.setImageURI(imageUri) } } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/profile/LoginFragment.kt
1873187053
package com.ralugan.raluganplus.ui.profile import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.NavController import com.google.firebase.auth.FirebaseAuth import com.ralugan.raluganplus.databinding.FragmentProfileBinding import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide 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.google.firebase.storage.FirebaseStorage import com.ralugan.raluganplus.R import com.ralugan.raluganplus.databinding.FragmentLoginBinding import java.lang.Exception class LoginFragment : Fragment() { private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! private lateinit var auth: FirebaseAuth private var imageUri: Uri? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } lateinit var imageView: ImageView override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) auth = FirebaseAuth.getInstance() val emailEditText: EditText = binding.editTextEmail val passwordEditText: EditText = binding.editTextPassword val loginButton: Button = binding.loginButton val signupRedirectButton: Button = binding.signupRedirectButton // Vérifiez si l'utilisateur est connecté if (userIsLoggedIn()) { findNavController().navigate(R.id.navigation_profile) } loginButton.setOnClickListener { val email = emailEditText.text.toString() val password = passwordEditText.text.toString() if (email.isNotEmpty() && password.isNotEmpty()) { signIn(email, password) } else { Toast.makeText( requireContext(), "Veuillez remplir tous les champs afin de vous connectez", Toast.LENGTH_SHORT ).show() } } signupRedirectButton.setOnClickListener { findNavController().navigate(R.id.navigation_signup) } } private fun signIn(email: String, password: String) { auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(requireActivity()) { task -> if (task.isSuccessful) { // Connexion réussie findNavController().navigate(R.id.navigation_profile) } else { // La connexion a échoué Toast.makeText( requireContext(), "Erreur de connexion: ${task.exception?.localizedMessage}", Toast.LENGTH_SHORT ).show() } } } private fun userIsLoggedIn(): Boolean { return auth.currentUser != null } override fun onDestroyView() { super.onDestroyView() _binding = null } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/profile/EditProfileFragment.kt
2814877716
package com.ralugan.raluganplus.ui.profile import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.google.firebase.database.DatabaseError import com.bumptech.glide.request.RequestOptions import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.ralugan.raluganplus.R import com.ralugan.raluganplus.databinding.FragmentEditprofileBinding class EditProfileFragment : Fragment() { private var _binding: FragmentEditprofileBinding? = null private val binding get() = _binding!! private lateinit var auth: FirebaseAuth private var imageUri: Uri? = null lateinit var imageView: ImageView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentEditprofileBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) auth = FirebaseAuth.getInstance() val firstNameEditText: EditText = binding.editTextFirstName val currentPasswordEditText = binding.editTextCurrentPassword val newPasswordEditText = binding.editTextNewPassword val confirmButton: Button = binding.confirmButton val backButton: Button = binding.backButton // Initialiser l'ImageView imageView = view.findViewById(R.id.imageView) // Trouver le bouton par son ID val selectImageButton: Button = view.findViewById(R.id.selectImageButton) // Récupérer l'UID de l'utilisateur actuellement connecté val currentUserId = auth.currentUser?.uid // Référence à la base de données Firebase Realtime val databaseReference = FirebaseDatabase.getInstance().reference // Vérifier si l'UID est non nul currentUserId?.let { userId -> // Référence spécifique à l'utilisateur dans la base de données val userReference = databaseReference.child("users").child(userId) // Écouter les changements dans la base de données pour cet utilisateur userReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { // Récupérer les données de l'utilisateur val firstName = snapshot.child("firstName").value.toString() val imageUrl = snapshot.child("imageUrl").value.toString() // Mettre à jour les champs d'édition et l'URL de l'image firstNameEditText.setText(firstName) imageUri = Uri.parse(imageUrl) // Charger et afficher l'image avec votre méthode loadImage(imageUrl) } } override fun onCancelled(error: DatabaseError) { // Gérer les erreurs de lecture depuis la base de données } }) } // Ajouter un gestionnaire de clic au bouton selectImageButton.setOnClickListener { // Code pour sélectionner une image à partir du répertoire du téléphone val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" startActivityForResult(intent, IMAGE_PICK_CODE) } confirmButton.setOnClickListener { val firstName = firstNameEditText.text.toString() val currentPassword = currentPasswordEditText.text.toString() val newPassword = newPasswordEditText.text.toString() editProfile(currentPassword, newPassword, firstName, imageUri) } backButton.setOnClickListener { findNavController().navigate(R.id.navigation_profile) } } private fun editProfile(currentPassword: String, newPassword: String, firstName: String, imageUri: Uri?) { val user = auth.currentUser var profileUpdated = false // Vérifier si l'utilisateur est connecté if (user != null) { // Vérifier si un changement d'image est demandé if (imageUri != null) { // Mettre à jour l'image de profil updateProfileImage(user.uid, imageUri) profileUpdated = true } // Vérifier si un changement de prénom est demandé if (firstName != user.displayName) { // Mettre à jour le prénom de l'utilisateur updateFirstName(user.uid, firstName) profileUpdated = true } // Vérifier si un changement de mot de passe est demandé if (currentPassword.isNotEmpty() && newPassword.isNotEmpty()) { val credential = EmailAuthProvider.getCredential(user.email!!, currentPassword) // Prompt the user to reauthenticate user.reauthenticate(credential) .addOnCompleteListener { reauthTask -> if (reauthTask.isSuccessful) { // User has been reauthenticated, proceed with password update updatePassword(user, newPassword) profileUpdated = true } else { profileUpdated = false // Reauthentication failed, handle the error Toast.makeText( requireContext(), "Le mot de passe actuel est incorrect", Toast.LENGTH_SHORT ).show() } } } else { // Si aucune mise à jour de mot de passe n'est nécessaire, afficher le message showSuccessMessage(profileUpdated) } } } private fun showSuccessMessage(success: Boolean) { // Afficher le message uniquement si toutes les mises à jour ont été effectuées avec succès if (success) { Toast.makeText( requireContext(), "Profil mis à jour avec succès", Toast.LENGTH_SHORT ).show() } } private fun updateFirstName(userId: String, newFirstName: String) { val database: FirebaseDatabase = FirebaseDatabase.getInstance() val usersReference: DatabaseReference = database.getReference("users") // Mettre à jour le prénom de l'utilisateur dans la base de données usersReference.child(userId).child("firstName").setValue(newFirstName) .addOnSuccessListener { // Succès de la mise à jour Log.d("ProfileUpdate", "Prénom mis à jour avec succès") } .addOnFailureListener { // Échec de la mise à jour Log.d("ProfileUpdate", "Échec de la mise à jour du prénom") } } private fun updatePassword(user: FirebaseUser, newPassword: String) { user.updatePassword(newPassword) .addOnCompleteListener { task -> if (task.isSuccessful) { // Succès de la mise à jour du mot de passe showSuccessMessage(true) } else { // Échec de la mise à jour du mot de passe Toast.makeText( requireContext(), "Échec de la mise à jour du mot de passe: ${task.exception?.message}", Toast.LENGTH_SHORT ).show() showSuccessMessage(false) } } } private fun updateProfileImage(userId: String, imageUri: Uri) { // Référence à l'emplacement actuel de l'image de profil val databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference("users").child(userId) val storage: FirebaseStorage = FirebaseStorage.getInstance() val storageReference: StorageReference = storage.getReference("userProfile") .child("image_${System.currentTimeMillis()}.jpeg") // Récupérer l'ancien lien de l'image de profil databaseReference.child("imageUrl").get().addOnSuccessListener { dataSnapshot -> val oldImageUrl: String? = dataSnapshot.value as? String // Si une ancienne image existe, la supprimer if (!oldImageUrl.isNullOrEmpty()) { val oldImageReference: StorageReference = storage.getReferenceFromUrl(oldImageUrl) oldImageReference.delete().addOnSuccessListener { // Succès de la suppression de l'ancienne image Log.d("ProfileUpdate", "Ancienne image supprimée avec succès.") }.addOnFailureListener { // Échec de la suppression de l'ancienne image Log.e("ProfileUpdate", "Échec de la suppression de l'ancienne image.", it) } } // Télécharger la nouvelle image sur Firebase Storage storageReference.putFile(imageUri) .addOnSuccessListener { // Succès du téléchargement // Récupérer le lien de téléchargement de la nouvelle image téléchargée storageReference.downloadUrl.addOnSuccessListener { downloadUri -> // Mettre à jour le lien de la nouvelle image de profil dans la base de données updateProfileImageUrl(userId, downloadUri.toString()) }.addOnFailureListener { // Échec de la récupération du lien de téléchargement Log.d("ProfileUpdate", "Échec de la récupération du lien de téléchargement") } } .addOnFailureListener { // Échec du téléchargement Log.d("ProfileUpdate", "Échec du téléchargement de la nouvelle image de profil") } }.addOnFailureListener { // Échec de la récupération de l'ancien lien de l'image de profil Log.d("ProfileUpdate", "Échec de la récupération de l'ancien lien de l'image de profil") } } private fun updateProfileImageUrl(userId: String, imageUrl: String) { val database: FirebaseDatabase = FirebaseDatabase.getInstance() val usersReference: DatabaseReference = database.getReference("users") // Mettre à jour le lien de l'image de profil dans la base de données usersReference.child(userId).child("imageUrl").setValue(imageUrl) .addOnSuccessListener { // Succès de la mise à jour Log.d("ProfileUpdate", "Image de profil mise à jour avec succès") } .addOnFailureListener { // Échec de la mise à jour Log.d("ProfileUpdate", "Échec de la récupération de l'ancien lien de l'image de profil") } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun loadImage(imageUrl: String) { // Utiliser une bibliothèque comme Picasso ou Glide pour charger et afficher l'image // Exemple avec Picasso : Glide.with(requireContext()) .load(imageUrl) .apply(RequestOptions.circleCropTransform()) // Option pour afficher une image circulaire, facultatif .into(imageView) } // Assurez-vous de définir le code de demande IMAGE_PICK_CODE companion object { const val IMAGE_PICK_CODE = 1000 } // Gérez le résultat de la sélection d'image dans onActivityResult override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == IMAGE_PICK_CODE && resultCode == Activity.RESULT_OK && data != null) { // L'utilisateur a sélectionné une image imageUri = data.data // Mettez à jour l'ImageView avec l'image sélectionnée imageView.setImageURI(imageUri) } } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/profile/ProfileViewModel.kt
2346353440
package com.ralugan.raluganplus.ui.profile import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ProfileViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is Profile Fragment" } val text: LiveData<String> = _text }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/profile/ProfileFragment.kt
2433124765
package com.ralugan.raluganplus.ui.profile import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import com.google.firebase.auth.FirebaseAuth import com.ralugan.raluganplus.databinding.FragmentProfileBinding import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide 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.google.firebase.storage.FirebaseStorage import com.ralugan.raluganplus.R import com.ralugan.raluganplus.ui.favorite.FavoriteFragment import java.lang.Exception class ProfileFragment : Fragment() { private var _binding: FragmentProfileBinding? = null private val binding get() = _binding!! private lateinit var auth: FirebaseAuth override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfileBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) auth = FirebaseAuth.getInstance() val editProfileButton: Button = view.findViewById(R.id.editProfileButton) val watchListButton: Button = view.findViewById(R.id.watchListButton) val settingsButton: Button = view.findViewById(R.id.settingsButton) val accountButton: Button = view.findViewById(R.id.accountButton) val legalButton: Button = view.findViewById(R.id.legalButton) val helpButton: Button = view.findViewById(R.id.helpButton) val logoutButton: Button = binding.logoutButton // Vérifiez si l'utilisateur est connecté if (userIsLoggedIn()) { val logoImageView: ImageView = binding.logoImageView val userNameTextView: TextView = binding.userNameTextView editProfileButton.setOnClickListener { findNavController().navigate(R.id.navigation_editprofile) } watchListButton.setOnClickListener { findNavController().navigate(R.id.navigation_favorite) } settingsButton.setOnClickListener { showUnderConstructionDialog() } accountButton.setOnClickListener { showUnderConstructionDialog() } legalButton.setOnClickListener { showUnderConstructionDialog() } helpButton.setOnClickListener { showUnderConstructionDialog() } logoutButton.setOnClickListener { showLogoutConfirmationDialog() } // Récupérez le prénom de l'utilisateur depuis la base de données val user = auth.currentUser val uid = user?.uid if (uid != null) { val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users") usersRef.child(uid).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { val firstName = snapshot.child("firstName").value.toString() val imageUrl = snapshot.child("imageUrl").value.toString() if (!imageUrl.isNullOrEmpty()) { // Utilisez Glide pour charger l'image dans votre ImageView Glide.with(requireContext()) .load(imageUrl) .circleCrop() .into(logoImageView) } else { // Gérer le cas où l'URL de l'image est vide ou nulle Log.e("DEBUG", "Image URL is empty or null") Glide.with(requireContext()) .load(R.drawable.default_image) .circleCrop() .into(logoImageView) } // Affichez le prénom de l'utilisateur userNameTextView.text = "$firstName" } else { print("NOT EXISTS") } } override fun onCancelled(error: DatabaseError) { // Gérez les erreurs ici Log.e("ERROR", "DatabaseError: ${error.message}") } }) } else { print("UID NULL") } } else { findNavController().navigate(R.id.navigation_login) } } private fun signOut() { auth.signOut() findNavController().navigate(R.id.navigation_login) } private fun userIsLoggedIn(): Boolean { return auth.currentUser != null } override fun onDestroyView() { super.onDestroyView() _binding = null } 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() } private fun showLogoutConfirmationDialog() { // Créez une boîte de dialogue (AlertDialog) pour confirmer la déconnexion val builder = AlertDialog.Builder(requireContext()) builder.setTitle("Déconnexion") builder.setMessage("Voulez-vous vraiment vous déconnecter ?") builder.setPositiveButton("Déconnexion") { _, _ -> signOut() } builder.setNegativeButton("Annuler") { dialog, _ -> dialog.dismiss() } // Affichez la boîte de dialogue val dialog = builder.create() dialog.show() } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/download/DownloadFragment.kt
1926971272
package com.ralugan.raluganplus.ui.download import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.ralugan.raluganplus.databinding.FragmentDownloadBinding class DownloadFragment : Fragment() { private var _binding: FragmentDownloadBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val dashboardViewModel = ViewModelProvider(this).get(DownloadViewModel::class.java) _binding = FragmentDownloadBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textDownload dashboardViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/ui/download/DownloadViewModel.kt
3677668715
package com.ralugan.raluganplus.ui.download import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DownloadViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "Vos téléchargements apparaîtront ici." } val text: LiveData<String> = _text }
raluganplus/app/src/main/java/com/ralugan/raluganplus/MainActivity.kt
1934267856
package com.ralugan.raluganplus import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.ralugan.raluganplus.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) val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_home, R.id.navigation_search, R.id.navigation_download, R.id.navigation_profile ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/api/Wikidata.kt
4004819681
package com.ralugan.raluganplus.api import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface WikidataApi { @GET("sparql") fun getDisneyPlusInfo(@Query("query") query: String, @Query("format") format: String): Call<ResponseBody> }
raluganplus/app/src/main/java/com/ralugan/raluganplus/api/ApiClient.kt
1873631
package com.ralugan.raluganplus.api import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { private const val BASE_URL = "https://query.wikidata.org/bigdata/namespace/wdq/" private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() fun getWikidataApi(): WikidataApi { return retrofit.create(WikidataApi::class.java) } }
raluganplus/app/src/main/java/com/ralugan/raluganplus/dataclass/DetailsItem.kt
3099188577
package com.ralugan.raluganplus.dataclass data class DetailsItem( val itemLabel: String?, val pic: String?, val note: String?, val award: String?, val cost: String?, val date: String?, val dir: String?, val duration: String?, val episodes: String?, val seasons: String?, val genre: String? )
raluganplus/app/src/main/java/com/ralugan/raluganplus/dataclass/RaluganPlus.kt
2521005842
package com.ralugan.raluganplus.dataclass data class RaluganPlus( val title: String, val imageUrl: String ) { constructor() : this("", "") }
UTSPemrogMobile1/Main.kt
778491839
package com.example.utspemrogramanmobilesatu fun main() { // Inisialisasi mutableList dan tambah data List val clubs = mutableListOf<Club>() clubs.add(Club("Liverpool",19,8,9,6,3)) clubs.add(Club("Manchester United",20,12,6,3,1)) clubs.add(Club("Chelsea",20,12,6,3,1)) clubs.add(Club("Manchester City",8,8,8,0,0)) clubs.add(Club("Arsenal",13,14,2,0,0)) println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~====~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // Passing a named function ::sortByNumberTrophyTotal val sortedClubs = sortByNumberTrophyTotal(clubs) // Hasil sorting total trofi println("Urutan klub berdasarkan jumlah total trofi: ") for (club in sortedClubs) { println("${club.name} - ${club.totalTrophy} trofi") } println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~====~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // Passing a named function ::filterByEuropeanTrophy val filteredClubs = filterByEuropeanTrophy(clubs) // Hasil sorting total trofi println("Klub yang belum pernah memenangkan UCL dan UEL:") for (club in clubs) { if (club.ucl == 0 && club.uel == 0) { println("${club.name} ") } } println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~====~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // Panggil extension function Club recap println("Rekap Perolehan Trofi Dari Setiap Club:") for (club in clubs){ println(club.recap()) } println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~====~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") } // High order function filter and sort fun filterAndSort(clubs: List<Club>, options: (List<Club>) -> List<Club>): List<Club> { return options(clubs) } // Fungsi sorting fun sortByNumberTrophyTotal(clubs: List<Club>): List<Club> { val sortedClubs = clubs.sortedByDescending { it.totalTrophy } return sortedClubs } // Fungsi filter fun filterByEuropeanTrophy(clubs: List<Club>): List<Club> { val filteredClubs = clubs.filter { it.uel > 0 } return filteredClubs }
UTSPemrogMobile1/Club.kt
531196596
package com.example.utspemrogramanmobilesatu // data class Club data class Club( val name: String, val epl: Int, val fa: Int, val efl: Int, val ucl: Int, val uel: Int, ) { val totalTrophy: Int get() = epl + fa + efl + efl + ucl + uel ; } // extension function recap fun Club.recap(): String { return "$name berhasil meraih $epl trofi liga primer Inggris,$fa trofi FA, $efl trofi EFL, $ucl trofi Liga Champions, dan $uel trofi Liga Eropa" }
2slab4/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
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) } }
2slab4/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
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) } }
2slab4/app/src/main/java/com/example/myapplication/MainActivity.kt
3647300206
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val textView : TextView = findViewById(R.id.textView) val Lay:ConstraintLayout = findViewById(R.id.bb) when (item.itemId){ R.id.action1 -> { textView.text = "Вы выбрали пункт 1!" Lay.setBackgroundColor(resources.getColor(R.color.white)) } R.id.action2 -> { textView.text = "Вы выбрали пункт 2!" Lay.setBackgroundColor(resources.getColor(R.color.blue)) } R.id.action3 -> { textView.text = "Вы выбрали пункт 3!" Lay.setBackgroundColor(resources.getColor(R.color.red)) } } return super.onOptionsItemSelected(item) } }
jetpack-take-select-photo-image-2/app/src/androidTest/java/com/jerry/jetpack_take_select_photo_image_2/ExampleInstrumentedTest.kt
3404348894
package com.jerry.jetpack_take_select_photo_image_2 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.jerry.jetpack_take_select_photo_image_2", appContext.packageName) } }
jetpack-take-select-photo-image-2/app/src/test/java/com/jerry/jetpack_take_select_photo_image_2/ExampleUnitTest.kt
1510267389
package com.jerry.jetpack_take_select_photo_image_2 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/viewmodel/MainViewModel.kt
1440661369
package com.jerry.jetpack_take_select_photo_image_2.viewmodel import android.content.Context import android.net.Uri import android.provider.OpenableColumns import android.util.Log import androidx.core.net.toFile import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jerry.jetpack_take_select_photo_image_2.api.FileApi import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import kotlinx.coroutines.launch import okhttp3.Interceptor import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.concurrent.TimeUnit class MainViewModel: ViewModel() { private lateinit var context: Context fun setContext(context: Context){ this.context = context } fun upload(uri: Uri){ val api = provideFileApi() val path = getRealPathFromURI(uri = uri) val file = File(path) val image = MultipartBody.Part .createFormData( "image", file.name, file.asRequestBody() ) viewModelScope.launch { // val result = api.formWithImage( // name = "name", // image = image, // ) val multipartBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("name", "name") .addFormDataPart("avatarUrl", file.name, file.asRequestBody()) .build() val result = api.formWithImage2(body = multipartBody) // println("result:${result}") } } fun provideMoshi(): Moshi { return Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() } fun provideOKHttpClientLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } } fun provideOKHttpClientInterceptor(): Interceptor { return object: Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val original = chain.request() val newRequest = original.newBuilder() //.removeHeader("User-Agent") //.addHeader("User-Agent", "other-user-agent") //.addHeader("Accept-Encoding", "deflate") //.addHeader("Cache-Control", "no-cache") .addHeader("Content-Type","application/json") .build() return chain.proceed(newRequest) } } } fun provideOKHttpClient(logInterceptor: HttpLoggingInterceptor, interceptor: Interceptor): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .addInterceptor(logInterceptor) .addInterceptor(interceptor) .build() } fun provideRetrofit(client: OkHttpClient, moshi: Moshi): Retrofit { return Retrofit.Builder() .baseUrl("https://postman-echo.com") .client(client) .addConverterFactory(MoshiConverterFactory.create(moshi).asLenient()) .build() } fun provideFileApi(): FileApi { val moshi: Moshi = provideMoshi() val logInterceptor: HttpLoggingInterceptor = provideOKHttpClientLoggingInterceptor() val client: OkHttpClient = provideOKHttpClient( logInterceptor = logInterceptor, interceptor = provideOKHttpClientInterceptor() ) val retrofit: Retrofit = provideRetrofit(client = client, moshi = moshi) return retrofit.create(FileApi::class.java) } fun getRealPathFromURI(uri: Uri ): String? { val returnCursor = context.contentResolver.query(uri, null, null, null, null) val nameIndex = returnCursor!!.getColumnIndex(OpenableColumns.DISPLAY_NAME) val sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE) returnCursor.moveToFirst() val name = returnCursor.getString(nameIndex) val size = returnCursor.getLong(sizeIndex).toString() val file = File(context.filesDir, name) try { val inputStream: InputStream? = context.contentResolver.openInputStream(uri) val outputStream = FileOutputStream(file) var read = 0 val maxBufferSize = 1 * 1024 * 1024 val bytesAvailable: Int = inputStream?.available() ?: 0 //int bufferSize = 1024; val bufferSize = Math.min(bytesAvailable, maxBufferSize) val buffers = ByteArray(bufferSize) while (inputStream?.read(buffers).also { if (it != null) { read = it } } != -1) { outputStream.write(buffers, 0, read) } Log.e("File Size", "Size " + file.length()) inputStream?.close() outputStream.close() Log.e("File Path", "Path " + file.path) } catch (e: java.lang.Exception) { Log.e("Exception", e.message!!) } return file.path } // private fun fileFromContentUri(context: Context, contentUri: Uri): File { // // val fileExtension = getFileExtension(context, contentUri) // val fileName = "temporary_file" + if (fileExtension != null) ".$fileExtension" else "" // // val tempFile = File(context.cacheDir, fileName) // tempFile.createNewFile() // // try { // val oStream = FileOutputStream(tempFile) // val inputStream = context.contentResolver.openInputStream(contentUri) // // inputStream?.let { // copy(inputStream, oStream) // } // // oStream.flush() // } catch (e: Exception) { // e.printStackTrace() // } // // return tempFile // } // // private fun getFileExtension( uri: Uri): String? { // val fileType: String? = context.contentResolver.getType(uri) // return context.MimeTypeMap .getSingleton().getExtensionFromMimeType(fileType) // } // // @Throws(IOException::class) // private fun copy(source: InputStream, target: OutputStream) { // val buf = ByteArray(8192) // var length: Int // while (source.read(buf).also { length = it } > 0) { // target.write(buf, 0, length) // } // } }
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/ui/theme/Color.kt
96860870
package com.jerry.jetpack_take_select_photo_image_2.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/ui/theme/Theme.kt
532159764
package com.jerry.jetpack_take_select_photo_image_2.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 Jetpacktakeselectphotoimage2Theme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/ui/theme/Type.kt
948316251
package com.jerry.jetpack_take_select_photo_image_2.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/MainActivity.kt
2261171480
package com.jerry.jetpack_take_select_photo_image_2 import android.net.Uri import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.core.view.WindowCompat import com.jerry.jetpack_take_select_photo_image_2.components.MyImageArea import com.jerry.jetpack_take_select_photo_image_2.ui.theme.Jetpacktakeselectphotoimage2Theme import com.jerry.jetpack_take_select_photo_image_2.viewmodel.MainViewModel import java.io.File class MainActivity : ComponentActivity() { private val viewModel by viewModels<MainViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) viewModel.setContext(this) setContent { Jetpacktakeselectphotoimage2Theme { Scaffold { paddingValues -> Box ( modifier = Modifier .padding(paddingValues) ){ Column( modifier = Modifier.fillMaxSize() ) { val uri = remember { mutableStateOf<Uri?>(null) } //image to show bottom sheet MyImageArea( directory = File(cacheDir, "images"), uri = uri.value, onSetUri = { uri.value = it }, upload = { viewModel.upload(it) } ) } } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { Jetpacktakeselectphotoimage2Theme { Greeting("Android") } }
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/response/PostManResponse.kt
361927993
package com.jerry.jetpack_take_select_photo_image_2.response import com.squareup.moshi.Json data class PostManResponse ( @field:Json(name = "url") val url: String? )
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/components/MyButton.kt
2119304500
package com.jerry.jetpack_take_select_photo_image_2.components import android.Manifest import android.content.pm.PackageManager import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import coil.compose.AsyncImage import com.jerry.jetpack_take_select_photo_image_2.R import java.io.File @Composable fun MyImageArea( uri: Uri? = null, //target url to preview directory: File? = null, // stored directory onSetUri : (Uri) -> Unit = {}, // selected / taken uri upload:(Uri) -> Unit = {}, ) { val context = LocalContext.current val tempUri = remember { mutableStateOf<Uri?>(null) } val authority = stringResource(id = R.string.fileprovider) fun getTempUri(): Uri? { directory?.let { it.mkdirs() val file = File.createTempFile( "image_" + System.currentTimeMillis().toString(), ".jpg", it ) return FileProvider.getUriForFile( context, authority, file ) } return null } val imagePicker = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia(), onResult = { it?.let { onSetUri.invoke(it) } } ) val takePhotoLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicture(), onResult = {isSaved -> tempUri.value?.let { onSetUri.invoke(it) } } ) val cameraPermissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission is granted, proceed to step 2 val tmpUri = getTempUri() tempUri.value = tmpUri tempUri.value?.let { takePhotoLauncher.launch(it) } } else { // Permission is denied, handle it accordingly } } var showBottomSheet by remember { mutableStateOf(false) } if (showBottomSheet){ MyModalBottomSheet( onDismiss = { showBottomSheet = false }, onTakePhotoClick = { showBottomSheet = false val permission = Manifest.permission.CAMERA if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED ) { // Permission is already granted, proceed to step 2 val tmpUri = getTempUri() tempUri.value = tmpUri tempUri.value?.let { takePhotoLauncher.launch(it) } } else { // Permission is not granted, request it cameraPermissionLauncher.launch(permission) } }, onPhotoGalleryClick = { showBottomSheet = false imagePicker.launch( PickVisualMediaRequest( ActivityResultContracts.PickVisualMedia.ImageOnly ) ) }, ) } Column ( modifier = Modifier.fillMaxWidth() ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Button( onClick = { showBottomSheet = true } ) { Text(text = "Select / Take") } } //preview selfie uri?.let { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { AsyncImage( model = it, modifier = Modifier.size( 160.dp ), contentDescription = null, ) } Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { upload.invoke(it) } ) { Text(text = "upload to server") } } } }
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/components/MyModalBottomSheet.kt
4245788441
package com.jerry.jetpack_take_select_photo_image_2.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CornerSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountBox import androidx.compose.material.icons.filled.Place import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.ui.unit.dp @Composable fun MyModalBottomSheet( onDismiss: () -> Unit, onTakePhotoClick: () -> Unit, onPhotoGalleryClick: () -> Unit ) { MyModalBottomSheetContent( header = "Choose Option", onDismiss = { onDismiss.invoke() }, items = listOf( BottomSheetItem( title = "Take Photo", icon = Icons.Default.AccountBox, onClick = { onTakePhotoClick.invoke() } ), BottomSheetItem( title = "select image", icon = Icons.Default.Place, onClick = { onPhotoGalleryClick.invoke() } ), ) ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MyModalBottomSheetContent( onDismiss: () -> Unit, //header header: String = "Choose Option", items: List<BottomSheetItem> = listOf(), ) { val skipPartiallyExpanded by remember { mutableStateOf(false) } val bottomSheetState = rememberModalBottomSheetState( skipPartiallyExpanded = skipPartiallyExpanded ) val edgeToEdgeEnabled by remember { mutableStateOf(false) } val windowInsets = if (edgeToEdgeEnabled) WindowInsets(0) else BottomSheetDefaults.windowInsets ModalBottomSheet( shape = MaterialTheme.shapes.medium.copy( bottomStart = CornerSize(0), bottomEnd = CornerSize(0) ), onDismissRequest = { onDismiss.invoke() }, sheetState = bottomSheetState, windowInsets = windowInsets ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( modifier = Modifier.padding(start = 16.dp, end = 16.dp), text = header, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center ) items.forEach {item -> androidx.compose.material3.ListItem( modifier = Modifier.clickable { item.onClick.invoke() }, headlineContent = { Text( text = item.title, style = MaterialTheme.typography.titleMedium, ) }, leadingContent = { Icon( imageVector = item.icon, contentDescription = item.title ) }, ) } } } } data class BottomSheetItem( val title: String = "", val icon: ImageVector, val onClick: () -> Unit )
jetpack-take-select-photo-image-2/app/src/main/java/com/jerry/jetpack_take_select_photo_image_2/api/FileApi.kt
3625517938
package com.jerry.jetpack_take_select_photo_image_2.api import com.jerry.jetpack_take_select_photo_image_2.response.PostManResponse import okhttp3.MultipartBody import retrofit2.http.Body import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part interface FileApi { @Multipart @POST("/post") fun formWithImage( @Part("name") name: String, @Part("image") image: MultipartBody.Part ) :retrofit2.Response<String> // @POST("/post") suspend fun formWithImage2(@Body body: MultipartBody): retrofit2.Response<PostManResponse> }
PIM70/app/src/androidTest/java/com/example/pim/ExampleInstrumentedTest.kt
3143320498
package com.example.pim 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.pim", appContext.packageName) } }
PIM70/app/src/test/java/com/example/pim/ExampleUnitTest.kt
1631350260
package com.example.pim 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) } }
PIM70/app/src/main/java/com/example/pim/ui/theme/Color.kt
1000763895
package com.example.pim.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)
PIM70/app/src/main/java/com/example/pim/ui/theme/Theme.kt
1318558499
package com.example.pim.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 PIMTheme( 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 ) }
PIM70/app/src/main/java/com/example/pim/ui/theme/TelaPrincipal.kt
1256449956
package com.example.pim.ui.theme import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.pim.R class TelaPrincipal : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tela_principal) supportActionBar!!.hide() window.statusBarColor = Color.parseColor("#FFFFFF") } }
PIM70/app/src/main/java/com/example/pim/ui/theme/Type.kt
1548906837
package com.example.pim.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 ) */ )
PIM70/app/src/main/java/com/example/pim/MainActivity.kt
907412895
package com.example.pim 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.example.pim.ui.theme.PIMTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PIMTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { PIMTheme { Greeting("Android") } }
PIM70/app/src/main/java/com/example/pim/FormLogin.kt
1518394136
package com.example.pim import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.example.pim.databinding.ActivityFormLoginBinding // Correct import import com.example.pim.ui.theme.TelaPrincipal import com.google.android.material.snackbar.Snackbar class FormLogin : AppCompatActivity() { private lateinit var binding: ActivityFormLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFormLoginBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar!!.hide() window.statusBarColor = Color.parseColor("#FFFFFF") binding.ButtonLogin.setOnClickListener{//validacao ao apertar o botao(Button_Login) de login val email = binding.EditEmail.text.toString() val password = binding.EditPassword.text.toString() when{ email.isEmpty() -> {//erro por falta de Emal binding.EditEmail.error = "Preencha o Email!" } password.isEmpty() ->{//erro por falto da senha binding.EditPassword.error = "Digite a senha!" } !email.contains("@gmail.com") -> {//validacao se tem o @gmail ou nao val snackbar = Snackbar.make(it,"Email invalido!",Snackbar.LENGTH_SHORT) snackbar.show() } password.length <= 5 ->{//erro senha invalida val snackbar = Snackbar.make(it,"Senha invalida! A senha tem pelo menos 6 caracteres!",Snackbar.LENGTH_SHORT) snackbar.show() } else ->{//mensagem logao com sucesso login(it) } } } } private fun login(view: View){//login binding.ButtonLogin.isEnabled = false //desabilita o botao(Button_Login) apos clicar nele binding.ButtonLogin.setTextColor(Color.parseColor("#FFFFFF")) Handler(Looper.getMainLooper()).postDelayed({ navegarTelaPrincipal()//Navega para a tela principal val snackbar = Snackbar.make(view,"Login efetuado com sucesso!",Snackbar.LENGTH_SHORT) snackbar.show() // Desbloqueia o botão após o atraso binding.ButtonLogin.isEnabled = true binding.ButtonLogin.setTextColor(Color.parseColor("#000000")) },3000) } private fun navegarTelaPrincipal(){//manda para tela principal val intent = Intent(this,TelaPrincipal::class.java) startActivity(intent) finish() } class FormLogin : AppCompatActivity() { private lateinit var recuperarCadastro: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rec_senha) recuperarCadastro.setOnClickListener { val intent = Intent(this@FormLogin, RecSenha::class.java) startActivity(intent) } } } }
PIM70/app/src/main/java/com/example/pim/RecSenha.kt
1178287318
package com.example.pim import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class RecSenha : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rec_senha) } }
Cardshadow/app/src/androidTest/java/com/mr/kaushalya/cardshadow/ExampleInstrumentedTest.kt
15022286
package com.mr.kaushalya.cardshadow 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.mr.kaushalya.cardshadow", appContext.packageName) } }
Cardshadow/app/src/test/java/com/mr/kaushalya/cardshadow/ExampleUnitTest.kt
1423979981
package com.mr.kaushalya.cardshadow 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) } }
Cardshadow/app/src/main/java/com/mr/kaushalya/cardshadow/MainActivity.kt
3090440114
package com.mr.kaushalya.cardshadow import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Cardshadow/shadowcard/src/androidTest/java/com/mr/kaushalya/shadowcard/ExampleInstrumentedTest.kt
59968574
package com.mr.kaushalya.shadowcard 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.mr.kaushalya.shadowcard.test", appContext.packageName) } }
Cardshadow/shadowcard/src/test/java/com/mr/kaushalya/shadowcard/ExampleUnitTest.kt
4262449203
package com.mr.kaushalya.shadowcard 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) } }
Cardshadow/shadowcard/src/main/java/com/mr/kaushalya/shadowcard/ShadowView.kt
4215972115
package com.mr.kaushalya.shadowcard import android.content.Context import android.content.res.ColorStateList import android.graphics.* import android.graphics.drawable.Drawable import android.graphics.drawable.RippleDrawable import android.os.Build import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.content.ContextCompat open class ShadowView @JvmOverloads constructor( context: Context?, attributeSet: AttributeSet? = null, defStyleInt: Int = 0 ) : ViewGroup(context, attributeSet, defStyleInt) { private val DEFAULT_CHILD_GRAVITY = Gravity.TOP or Gravity.START private var SIZE_UNSET = -1 private var SIZE_DEFAULT = 0 private var foregroundDraw: Drawable? = null private val selfBounds = Rect() private val overlayBounds = Rect() private var foregroundDrawGravity = Gravity.FILL private var foregroundDrawInPadding = true private var foregroundDrawBoundsChanged = false private val bgPaint = Paint() var shadowColor: Int = 0 set(value) { field = value updatePaintShadow(shadowRadius, shadowDx, shadowDy, value) } var foregroundColor: Int = 0 set(value) { field = value updateForegroundColor() } var backgroundClr: Int = 0 set(value) { field = value invalidate() } var shadowRadius = 0f set(value) { var v = value if (v > getShadowMarginMax() && getShadowMarginMax() != 0f) { v = getShadowMarginMax() } field = value updatePaintShadow(v, shadowDx, shadowDy, shadowColor) } get() { return if (field > getShadowMarginMax() && getShadowMarginMax() != 0f) { getShadowMarginMax() } else { field } } var shadowDx = 0f set(value) { field = value updatePaintShadow(shadowRadius, value, shadowDy, shadowColor) } var shadowDy = 0f set(value) { field = value updatePaintShadow(shadowRadius, shadowDx, value, shadowColor) } var cornerRadiusTL: Float var cornerRadiusTR: Float var cornerRadiusBL: Float var cornerRadiusBR: Float var shadowMarginTop: Int = 0 set(value) { field = value updatePaintShadow() } var shadowMarginLeft: Int = 0 set(value) { field = value updatePaintShadow() } var shadowMarginRight: Int = 0 set(value) { field = value updatePaintShadow() } var shadowMarginBottom: Int = 0 set(value) { field = value updatePaintShadow() } init { val a = getContext().obtainStyledAttributes( attributeSet, R.styleable.ShadowView, defStyleInt, 0 ) shadowColor = a.getColor( R.styleable.ShadowView_shadowColor, ContextCompat.getColor(context!!, R.color.shadow_view_default_shadow_color) ) foregroundColor = a.getColor( R.styleable.ShadowView_foregroundColor, ContextCompat.getColor(context, R.color.shadow_view_foreground_color_dark) ) backgroundClr = a.getColor(R.styleable.ShadowView_backgroundColor, Color.WHITE) shadowDx = a.getFloat(R.styleable.ShadowView_shadowDx, 0f) shadowDy = a.getFloat(R.styleable.ShadowView_shadowDy, 1f) shadowRadius = a.getDimensionPixelSize(R.styleable.ShadowView_shadowRadius, SIZE_DEFAULT).toFloat() val d = a.getDrawable(R.styleable.ShadowView_android_foreground) if (d != null) { setForeground(d) } val shadowMargin = a.getDimensionPixelSize(R.styleable.ShadowView_shadowMargin, SIZE_UNSET) if (shadowMargin >= 0) { shadowMarginTop = shadowMargin shadowMarginLeft = shadowMargin shadowMarginRight = shadowMargin shadowMarginBottom = shadowMargin } else { shadowMarginTop = a.getDimensionPixelSize(R.styleable.ShadowView_shadowMarginTop, SIZE_DEFAULT) shadowMarginLeft = a.getDimensionPixelSize(R.styleable.ShadowView_shadowMarginLeft, SIZE_DEFAULT) shadowMarginRight = a.getDimensionPixelSize(R.styleable.ShadowView_shadowMarginRight, SIZE_DEFAULT) shadowMarginBottom = a.getDimensionPixelSize(R.styleable.ShadowView_shadowMarginBottom, SIZE_DEFAULT) } val cornerRadius = a.getDimensionPixelSize(R.styleable.ShadowView_cornerRadius, SIZE_UNSET).toFloat() if (cornerRadius >= 0) { cornerRadiusTL = cornerRadius cornerRadiusTR = cornerRadius cornerRadiusBL = cornerRadius cornerRadiusBR = cornerRadius } else { cornerRadiusTL = a.getDimensionPixelSize(R.styleable.ShadowView_cornerRadiusTL, SIZE_DEFAULT) .toFloat() cornerRadiusTR = a.getDimensionPixelSize(R.styleable.ShadowView_cornerRadiusTR, SIZE_DEFAULT) .toFloat() cornerRadiusBL = a.getDimensionPixelSize(R.styleable.ShadowView_cornerRadiusBL, SIZE_DEFAULT) .toFloat() cornerRadiusBR = a.getDimensionPixelSize(R.styleable.ShadowView_cornerRadiusBR, SIZE_DEFAULT) .toFloat() } a.recycle() bgPaint.color = backgroundClr bgPaint.isAntiAlias = true bgPaint.style = Paint.Style.FILL setLayerType(LAYER_TYPE_SOFTWARE, null) setWillNotDraw(false) background = null } private fun updatePaintShadow() { updatePaintShadow(shadowRadius, shadowDx, shadowDy, shadowColor) } private fun updatePaintShadow(radius: Float, dx: Float, dy: Float, color: Int) { bgPaint.setShadowLayer( radius, dx, dy, color ) invalidate() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var maxHeight = 0 var maxWidth = 0 var childState = 0 setMeasuredDimension( getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec) ) val shadowMeasureWidthMatchParent = layoutParams.width == ViewGroup.LayoutParams.MATCH_PARENT val shadowMeasureHeightMatchParent = layoutParams.height == ViewGroup.LayoutParams.MATCH_PARENT var widthSpec = widthMeasureSpec if (shadowMeasureWidthMatchParent) { val childWidthSize = measuredWidth - shadowMarginRight - shadowMarginLeft widthSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY) } var heightSpec = heightMeasureSpec if (shadowMeasureHeightMatchParent) { val childHeightSize = measuredHeight - shadowMarginTop - shadowMarginBottom heightSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY) } val child = getChildAt(0) if (child.visibility !== View.GONE) { measureChildWithMargins(child, widthSpec, 0, heightSpec, 0) val lp = child.layoutParams as LayoutParams maxWidth = if (shadowMeasureWidthMatchParent) Math.max( maxWidth, child.measuredWidth + lp.leftMargin + lp.rightMargin ) else Math.max( maxWidth, child.measuredWidth + shadowMarginLeft + shadowMarginRight + lp.leftMargin + lp.rightMargin ) maxHeight = if (shadowMeasureHeightMatchParent) Math.max( maxHeight, child.measuredHeight + lp.topMargin + lp.bottomMargin ) else Math.max( maxHeight, child.measuredHeight + shadowMarginTop + shadowMarginBottom + lp.topMargin + lp.bottomMargin ) childState = View.combineMeasuredStates(childState, child.measuredState) } maxWidth += paddingLeft + paddingRight maxHeight += paddingTop + paddingBottom maxHeight = Math.max(maxHeight, suggestedMinimumHeight) maxWidth = Math.max(maxWidth, suggestedMinimumWidth) val drawable = foreground if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.minimumHeight) maxWidth = Math.max(maxWidth, drawable.minimumWidth) } setMeasuredDimension( View.resolveSizeAndState( maxWidth, if (shadowMeasureWidthMatchParent) widthMeasureSpec else widthSpec, childState ), View.resolveSizeAndState( maxHeight, if (shadowMeasureHeightMatchParent) heightMeasureSpec else heightSpec, childState shl View.MEASURED_HEIGHT_STATE_SHIFT ) ) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { layoutChildren(left, top, right, bottom, false) if (changed) foregroundDrawBoundsChanged = changed } private fun layoutChildren( left: Int, top: Int, right: Int, bottom: Int, forceLeftGravity: Boolean ) { val count = childCount val parentLeft = getPaddingLeftWithForeground() val parentRight = right - left - getPaddingRightWithForeground() val parentTop = getPaddingTopWithForeground() val parentBottom = bottom - top - getPaddingBottomWithForeground() for (i in 0..(count - 1)) { val child = getChildAt(i) if (child.visibility != View.GONE) { val lp = child.layoutParams as LayoutParams val width = child.measuredWidth val height = child.measuredHeight var childLeft = 0 var childTop: Int var gravity = lp.gravity if (gravity == -1) { gravity = DEFAULT_CHILD_GRAVITY } val layoutDirection = layoutDirection val absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection) val verticalGravity = gravity and Gravity.VERTICAL_GRAVITY_MASK when (absoluteGravity and Gravity.HORIZONTAL_GRAVITY_MASK) { Gravity.CENTER_HORIZONTAL -> childLeft = parentLeft + (parentRight - parentLeft - width) / 2 + lp.leftMargin - lp.rightMargin + shadowMarginLeft - shadowMarginRight Gravity.RIGHT -> { if (!forceLeftGravity) { childLeft = parentRight - width - lp.rightMargin - shadowMarginRight } } Gravity.LEFT -> { childLeft = parentLeft + lp.leftMargin + shadowMarginLeft } else -> childLeft = parentLeft + lp.leftMargin + shadowMarginLeft } when (verticalGravity) { Gravity.TOP -> childTop = parentTop + lp.topMargin + shadowMarginTop Gravity.CENTER_VERTICAL -> childTop = parentTop + (parentBottom - parentTop - height) / 2 + lp.topMargin - lp.bottomMargin + shadowMarginTop - shadowMarginBottom Gravity.BOTTOM -> childTop = parentBottom - height - lp.bottomMargin - shadowMarginBottom else -> childTop = parentTop + lp.topMargin + shadowMarginTop } child.layout(childLeft, childTop, childLeft + width, childTop + height) } } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val w = measuredWidth val h = measuredHeight val path = ShapeUtils.roundedRect( shadowMarginLeft.toFloat(), shadowMarginTop.toFloat(), (w - shadowMarginRight).toFloat(), (h - shadowMarginBottom).toFloat(), cornerRadiusTL, cornerRadiusTR, cornerRadiusBR, cornerRadiusBL ) canvas.drawPath(path, bgPaint) canvas.clipPath(path) } override fun draw(canvas: Canvas) { super.draw(canvas) canvas.save() val w = measuredWidth val h = measuredHeight val path = ShapeUtils.roundedRect( shadowMarginLeft.toFloat(), shadowMarginTop.toFloat(), (w - shadowMarginRight).toFloat(), (h - shadowMarginBottom).toFloat(), cornerRadiusTL, cornerRadiusTR, cornerRadiusBR, cornerRadiusBL ) canvas.clipPath(path) drawForeground(canvas) canvas.restore() } private fun getShadowMarginMax() = intArrayOf(shadowMarginLeft, shadowMarginTop, shadowMarginRight, shadowMarginBottom).max() .toFloat() fun drawForeground(canvas: Canvas) { foregroundDraw?.let { if (foregroundDrawBoundsChanged) { foregroundDrawBoundsChanged = false val w = right - left val h = bottom - top if (foregroundDrawInPadding) { selfBounds.set(0, 0, w, h) } else { selfBounds.set( paddingLeft, paddingTop, w - paddingRight, h - paddingBottom ) } Gravity.apply( foregroundDrawGravity, it.intrinsicWidth, it.intrinsicHeight, selfBounds, overlayBounds ) it.bounds = overlayBounds } it.draw(canvas) } } override fun getForeground(): Drawable? { return foregroundDraw } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) foregroundDrawBoundsChanged = true } override fun getForegroundGravity(): Int { return foregroundDrawGravity } override fun setForegroundGravity(foregroundGravity: Int) { var foregroundGravity = foregroundGravity if (foregroundDrawGravity != foregroundGravity) { if (foregroundGravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK == 0) { foregroundGravity = foregroundGravity or Gravity.START } if (foregroundGravity and Gravity.VERTICAL_GRAVITY_MASK == 0) { foregroundGravity = foregroundGravity or Gravity.TOP } foregroundDrawGravity = foregroundGravity if (foregroundDrawGravity == Gravity.FILL && foregroundDraw != null) { val padding = Rect() foregroundDraw?.getPadding(padding) } requestLayout() } } override fun verifyDrawable(who: Drawable): Boolean { return super.verifyDrawable(who) || who === foregroundDraw } override fun jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState() foregroundDraw?.let { it.jumpToCurrentState() } } override fun drawableStateChanged() { super.drawableStateChanged() foregroundDraw?.takeIf { it.isStateful }?.let { it.state = drawableState } } override fun setForeground(drawable: Drawable?) { if (foregroundDraw != null) { foregroundDraw?.callback = null unscheduleDrawable(foregroundDraw) } foregroundDraw = drawable updateForegroundColor() if (drawable != null) { setWillNotDraw(false) drawable.callback = this if (drawable.isStateful) { drawable.state = drawableState } if (foregroundDrawGravity == Gravity.FILL) { val padding = Rect() drawable.getPadding(padding) } } requestLayout() invalidate() } private fun updateForegroundColor() { (foregroundDraw as RippleDrawable?)?.setColor(ColorStateList.valueOf(foregroundColor)) } override fun drawableHotspotChanged(x: Float, y: Float) { super.drawableHotspotChanged(x, y) foregroundDraw?.let { it.setHotspot(x, y) } } fun setShadowMargin(left: Int, top: Int, right: Int, bottom: Int) { shadowMarginLeft = left shadowMarginTop = top shadowMarginRight = right shadowMarginBottom = bottom requestLayout() invalidate() } fun setCornerRadius(tl: Float, tr: Float, br: Float, bl: Float) { cornerRadiusTL = tl cornerRadiusTR = tr cornerRadiusBR = br cornerRadiusBL = bl invalidate() } override fun generateLayoutParams(attrs: AttributeSet): LayoutParams { return LayoutParams(context, attrs) } override fun shouldDelayChildPressedState(): Boolean { return false } override fun checkLayoutParams(p: ViewGroup.LayoutParams): Boolean { return p is LayoutParams } override fun generateLayoutParams(lp: ViewGroup.LayoutParams): ViewGroup.LayoutParams { return LayoutParams(lp) } override fun getAccessibilityClassName(): CharSequence { return FrameLayout::class.java.name } fun getPaddingLeftWithForeground(): Int { return paddingLeft } fun getPaddingRightWithForeground(): Int { return paddingRight } private fun getPaddingTopWithForeground(): Int { return paddingTop } private fun getPaddingBottomWithForeground(): Int { return paddingBottom } class LayoutParams : ViewGroup.MarginLayoutParams { var gravity = UNSPECIFIED_GRAVITY constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) { val a = c.obtainStyledAttributes(attrs, R.styleable.ShadowView_Layout) gravity = a.getInt(R.styleable.ShadowView_Layout_layout_gravity, UNSPECIFIED_GRAVITY) a.recycle() } constructor(source: ViewGroup.LayoutParams) : super(source) companion object { val UNSPECIFIED_GRAVITY = -1 } } }
Cardshadow/shadowcard/src/main/java/com/mr/kaushalya/shadowcard/ShapeUtils.kt
4125761035
package com.mr.kaushalya.shadowcard import android.graphics.Path object ShapeUtils { fun roundedRect( left: Float, top: Float, right: Float, bottom: Float, rx: Float, ry: Float, tl: Boolean = true, tr: Boolean = true, br: Boolean = true, bl: Boolean = true): Path { var rx = rx var ry = ry val path = Path() if (rx < 0) rx = 0f if (ry < 0) ry = 0f val width = right - left val height = bottom - top if (rx > width / 2) rx = width / 2 if (ry > height / 2) ry = height / 2 val widthMinusCorners = width - 2 * rx val heightMinusCorners = height - 2 * ry path.moveTo(right, top + ry) if (tr) path.rQuadTo(0f, -ry, -rx, -ry)//top-right corner else { path.rLineTo(0f, -ry) path.rLineTo(-rx, 0f) } path.rLineTo(-widthMinusCorners, 0f) if (tl) path.rQuadTo(-rx, 0f, -rx, ry) //top-left corner else { path.rLineTo(-rx, 0f) path.rLineTo(0f, ry) } path.rLineTo(0f, heightMinusCorners) if (bl) path.rQuadTo(0f, ry, rx, ry)//bottom-left corner else { path.rLineTo(0f, ry) path.rLineTo(rx, 0f) } path.rLineTo(widthMinusCorners, 0f) if (br) path.rQuadTo(rx, 0f, rx, -ry) //bottom-right corner else { path.rLineTo(rx, 0f) path.rLineTo(0f, -ry) } path.rLineTo(0f, -heightMinusCorners) path.close()//Given close, last lineto can be removed. return path } fun roundedRect( left: Float, top: Float, right: Float, bottom: Float, tl: Float, tr: Float, br: Float, bl: Float): Path { var tl = tl var tr = tr var br = br var bl = bl val path = Path() if (tl < 0) tl = 0f if (tr < 0) tr = 0f if (br < 0) br = 0f if (bl < 0) bl = 0f val width = right - left val height = bottom - top val min = Math.min(width, height) if (tl > min / 2) tl = min / 2 if (tr > min / 2) tr = min / 2 if (br > min / 2) br = min / 2 if (bl > min / 2) bl = min / 2 // val widthMinusCorners = width - 2 * rx // val heightMinusCorners = height - 2 * ry if (tl == tr && tr == br && br == bl && tl == min / 2) { val radius = min / 2F path.addCircle(left + radius, top + radius, radius, Path.Direction.CW) return path } path.moveTo(right, top + tr) if (tr > 0) path.rQuadTo(0f, -tr, -tr, -tr)//top-right corner else { path.rLineTo(0f, -tr) path.rLineTo(-tr, 0f) } path.rLineTo(-(width - tr - tl), 0f) if (tl > 0) path.rQuadTo(-tl, 0f, -tl, tl) //top-left corner else { path.rLineTo(-tl, 0f) path.rLineTo(0f, tl) } path.rLineTo(0f, height - tl - bl) if (bl > 0) path.rQuadTo(0f, bl, bl, bl)//bottom-left corner else { path.rLineTo(0f, bl) path.rLineTo(bl, 0f) } path.rLineTo(width - bl - br, 0f) if (br > 0) path.rQuadTo(br, 0f, br, -br) //bottom-right corner else { path.rLineTo(br, 0f) path.rLineTo(0f, -br) } path.rLineTo(0f, -(height - br - tr)) path.close()//Given close, last lineto can be removed. return path } }
MSTechnologies/app/src/androidTest/java/com/example/demotest/ExampleInstrumentedTest.kt
3662818200
package com.example.demotest 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.demotest", appContext.packageName) } }
MSTechnologies/app/src/test/java/com/example/demotest/ExampleUnitTest.kt
1409912731
package com.example.demotest 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) } }
MSTechnologies/app/src/main/java/com/example/demotest/MainActivity.kt
1433918582
package com.example.demotest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.gms.common.api.Api import retrofit2.Call import retrofit2.Response import javax.security.auth.callback.Callback class MainActivity : AppCompatActivity() { private lateinit var recyclerView: RecyclerView private lateinit var manager: RecyclerView.LayoutManager private lateinit var myAdapter: RecyclerView.Adapter<*> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) manager = LinearLayoutManager(this) getAllData() } fun getAllData(){ com.example.demotest.Api.retrofitService.getAllData().enqueue(object: retrofit2.Callback<List<Image>> { override fun onResponse( call: Call<List<Image>>, response: Response<List<Image>> ) { if(response.isSuccessful){ recyclerView = findViewById<RecyclerView>(R.id.recylerView).apply{ myAdapter = MyAdapter(response.body()!!) layoutManager = manager adapter = myAdapter } } } override fun onFailure(call: Call<List<Image>>, t: Throwable) { t.printStackTrace() } }) } }
MSTechnologies/app/src/main/java/com/example/demotest/Image.kt
4190602941
package com.example.demotest data class Image( val imgurl: String, val name: String, val order: String, val tag: String )