content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.adiluhung.mobilejournaling.ui.screen.authed.listMood import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.adiluhung.mobilejournaling.data.local.UserPreferences import com.adiluhung.mobilejournaling.data.network.config.ApiConfig import com.adiluhung.mobilejournaling.data.network.responses.CurrentDateMoodResponse import com.adiluhung.mobilejournaling.data.network.responses.MonthlyMoodResponse import com.adiluhung.mobilejournaling.data.network.responses.Mood import com.adiluhung.mobilejournaling.ui.common.UiState import com.adiluhung.mobilejournaling.ui.utils.currentDate import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response class ListMoodViewModel(private val pref: UserPreferences) : ViewModel() { private val token = runBlocking { pref.getUserToken() .map { token -> token } .first() } private val _monthlyMood = MutableLiveData<UiState<List<Mood>>>(UiState.Empty) val monthlyMood: LiveData<UiState<List<Mood>>> get() = _monthlyMood private val _selectedMood = MutableLiveData<UiState<Mood?>>(UiState.Empty) val selectedMood: LiveData<UiState<Mood?>> get() = _selectedMood private val _currentDateState = MutableLiveData(currentDate) private val currentDateState: LiveData<String> get() = _currentDateState private val _currentMonthAndYear = MutableLiveData(currentDate.split("-")[0] + "-" + currentDate.split("-")[1]) private val currentMonthAndYear: LiveData<String> get() = _currentMonthAndYear private val _isCheckedIn = MutableLiveData<Boolean>() val isCheckedIn: LiveData<Boolean> get() = _isCheckedIn fun updateCurrentDate(date: String) { val isDifferentDate = date != currentDateState.value _currentDateState.value = date if (isDifferentDate) { getMoodByDate() } } fun updateCurrentMonthAndYear(monthAndYear: String) { val isDifferentMonth = monthAndYear != currentMonthAndYear.value _currentMonthAndYear.value = monthAndYear if (isDifferentMonth) { getMonthlyMood() } } private fun getMonthlyMood() { _monthlyMood.value = UiState.Loading val client = ApiConfig.getApiService() .getMonthlyMood("Bearer $token", "${currentMonthAndYear.value}-01") client.enqueue(object : Callback<MonthlyMoodResponse> { override fun onResponse( call: Call<MonthlyMoodResponse>, response: Response<MonthlyMoodResponse> ) { if (response.isSuccessful) { val resBody = response.body() if (resBody != null) { _monthlyMood.value = UiState.Success(resBody.data.moods) } } else { val errorMessage = response.errorBody()?.string().let { if (it != null) { JSONObject(it).getString("message") } else { "Unknown Error" } } _monthlyMood.value = UiState.Error(errorMessage) } } override fun onFailure(call: Call<MonthlyMoodResponse>, t: Throwable) { _monthlyMood.value = UiState.Error(t.message ?: "Unknown error") } }) } private fun getMoodByDate() { _selectedMood.value = UiState.Loading val client = ApiConfig.getApiService() .getMoodByDate("Bearer $token", currentDateState.value!!) client.enqueue(object : Callback<CurrentDateMoodResponse> { override fun onResponse( call: Call<CurrentDateMoodResponse>, response: Response<CurrentDateMoodResponse> ) { if (response.isSuccessful) { val resBody = response.body() if (resBody != null) { _selectedMood.value = UiState.Success(resBody.data) } } else { _selectedMood.value = UiState.Success(null) } } override fun onFailure(call: Call<CurrentDateMoodResponse>, t: Throwable) { _selectedMood.value = UiState.Error(t.message ?: "Unknown error") Log.e("ListMoodViewModel", t.message ?: "Unknown error") } }) } private fun isCheckedIn() { val client = ApiConfig.getApiService().getMoodByDate("Bearer $token", currentDate) client.enqueue(object : Callback<CurrentDateMoodResponse> { override fun onResponse( call: Call<CurrentDateMoodResponse>, response: Response<CurrentDateMoodResponse> ) { _isCheckedIn.value = response.isSuccessful } override fun onFailure(call: Call<CurrentDateMoodResponse>, t: Throwable) { Log.e("HomeViewModel", "Error: ${t.message}") } }) } init { getMonthlyMood() getMoodByDate() isCheckedIn() } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/ui/screen/authed/listMood/ListMoodViewModel.kt
1983788893
package com.adiluhung.mobilejournaling.ui import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.compose.animation.core.tween import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.adiluhung.mobilejournaling.route.Routes import com.adiluhung.mobilejournaling.ui.common.UiState import com.adiluhung.mobilejournaling.ui.screen.authed.accountInfo.AccountInfoScreen import com.adiluhung.mobilejournaling.ui.screen.authed.advancedListMood.AdvancedListMoodScreen import com.adiluhung.mobilejournaling.ui.screen.authed.completeProfile.CompleteProfileScreen import com.adiluhung.mobilejournaling.ui.screen.authed.detailProgram.DetailProgramScreen import com.adiluhung.mobilejournaling.ui.screen.authed.detailSession.DetailSessionScreen import com.adiluhung.mobilejournaling.ui.screen.authed.home.HomeScreen import com.adiluhung.mobilejournaling.ui.screen.authed.listFavoriteProgram.ListFavoriteScreen import com.adiluhung.mobilejournaling.ui.screen.authed.listMood.ListMoodScreen import com.adiluhung.mobilejournaling.ui.screen.authed.listProgram.ListProgramScreen import com.adiluhung.mobilejournaling.ui.screen.authed.moodAddNote.MoodAddNoteScreen import com.adiluhung.mobilejournaling.ui.screen.authed.moodCheckIn.MoodCheckInScreen import com.adiluhung.mobilejournaling.ui.screen.authed.personalInfo.PersonalInfoScreen import com.adiluhung.mobilejournaling.ui.screen.authed.profile.ProfileScreen import com.adiluhung.mobilejournaling.ui.screen.authed.reminder.ReminderScreen import com.adiluhung.mobilejournaling.ui.screen.authed.sessionComplete.SessionCompleteScreen import com.adiluhung.mobilejournaling.ui.screen.common.LoadingScreen import com.adiluhung.mobilejournaling.ui.screen.guest.LoginScreen import com.adiluhung.mobilejournaling.ui.screen.guest.RegisterScreen import com.adiluhung.mobilejournaling.ui.screen.guest.StartScreen @RequiresApi(Build.VERSION_CODES.TIRAMISU) @Composable fun JournalingApp( viewModel: MainViewModel = viewModel( factory = ViewModelFactory(context = LocalContext.current) ) ) { val navController = rememberNavController() val token = viewModel.token.observeAsState().value var startDestination by remember { mutableStateOf(Routes.Loading.route) } val isProfileCompleted = viewModel.isProfileComplete.observeAsState().value viewModel.uiState.observeAsState(initial = UiState.Empty).value.let { uiState -> SideEffect { when (uiState) { is UiState.Loading -> { startDestination = Routes.Loading.route } is UiState.Error -> { Log.d("JournalingApp", "Error: ${uiState.errorMessage}") } is UiState.Success -> { viewModel.observeCompleteProfile() startDestination = if (token == null) { Routes.Start.route } else { if (isProfileCompleted == false) { Routes.CompleteProfile.route } else { Routes.Home.route } } } is UiState.Empty -> { startDestination = Routes.Loading.route } } } } NavHost(navController, startDestination = startDestination) { composable(Routes.Start.route) { StartScreen(navController) } composable( route = Routes.Register.route, enterTransition = { slideInHorizontally( initialOffsetX = { fullWidth -> fullWidth }, animationSpec = tween(durationMillis = 500) ) }, exitTransition = { slideOutHorizontally( targetOffsetX = { fullWidth -> fullWidth }, animationSpec = tween(durationMillis = 500) ) } ) { RegisterScreen(navController) } composable(route = Routes.Loading.route, enterTransition = { slideInHorizontally( initialOffsetX = { fullWidth -> fullWidth }, animationSpec = tween(durationMillis = 500) ) }, exitTransition = { slideOutHorizontally( targetOffsetX = { fullWidth -> fullWidth }, animationSpec = tween(durationMillis = 500) ) } ) { LoadingScreen() } composable(Routes.Login.route) { LoginScreen(navController) } composable(Routes.Home.route) { HomeScreen(navController) } composable(Routes.ListMood.route) { ListMoodScreen(navController = navController) } composable(Routes.Profile.route) { ProfileScreen(navController = navController) } composable(Routes.ListProgram.route) { ListProgramScreen(navController = navController) } composable(Routes.DetailProgram.route) { DetailProgramScreen(navController, it.arguments?.getString("programId") ?: "0") } composable(Routes.DetailSession.route) { DetailSessionScreen( navController, it.arguments?.getString("sessionId") ?: "0" ) } composable(Routes.CompleteProfile.route) { CompleteProfileScreen(navController = navController) } composable(Routes.MoodCheckIn.route) { MoodCheckInScreen(navController = navController) } composable(Routes.MoodAddNote.route) { MoodAddNoteScreen( navController, it.arguments?.getString("moodId") ?: "0" ) } composable(Routes.AdvancedListMood.route) { AdvancedListMoodScreen(navController = navController) } composable(Routes.Favorites.route) { ListFavoriteScreen(navController = navController) } composable(Routes.PersonalInfo.route) { PersonalInfoScreen(navController = navController) } composable(Routes.AccountInfo.route) { AccountInfoScreen(navController = navController) } composable(Routes.Reminder.route) { ReminderScreen(navController = navController) } composable(Routes.SessionComplete.route){ SessionCompleteScreen( navController = navController, sessionId = it.arguments?.getString("sessionId") ?: "0" ) } } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/ui/JournalingApp.kt
3689294872
package com.adiluhung.mobilejournaling import android.app.NotificationChannel import android.os.Build import android.os.Bundle import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.adiluhung.mobilejournaling.ui.JournalingApp import com.adiluhung.mobilejournaling.ui.theme.JournalingTheme class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Make status bar transparent // window.setFlags( // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS // ) setContent { JournalingTheme(darkTheme = false) { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { JournalingApp() } } } } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/MainActivity.kt
2168584373
package com.adiluhung.mobilejournaling import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager class MyApp : Application() { override fun onCreate() { super.onCreate() val notificationChannel = NotificationChannel( "journaling_notification", "Journaling", NotificationManager.IMPORTANCE_HIGH ) val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(notificationChannel) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/MyApp.kt
4191702507
package com.adiluhung.mobilejournaling.di import android.content.Context import com.adiluhung.mobilejournaling.data.local.UserPreferences object Injection { fun provideUserPreference(context: Context): UserPreferences { return UserPreferences(context) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/di/Injection.kt
3313565195
package com.adiluhung.mobilejournaling import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import androidx.annotation.DrawableRes import androidx.core.app.NotificationCompat import kotlin.random.Random class JournalingNotificationService( private val context: Context ) { private val notificationManager = context.getSystemService(NotificationManager::class.java) fun showBasicNotification(message: String) { // Intent untuk membuka aktivitas utama aplikasi Anda val intent = Intent(context, MainActivity::class.java) // Menetapkan tindakan untuk intent, jika aplikasi sedang berjalan, intent ini akan menjadi bagian dari tumpukan kegiatan saat ini. intent.action = Intent.ACTION_MAIN intent.addCategory(Intent.CATEGORY_LAUNCHER) // Membuat PendingIntent val pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(context, "journaling_notification") .setContentTitle("Pengingat Meditasi") .setContentText(message) .setSmallIcon(R.drawable.ic_mood) .setPriority(NotificationManager.IMPORTANCE_HIGH) .setAutoCancel(true) .setContentIntent( pendingIntent ) .build() notificationManager.notify( Random.nextInt(), notification ) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/JournalingNotificationService.kt
715744089
package com.adiluhung.mobilejournaling.route sealed class Routes(val route: String) { // common data object Loading : Routes("loading") data object CompleteProfile : Routes("completeProfile") // unauthenticated data object Login : Routes("login") data object Register : Routes("register") data object Start : Routes("start") // authenticated data object Home : Routes("home") data object ListMood : Routes("listMood") data object ListProgram : Routes("listProgram") data object Favorites : Routes("Favorites") data object Profile : Routes("profile") data object DetailProgram : Routes("detailProgram/{programId}") { fun createRoute(programId: Int) = "detailProgram/$programId" } data object DetailSession : Routes("detailSession/{sessionId}") { fun createRoute(sessionId: Int) = "detailSession/$sessionId" } data object MoodCheckIn : Routes("moodCheckIn") data object MoodAddNote : Routes("moodAddNote/{moodId}") { fun createRoute(moodId: Int) = "moodAddNote/$moodId" } data object AdvancedListMood : Routes("advancedListMood") data object PersonalInfo : Routes("personalInfo") data object AccountInfo : Routes("accountInfo") data object Reminder : Routes("reminder") data object SessionComplete : Routes("sessionComplete/{sessionId}") { fun createRoute(sessionId: Int) = "sessionComplete/$sessionId" } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/route/Routes.kt
2092213235
package com.adiluhung.mobilejournaling.route import com.adiluhung.mobilejournaling.R // List of Bottom Navbar Item sealed class NavItem(val route: String, val icon: Int, val activeIcon: Int, val title: String) { data object Home: NavItem(Routes.Home.route, R.drawable.ic_home, R.drawable.ic_home_active, "Home") data object Mood: NavItem(Routes.ListMood.route, R.drawable.ic_mood, R.drawable.ic_mood_active, "Mood") data object Program: NavItem(Routes.ListProgram.route, R.drawable.ic_program, R.drawable.ic_program_active, "Program") data object Favorites: NavItem(Routes.Favorites.route, R.drawable.ic_hearth, R.drawable.ic_hearth_active, "Favoties") data object Profile: NavItem(Routes.Profile.route, R.drawable.ic_profil, R.drawable.ic_profil_active, "Profile") }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/route/NavItem.kt
1887486765
package com.adiluhung.mobilejournaling import android.Manifest import android.annotation.SuppressLint import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import kotlin.random.Random class AlarmReceiver : BroadcastReceiver() { @SuppressLint("MissingPermission") override fun onReceive(context: Context?, intent: Intent?) { // val message = intent?.getStringExtra("EXTRA_MESSAGE") ?: return // // context?.let { // val notificationService = JournalingNotificationService(context) // notificationService.showBasicNotification(message) // } val i = Intent(context, MainActivity::class.java) intent!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_IMMUTABLE) val builder = NotificationCompat.Builder(context!!, "journaling_notification") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle("Pengingat Meditasi") .setContentText("Waktunya meditasi") .setAutoCancel(true) .setDefaults(NotificationCompat.DEFAULT_ALL) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(123, builder.build()) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/AlarmReceiver.kt
4218003447
package com.adiluhung.mobilejournaling.alarm import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.util.Log import com.adiluhung.mobilejournaling.AlarmReceiver import java.time.LocalDate class AlarmSchedulerImpl( private val context: Context ) : AlarmScheduler { private val alarmManager = context.getSystemService(AlarmManager::class.java) override fun schedule(alarmItem: AlarmItem) { val intent = Intent(context, AlarmReceiver::class.java).apply { putExtra("EXTRA_MESSAGE", alarmItem.message) } val alarmTime = alarmItem.alarmTime.timeInMillis // Log.d("AlarmSchedulerImpl", "schedule: $alarmTime") val pendingIntent = PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent ) } override fun cancel(alarmItem: AlarmItem) { alarmManager.cancel( PendingIntent.getBroadcast( context, 0, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/alarm/AlarmSchedulerImpl.kt
628789542
package com.adiluhung.mobilejournaling.alarm import java.util.Calendar data class AlarmItem( val alarmTime : Calendar, val message : String )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/alarm/AlarmItem.kt
3527540822
package com.adiluhung.mobilejournaling.alarm interface AlarmScheduler { fun schedule(alarmItem: AlarmItem) fun cancel(alarmItem: AlarmItem) }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/alarm/AlarmScheduler.kt
538984908
package com.adiluhung.mobilejournaling.data.network.config import com.adiluhung.mobilejournaling.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiConfig { private const val BASE_URL = BuildConfig.BASE_URL fun getApiService(): ApiService { val loggingInterceptor = if (BuildConfig.DEBUG) { HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) } else { HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE) } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() return retrofit.create(ApiService::class.java) } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/config/ApiConfig.kt
3925999385
package com.adiluhung.mobilejournaling.data.network.config import com.adiluhung.mobilejournaling.data.network.responses.AchievementResponse import com.adiluhung.mobilejournaling.data.network.responses.AllProgramResponse import com.adiluhung.mobilejournaling.data.network.responses.AllTagsResponse import com.adiluhung.mobilejournaling.data.network.responses.AuthResponse import com.adiluhung.mobilejournaling.data.network.responses.CheckInMoodResponse import com.adiluhung.mobilejournaling.data.network.responses.CompleteSessionResponse import com.adiluhung.mobilejournaling.data.network.responses.CurrentDateMoodResponse import com.adiluhung.mobilejournaling.data.network.responses.FavoriteSessionsResponse import com.adiluhung.mobilejournaling.data.network.responses.GetUserProfileResponse import com.adiluhung.mobilejournaling.data.network.responses.MonthlyMoodResponse import com.adiluhung.mobilejournaling.data.network.responses.ProgramDetailResponse import com.adiluhung.mobilejournaling.data.network.responses.RecommendedProgramResponse import com.adiluhung.mobilejournaling.data.network.responses.SessionDetailResponse import com.adiluhung.mobilejournaling.data.network.responses.TipsResponse import com.adiluhung.mobilejournaling.data.network.responses.UpcomingSessionResponse import com.adiluhung.mobilejournaling.data.network.responses.UpdateFavoriteProgramResponse import com.adiluhung.mobilejournaling.data.network.responses.UpdateFavoriteSessionResponse import com.adiluhung.mobilejournaling.data.network.responses.UpdateUserProfileResponse import com.adiluhung.mobilejournaling.data.network.responses.WeeklyMoodResponse import okhttp3.MultipartBody import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Headers import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path interface ApiService { // AUTH @FormUrlEncoded @POST("register") @Headers("Accept: application/json") fun register( @Field("email") email: String, @Field("password") password: String, @Field("first_name") firstName: String, @Field("last_name") lastName: String? ): Call<AuthResponse> @FormUrlEncoded @Headers("Accept: application/json") @POST("login") fun login( @Field("email") email: String, @Field("password") password: String, ): Call<AuthResponse> // Update Profile @FormUrlEncoded @Headers("Accept: application/json") @POST("profile") fun updateProfile( @Header("Authorization") token: String, @Field("first_name") firstName: String, @Field("last_name") lastName: String?, @Field("age") age: Int?, @Field("gender") gender: String?, @Field("school_name") schoolName: String?, ): Call<UpdateUserProfileResponse> // Get Profile @GET("profile") fun getUserProfile( @Header("Authorization") token: String, ): Call<GetUserProfileResponse> // Get Weekly Mood @GET("moods/{date}/weekly") fun getWeeklyMood( @Header("Authorization") token: String, @Path("date") date: String, ): Call<WeeklyMoodResponse> // Get Achievements @GET("achievements/{date}") fun getAchievements( @Header("Authorization") token: String, @Path("date") date: String, ): Call<AchievementResponse> // Get Upcoming Sessions @GET("sessions/upcoming") fun getUpcomingSession( @Header("Authorization") token: String, ): Call<UpcomingSessionResponse> // Get Tips @GET("tips") fun getTips( @Header("Authorization") token: String, ): Call<TipsResponse> // Get Recommended Programs @GET("programs/recommended") fun getRecommendedPrograms( @Header("Authorization") token: String, ): Call<RecommendedProgramResponse> // Get Detail Program @GET("programs/{id}") fun getDetailProgram( @Header("Authorization") token: String, @Path("id") id: String, ): Call<ProgramDetailResponse> // Update Favorite Program @FormUrlEncoded @Headers("Accept: application/json") @POST("favorites/programs") fun updateFavoriteProgram( @Header("Authorization") token: String, @Field("program_id") programId: Int, ): Call<UpdateFavoriteProgramResponse> // Update Favorite Session @FormUrlEncoded @Headers("Accept: application/json") @POST("favorites/sessions") fun updateFavoriteSession( @Header("Authorization") token: String, @Field("session_id") sessionId: Int, ): Call<UpdateFavoriteSessionResponse> // Get Detail Session @GET("sessions/{id}") fun getDetailSession( @Header("Authorization") token: String, @Path("id") id: String, ): Call<SessionDetailResponse> // Complete Session @FormUrlEncoded @POST("sessions/{id}/complete") @Headers("Accept: application/json") fun completeSession( @Header("Authorization") token: String, @Path("id") id: String, @Field("date") date: String, ): Call<CompleteSessionResponse> // Get All Programs @GET("programs") fun getAllPrograms( @Header("Authorization") token: String, ): Call<AllProgramResponse> // Get All Tags @GET("tags") fun getAllTags( @Header("Authorization") token: String, ): Call<AllTagsResponse> // Create CheckIn Mood @FormUrlEncoded @Headers("Accept: application/json") @POST("moods") fun createCheckInMood( @Header("Authorization") token: String, @Field("checkin_date") checkinDate: String, @Field("mood") mood: String, @Field("note") note: String, @Field("tags[]") tags: Array<Int>, ): Call<CheckInMoodResponse> // Get Mood by Date @GET("moods/{date}") fun getMoodByDate( @Header("Authorization") token: String, @Path("date") date: String, ): Call<CurrentDateMoodResponse> // Get Monthly Mood @GET("moods/{date}/monthly") fun getMonthlyMood( @Header("Authorization") token: String, @Path("date") date: String, ): Call<MonthlyMoodResponse> // Get Favorite Programs @GET("favorites/programs") fun getAllFavoritePrograms( @Header("Authorization") token: String, ): Call<AllProgramResponse> // Get Favorite Sessions @GET("favorites/sessions") fun getAllFavoriteSessions( @Header("Authorization") token: String, ): Call<FavoriteSessionsResponse> // Update Email @FormUrlEncoded @Headers("Accept: application/json") @POST("profile/change_email") fun updateEmail( @Header("Authorization") token: String, @Field("email") email: String, ): Call<UpdateUserProfileResponse> /// Update Password @FormUrlEncoded @Headers("Accept: application/json") @POST("profile/change_password") fun updatePassword( @Header("Authorization") token: String, @Field("password") password: String, @Field("password_confirmation") passwordConfirmation: String, ): Call<UpdateUserProfileResponse> // Update Profile Picture @Multipart @POST("profile/photo") fun updateProfilePicture( @Header("Authorization") token: String, @Part photo: MultipartBody.Part, ): Call<UpdateUserProfileResponse> }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/config/ApiService.kt
382829407
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class UpdateUserProfileResponse( val data: DataProfile, val message: String ) data class GetUserProfileResponse( val data: DataProfile ) data class DataProfile( val gender: String? = null, @field:SerializedName("updated_at") val updatedAt: String, @field:SerializedName("last_name") val lastName: String? = null, @field:SerializedName("created_at") val createdAt: String, @field:SerializedName("school_name") val schoolName: String? = null, val id: Int, @field:SerializedName("user_id") val photoUrl: String? = null, @field:SerializedName("first_name") val firstName: String, val age: Int? = null, val email: String )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/ProfileResponse.kt
2190979202
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class AchievementResponse( val data: AchievementData ) data class AchievementData( val streak: Int, val sessionCount: Int ) data class UpcomingSessionResponse( val data: UpcomingSession ) data class UpcomingSession( val id: Int, val type: String, val title: String, @SerializedName("media_file") val mediaFile: String, val description: String?, @SerializedName("is_favorite") val isFavorite: Boolean, @SerializedName("module_name") val moduleName: String, @SerializedName("is_completed") val isCompleted: Boolean, @SerializedName("media_length") val mediaLength: String, @SerializedName("program_name") val programName: String ) data class UpdateFavoriteSessionResponse( val message : String ) data class SessionDetailResponse( val data: SessionDetail ) data class FavoriteSessionsResponse( val data: List<SessionDetail> ) data class SessionDetail( val id: Int, val type: String, val title: String, @SerializedName("media_file") val mediaFile: String, val description: String?, @SerializedName("is_favorite") val isFavorite: Boolean, @SerializedName("module_name") val moduleName: String, @SerializedName("is_completed") val isCompleted: Boolean, @SerializedName("media_length") val mediaLength: String, @SerializedName("program_name") val programName: String ) data class CompleteSessionResponse( val message: String, val data: SessionDetail )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/SessionResponse.kt
3446713716
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class RecommendedProgramResponse( val data: List<RecommendedProgram> ) data class RecommendedProgram( val id: Int, val image: String?, val title: String, val progress: Int, val description: String, @SerializedName("modules_count") val modulesCount: Int, @SerializedName("sessions_count") val sessionsCount: Int ) data class ProgramDetailResponse( val data: ProgramDetail ) data class ProgramDetail( val id: Int, val image: String?, val title: String, val modules: List<Module>, val description: String, @SerializedName("is_favorite") var isFavorite: Boolean, ) data class Module( val id: Int, val title: String, val sessions: List<Session>, @SerializedName("total_duration") val totalDuration: String ) data class Session( val id: Int, val type: String?, val title: String, @SerializedName("media_file") val mediaFile: String, val description: String?, @SerializedName("is_favorite") var isFavorite: Boolean, @SerializedName("module_name") val moduleName: String, @SerializedName("is_completed") val isCompleted: Boolean, @SerializedName("media_length") val mediaLength: String, @SerializedName("program_name") val programName: String ) data class UpdateFavoriteProgramResponse( val message : String ) data class AllProgramResponse( val data: List<Program> ) data class Program( val id: Int, val image: String?, val title: String, val progress: Int, val description: String, @SerializedName("modules_count") val modulesCount: Int, @SerializedName("sessions_count") val sessionsCount: Int )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/ProgramResponse.kt
3262982577
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class TipsResponse( val data: TipsData ) data class TipsData( val id: Int, val quote: String, @SerializedName("created_at") val createdAt: String, @SerializedName("updated_at") val updatedAt: String )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/AnotherResponse.kt
3955024427
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class WeeklyMoodResponse( val data: Map<String, Mood> ) data class MonthlyMoodResponse( val data: MonthlyMood ) data class MonthlyMood( @SerializedName("first_day") val firstDay: String, val days: Int, @SerializedName("month_name") val monthName: String, val moods: List<Mood> ) data class CurrentDateMoodResponse( val data: Mood ) data class Mood( val id: Int, val day: String, val mood: String, val note: String, val tags: List<Tag>, @SerializedName("user_id") val userId: Int, @SerializedName("checkin_date") val checkinDate: String ) data class Tag( val id: Int, val name: String ) data class AllTagsResponse( val data: List<Tag> ) data class CheckInMoodResponse( val message: String )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/MoodResponse.kt
4274570951
package com.adiluhung.mobilejournaling.data.network.responses import com.google.gson.annotations.SerializedName data class AuthResponse( val data: DataAuth, val message: String ) data class DataAuth( val user: User, val token: String ) data class User( @field:SerializedName("is_admin") val isAdmin: Int, @field:SerializedName("updated_at") val updatedAt: String, @field:SerializedName("last_name") val lastName: Any, @field:SerializedName("created_at") val createdAt: String, @field:SerializedName("email_verified_at") val emailVerifiedAt: Any, val id: Int, @field:SerializedName("first_name") val firstName: String, val email: String )
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/network/responses/AuthResponse.kt
478783458
package com.adiluhung.mobilejournaling.data.local import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class UserPreferences(private val context: Context) { fun getUserToken(): Flow<String?> { return context.dataStore.data.map { preferences -> preferences[TOKEN_KEY] } } suspend fun saveUserToken(token: String) { context.dataStore.edit { preference -> preference[TOKEN_KEY] = token } } suspend fun deleteUserToken() { context.dataStore.edit { preference -> preference.remove(TOKEN_KEY) } } fun getCompleteProfile(): Flow<Boolean> { return context.dataStore.data.map { preferences -> preferences[COMPLETE_PROFILE_KEY] ?: false } } suspend fun saveCompleteProfile(complete: Boolean) { context.dataStore.edit { preference -> preference[COMPLETE_PROFILE_KEY] = complete } } fun getAlarm(): Flow<String?> { return context.dataStore.data.map { preferences -> preferences[ALARM_KEY] } } suspend fun saveAlarm(alarm: String) { context.dataStore.edit { preference -> preference[ALARM_KEY] = alarm } } companion object { private val TOKEN_KEY = stringPreferencesKey("token") private val COMPLETE_PROFILE_KEY = booleanPreferencesKey("complete_profile") private val ALARM_KEY = stringPreferencesKey("alarm") private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("user") } }
mobile-journaling/app/src/main/java/com/adiluhung/mobilejournaling/data/local/UserPreferences.kt
2940783163
package me.lab.happyprimo 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("me.lab.happyprimo", appContext.packageName) } }
HappyPrimo/app/src/androidTest/java/me/lab/happyprimo/ExampleInstrumentedTest.kt
2567740477
package me.lab.happyprimo 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) } }
HappyPrimo/app/src/test/java/me/lab/happyprimo/ExampleUnitTest.kt
371691944
package me.lab.happyprimo.ui.home import android.content.ContentValues.TAG import android.content.Context import android.util.Log import android.widget.Toast import androidx.lifecycle.LifecycleCoroutineScope import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import me.lab.happyprimo.data.network.ServiceClient import retrofit2.HttpException import okhttp3.ResponseBody import com.google.gson.Gson import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.MainScope import me.lab.happyprimo.data.local.dao.DatabaseHelper import me.lab.happyprimo.data.models.FeedData import me.lab.happyprimo.data.models.FeedResponseModel import me.lab.happyprimo.data.repositories.DatabaseRepository import me.lab.happyprimo.utils.xmlToJson import retrofit2.Response class HomeViewModel( private val applicationContext: Context, private val lifecycleScope: LifecycleCoroutineScope ) : ViewModel() { private val _text = MutableLiveData<String>() val text: LiveData<String> = _text private val dbHelper = DatabaseHelper(applicationContext) private val repository = DatabaseRepository(dbHelper) val meduimProfileUrl = MutableLiveData<String?>() val showProgressbar = MutableLiveData<Boolean>() val feedData = MutableLiveData<List<FeedResponseModel>>() fun getDataFeed() { val url = "https://medium.com/" showProgressbar.value = true MainScope().launch { try { val result = async(Dispatchers.IO) { ServiceClient.createForXML(url).getFeed() } val response = result.await() if (response.isSuccessful) { showProgressbar.value = false val responseBody: Response<ResponseBody> = response val xmlString = responseBody.body()?.source()?.readUtf8() val json = xmlToJson(xmlString.orEmpty()) val responseJsonBody = Gson().fromJson(json.toString(), FeedResponseModel::class.java) handleDataFeed(responseJsonBody) } else { showProgressbar.value = false Log.e(TAG, "Response not successful: ${response.code()}") } } catch (ex: Exception) { handleException(ex) } } } private fun handleDataFeed(responseJsonBody: FeedResponseModel) { val feedDataLocal = repository.getFeedData() if (feedDataLocal == null) { Toast.makeText(applicationContext, "Create", Toast.LENGTH_SHORT).show() if (saveFeedDataToDatabase(FeedData(1, Gson().toJson(responseJsonBody)))) { getFeedDataFromDatabase() } } else { val localData = Gson().fromJson(feedDataLocal.feedData, FeedResponseModel::class.java) if (localData.item?.size != responseJsonBody.item?.size) { Toast.makeText(applicationContext, "Update", Toast.LENGTH_SHORT).show() if (saveFeedDataToDatabase(FeedData(1, Gson().toJson(responseJsonBody)))) { getFeedDataFromDatabase() } } else { // Toast.makeText(applicationContext, "No update", Toast.LENGTH_SHORT).show() getFeedDataFromDatabase() } } } private fun handleException(ex: Exception) { showProgressbar.value = false Log.e("Exception", "Error: ${ex.message}", ex) if (ex is HttpException) { Log.e("HttpException", "(${ex.code()}): $ex") } } private fun getFeedDataFromDatabase() { val feedDataLocal = repository.getFeedData() feedDataLocal?.let { val responseJsonBody = Gson().fromJson(it.feedData, FeedResponseModel::class.java) feedData.value = listOf(responseJsonBody) meduimProfileUrl.value = responseJsonBody.rss?.channel!!.title!!.description!!.link!!.image!!.url!!.urlData _text.value = responseJsonBody.rss.channel.title!!.titleData.toString() } } private fun saveFeedDataToDatabase(feedData: FeedData): Boolean { return repository.saveFeedData(feedData) } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/home/HomeViewModel.kt
3553718779
package me.lab.happyprimo.ui.home import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import me.lab.happyprimo.databinding.ItemFeedBinding import me.lab.happyprimo.data.models.FeedResponseModel.Item class FeedAdapter(private val items: List<Item?>? ,private val itemClickListener: OnItemClickListener) : RecyclerView.Adapter<FeedAdapter.ItemViewHolder>() { interface OnItemClickListener { fun onItemClick(item: Item ) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ItemFeedBinding.inflate(inflater, parent, false) return ItemViewHolder(binding) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val item = items?.get(position) if (item != null) { holder.bind(item) } } override fun getItemCount(): Int { return items?.size ?: 0 } inner class ItemViewHolder(private val binding: ItemFeedBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Item) { binding.apply { textViewTitle.text = item.title?.titleData textViewCategory.text = "Cetegory : ${item.title!!.link!!.guid!!.category.toString()}" textViewCreateBy.text = "Create by: " + item.title!!.link!!.guid!!.dcCreator!!.dcCreatorData root.setOnClickListener { itemClickListener.onItemClick(item) } } } } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/home/FeedAdapter.kt
531303734
package me.lab.happyprimo.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.TextView import androidx.activity.addCallback import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import me.lab.happyprimo.R import me.lab.happyprimo.data.models.FeedResponseModel import me.lab.happyprimo.databinding.FragmentHomeBinding import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class HomeFragment : Fragment() ,FeedAdapter.OnItemClickListener{ private var _binding: FragmentHomeBinding? = null private lateinit var feedAdapter: FeedAdapter private val binding get() = _binding!! private val homeViewModel: HomeViewModel by viewModel { parametersOf(requireContext(), viewLifecycleOwner.lifecycleScope) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val textView: TextView = binding.textMeduimName homeViewModel.getDataFeed() homeViewModel.apply { text.observe(viewLifecycleOwner) { textView.text = it } meduimProfileUrl.observe(viewLifecycleOwner) { Glide.with(requireContext()) .load(it) .into(binding.imageViewMeduimProfile) } showProgressbar.observe(viewLifecycleOwner) { isVisible -> binding.animationView.visibility = if (isVisible) VISIBLE else GONE binding.recyclerViewFeed.visibility = if (isVisible) GONE else VISIBLE } feedData.observe(viewLifecycleOwner){ val data :List<FeedResponseModel> = it feedAdapter = FeedAdapter(data.first().item,this@HomeFragment) binding.recyclerViewFeed.apply { adapter = feedAdapter layoutManager = LinearLayoutManager(requireContext()) } } } requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { activity?.finish() } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onItemClick(item: FeedResponseModel.Item) { val bundle = Bundle().apply { putString("url", item.title!!.link!!.guid!!.guidData) } findNavController().navigate(R.id.action_fragment_home_to_fragment_detail, bundle) } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/home/HomeFragment.kt
1694714660
package me.lab.happyprimo.ui import android.os.Bundle import android.util.Log import android.widget.Toast import android.widget.Toast.LENGTH_SHORT import androidx.appcompat.app.AppCompatActivity import androidx.navigation.fragment.NavHostFragment import me.lab.happyprimo.R import me.lab.happyprimo.databinding.ActivityMainBinding import me.lab.happyprimo.utils.isNetworkAvailable class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) if (isNetworkAvailable()) { initFragment() } else { Toast.makeText( this, getString(R.string.no_internet_connection), LENGTH_SHORT ).show() } } private fun initFragment() { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/MainActivity.kt
2226035571
package me.lab.happyprimo.ui.detail import android.content.Context import androidx.lifecycle.LifecycleCoroutineScope import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DetailsViewModel(context: Context, lifecycleScope: LifecycleCoroutineScope) : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is dashboard Fragment" } val text: LiveData<String> = _text }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/detail/DetailsViewModel.kt
2342933067
package me.lab.happyprimo.ui.detail import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import android.widget.TextView import androidx.activity.addCallback import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import me.lab.happyprimo.R import me.lab.happyprimo.databinding.FragmentDashboardBinding import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class DetailsFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private val dashboardViewModel: DetailsViewModel by viewModel { parametersOf(requireContext(),lifecycleScope) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDashboardBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val url = arguments?.getString("url") binding.apply { webView.webViewClient = WebViewClient() webView.settings.apply { javaScriptEnabled = true builtInZoomControls = true displayZoomControls = true domStorageEnabled = true } webView.loadUrl(url.toString()) webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { val url = request?.url.toString() if (url.startsWith("http:") || url.startsWith("https:")) { return false } else { return true } } } buttonBack.setOnClickListener { findNavController().navigate(R.id.action_fragment_detail_to_fragment_home) } requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { findNavController().navigate(R.id.action_fragment_detail_to_fragment_home) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/ui/detail/DetailsFragment.kt
1263329900
package me.lab.happyprimo.di import me.lab.happyprimo.ui.home.HomeViewModel import android.content.Context import androidx.lifecycle.LifecycleCoroutineScope import me.lab.happyprimo.ui.detail.DetailsViewModel import org.koin.dsl.module val appModule = module { single { (context: Context, lifecycleScope: LifecycleCoroutineScope) -> DetailsViewModel(context, lifecycleScope) } single { (context: Context, lifecycleScope: LifecycleCoroutineScope) -> HomeViewModel(context, lifecycleScope) } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/di/AppModule.kt
420754043
package me.lab.happyprimo.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import android.util.Log import com.google.gson.Gson import org.json.JSONArray import org.json.JSONObject import org.simpleframework.xml.core.Persister import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.StringReader fun Context.isNetworkAvailable(): Boolean { val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } //Internet connectivity check in Android Q val networks = connectivityManager.allNetworks var hasInternet = false if (networks.isNotEmpty()) { for (network in networks) { val networkCapabilities = connectivityManager.getNetworkCapabilities(network) if (networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) hasInternet = true } } return hasInternet }
HappyPrimo/app/src/main/java/me/lab/happyprimo/utils/Extensions.kt
1596599037
package me.lab.happyprimo.utils import com.google.gson.Gson import org.json.JSONArray import org.json.JSONObject import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.StringReader fun xmlToJson(xmlString: String): JSONObject { val json = JSONObject() val factory = XmlPullParserFactory.newInstance() val parser = factory.newPullParser() parser.setInput(StringReader(xmlString)) var currentArray: JSONArray? = null var currentElement: JSONObject? = null var tagName: String? = null var isCData = false var textContent: String? = null var eventType = parser.eventType while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { XmlPullParser.START_TAG -> { tagName = parser.name if (tagName == "item") { if (currentArray == null) { currentArray = JSONArray() json.put(tagName, currentArray) } currentElement = JSONObject() currentArray.put(currentElement) } else { val tagList = currentElement?.opt(tagName) if (tagList == null) { if (currentElement != null) { if (tagName == "category") { val categoryList = JSONArray() categoryList.put(parser.nextText()) currentElement.put(tagName, categoryList) } else { val newObject = JSONObject() currentElement.put(tagName, newObject) currentElement = newObject } } else { currentElement = JSONObject() json.put(tagName, currentElement) } } else { if (tagList is JSONArray) { tagList.put(parser.nextText()) } else { // If it's not an array, convert it to an array and add the existing value val newArray = JSONArray() if (tagList is String) { newArray.put(tagList) } else { // If it's not a string or an array, skip for now } newArray.put(parser.nextText()) currentElement?.put(tagName, newArray) } } } } XmlPullParser.TEXT -> { val text = parser.text.trim() if (text.isNotEmpty()) { if (isCData) { textContent = text } else { currentElement?.put(tagName + "_data", text) } } } XmlPullParser.END_TAG -> { tagName = parser.name if (tagName == "item") { currentElement = null } } } eventType = parser.next() } return json }
HappyPrimo/app/src/main/java/me/lab/happyprimo/utils/HttpsExtensions.kt
911879226
package me.lab.happyprimo.data.network import android.content.Context import com.google.gson.Gson import com.google.gson.GsonBuilder import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import me.lab.happyprimo.data.repositories.ServiceAPI import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.converter.simplexml.SimpleXmlConverterFactory import java.util.concurrent.TimeUnit class ServiceClient { companion object { @JvmStatic fun createWithToken( androidContext: Context ,token: String,baseUrl:String): ServiceAPI { val logging = HttpInterceptor() logging.apply { level = HttpInterceptor.Level.BODY } val header = Interceptor { chain -> chain.proceed( chain.request().newBuilder() .addHeader("Content-Type", "application/json") .addHeader("Authorization", token) .build() ) } val okHttpBuilder = OkHttpClient.Builder() .addInterceptor(header) .addInterceptor(logging) .connectTimeout(2000, TimeUnit.SECONDS) .writeTimeout(2000, TimeUnit.SECONDS) .readTimeout(2000, TimeUnit.SECONDS) val retrofit = Retrofit.Builder() .addConverterFactory( MoshiConverterFactory.create( Moshi.Builder().add( KotlinJsonAdapterFactory() ).build())) .client(okHttpBuilder.build()) .baseUrl(baseUrl) .build() return retrofit.create(ServiceAPI::class.java) } @JvmStatic fun create(androidContext: Context,baseUrl: String): ServiceAPI { val logging = HttpInterceptor() logging.apply { level = HttpInterceptor.Level.BODY } val header = Interceptor { chain -> chain.proceed( chain.request().newBuilder() .addHeader("Content-Type", "application/json") .build() ) } val okHttpBuilder = OkHttpClient.Builder() .addInterceptor(header) .addInterceptor(logging) .connectTimeout(2000, TimeUnit.SECONDS) .writeTimeout(2000, TimeUnit.SECONDS) .readTimeout(2000, TimeUnit.SECONDS) val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create( Moshi.Builder().add( KotlinJsonAdapterFactory() ).build())) .client(okHttpBuilder.build()) .baseUrl(baseUrl) .build() return retrofit.create(ServiceAPI::class.java) } fun createForXML(baseUrl: String): ServiceAPI { val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val headerInterceptor = Interceptor { chain -> chain.proceed( chain.request().newBuilder() .build() ) } val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(headerInterceptor) .connectTimeout(5000, TimeUnit.SECONDS) .writeTimeout(5000, TimeUnit.SECONDS) .readTimeout(5000, TimeUnit.SECONDS) .build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(SimpleXmlConverterFactory.create()) .client(okHttpClient) .build() return retrofit.create(ServiceAPI::class.java) } } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/network/ServiceClient.kt
979458431
package me.lab.happyprimo.data.network import java.nio.charset.Charset import java.util.concurrent.TimeUnit import okhttp3.Headers import okhttp3.Interceptor import okhttp3.Response import okhttp3.internal.http.promisesBody import okhttp3.internal.platform.Platform import okio.Buffer import okio.GzipSource import java.io.EOFException import java.nio.charset.StandardCharsets class HttpInterceptor(private val logger: Logger = Logger.DEFAULT) : Interceptor { var level = Level.NONE private var headersToRedact = emptySet<String>() fun interface Logger { fun log(message: String) companion object { /** A [Logger] defaults output appropriate for the current platform. */ @JvmField val DEFAULT: Logger = DefaultLogger() private class DefaultLogger : Logger { override fun log(message: String) { Platform.get().log(message) } } } } enum class Level { NONE, BASIC, HEADERS, BODY } override fun intercept(chain: Interceptor.Chain): Response { val level = this.level val request = chain.request() if (level == Level.NONE) { return chain.proceed(request) } val logBody = level == Level.BODY val logHeaders = logBody || level == Level.HEADERS val requestBody = request.body val connection = chain.connection() var requestStartMessage = ("--> ${request.method} ${request.url}${if (connection != null) " " + connection.protocol() else ""}") if (!logHeaders && requestBody != null) { requestStartMessage += " (${requestBody.contentLength()}-byte body)" } logger.log(requestStartMessage) if (logHeaders) { val headers = request.headers if (requestBody != null) { // Request body headers are only present when installed as a network interceptor. When not // already present, force them to be included (if available) so their values are known. requestBody.contentType()?.let { if (headers["Content-Type"] == null) { logger.log("Content-Type: $it") } } if (requestBody.contentLength() != -1L) { if (headers["Content-Length"] == null) { logger.log("Content-Length: ${requestBody.contentLength()}") } } } for (i in 0 until headers.size) { logHeader(headers, i) } if (!logBody || requestBody == null) { logger.log("--> END ${request.method}") } else if (bodyHasUnknownEncoding(request.headers)) { logger.log("--> END ${request.method} (encoded body omitted)") } else if (requestBody.isDuplex()) { logger.log("--> END ${request.method} (duplex request body omitted)") } else if (requestBody.isOneShot()) { logger.log("--> END ${request.method} (one-shot body omitted)") } else { val buffer = Buffer() requestBody.writeTo(buffer) val contentType = requestBody.contentType() val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8 logger.log("") if (buffer.isProbablyUtf8()) { logger.log(buffer.readString(charset)) logger.log("--> END ${request.method} (${requestBody.contentLength()}-byte body)") } else { logger.log( "--> END ${request.method} (binary ${requestBody.contentLength()}-byte body omitted)") } } } val startNs = System.nanoTime() val response: Response try { response = chain.proceed(request) } catch (e: Exception) { logger.log("<-- HTTP FAILED: $e") throw e } val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs) val responseBody = response.body!! val contentLength = responseBody.contentLength() val bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length" logger.log( "<-- ${response.code}${if (response.message.isEmpty()) "" else ' ' + response.message} ${response.request.url} (${tookMs}ms${if (!logHeaders) ", $bodySize body" else ""})") //Save log request to Realm if (logHeaders) { val headers = response.headers for (i in 0 until headers.size) { logHeader(headers, i) } if (!logBody || !response.promisesBody()) { logger.log("<-- END HTTP") } else if (bodyHasUnknownEncoding(response.headers)) { logger.log("<-- END HTTP (encoded body omitted)") } else { val source = responseBody.source() source.request(Long.MAX_VALUE) // Buffer the entire body. var buffer = source.buffer var gzippedLength: Long? = null if ("gzip".equals(headers["Content-Encoding"], ignoreCase = true)) { gzippedLength = buffer.size GzipSource(buffer.clone()).use { gzippedResponseBody -> buffer = Buffer() buffer.writeAll(gzippedResponseBody) } } val contentType = responseBody.contentType() val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8 if (!buffer.isProbablyUtf8()) { logger.log("") logger.log("<-- END HTTP (binary ${buffer.size}-byte body omitted)") return response } if (contentLength != 0L) { logger.log("") logger.log(buffer.clone().readString(charset)) } if (gzippedLength != null) { logger.log("<-- END HTTP (${buffer.size}-byte, $gzippedLength-gzipped-byte body)") } else { logger.log("<-- END HTTP (${buffer.size}-byte body)") } } } return response } private fun logHeader(headers: Headers, i: Int) { val value = if (headers.name(i) in headersToRedact) "โ–ˆโ–ˆ" else headers.value(i) logger.log(headers.name(i) + ": " + value) } private fun bodyHasUnknownEncoding(headers: Headers): Boolean { val contentEncoding = headers["Content-Encoding"] ?: return false return !contentEncoding.equals("identity", ignoreCase = true) && !contentEncoding.equals("gzip", ignoreCase = true) } private fun Buffer.isProbablyUtf8(): Boolean { try { val prefix = Buffer() val byteCount = size.coerceAtMost(64) copyTo(prefix, 0, byteCount) for (i in 0 until 16) { if (prefix.exhausted()) { break } val codePoint = prefix.readUtf8CodePoint() if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) { return false } } return true } catch (_: EOFException) { return false // Truncated UTF-8 sequence. } } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/network/HttpInterceptor.kt
347997700
package me.lab.happyprimo.data.repositories import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Headers interface ServiceAPI { // @GET("feed/@Tarn1997") @GET("feed/@primoapp") @Headers("Accept: application/xml") suspend fun getFeed( ): Response<ResponseBody> }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/repositories/ServiceAPI.kt
1223206475
package me.lab.happyprimo.data.repositories import android.content.ContentValues import me.lab.happyprimo.data.local.dao.DatabaseHelper import me.lab.happyprimo.data.models.FeedData class DatabaseRepository(private val dbHelper: DatabaseHelper) { fun saveFeedData(feedData: FeedData): Boolean { val db = dbHelper.writableDatabase val values = ContentValues().apply { put("feed_data", feedData.feedData) } db.beginTransaction() try { val id = feedData.id if (id != null && id != -1) { // Check if data with the given ID exists val cursor = db.query( "my_table", null, "id = ?", arrayOf(id.toString()), null, null, null ) val dataExists = cursor.count > 0 cursor.close() if (dataExists) { // Update existing data val rowsAffected = db.update("my_table", values, "id = ?", arrayOf(id.toString())) db.setTransactionSuccessful() return rowsAffected > 0 } else { // Insert new data val newRowId = db.insert("my_table", null, values) db.setTransactionSuccessful() return newRowId != -1L } } else { // If ID is null or -1, insert new data val newRowId = db.insert("my_table", null, values) db.setTransactionSuccessful() return newRowId != -1L } } catch (e: Exception) { // Handle any exceptions return false } finally { db.endTransaction() db.close() } } fun getFeedData(): FeedData? { val db = dbHelper.readableDatabase val cursor = db.rawQuery("SELECT * FROM my_table", null) var feedData: FeedData? = null cursor.use { if (it.moveToFirst()) { val idIndex = it.getColumnIndex("id") val feedIndex = it.getColumnIndex("feed_data") if (idIndex != -1 && feedIndex != -1) { val id = it.getInt(idIndex) val feed = it.getString(feedIndex) feedData = FeedData(id, feed) } } } return feedData } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/repositories/DatabaseRepository.kt
4223555683
package me.lab.happyprimo.data.models data class FeedData(val id: Int?, val feedData: String)
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/models/FeedData.kt
3888820989
package me.lab.happyprimo.data.models import com.google.gson.annotations.SerializedName data class FeedResponseModel( @SerializedName("item") val item: List<Item?>?, @SerializedName("rss") val rss: Rss? ) { data class Item( @SerializedName("title") val title: Title? ) { data class Title( @SerializedName("link") val link: Link?, @SerializedName("title_data") val titleData: String? ) { data class Link( @SerializedName("guid") val guid: Guid?, @SerializedName("link_data") val linkData: String? ) { data class Guid( @SerializedName("category") val category: List<String?>?, @SerializedName("dc:creator") val dcCreator: DcCreator?, @SerializedName("guid_data") val guidData: String? ) { data class DcCreator( @SerializedName("dc:creator_data") val dcCreatorData: String?, @SerializedName("pubDate") val pubDate: PubDate? ) { data class PubDate( @SerializedName("atom:updated") val atomUpdated: AtomUpdated?, @SerializedName("pubDate_data") val pubDateData: String? ) { data class AtomUpdated( @SerializedName("atom:updated_data") val atomUpdatedData: String?, @SerializedName("content:encoded") val contentEncoded: ContentEncoded? ) { data class ContentEncoded( @SerializedName("content:encoded_data") val contentEncodedData: String? ) } } } } } } } data class Rss( @SerializedName("channel") val channel: Channel? ) { data class Channel( @SerializedName("title") val title: Title? ) { data class Title( @SerializedName("description") val description: Description?, @SerializedName("title_data") val titleData: String? ) { data class Description( @SerializedName("description_data") val descriptionData: String?, @SerializedName("link") val link: Link? ) { data class Link( @SerializedName("image") val image: Image?, @SerializedName("link_data") val linkData: String? ) { data class Image( @SerializedName("url") val url: Url? ) { data class Url( @SerializedName("title") val title: Title?, @SerializedName("url_data") val urlData: String? ) { data class Title( @SerializedName("link") val link: Link?, @SerializedName("title_data") val titleData: String? ) { data class Link( @SerializedName("generator") val generator: Generator?, @SerializedName("link_data") val linkData: String? ) { data class Generator( @SerializedName("generator_data") val generatorData: String?, @SerializedName("lastBuildDate") val lastBuildDate: LastBuildDate? ) { data class LastBuildDate( @SerializedName("atom:link") val atomLink: AtomLink?, @SerializedName("lastBuildDate_data") val lastBuildDateData: String? ) { data class AtomLink( @SerializedName("webMaster") val webMaster: WebMaster? ) { data class WebMaster( @SerializedName("atom:link") val atomLink: AtomLink?, @SerializedName("webMaster_data") val webMasterData: String? ) { class AtomLink } } } } } } } } } } } } } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/models/FeedResponseModel.kt
223913788
package me.lab.happyprimo.data.local.dao import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.content.Context class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, "my_database", null, 2) { override fun onCreate(db: SQLiteDatabase) { db.execSQL("CREATE TABLE my_table (id INTEGER PRIMARY KEY AUTOINCREMENT, feed_data TEXT)") } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // Handle database schema changes here if needed } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/data/local/dao/DatabaseHelper.kt
4033494517
package me.lab.happyprimo import android.app.Application import me.lab.happyprimo.di.appModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MainApplication) modules(appModule) } } }
HappyPrimo/app/src/main/java/me/lab/happyprimo/MainApplication.kt
1502222653
package com.example.myfirstapp_opsc7411 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.myfirstapp_opsc7411", appContext.packageName) } }
MyFirstApp-OPSC7411NEW/app/src/androidTest/java/com/example/myfirstapp_opsc7411/ExampleInstrumentedTest.kt
87277712
package com.example.myfirstapp_opsc7411 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) } }
MyFirstApp-OPSC7411NEW/app/src/test/java/com/example/myfirstapp_opsc7411/ExampleUnitTest.kt
2590069629
package com.example.myfirstapp_opsc7411 import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.myfirstapp_opsc7411.databinding.ActivityOrderDetailsBinding class OrderDetailsActivity : AppCompatActivity() { var order = Order() var hello: String = "Hello" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityOrderDetailsBinding.inflate(layoutInflater) order.productName = intent.getStringExtra("order").toString() binding.txfOrder.text = order.productName when(order.productName){ "Soy Latte" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb1) "Chocco Frapp" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb2) "Bottled Americano" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb3) "Rainbow Frapp" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb4) "Caramel Frapp" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb5) "Black Forest Frapp" -> binding.imgSelectedDrink.setImageResource(R.drawable.sb6) } binding.fab.setOnClickListener(){ shareIntent(this, order.productName) } setContentView(R.layout.activity_order_details) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
MyFirstApp-OPSC7411NEW/app/src/main/java/com/example/myfirstapp_opsc7411/OrderDetailsActivity.kt
1740251256
package com.example.myfirstapp_opsc7411 import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.myfirstapp_opsc7411.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { var order = Order() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() var binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.imageView7.setOnClickListener(this) binding.imageView6.setOnClickListener(this) binding.imageView5.setOnClickListener(this) binding.imageView4.setOnClickListener(this) binding.imageView3.setOnClickListener(this) binding.imageView2.setOnClickListener(this) } override fun onClick(v: View?) { when(v?.id){ R.id.imageView2 -> order.productName = "Soy Latte" R.id.imageView3 -> order.productName = "Chocco Frapp" R.id.imageView4 -> order.productName = "Bottled Americano" R.id.imageView5 -> order.productName = "Rainbow Frapp" R.id.imageView6 -> order.productName = "Caramel Frapp" R.id.imageView7 -> order.productName = "Black Forest Frapp" } Toast.makeText(this@MainActivity, "MMM " + order.productName, Toast.LENGTH_SHORT).show() openIntent(this, order.productName, OrderDetailsActivity::class.java) } }
MyFirstApp-OPSC7411NEW/app/src/main/java/com/example/myfirstapp_opsc7411/MainActivity.kt
438350932
package com.example.myfirstapp_opsc7411 import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle fun openIntent(activity: Activity, order: String, activityToOpen: Class<*>){ //declare intenet with context and class to pass the value val intent = Intent(activity, activityToOpen) //pass through the string value with the key "order" intent.putExtra("Order", order) //Start activity activity.startActivity(intent) } fun shareIntent(context: Context, order: String){ //Create new intent object fr sending data var sendIntent = Intent() // Sets the action of the intent to the ACTION_SEND, indicating that the intent is sendIntent.setAction(Intent.ACTION_SEND) sendIntent.putExtra(Intent.EXTRA_TEXT, order) sendIntent.setType(("text/plain")) var shareIntent = Intent.createChooser(sendIntent, null) context.startActivity(shareIntent) } fun shareIntent(context: Context, order: Order){ var sendIntent = Intent() sendIntent.setAction(Intent.ACTION_SEND) var shareOrderDetails = Bundle() shareOrderDetails.putString("productname", order.productName) shareOrderDetails.putString("customerName", order.customerName) shareOrderDetails.putString("customerCell", order.customerCell) sendIntent.putExtra(Intent.EXTRA_TEXT, shareOrderDetails) sendIntent.setType("text/plain") var shareIntent = Intent.createChooser(sendIntent, null) context.startActivity(shareIntent) }
MyFirstApp-OPSC7411NEW/app/src/main/java/com/example/myfirstapp_opsc7411/IntentHelper.kt
280533685
package com.example.myfirstapp_opsc7411 import kotlin.experimental.ExperimentalObjCName class Order() { lateinit var productName: String lateinit var customerName: String lateinit var customerCell: String lateinit var orderDate: String constructor(pName: String) : this() { productName = pName } constructor(pName: String, cName: String, cCell: String, oDate: String): this(pName){ customerName = cName customerCell = cCell orderDate = oDate } }
MyFirstApp-OPSC7411NEW/app/src/main/java/com/example/myfirstapp_opsc7411/Order.kt
542851447
package com.lemondog.simpleplayer 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.lemondog.simpleplayer", appContext.packageName) } }
SimplePlayer/app/src/androidTest/java/com/lemondog/simpleplayer/ExampleInstrumentedTest.kt
2170333338
package com.lemondog.simpleplayer 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) } }
SimplePlayer/app/src/test/java/com/lemondog/simpleplayer/ExampleUnitTest.kt
2355740731
package com.lemondog.simpleplayer import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication : Application()
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/MyApplication.kt
652191749
package com.lemondog.simpleplayer import android.os.Bundle import androidx.fragment.app.FragmentActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/MainActivity.kt
1788121650
package com.lemondog.simpleplayer.di import android.content.Context import com.lemondog.simpleplayer.common.coroutine.ApplicationCoroutineScope import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.SupervisorJob import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideContext(@ApplicationContext context: Context): Context = context @Provides @Singleton internal fun provideApplicationCoroutineScope(): ApplicationCoroutineScope = ApplicationCoroutineScope(SupervisorJob()) }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/di/AppModule.kt
1666536267
package com.lemondog.simpleplayer.di import com.lemondog.simpleplayer.common.coroutine.DefaultDispatcherProvider import com.lemondog.simpleplayer.common.coroutine.DispatcherProvider import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class DispatcherModule { /** * Coroutines * */ @Binds @Singleton abstract fun bindDispatcherProvider( defaultDispatcherProvider: DefaultDispatcherProvider, ): DispatcherProvider }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/di/DispatcherModule.kt
2811519292
package com.lemondog.simpleplayer.common.coroutine import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import javax.inject.Inject interface DispatcherProvider { fun default(): CoroutineDispatcher = Dispatchers.Default fun io(): CoroutineDispatcher = Dispatchers.IO fun main(): CoroutineDispatcher = Dispatchers.Main fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined } class DefaultDispatcherProvider @Inject constructor() : DispatcherProvider
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/common/coroutine/DispatcherProvider.kt
2008183555
package com.lemondog.simpleplayer.common.coroutine import kotlinx.coroutines.CoroutineScope import kotlin.coroutines.CoroutineContext class ApplicationCoroutineScope(context: CoroutineContext) : CoroutineScope { override val coroutineContext: CoroutineContext = context }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/common/coroutine/ApplicationCoroutineScope.kt
1386983228
package com.lemondog.simpleplayer.view.videoscreen import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.material.Text import androidx.compose.material3.Scaffold import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import com.lemondog.simpleplayer.view.CustomBottomNavigationItemView import com.lemondog.simpleplayer.view.HomeFragmentViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class VideoFragment : Fragment() { private val viewModel by viewModels<HomeFragmentViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setContent { Scaffold( bottomBar = { CustomBottomNavigationItemView( videoPageSelected = true, onMusicButtonAction = { val action = VideoFragmentDirections.actionVideoFragmentToHomeFragment() findNavController().navigate(action) }, ) }, ) { Text("Video Screen") } } } } }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/view/videoscreen/VideoFragment.kt
2644557304
package com.lemondog.simpleplayer.view import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class HomeFragmentViewModel @Inject constructor( ) : ViewModel() { }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/view/HomeFragmentViewModel.kt
1077630922
package com.lemondog.simpleplayer.view import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.lemondog.simpleplayer.R @Composable fun CustomBottomNavigationItemView( modifier: Modifier = Modifier, musicPageSelected: Boolean = false, videoPageSelected: Boolean = false, onMusicButtonAction: () -> Unit = {}, onVideoButtonAction: () -> Unit = {}, ) { BottomNavigation(modifier = modifier) { BottomNavigationItem( selected = musicPageSelected, onClick = { onMusicButtonAction() }, icon = { Text(stringResource(R.string.music)) }, ) BottomNavigationItem( selected = videoPageSelected, onClick = { onVideoButtonAction() }, icon = { Text(stringResource(R.string.video)) }, ) } }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/view/CustomBottomNavigationItemView.kt
2120605051
package com.lemondog.simpleplayer.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Text import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.res.stringResource import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import com.lemondog.simpleplayer.R import dagger.hilt.android.AndroidEntryPoint /** * ToDos: * 1. setup youtube with simple data * 2. test setup music view * 3. test setup video view * 4. setup Repository * 5. setup RoomDB * */ @AndroidEntryPoint class HomeFragment : Fragment() { private val viewModel by viewModels<HomeFragmentViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setContent { Scaffold( bottomBar = { CustomBottomNavigationItemView( musicPageSelected = true, onVideoButtonAction = { val action = HomeFragmentDirections.actionHomeFragmentToVideoFragment() findNavController().navigate(action) }, ) }, ) { Text("Home") } } } } }
SimplePlayer/app/src/main/java/com/lemondog/simpleplayer/view/HomeFragment.kt
784490090
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) } }
seminario_desarrollo_interfaces_3/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
seminario_desarrollo_interfaces_3/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.myapplication.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) configurarBotones() } private fun configurarBotones() { binding.btnActividad1.setOnClickListener { val intent = Intent(this@MainActivity, PimerEjercicioActivity1::class.java) startActivity(intent) } binding.btnActividad2.setOnClickListener { val intent = Intent(this@MainActivity, SegundoEjercicioActivity::class.java) startActivity(intent) } binding.btnActividad3.setOnClickListener { val intent = Intent(this@MainActivity, TercerEjercicioActivity::class.java) startActivity(intent) } } }
seminario_desarrollo_interfaces_3/app/src/main/java/com/example/myapplication/MainActivity.kt
999235052
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import android.widget.ImageView import com.example.myapplication.databinding.ActivityMainBinding import com.example.myapplication.databinding.ActivitySegundoEjercicioBinding class SegundoEjercicioActivity : AppCompatActivity() { private lateinit var binding: ActivitySegundoEjercicioBinding private var isPressedButton = false private lateinit var countDownTimer: CountDownTimer private var tiempoRestante: Long = 2000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySegundoEjercicioBinding.inflate(layoutInflater) setContentView(binding.root) // Inicializar el contador regresivo countDownTimer = object : CountDownTimer(tiempoRestante, 1000) { override fun onTick(millisUntilFinished: Long) { tiempoRestante = millisUntilFinished } override fun onFinish() { recreate() } } configurarBotones() } private fun configurarBotones() { binding.ivPrimera.setOnClickListener { if (!isPressedButton){ // Iniciar el contador regresivo isPressedButton = true countDownTimer.start() binding.ivPrimera.setImageResource(R.drawable.card_2) } } binding.ivSegunda.setOnClickListener { if (!isPressedButton){ // Iniciar el contador regresivo isPressedButton = true countDownTimer.start() binding.ivSegunda.setImageResource(R.drawable.card_4) } } binding.ivTercera.setOnClickListener { if (!isPressedButton){ // Iniciar el contador regresivo isPressedButton = true countDownTimer.start() binding.ivTercera.setImageResource(R.drawable.card_joker) } } binding.ivBavk.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } }
seminario_desarrollo_interfaces_3/app/src/main/java/com/example/myapplication/SegundoEjercicioActivity.kt
946279947
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import com.example.myapplication.databinding.ActivityMainBinding import com.example.myapplication.databinding.ActivityPimerEjercicio1Binding class PimerEjercicioActivity1 : AppCompatActivity() { private lateinit var binding: ActivityPimerEjercicio1Binding private lateinit var countDownTimer: CountDownTimer private var tiempoRestante: Long = 10000 // Tiempo en milisegundos (en este ejemplo, 60 segundos) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPimerEjercicio1Binding.inflate(layoutInflater) setContentView(binding.root) // Inicializar el contador regresivo countDownTimer = object : CountDownTimer(tiempoRestante, 1000) { override fun onTick(millisUntilFinished: Long) { tiempoRestante = millisUntilFinished actualizarContador() } override fun onFinish() { // Acciones a realizar cuando el contador llega a cero val intent = Intent(this@PimerEjercicioActivity1, PrimerEjercicioActivity2::class.java) startActivity(intent) } } // Iniciar el contador regresivo countDownTimer.start() } private fun actualizarContador() { val segundos = tiempoRestante / 1000 binding.tvCuentaAtras.text = "$segundos" + " s" } }
seminario_desarrollo_interfaces_3/app/src/main/java/com/example/myapplication/PimerEjercicioActivity1.kt
901499855
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.myapplication.databinding.ActivityMainBinding import com.example.myapplication.databinding.ActivityPrimerEjercicio2Binding class PrimerEjercicioActivity2 : AppCompatActivity() { private lateinit var binding: ActivityPrimerEjercicio2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPrimerEjercicio2Binding.inflate(layoutInflater) setContentView(binding.root) binding.ivBavk.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } }
seminario_desarrollo_interfaces_3/app/src/main/java/com/example/myapplication/PrimerEjercicioActivity2.kt
3374450257
package com.example.myapplication import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.CountDownTimer import androidx.appcompat.app.AppCompatActivity import com.example.myapplication.databinding.ActivityTercerEjercicioBinding class TercerEjercicioActivity : AppCompatActivity() { private lateinit var binding: ActivityTercerEjercicioBinding private lateinit var countDownTimer: CountDownTimer private var tiempoRestante: Long = 5000 private var estadoSemaforo: Int = 0 // 0: verde, 1: amarillo, 2: rojo override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTercerEjercicioBinding.inflate(layoutInflater) setContentView(binding.root) binding.clCambiarColor.setBackgroundColor(Color.GREEN) // Inicializar el contador regresivo countDownTimer = object : CountDownTimer(tiempoRestante, 1000) { override fun onTick(millisUntilFinished: Long) { tiempoRestante = millisUntilFinished actualizarSemaforo() } override fun onFinish() { // Reiniciar el temporizador al llegar a cero tiempoRestante = 5000 // Inicializar tiempo a 5 segundos para el prรณximo ciclo countDownTimer.start() } } // Iniciar el contador regresivo countDownTimer.start() binding.ivBavk.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } private fun actualizarSemaforo() { when { tiempoRestante > 2000 && estadoSemaforo != 0 -> { // Cambiar a verde binding.clCambiarColor.setBackgroundColor(Color.GREEN) binding.ivFoto.setImageResource(R.drawable.semaforo_verde) estadoSemaforo = 0 } tiempoRestante in 1000..2000 && estadoSemaforo != 1 -> { // Cambiar a amarillo binding.clCambiarColor.setBackgroundColor(Color.YELLOW) binding.ivFoto.setImageResource(R.drawable.semaforo_amarillo) estadoSemaforo = 1 } tiempoRestante in 0..1000 && estadoSemaforo != 2 -> { // Cambiar a rojo binding.clCambiarColor.setBackgroundColor(Color.RED) binding.ivFoto.setImageResource(R.drawable.semaforo_rojo) estadoSemaforo = 2 } } } }
seminario_desarrollo_interfaces_3/app/src/main/java/com/example/myapplication/TercerEjercicioActivity.kt
2895017605
package com.example.calculator 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.calculator", appContext.packageName) } }
GUICalculator/app/src/androidTest/java/com/example/calculator/ExampleInstrumentedTest.kt
4259167099
package com.example.calculator 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) } }
GUICalculator/app/src/test/java/com/example/calculator/ExampleUnitTest.kt
3889441106
package com.example.calculator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.* import kotlin.math.sqrt class MainActivity : AppCompatActivity() { // declare variables private lateinit var editText: EditText private var currentInput: StringBuilder = StringBuilder() private var currentOperator: String? = null private var operand1: Double? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // find the id for editText and set it to the variable editText editText = findViewById(R.id.editText) // set click listener for number buttons (0-9) findViewById<Button>(R.id.zero_button).setOnClickListener { append("0") } findViewById<Button>(R.id.one_button).setOnClickListener { append("1") } findViewById<Button>(R.id.two_button).setOnClickListener { append("2") } findViewById<Button>(R.id.three_button).setOnClickListener { append("3") } findViewById<Button>(R.id.four_button).setOnClickListener{ append("4") } findViewById<Button>(R.id.five_button).setOnClickListener{ append("5") } findViewById<Button>(R.id.six_button).setOnClickListener{ append("6") } findViewById<Button>(R.id.seven_button).setOnClickListener { append("7") } findViewById<Button>(R.id.eight_button).setOnClickListener{ append("8") } findViewById<Button>(R.id.nine_button).setOnClickListener { append("9") } // set click listener for operators findViewById<Button>(R.id.add_button).setOnClickListener { operator("+") } findViewById<Button>(R.id.subtract_button).setOnClickListener { operator("-") } findViewById<Button>(R.id.multiply_button).setOnClickListener { operator("*") } findViewById<Button>(R.id.divide_button).setOnClickListener{ operator("/") } findViewById<Button>(R.id.sqrt_button).setOnClickListener { if (currentOperator == null && operand1 == null) { val input = currentInput.toString().toDoubleOrNull() if (input != null) { val result = sqrt(input) editText.setText(result.toString()) } else { editText.setText("Invalid input") } currentInput.clear() } else { editText.setText("Invalid input") currentInput.clear() operand1 = null currentOperator = null } } findViewById<Button>(R.id.dot_button).setOnClickListener { append(".") } findViewById<Button>(R.id.equal_button).setOnClickListener { calculate() } findViewById<Button>(R.id.clear_button).setOnClickListener { currentInput.clear() // clear input operand1 = null // set operand to null currentOperator = null // set current operator to null editText.text.clear() } } private fun append(value: String) { currentInput.append(value) editText.setText(currentInput.toString()) } private fun operator(operator: String) { if (operand1 == null) { operand1 = currentInput.toString().toDoubleOrNull() currentInput.clear() currentOperator = operator } else { calculate() currentOperator = operator } } private fun calculate() { val operand2 = currentInput.toString().toDoubleOrNull() if (operand1 != null && operand2 != null && currentOperator != null) { if (currentOperator == "/" && operand2 == 0.0) { // handle division by zero editText.setText("Divide by 0 Error") currentInput.clear() operand1 = null currentOperator = null } else { val result = if (currentOperator == "+") { operand1!! + operand2 } else if (currentOperator == "-") { operand1!! - operand2 } else if (currentOperator == "*") { operand1!! * operand2 } else if (currentOperator == "/") { operand1!! / operand2 } else { throw IllegalArgumentException("Invalid Operator") } editText.setText(result.toString()) currentInput.clear() operand1 = result currentOperator = null } } } }
GUICalculator/app/src/main/java/com/example/calculator/MainActivity.kt
2062376777
package xyz.axxonte.myrapp 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("xyz.axxonte.myrapp", appContext.packageName) } }
RiotStatApp/app/src/androidTest/java/xyz/axxonte/myrapp/ExampleInstrumentedTest.kt
1589116588
package xyz.axxonte.myrapp 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) } }
RiotStatApp/app/src/test/java/xyz/axxonte/myrapp/ExampleUnitTest.kt
628459617
package xyz.axxonte.myrapp.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF5F52A7) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFE5DEFF) val md_theme_light_onPrimaryContainer = Color(0xFF1A0261) val md_theme_light_secondary = Color(0xFF4658A9) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFDDE1FF) val md_theme_light_onSecondaryContainer = Color(0xFF001356) val md_theme_light_tertiary = Color(0xFF994700) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFDBC8) val md_theme_light_onTertiaryContainer = Color(0xFF321200) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFF8FDFF) val md_theme_light_onBackground = Color(0xFF001F25) val md_theme_light_surface = Color(0xFFF8FDFF) val md_theme_light_onSurface = Color(0xFF001F25) val md_theme_light_surfaceVariant = Color(0xFFE5E0EC) val md_theme_light_onSurfaceVariant = Color(0xFF48454E) val md_theme_light_outline = Color(0xFF79757F) val md_theme_light_inverseOnSurface = Color(0xFFD6F6FF) val md_theme_light_inverseSurface = Color(0xFF00363F) val md_theme_light_inversePrimary = Color(0xFFC9BFFF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF5F52A7) val md_theme_light_outlineVariant = Color(0xFFC9C5D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFC9BFFF) val md_theme_dark_onPrimary = Color(0xFF302175) val md_theme_dark_primaryContainer = Color(0xFF473A8D) val md_theme_dark_onPrimaryContainer = Color(0xFFE5DEFF) val md_theme_dark_secondary = Color(0xFFB9C3FF) val md_theme_dark_onSecondary = Color(0xFF122878) val md_theme_dark_secondaryContainer = Color(0xFF2D4090) val md_theme_dark_onSecondaryContainer = Color(0xFFDDE1FF) val md_theme_dark_tertiary = Color(0xFFFFB68B) val md_theme_dark_onTertiary = Color(0xFF522300) val md_theme_dark_tertiaryContainer = Color(0xFF753400) val md_theme_dark_onTertiaryContainer = Color(0xFFFFDBC8) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF001F25) val md_theme_dark_onBackground = Color(0xFFA6EEFF) val md_theme_dark_surface = Color(0xFF001F25) val md_theme_dark_onSurface = Color(0xFFA6EEFF) val md_theme_dark_surfaceVariant = Color(0xFF48454E) val md_theme_dark_onSurfaceVariant = Color(0xFFC9C5D0) val md_theme_dark_outline = Color(0xFF938F99) val md_theme_dark_inverseOnSurface = Color(0xFF001F25) val md_theme_dark_inverseSurface = Color(0xFFA6EEFF) val md_theme_dark_inversePrimary = Color(0xFF5F52A7) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFC9BFFF) val md_theme_dark_outlineVariant = Color(0xFF48454E) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFF1A1825)
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/theme/Color.kt
3736972155
package xyz.axxonte.myrapp.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun MyRAppTheme( useDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit ) { val colors = if (!useDarkTheme) { LightColors } else { DarkColors } MaterialTheme( colorScheme = colors, content = content ) }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/theme/Theme.kt
90601843
package xyz.axxonte.myrapp.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 ) */ )
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/theme/Type.kt
3774733124
package xyz.axxonte.myrapp.ui class HomeScreen { }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/HomeScreen.kt
1792248051
package xyz.axxonte.myrapp.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import xyz.axxonte.jacquesnoirremastered.network.ApiClient import xyz.axxonte.myrapp.network.Rank import xyz.axxonte.myrapp.network.Summoner class AppViewModel : ViewModel() { private val _uiState = MutableStateFlow<AppState>(AppState.Idle) val uiState = _uiState.asStateFlow() fun getFirstSummoner(summonerName: String) { _uiState.update { AppState.Loading } viewModelScope.launch { runBlocking { viewModelScope.async { if (summonerName.isBlank() || summonerName.isEmpty()) { _uiState.update { AppState.Error(error = "Vous devez entrer un nom !") } } else { val summonerAnswer = ApiClient.apiService.getSummoner(summonerName) if (summonerAnswer.code() <= 199 || summonerAnswer.code() >= 300) { _uiState.update { AppState.Error(error = summonerAnswer.message()) } } else { val response = summonerAnswer.body() if (response != null) { val responseRanked = Summoner( accountId = response.accountId, profileIconId = response.profileIconId, revisionDate = response.revisionDate, name = response.name, puuid = response.puuid, id = response.id, summonerLevel = response.summonerLevel, ranks = getRanks(id = response.id) ) _uiState.update { AppState.Success( listOf(responseRanked) ) } } } } } } } } fun getNextSummoner(summonerName: String, olderResults: List<Summoner>) { runBlocking { viewModelScope.async { if (summonerName.isBlank() || summonerName.isEmpty()) { _uiState.update { AppState.Error(error = "Vous devez entrer un nom !") } } else { val brutAnswer = ApiClient.apiService.getSummoner(summonerName) if (brutAnswer.code() <= 199 || brutAnswer.code() >= 300) { _uiState.update { AppState.Error(error = brutAnswer.message()) } } else { val response = brutAnswer.body() if (response != null) { response.copy(ranks = getRanks(response.id)) val responseRanked = Summoner( accountId = response.accountId, profileIconId = response.profileIconId, revisionDate = response.revisionDate, name = response.name, puuid = response.puuid, id = response.id, summonerLevel = response.summonerLevel, ranks = getRanks(id = response.id) ) println(olderResults) val newSummonersList = olderResults + listOf(responseRanked) _uiState.update { AppState.Success( newSummonersList ) } } } } } } } suspend fun getRanks(id: String): List<Rank> { val response = ApiClient.apiService.getRanks(id) if (response.code() <= 199 || response.code() >= 300) { _uiState.update { AppState.Error(response.message()) } } return response.body() ?: listOf() } } sealed interface AppState { object Idle : AppState data class Success( val searchedSummoners: List<Summoner> ) : AppState object Loading : AppState data class Error( val error: String, ) : AppState }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/ritoApp/RitoViewModel.kt
3619102087
package xyz.axxonte.myrapp.ui.ritoApp import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Card 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.Modifier import androidx.compose.ui.tooling.preview.Preview import xyz.axxonte.myrapp.data.RitoRepo import xyz.axxonte.myrapp.data.getDateTime import xyz.axxonte.myrapp.network.Info import xyz.axxonte.myrapp.network.MatchStats import xyz.axxonte.myrapp.ui.theme.MyRAppTheme @Composable fun RitoLastMatch() { val ritoRepo : RitoRepo val match = ritoRepo.getPuuid() Column( modifier = Modifier.fillMaxSize() ) { Row { MatchInfo(match = ) } } } @Composable fun MatchInfo(match: MatchStats) { var isDeployed by remember { mutableStateOf(false) } if (!isDeployed) { Card { Row { Text(text = "Mode de jeu : ") Text(text = match.info?.gameMode ?: "N/A") } Row { Text(text = "Date : ") Text(text = getDateTime(match.info!!.gameStartTimestamp!!)) } Row { Text(text = "Durรฉe : ") Text(text = match.info?.gameDuration?.toString() ?: "N/A") } } } } /* @Preview(showBackground = true) @Composable fun PreviewLastMatch(){ MyRAppTheme { RitoLastMatch(MatchStats()) } }*/ @Preview(showBackground = true) @Composable fun PreviewMatchInfo() { MyRAppTheme { MatchInfo(match = MatchStats(info = Info(gameStartTimestamp = 1702284051L))) } }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/ritoApp/RitoLastMatchScreen.kt
2055501736
package xyz.axxonte.myrapp.ui import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedCard import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage import xyz.axxonte.myrapp.R import xyz.axxonte.myrapp.network.Rank import xyz.axxonte.myrapp.network.Summoner import xyz.axxonte.myrapp.ui.theme.MyRAppTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun RitoAppScreen( appViewModel: AppViewModel = viewModel() ) { val appUiState by appViewModel.uiState.collectAsState() Column( modifier = Modifier .fillMaxSize() .padding(), horizontalAlignment = Alignment.CenterHorizontally ) { var recherche by remember { mutableStateOf("") } OutlinedTextField( value = recherche, onValueChange = { type -> recherche = type }, singleLine = true, label = { Text("Entrez un nom de joueur") }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search, autoCorrect = false, capitalization = KeyboardCapitalization.None ), keyboardActions = KeyboardActions(onSearch = { if (appUiState is AppState.Success) { appViewModel.getNextSummoner( recherche, (appUiState as AppState.Success).searchedSummoners ) } else { appViewModel.getFirstSummoner( recherche ) } }) ) OutlinedButton(onClick = { if (appUiState is AppState.Success) { if ((appUiState as AppState.Success).searchedSummoners.isNotEmpty()) appViewModel.getNextSummoner( recherche, (appUiState as AppState.Success).searchedSummoners ) } else { appViewModel.getFirstSummoner(recherche) } }) { Text(text = "Rechercher") } when (val state = appUiState) { is AppState.Error -> { Box( modifier = Modifier .fillMaxSize() .padding(vertical = 16.dp), contentAlignment = Alignment.TopCenter ) { Text(text = state.error) } } AppState.Idle -> { Column { Spacer(modifier = Modifier.padding(16.dp)) Text("Aucun nom de joueur saisi.") } } AppState.Loading -> { Box( contentAlignment = Alignment.Center ) { CircularProgressIndicator(modifier = Modifier.padding(16.dp)) } } is AppState.Success -> { LazyColumn { items(state.searchedSummoners) { summoner -> SummonerInfos(summoner = summoner) } } } } } } @Composable fun SummonerInfos(modifier: Modifier = Modifier, summoner: Summoner) { var isDeployed by remember { mutableStateOf(false) } val ranks = summoner.ranks ?: listOf() OutlinedCard( modifier = Modifier .padding(8.dp) .fillMaxWidth() .clickable { isDeployed = !isDeployed }, border = BorderStroke(1.dp, MaterialTheme.colorScheme.primaryContainer) ) { Text( text = summoner.name, modifier = Modifier.padding(16.dp) ) if (isDeployed) { Divider(modifier = Modifier.padding(bottom = 16.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Column { Row { Text(text = "Niveau : ") Text(text = summoner.summonerLevel.toString()) } Spacer(modifier = Modifier.padding(12.dp)) if (ranks.isEmpty()) { Text(text = "Ce joueur n'est pas classรฉ.") } else { Column( content = { for (it in ranks) { Row( modifier = Modifier.fillMaxWidth(0.60f), horizontalArrangement = Arrangement.SpaceBetween ) { Column { if (it.queueType == "RANKED_FLEX_SR") { Text(text = "Flexible : ") } else { Text(text = "Solo Queue : ") } Row( horizontalArrangement = Arrangement.SpaceBetween ) { Column { Text(text = "${it.tier} ${it.rank}") Text(text = "LP : ${it.leaguePoints}") } } Spacer(modifier = Modifier.padding(12.dp)) } val imgId: Int = when (it.tier) { "IRON" -> R.drawable.iron "BRONZE" -> R.drawable.bronze "SILVER" -> R.drawable.silver "GOLD" -> R.drawable.gold "PLATINUM" -> R.drawable.platinum "EMERALD" -> R.drawable.emerald "DIAMOND" -> R.drawable.diamond "MASTER" -> R.drawable.master "GRANDMASTER" -> R.drawable.grandmaster "CHALLENGER" -> R.drawable.challenger else -> R.drawable.missingtexture } Image( modifier = Modifier.size(110.dp), painter = painterResource(id = imgId), contentDescription = null ) } } } ) } } Box( modifier = Modifier .size(110.dp) ) { AsyncImage( modifier = Modifier .fillMaxWidth(), contentScale = ContentScale.FillBounds, model = "https://ddragon.leagueoflegends.com/cdn/13.23.1/img/profileicon/${summoner.profileIconId}.png", contentDescription = "Profile Picture" ) } } } } } @Preview(showBackground = true) @Composable fun GreetingPreviewDark() { MyRAppTheme(useDarkTheme = true) { RitoAppScreen() } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyRAppTheme { RitoAppScreen() } } @Preview(showBackground = true) @Composable fun InfosPreview() { val dummyRanks = listOf( Rank( leaguePoints = 55, tier = "BRONZE", rank = "IV", queueType = "RANKED_FLEX_SR" ), Rank( leaguePoints = 98, tier = "GRANDMASTER", rank = "IV", queueType = "RANKED_SOLO_5x5" ) ) val dummySummoner = Summoner( id = "hBwemIzdR1hZGn0WM4IS-YlUJdVYN9YP-GDdtrg7hSbhcHk9", accountId = "pvJQQh3tvsdKhTQR-_MyHab0pRIehQetPFVe8-YgfFUJPJED6Y10_rWO", puuid = "IB3w2q5pBWPZQy8Cn6uhB9eGpNYqFbH1S_JFW2npNBKUbmgFES5RzhQX7dQ8cL2Q60sJXOuwDD15SQ", name = "Maxbaxter", profileIconId = 6369, revisionDate = 1701104189000, summonerLevel = 417, ranks = dummyRanks ) MyRAppTheme(useDarkTheme = true) { SummonerInfos(summoner = dummySummoner) } }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/ritoApp/RitoAppScreen.kt
2856082391
package xyz.axxonte.myrapp.ui.ritoApp class LastMatchViewModel { }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/ritoApp/LastMatchViewModel.kt
791910390
package xyz.axxonte.myrapp.ui import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedCard import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage import xyz.axxonte.myrapp.R import xyz.axxonte.myrapp.network.Rank import xyz.axxonte.myrapp.network.Summoner import xyz.axxonte.myrapp.ui.theme.MyRAppTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun AppScreen(appViewModel: AppViewModel = viewModel()) { val appUiState by appViewModel.uiState.collectAsState() Scaffold( topBar = { TopAppBar( title = { Box( modifier = Modifier .fillMaxWidth(), // .height(32.dp), contentAlignment = Alignment.Center ) { Text( text = "LoL NoLife Stats" ) } }, modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer), colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = MaterialTheme.colorScheme.primaryContainer) ) } ) { Column( modifier = Modifier .fillMaxSize() .padding(paddingValues = it), horizontalAlignment = Alignment.CenterHorizontally ) { var recherche by remember { mutableStateOf("") } OutlinedTextField( value = recherche, onValueChange = { type -> recherche = type }, singleLine = true, label = { Text("Entrez un nom de joueur") }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search, autoCorrect = false, capitalization = KeyboardCapitalization.None ), keyboardActions = KeyboardActions(onSearch = { if (appUiState is AppState.Success) { appViewModel.getNextSummoner(recherche, (appUiState as AppState.Success).searchedSummoners) } else { appViewModel.getFirstSummoner( recherche ) } }) ) OutlinedButton(onClick = { if (appUiState is AppState.Success){ if ((appUiState as AppState.Success).searchedSummoners.isNotEmpty()) appViewModel.getNextSummoner(recherche, (appUiState as AppState.Success).searchedSummoners) } else { appViewModel.getFirstSummoner(recherche) } }) { Text(text = "Rechercher") } when (val state = appUiState) { is AppState.Error -> { Box( modifier = Modifier .fillMaxSize() .padding(vertical = 16.dp), contentAlignment = Alignment.TopCenter ) { Text(text = state.error) } } AppState.Idle -> { Column { Spacer(modifier = Modifier.padding(16.dp)) Text("Aucun nom de joueur saisi.") } } AppState.Loading -> { Box( contentAlignment = Alignment.Center ) { CircularProgressIndicator(modifier = Modifier.padding(16.dp)) } } is AppState.Success -> { LazyColumn { items(state.searchedSummoners){ summoner -> SummonerInfos(summoner = summoner) } } } } } } } @Composable fun SummonerInfos(modifier: Modifier = Modifier, summoner: Summoner) { var isDeployed by remember { mutableStateOf(false) } val ranks = summoner.ranks ?: listOf() OutlinedCard( modifier = Modifier .padding(8.dp) .fillMaxWidth() .clickable { isDeployed = !isDeployed }, border = BorderStroke(1.dp, MaterialTheme.colorScheme.primaryContainer) ) { Text( text = summoner.name, modifier = Modifier.padding(16.dp) ) if (isDeployed) { Divider(modifier = Modifier.padding(bottom = 16.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Column { Row { Text(text = "Niveau : ") Text(text = summoner.summonerLevel.toString()) } Spacer(modifier = Modifier.padding(12.dp)) if (ranks.isEmpty()) { Text(text = "Ce joueur n'est pas classรฉ.") } else { Column( content = { for (it in ranks) { Row( modifier = Modifier.fillMaxWidth(0.60f), horizontalArrangement = Arrangement.SpaceBetween ) { Column { if (it.queueType == "RANKED_FLEX_SR") { Text(text = "Flexible : ") } else { Text(text = "Solo Queue : ") } Row( horizontalArrangement = Arrangement.SpaceBetween ) { Column { Text(text = "${it.tier} ${it.rank}") Text(text = "LP : ${it.leaguePoints}") } } Spacer(modifier = Modifier.padding(12.dp)) } val imgId: Int = when (it.tier) { "IRON" -> R.drawable.iron "BRONZE" -> R.drawable.bronze "SILVER" -> R.drawable.silver "GOLD" -> R.drawable.gold "PLATINUM" -> R.drawable.platinum "EMERALD" -> R.drawable.emerald "DIAMOND" -> R.drawable.diamond "MASTER" -> R.drawable.master "GRANDMASTER" -> R.drawable.grandmaster "CHALLENGER" -> R.drawable.challenger else -> R.drawable.missingtexture } Image( modifier = Modifier.size(110.dp), painter = painterResource(id = imgId), contentDescription = null ) } } } ) } } Box( modifier = Modifier .size(110.dp) ) { AsyncImage( modifier = Modifier .fillMaxWidth(), contentScale = ContentScale.FillBounds, model = "https://ddragon.leagueoflegends.com/cdn/13.23.1/img/profileicon/${summoner.profileIconId}.png", contentDescription = "Profile Picture" ) } } } } } @Preview(showBackground = true) @Composable fun GreetingPreviewDark() { MyRAppTheme(useDarkTheme = true) { AppScreen() } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyRAppTheme { AppScreen() } } @Preview(showBackground = true) @Composable fun InfosPreview() { val dummyRanks = listOf( Rank( leaguePoints = 55, tier = "BRONZE", rank = "IV", queueType = "RANKED_FLEX_SR" ), Rank( leaguePoints = 98, tier = "GRANDMASTER", rank = "IV", queueType = "RANKED_SOLO_5x5" ) ) val dummySummoner = Summoner( id = "hBwemIzdR1hZGn0WM4IS-YlUJdVYN9YP-GDdtrg7hSbhcHk9", accountId = "pvJQQh3tvsdKhTQR-_MyHab0pRIehQetPFVe8-YgfFUJPJED6Y10_rWO", puuid = "IB3w2q5pBWPZQy8Cn6uhB9eGpNYqFbH1S_JFW2npNBKUbmgFES5RzhQX7dQ8cL2Q60sJXOuwDD15SQ", name = "Maxbaxter", profileIconId = 6369, revisionDate = 1701104189000, summonerLevel = 417, ranks = dummyRanks ) MyRAppTheme(useDarkTheme = true) { SummonerInfos(summoner = dummySummoner) } }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/ui/MainAppScreen.kt
219163193
package xyz.axxonte.myrapp 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 xyz.axxonte.myrapp.ui.AppScreen import xyz.axxonte.myrapp.ui.theme.MyRAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyRAppTheme (useDarkTheme = true) { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { AppScreen() } } } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyRAppTheme { AppScreen() } }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/MainActivity.kt
3381172291
package xyz.axxonte.myrapp class AxxToolsApplication { }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/AxxToolsApplication.kt
4192716074
package xyz.axxonte.jacquesnoirremastered.network import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Path import xyz.axxonte.myrapp.network.Rank import xyz.axxonte.myrapp.network.Summoner private const val TOKEN: String = "RGAPI-01ee26a8-bf5b-4711-ae86-9a3d8c85e711" interface ApiInterface { @GET("/lol/summoner/v4/summoners/by-name/{summonerName}?api_key=${TOKEN}") suspend fun getSummoner(@Path("summonerName") summonerName: String): Response<Summoner> @GET("/lol/league/v4/entries/by-summoner/{encryptedSummonerId}?api_key=${TOKEN}") suspend fun getRanks(@Path("encryptedSummonerId") encryptedSummonerId: String): Response<List<Rank>> // @GET("cards/{num}") // suspend fun getCardById(@Path("num") num: Int): Response<> // // @GET("name/{name}") // suspend fun getCardsByName(@Path("name") name : String): Response<MutableList<>> // @GET("sets") // suspend fun getSets(): Response<MutableList<CardSet>> }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/network/ApiInterface.kt
3525164670
package xyz.axxonte.myrapp.network import com.google.gson.annotations.SerializedName data class MatchStats( @field:SerializedName("metadata") val metadata: Metadata? = null, @field:SerializedName("info") val info: Info? = null ) data class Champion( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class Horde( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class SelectionsItem( @field:SerializedName("perk") val perk: Int? = null, @field:SerializedName("var3") val var3: Int? = null, @field:SerializedName("var2") val var2: Int? = null, @field:SerializedName("var1") val var1: Int? = null ) data class Objectives( @field:SerializedName("baron") val baron: Baron? = null, @field:SerializedName("horde") val horde: Horde? = null, @field:SerializedName("inhibitor") val inhibitor: Inhibitor? = null, @field:SerializedName("dragon") val dragon: Dragon? = null, @field:SerializedName("riftHerald") val riftHerald: RiftHerald? = null, @field:SerializedName("champion") val champion: Champion? = null, @field:SerializedName("tower") val tower: Tower? = null ) data class TeamsItem( @field:SerializedName("teamId") val teamId: Int? = null, @field:SerializedName("bans") val bans: List<BansItem?>? = null, @field:SerializedName("objectives") val objectives: Objectives? = null, @field:SerializedName("win") val win: Boolean? = null ) data class RiftHerald( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class StylesItem( @field:SerializedName("selections") val selections: List<SelectionsItem?>? = null, @field:SerializedName("description") val description: String? = null, @field:SerializedName("style") val style: Int? = null ) data class ParticipantsItem( @field:SerializedName("bountyLevel") val bountyLevel: Int? = null, @field:SerializedName("totalUnitsHealed") val totalUnitsHealed: Int? = null, @field:SerializedName("largestMultiKill") val largestMultiKill: Int? = null, @field:SerializedName("spell2Casts") val spell2Casts: Int? = null, @field:SerializedName("champExperience") val champExperience: Int? = null, @field:SerializedName("onMyWayPings") val onMyWayPings: Int? = null, @field:SerializedName("summonerLevel") val summonerLevel: Int? = null, @field:SerializedName("holdPings") val holdPings: Int? = null, @field:SerializedName("damageDealtToObjectives") val damageDealtToObjectives: Int? = null, @field:SerializedName("pushPings") val pushPings: Int? = null, @field:SerializedName("totalEnemyJungleMinionsKilled") val totalEnemyJungleMinionsKilled: Int? = null, @field:SerializedName("turretTakedowns") val turretTakedowns: Int? = null, @field:SerializedName("magicDamageTaken") val magicDamageTaken: Int? = null, @field:SerializedName("playerScore0") val playerScore0: Int? = null, @field:SerializedName("perks") val perks: Perks? = null, @field:SerializedName("deaths") val deaths: Int? = null, @field:SerializedName("objectivesStolen") val objectivesStolen: Int? = null, @field:SerializedName("detectorWardsPlaced") val detectorWardsPlaced: Int? = null, @field:SerializedName("enemyMissingPings") val enemyMissingPings: Int? = null, @field:SerializedName("magicDamageDealtToChampions") val magicDamageDealtToChampions: Int? = null, @field:SerializedName("playerScore7") val playerScore7: Int? = null, @field:SerializedName("wardsKilled") val wardsKilled: Int? = null, @field:SerializedName("playerScore8") val playerScore8: Int? = null, @field:SerializedName("pentaKills") val pentaKills: Int? = null, @field:SerializedName("playerScore5") val playerScore5: Int? = null, @field:SerializedName("playerScore6") val playerScore6: Int? = null, @field:SerializedName("playerScore3") val playerScore3: Int? = null, @field:SerializedName("playerScore4") val playerScore4: Int? = null, @field:SerializedName("playerScore1") val playerScore1: Int? = null, @field:SerializedName("playerScore2") val playerScore2: Int? = null, @field:SerializedName("spell3Casts") val spell3Casts: Int? = null, @field:SerializedName("firstTowerKill") val firstTowerKill: Boolean? = null, @field:SerializedName("individualPosition") val individualPosition: String? = null, @field:SerializedName("playerScore9") val playerScore9: Int? = null, @field:SerializedName("wardsPlaced") val wardsPlaced: Int? = null, @field:SerializedName("totalDamageDealt") val totalDamageDealt: Int? = null, @field:SerializedName("largestKillingSpree") val largestKillingSpree: Int? = null, @field:SerializedName("totalDamageDealtToChampions") val totalDamageDealtToChampions: Int? = null, @field:SerializedName("placement") val placement: Int? = null, @field:SerializedName("playerAugment2") val playerAugment2: Int? = null, @field:SerializedName("playerAugment3") val playerAugment3: Int? = null, @field:SerializedName("summoner2Id") val summoner2Id: Int? = null, @field:SerializedName("playerAugment1") val playerAugment1: Int? = null, @field:SerializedName("role") val role: String? = null, @field:SerializedName("totalTimeSpentDead") val totalTimeSpentDead: Int? = null, @field:SerializedName("playerAugment4") val playerAugment4: Int? = null, @field:SerializedName("inhibitorKills") val inhibitorKills: Int? = null, @field:SerializedName("puuid") val puuid: String? = null, @field:SerializedName("totalTimeCCDealt") val totalTimeCCDealt: Int? = null, @field:SerializedName("participantId") val participantId: Int? = null, @field:SerializedName("profileIcon") val profileIcon: Int? = null, @field:SerializedName("teamEarlySurrendered") val teamEarlySurrendered: Boolean? = null, @field:SerializedName("goldSpent") val goldSpent: Int? = null, @field:SerializedName("unrealKills") val unrealKills: Int? = null, @field:SerializedName("consumablesPurchased") val consumablesPurchased: Int? = null, @field:SerializedName("visionScore") val visionScore: Int? = null, @field:SerializedName("firstBloodKill") val firstBloodKill: Boolean? = null, @field:SerializedName("longestTimeSpentLiving") val longestTimeSpentLiving: Int? = null, @field:SerializedName("killingSprees") val killingSprees: Int? = null, @field:SerializedName("sightWardsBoughtInGame") val sightWardsBoughtInGame: Int? = null, @field:SerializedName("riotIdGameName") val riotIdGameName: String? = null, @field:SerializedName("eligibleForProgression") val eligibleForProgression: Boolean? = null, @field:SerializedName("missions") val missions: Missions? = null, @field:SerializedName("turretsLost") val turretsLost: Int? = null, @field:SerializedName("commandPings") val commandPings: Int? = null, @field:SerializedName("quadraKills") val quadraKills: Int? = null, @field:SerializedName("item4") val item4: Int? = null, @field:SerializedName("nexusTakedowns") val nexusTakedowns: Int? = null, @field:SerializedName("item3") val item3: Int? = null, @field:SerializedName("item6") val item6: Int? = null, @field:SerializedName("item5") val item5: Int? = null, @field:SerializedName("item0") val item0: Int? = null, @field:SerializedName("item2") val item2: Int? = null, @field:SerializedName("summoner1Id") val summoner1Id: Int? = null, @field:SerializedName("item1") val item1: Int? = null, @field:SerializedName("totalDamageShieldedOnTeammates") val totalDamageShieldedOnTeammates: Int? = null, @field:SerializedName("summoner2Casts") val summoner2Casts: Int? = null, @field:SerializedName("goldEarned") val goldEarned: Int? = null, @field:SerializedName("nexusLost") val nexusLost: Int? = null, @field:SerializedName("physicalDamageTaken") val physicalDamageTaken: Int? = null, @field:SerializedName("champLevel") val champLevel: Int? = null, @field:SerializedName("totalDamageTaken") val totalDamageTaken: Int? = null, @field:SerializedName("neutralMinionsKilled") val neutralMinionsKilled: Int? = null, @field:SerializedName("basicPings") val basicPings: Int? = null, @field:SerializedName("totalAllyJungleMinionsKilled") val totalAllyJungleMinionsKilled: Int? = null, @field:SerializedName("allInPings") val allInPings: Int? = null, @field:SerializedName("championTransform") val championTransform: Int? = null, @field:SerializedName("tripleKills") val tripleKills: Int? = null, @field:SerializedName("damageSelfMitigated") val damageSelfMitigated: Int? = null, @field:SerializedName("inhibitorsLost") val inhibitorsLost: Int? = null, @field:SerializedName("inhibitorTakedowns") val inhibitorTakedowns: Int? = null, @field:SerializedName("largestCriticalStrike") val largestCriticalStrike: Int? = null, @field:SerializedName("assistMePings") val assistMePings: Int? = null, @field:SerializedName("totalHealsOnTeammates") val totalHealsOnTeammates: Int? = null, @field:SerializedName("summoner1Casts") val summoner1Casts: Int? = null, @field:SerializedName("subteamPlacement") val subteamPlacement: Int? = null, @field:SerializedName("damageDealtToBuildings") val damageDealtToBuildings: Int? = null, @field:SerializedName("magicDamageDealt") val magicDamageDealt: Int? = null, @field:SerializedName("playerSubteamId") val playerSubteamId: Int? = null, @field:SerializedName("timePlayed") val timePlayed: Int? = null, @field:SerializedName("championName") val championName: String? = null, @field:SerializedName("timeCCingOthers") val timeCCingOthers: Int? = null, @field:SerializedName("teamPosition") val teamPosition: String? = null, @field:SerializedName("physicalDamageDealtToChampions") val physicalDamageDealtToChampions: Int? = null, @field:SerializedName("totalMinionsKilled") val totalMinionsKilled: Int? = null, @field:SerializedName("visionWardsBoughtInGame") val visionWardsBoughtInGame: Int? = null, @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("firstTowerAssist") val firstTowerAssist: Boolean? = null, @field:SerializedName("championId") val championId: Int? = null, @field:SerializedName("challenges") val challenges: Challenges? = null, @field:SerializedName("baitPings") val baitPings: Int? = null, @field:SerializedName("getBackPings") val getBackPings: Int? = null, @field:SerializedName("needVisionPings") val needVisionPings: Int? = null, @field:SerializedName("turretKills") val turretKills: Int? = null, @field:SerializedName("enemyVisionPings") val enemyVisionPings: Int? = null, @field:SerializedName("firstBloodAssist") val firstBloodAssist: Boolean? = null, @field:SerializedName("trueDamageTaken") val trueDamageTaken: Int? = null, @field:SerializedName("assists") val assists: Int? = null, @field:SerializedName("itemsPurchased") val itemsPurchased: Int? = null, @field:SerializedName("objectivesStolenAssists") val objectivesStolenAssists: Int? = null, @field:SerializedName("summonerId") val summonerId: String? = null, @field:SerializedName("damageDealtToTurrets") val damageDealtToTurrets: Int? = null, @field:SerializedName("totalHeal") val totalHeal: Int? = null, @field:SerializedName("visionClearedPings") val visionClearedPings: Int? = null, @field:SerializedName("win") val win: Boolean? = null, @field:SerializedName("lane") val lane: String? = null, @field:SerializedName("playerScore11") val playerScore11: Int? = null, @field:SerializedName("playerScore10") val playerScore10: Int? = null, @field:SerializedName("gameEndedInSurrender") val gameEndedInSurrender: Boolean? = null, @field:SerializedName("physicalDamageDealt") val physicalDamageDealt: Int? = null, @field:SerializedName("summonerName") val summonerName: String? = null, @field:SerializedName("trueDamageDealtToChampions") val trueDamageDealtToChampions: Int? = null, @field:SerializedName("dragonKills") val dragonKills: Int? = null, @field:SerializedName("baronKills") val baronKills: Int? = null, @field:SerializedName("doubleKills") val doubleKills: Int? = null, @field:SerializedName("nexusKills") val nexusKills: Int? = null, @field:SerializedName("trueDamageDealt") val trueDamageDealt: Int? = null, @field:SerializedName("spell1Casts") val spell1Casts: Int? = null, @field:SerializedName("gameEndedInEarlySurrender") val gameEndedInEarlySurrender: Boolean? = null, @field:SerializedName("teamId") val teamId: Int? = null, @field:SerializedName("riotIdTagline") val riotIdTagline: String? = null, @field:SerializedName("dangerPings") val dangerPings: Int? = null, @field:SerializedName("spell4Casts") val spell4Casts: Int? = null ) data class Metadata( @field:SerializedName("dataVersion") val dataVersion: String? = null, @field:SerializedName("matchId") val matchId: String? = null, @field:SerializedName("participants") val participants: List<String?>? = null ) data class Tower( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class Inhibitor( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class Challenges( @field:SerializedName("acesBefore15Minutes") val acesBefore15Minutes: Int? = null, @field:SerializedName("wardTakedowns") val wardTakedowns: Int? = null, @field:SerializedName("firstTurretKilled") val firstTurretKilled: Int? = null, @field:SerializedName("saveAllyFromDeath") val saveAllyFromDeath: Int? = null, @field:SerializedName("elderDragonMultikills") val elderDragonMultikills: Int? = null, @field:SerializedName("poroExplosions") val poroExplosions: Int? = null, @field:SerializedName("soloKills") val soloKills: Int? = null, @field:SerializedName("turretPlatesTaken") val turretPlatesTaken: Int? = null, @field:SerializedName("abilityUses") val abilityUses: Int? = null, @field:SerializedName("dodgeSkillShotsSmallWindow") val dodgeSkillShotsSmallWindow: Int? = null, @field:SerializedName("damagePerMinute") val damagePerMinute: Any? = null, @field:SerializedName("knockEnemyIntoTeamAndKill") val knockEnemyIntoTeamAndKill: Int? = null, @field:SerializedName("killParticipation") val killParticipation: Any? = null, @field:SerializedName("turretTakedowns") val turretTakedowns: Int? = null, @field:SerializedName("killsOnOtherLanesEarlyJungleAsLaner") val killsOnOtherLanesEarlyJungleAsLaner: Int? = null, @field:SerializedName("goldPerMinute") val goldPerMinute: Any? = null, @field:SerializedName("perfectGame") val perfectGame: Int? = null, @field:SerializedName("skillshotsHit") val skillshotsHit: Int? = null, @field:SerializedName("multikills") val multikills: Int? = null, @field:SerializedName("wardTakedownsBefore20M") val wardTakedownsBefore20M: Int? = null, @field:SerializedName("outerTurretExecutesBefore10Minutes") val outerTurretExecutesBefore10Minutes: Int? = null, @field:SerializedName("takedownsInAlcove") val takedownsInAlcove: Int? = null, @field:SerializedName("kda") val kda: Any? = null, @field:SerializedName("unseenRecalls") val unseenRecalls: Int? = null, @field:SerializedName("takedownsFirstXMinutes") val takedownsFirstXMinutes: Int? = null, @field:SerializedName("kTurretsDestroyedBeforePlatesFall") val kTurretsDestroyedBeforePlatesFall: Int? = null, @field:SerializedName("epicMonsterKillsNearEnemyJungler") val epicMonsterKillsNearEnemyJungler: Int? = null, @field:SerializedName("survivedSingleDigitHpCount") val survivedSingleDigitHpCount: Int? = null, @field:SerializedName("outnumberedNexusKill") val outnumberedNexusKill: Int? = null, @field:SerializedName("damageTakenOnTeamPercentage") val damageTakenOnTeamPercentage: Any? = null, @field:SerializedName("laneMinionsFirst10Minutes") val laneMinionsFirst10Minutes: Int? = null, @field:SerializedName("quickCleanse") val quickCleanse: Int? = null, @field:SerializedName("initialCrabCount") val initialCrabCount: Int? = null, @field:SerializedName("completeSupportQuestInTime") val completeSupportQuestInTime: Int? = null, @field:SerializedName("takedownsAfterGainingLevelAdvantage") val takedownsAfterGainingLevelAdvantage: Int? = null, @field:SerializedName("controlWardsPlaced") val controlWardsPlaced: Int? = null, @field:SerializedName("epicMonsterStolenWithoutSmite") val epicMonsterStolenWithoutSmite: Int? = null, @field:SerializedName("tookLargeDamageSurvived") val tookLargeDamageSurvived: Int? = null, @field:SerializedName("enemyJungleMonsterKills") val enemyJungleMonsterKills: Int? = null, @field:SerializedName("teamDamagePercentage") val teamDamagePercentage: Any? = null, @field:SerializedName("jungleCsBefore10Minutes") val jungleCsBefore10Minutes: Int? = null, @field:SerializedName("lostAnInhibitor") val lostAnInhibitor: Int? = null, @field:SerializedName("takedownsBeforeJungleMinionSpawn") val takedownsBeforeJungleMinionSpawn: Int? = null, @field:SerializedName("elderDragonKillsWithOpposingSoul") val elderDragonKillsWithOpposingSoul: Int? = null, @field:SerializedName("killsWithHelpFromEpicMonster") val killsWithHelpFromEpicMonster: Int? = null, @field:SerializedName("killingSprees") val killingSprees: Int? = null, @field:SerializedName("outnumberedKills") val outnumberedKills: Int? = null, @field:SerializedName("wardsGuarded") val wardsGuarded: Int? = null, @field:SerializedName("flawlessAces") val flawlessAces: Int? = null, @field:SerializedName("teamRiftHeraldKills") val teamRiftHeraldKills: Int? = null, @field:SerializedName("turretsTakenWithRiftHerald") val turretsTakenWithRiftHerald: Int? = null, @field:SerializedName("dragonTakedowns") val dragonTakedowns: Int? = null, @field:SerializedName("riftHeraldTakedowns") val riftHeraldTakedowns: Int? = null, @field:SerializedName("takedowns") val takedowns: Int? = null, @field:SerializedName("fullTeamTakedown") val fullTeamTakedown: Int? = null, @field:SerializedName("buffsStolen") val buffsStolen: Int? = null, @field:SerializedName("takedownsInEnemyFountain") val takedownsInEnemyFountain: Int? = null, @field:SerializedName("enemyChampionImmobilizations") val enemyChampionImmobilizations: Int? = null, @field:SerializedName("soloBaronKills") val soloBaronKills: Int? = null, @field:SerializedName("multikillsAfterAggressiveFlash") val multikillsAfterAggressiveFlash: Int? = null, @field:SerializedName("deathsByEnemyChamps") val deathsByEnemyChamps: Int? = null, @field:SerializedName("takedownOnFirstTurret") val takedownOnFirstTurret: Int? = null, @field:SerializedName("twentyMinionsIn3SecondsCount") val twentyMinionsIn3SecondsCount: Int? = null, @field:SerializedName("killsUnderOwnTurret") val killsUnderOwnTurret: Int? = null, @field:SerializedName("moreEnemyJungleThanOpponent") val moreEnemyJungleThanOpponent: Int? = null, @field:SerializedName("killAfterHiddenWithAlly") val killAfterHiddenWithAlly: Int? = null, @field:SerializedName("hadOpenNexus") val hadOpenNexus: Int? = null, @field:SerializedName("doubleAces") val doubleAces: Int? = null, @field:SerializedName("blastConeOppositeOpponentCount") val blastConeOppositeOpponentCount: Int? = null, @field:SerializedName("epicMonsterSteals") val epicMonsterSteals: Int? = null, @field:SerializedName("baronTakedowns") val baronTakedowns: Int? = null, @field:SerializedName("junglerTakedownsNearDamagedEpicMonster") val junglerTakedownsNearDamagedEpicMonster: Int? = null, @field:SerializedName("epicMonsterKillsWithin30SecondsOfSpawn") val epicMonsterKillsWithin30SecondsOfSpawn: Int? = null, @field:SerializedName("killedChampTookFullTeamDamageSurvived") val killedChampTookFullTeamDamageSurvived: Int? = null, @field:SerializedName("maxKillDeficit") val maxKillDeficit: Int? = null, @field:SerializedName("mythicItemUsed") val mythicItemUsed: Int? = null, @field:SerializedName("multiKillOneSpell") val multiKillOneSpell: Int? = null, @field:SerializedName("landSkillShotsEarlyGame") val landSkillShotsEarlyGame: Int? = null, @field:SerializedName("mejaisFullStackInTime") val mejaisFullStackInTime: Int? = null, @field:SerializedName("quickFirstTurret") val quickFirstTurret: Int? = null, @field:SerializedName("initialBuffCount") val initialBuffCount: Int? = null, @field:SerializedName("quickSoloKills") val quickSoloKills: Int? = null, @field:SerializedName("snowballsHit") val snowballsHit: Int? = null, @field:SerializedName("immobilizeAndKillWithAlly") val immobilizeAndKillWithAlly: Int? = null, @field:SerializedName("stealthWardsPlaced") val stealthWardsPlaced: Int? = null, @field:SerializedName("twoWardsOneSweeperCount") val twoWardsOneSweeperCount: Int? = null, @field:SerializedName("effectiveHealAndShielding") val effectiveHealAndShielding: Int? = null, @field:SerializedName("dancedWithRiftHerald") val dancedWithRiftHerald: Int? = null, @field:SerializedName("pickKillWithAlly") val pickKillWithAlly: Int? = null, @field:SerializedName("teamElderDragonKills") val teamElderDragonKills: Int? = null, @field:SerializedName("gameLength") val gameLength: Any? = null, @field:SerializedName("multiTurretRiftHeraldCount") val multiTurretRiftHeraldCount: Int? = null, @field:SerializedName("killsOnRecentlyHealedByAramPack") val killsOnRecentlyHealedByAramPack: Int? = null, @field:SerializedName("perfectDragonSoulsTaken") val perfectDragonSoulsTaken: Int? = null, @field:SerializedName("teamBaronKills") val teamBaronKills: Int? = null, @field:SerializedName("skillshotsDodged") val skillshotsDodged: Int? = null, @field:SerializedName("legendaryCount") val legendaryCount: Int? = null, @field:SerializedName("getTakedownsInAllLanesEarlyJungleAsLaner") val getTakedownsInAllLanesEarlyJungleAsLaner: Int? = null, @field:SerializedName("visionScorePerMinute") val visionScorePerMinute: Int? = null, @field:SerializedName("alliedJungleMonsterKills") val alliedJungleMonsterKills: Int? = null, @field:SerializedName("scuttleCrabKills") val scuttleCrabKills: Int? = null, @field:SerializedName("shortestTimeToAceFromFirstTakedown") val shortestTimeToAceFromFirstTakedown: Any? = null, @field:SerializedName("bountyGold") val bountyGold: Int? = null, @field:SerializedName("killsNearEnemyTurret") val killsNearEnemyTurret: Int? = null, @field:SerializedName("12AssistStreakCount") val jsonMember12AssistStreakCount: Int? = null, @field:SerializedName("survivedThreeImmobilizesInFight") val survivedThreeImmobilizesInFight: Int? = null, @field:SerializedName("fastestLegendary") val fastestLegendary: Any? = null, @field:SerializedName("highestChampionDamage") val highestChampionDamage: Int? = null ) data class Dragon( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class Info( @field:SerializedName("gameId") val gameId: Long? = null, @field:SerializedName("gameType") val gameType: String? = null, @field:SerializedName("queueId") val queueId: Int? = null, @field:SerializedName("gameDuration") val gameDuration: Int? = null, @field:SerializedName("teams") val teams: List<TeamsItem?>? = null, @field:SerializedName("gameEndTimestamp") val gameEndTimestamp: Long? = null, @field:SerializedName("gameStartTimestamp") val gameStartTimestamp: Long? = null, @field:SerializedName("platformId") val platformId: String? = null, @field:SerializedName("gameCreation") val gameCreation: Long? = null, @field:SerializedName("gameName") val gameName: String? = null, @field:SerializedName("tournamentCode") val tournamentCode: String? = null, @field:SerializedName("gameVersion") val gameVersion: String? = null, @field:SerializedName("mapId") val mapId: Int? = null, @field:SerializedName("gameMode") val gameMode: String? = null, @field:SerializedName("participants") val participants: List<ParticipantsItem?>? = null ) data class BansItem( @field:SerializedName("championId") val championId: Int? = null, @field:SerializedName("pickTurn") val pickTurn: Int? = null ) data class Missions( @field:SerializedName("playerScore7") val playerScore7: Int? = null, @field:SerializedName("playerScore8") val playerScore8: Int? = null, @field:SerializedName("playerScore5") val playerScore5: Int? = null, @field:SerializedName("playerScore6") val playerScore6: Int? = null, @field:SerializedName("playerScore3") val playerScore3: Int? = null, @field:SerializedName("playerScore4") val playerScore4: Int? = null, @field:SerializedName("playerScore1") val playerScore1: Int? = null, @field:SerializedName("playerScore2") val playerScore2: Int? = null, @field:SerializedName("playerScore0") val playerScore0: Int? = null, @field:SerializedName("playerScore11") val playerScore11: Int? = null, @field:SerializedName("playerScore9") val playerScore9: Int? = null, @field:SerializedName("playerScore10") val playerScore10: Int? = null ) data class Baron( @field:SerializedName("kills") val kills: Int? = null, @field:SerializedName("first") val first: Boolean? = null ) data class StatPerks( @field:SerializedName("offense") val offense: Int? = null, @field:SerializedName("defense") val defense: Int? = null, @field:SerializedName("flex") val flex: Int? = null ) data class Perks( @field:SerializedName("statPerks") val statPerks: StatPerks? = null, @field:SerializedName("styles") val styles: List<StylesItem?>? = null )
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/network/MatchStats.kt
4244653243
package xyz.axxonte.myrapp.network import com.google.gson.annotations.SerializedName data class Rank( @field:SerializedName("wins") val wins: Int? = null, @field:SerializedName("freshBlood") val freshBlood: Boolean? = null, @field:SerializedName("summonerName") val summonerName: String? = null, @field:SerializedName("leaguePoints") val leaguePoints: Int? = null, @field:SerializedName("losses") val losses: Int? = null, @field:SerializedName("inactive") val inactive: Boolean? = null, @field:SerializedName("tier") val tier: String? = null, @field:SerializedName("veteran") val veteran: Boolean? = null, @field:SerializedName("leagueId") val leagueId: String? = null, @field:SerializedName("hotStreak") val hotStreak: Boolean? = null, @field:SerializedName("queueType") val queueType: String? = null, @field:SerializedName("rank") val rank: String? = null, @field:SerializedName("summonerId") val summonerId: String? = null )
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/network/Rank.kt
2372275912
package xyz.axxonte.myrapp.network import com.google.gson.annotations.SerializedName data class Summoner( @field:SerializedName("accountId") val accountId: String, @field:SerializedName("profileIconId") val profileIconId: Int, @field:SerializedName("revisionDate") val revisionDate: Long, @field:SerializedName("name") val name: String, @field:SerializedName("puuid") val puuid: String, @field:SerializedName("id") val id: String, @field:SerializedName("summonerLevel") val summonerLevel: Int, val ranks : List<Rank>? )
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/network/Summoner.kt
3574208367
package xyz.axxonte.jacquesnoirremastered.network import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { private const val BASE_URL: String = "https://euw1.api.riotgames.com/" private val gson : Gson by lazy { GsonBuilder().setLenient().create() } private val httpClient : OkHttpClient by lazy { OkHttpClient.Builder() .build() } private val retrofit : Retrofit by lazy { Retrofit.Builder() .baseUrl(BASE_URL) .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build() } val apiService : ApiInterface by lazy{ retrofit.create(ApiInterface::class.java) } }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/network/ApiClient.kt
4221025423
package xyz.axxonte.myrapp.data class Utilities { }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/data/Utilities.kt
3018436872
package xyz.axxonte.myrapp.ui.RitoApp class RitoRepo( ) { }
RiotStatApp/app/src/main/java/xyz/axxonte/myrapp/data/RitoRepo.kt
3135237270
package com.example.labretrofitktejemplo 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.labretrofitktejemplo", appContext.packageName) } }
LabRetrofitKtEjemplo/app/src/androidTest/java/com/example/labretrofitktejemplo/ExampleInstrumentedTest.kt
3304217299
package com.example.labretrofitktejemplo 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) } }
LabRetrofitKtEjemplo/app/src/test/java/com/example/labretrofitktejemplo/ExampleUnitTest.kt
2545479044
package com.example.labretrofitktejemplo data class Paises( var id: Int, var nombre: String, var id_estado: String )
LabRetrofitKtEjemplo/app/src/main/java/com/example/labretrofitktejemplo/Paises.kt
430530529
package com.example.labretrofitktejemplo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.TextView import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MainActivity : AppCompatActivity() { lateinit var retrofit:Retrofit lateinit var paisesAPI:PaisesClientAPI override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val jsonText = findViewById<TextView>(R.id.jsonText) retrofit = Retrofit.Builder() .baseUrl("https://www.uajms.edu.bo/") .addConverterFactory(GsonConverterFactory.create()) .build() paisesAPI = retrofit.create(PaisesClientAPI::class.java) // val paisesAPI = RetrofitHelper.getInstance().create(PaisesClientAPI::class.java) // GlobalScope.launch { // val result = paisesAPI.getPaises() // if(result != null){ // Log.d("paises",result.body().toString()) // } // // } //agregar() val paisesMod = Paises(2,"BRASIL MODIFICADO","A") modificar(paisesMod) } fun listar(jsonText: TextView){ val listarCall: Call<List<Paises>> = paisesAPI.getPaises2() listarCall.enqueue(object : Callback<List<Paises>> { override fun onResponse(call: Call<List<Paises>>, response: Response<List<Paises>>) { if (response.isSuccessful) { val paisesList: List<Paises>? = response.body() val paisesIterator: Iterator<Paises>? = paisesList?.iterator() var paises = "" while (paisesIterator?.hasNext() == true) { val pais: Paises? = paisesIterator.next() paises += "${pais?.nombre}\n" } jsonText.text = paises } Log.i("TEOTEO","conexion exitosa") } override fun onFailure(call: Call<List<Paises>>, t: Throwable) { // Handle failure Log.i("TEOTEO","Fallo en la conexion"+t.message+"\n"+t.stackTrace) Log.d("TEOTEO", Log.getStackTraceString(t)); jsonText.text = Log.getStackTraceString(t) } }) } fun agregar(){ //agregar val paisesAPI: PaisesClientAPI = retrofit.create(PaisesClientAPI::class.java) val paises = Paises(2,"ITALIA","A") val callAdd:Call<Paises> = paisesAPI.agregar(paises) callAdd.enqueue(object : Callback<Paises>{ override fun onResponse(p0: Call<Paises>, p1: Response<Paises>) { Log.i("TEOTEO","Agregado correctamente") } override fun onFailure(p0: Call<Paises>, p1: Throwable) { Log.i("TEOTEO","Se produjo un error al agregar") } }) } fun modificar(p:Paises){ //modificar val callAdd:Call<Paises> = paisesAPI.modificar(p) callAdd.enqueue(object : Callback<Paises>{ override fun onResponse(p0: Call<Paises>, p1: Response<Paises>) { if(p1.isSuccessful){ Log.i("TEOTEO","Actualizado correctamente") }else{ Log.i("TEOTEO","no actualizado "+p1.body()) } } override fun onFailure(p0: Call<Paises>, p1: Throwable) { Log.i("TEOTEO","Se produjo un error en la conexiรณn al API") } }) } }
LabRetrofitKtEjemplo/app/src/main/java/com/example/labretrofitktejemplo/MainActivity.kt
1764347530
package com.example.labretrofitktejemplo import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitHelper { // val baseurl = "https://crudcrud.com/api/d8834a8c7808406fa569f8460bcee436/" val baseurl = "https://www.uajms.edu.bo/blogdis413/wp-json/paises/v1/" fun getInstance():Retrofit{ return Retrofit.Builder().baseUrl(baseurl) .addConverterFactory(GsonConverterFactory.create()) .build() } }
LabRetrofitKtEjemplo/app/src/main/java/com/example/labretrofitktejemplo/RetrofitHelper.kt
3515742381
package com.example.labretrofitktejemplo import retrofit2.Call import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT interface PaisesClientAPI { // @GET("/d8834a8c7808406fa569f8460bcee436/paises") // suspend fun getPaises(): Response<List<Paises>> @GET("/blogdis413/wp-json/paises/v1/listar") fun getPaises2(): Call<List<Paises>> @POST("/blogdis413/wp-json/paises/v1/agregar") fun agregar(@Body paises: Paises): Call<Paises> @PUT("/blogdis413/wp-json/paises/v1/modificar") fun modificar(@Body paises: Paises): Call<Paises> @PUT("/blogdis413/wp-json/paises/v1/eliminar") fun eliminar(@Body paises: Paises): Call<Paises> }
LabRetrofitKtEjemplo/app/src/main/java/com/example/labretrofitktejemplo/PaisesClientAPI.kt
4059666301
package com.example.untitled6 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
Basic_file/android/app/src/main/kotlin/com/example/untitled6/MainActivity.kt
203292591
package com.example.projectapplication 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.projectapplication", appContext.packageName) } }
Helper_Subway/app/src/androidTest/java/com/example/projectapplication/ExampleInstrumentedTest.kt
4031115139
package com.example.projectapplication 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) } }
Helper_Subway/app/src/test/java/com/example/projectapplication/ExampleUnitTest.kt
2634902388
package com.example.projectapplication import android.app.Activity import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.projectapplication.databinding.ActivityAddBinding import java.io.File import java.text.SimpleDateFormat import java.util.* class AddActivity : AppCompatActivity() { lateinit var binding: ActivityAddBinding lateinit var filePath: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding= ActivityAddBinding.inflate(layoutInflater) setContentView(binding.root) val requestLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ if(it.resultCode === android.app.Activity.RESULT_OK){ // ์ด๋ฏธ์ง€๊ฐ€ ์ œ๋Œ€๋กœ ์™”์œผ๋ฉด // ์ด๋ฏธ์ง€๋ฅผ ImageView์— ๋ณด์ด๊ธฐ Glide .with(applicationContext) .load(it.data?.data) .apply(RequestOptions().override(250, 200)) // ์‚ฌ์ง„ ๊ทœ๊ฒฉ ์„ค์ • .centerCrop() // ์„ผํ„ฐ์— ์ž๋ฆฌํ•œ๋‹ค. .into(binding.addImageView) // ์ด๋ฏธ์ง€ ๋„ฃ๊ธฐ // ์ด๋ฏธ์ง€์˜ ์ฃผ์†Œ ์ €์žฅ val cursor = contentResolver.query(it.data?.data as Uri, arrayOf<String>(MediaStore.Images.Media.DATA), null, null, null) cursor?.moveToFirst().let{ filePath = cursor?.getString(0) as String // ๊ทธ๋ƒฅ filePath ํ™•์ธํ•˜๋Š” ๊ฒƒ์ž„. Log.d("mobileApp", "${filePath}") } } } binding.btnGallery.setOnClickListener { val intent = Intent(Intent.ACTION_PICK) intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "images/"); requestLauncher.launch(intent) } // btnSave๋ˆŒ๋ €์„ ๋•Œ ์ฒ˜๋ฆฌํ•˜๋Š” ์ฝ”๋“œ๊ฐ€ ์žˆ์–ด์•ผํ•จ. binding.btnSave.setOnClickListener { if(binding.addEditView.text.isNotEmpty() && binding.addImageView.drawable !== null) { // addEditView์— ๋ญ๋ผ๋„ ์ ์—ˆ์–ด์•ผ ์ €์žฅ๋„ ๊ฐ€๋Šฅ // firestore์— ์ €์žฅํ•ด์•ผํ•จ. saveStore() // ํ•จ์ˆ˜ ํ˜ธ์ถœ... ์•„๋ž˜์— ์žˆ์Œ. } else{ Toast.makeText(this, "๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.", Toast.LENGTH_SHORT).show() } finish() // addActivity๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด BoardFragment.kt๋กœ ๋Œ์•„๊ฐ. ๊ทธ๋‹ค์Œ์€ onstart ์‹คํ–‰. } } fun dateToString(date:Date): String{ val format = SimpleDateFormat("yyyy-mm-dd hh:mm") return format.format(date) } fun saveStore(){ val data = mapOf( "email" to MyApplication.email, "content" to binding.addEditView.text.toString(), "date" to dateToString(Date()) ) // ๋“œ๋””์–ด firestore์— ์ €์žฅ MyApplication.db.collection("news") .add(data) .addOnSuccessListener { Log.d("mobileApp", "data firestore save Ok") //uploadImage(it.id) } .addOnFailureListener { Log.d("mobileApp", "data firestore save error") } } fun uploadImage(docId:String){ // storage ์ ‘๊ทผ ๋ฐฉ๋ฒ• val storage = MyApplication.storage val storageRef = storage.reference val imageRef = storageRef.child("images/${docId}.jpg") val file = Uri.fromFile(File(filePath)) imageRef.putFile(file) .addOnSuccessListener { Log.d("mobileApp", "imageRef.putFile(file) - addOnSuccessListener") finish() } .addOnFailureListener { Log.d("mobileApp", "imageRef.putFile(file) - addOnFailureListener") } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/AddActivity.kt
3780491368
package com.example.projectapplication import androidx.multidex.MultiDexApplication import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.ktx.storage import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory // mainactivity๋ณด๋‹ค ๋จผ์ € ์‹คํ–‰๋œ๋‹ค. - application class MyApplication : MultiDexApplication() { companion object{ // ์ „์—ญ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ๋ถ€๋ถ„ ์„ ์–ธ lateinit var db : FirebaseFirestore lateinit var storage : FirebaseStorage lateinit var auth : FirebaseAuth // ์ด๋ฉ”์ผ ์ธ์ฆ์— ํ•„์š”ํ•œ 2๊ฐœ์˜ ๋ณ€์ˆ˜ var email: String? = null // ํ•จ์ˆ˜ ์„ ์–ธ : auth ํ™•์ธ(์Šน์ธํ™•์ธ) fun checkAuth(): Boolean{ var currentuser = auth.currentUser return currentuser?.let{ email = currentuser.email if(currentuser.isEmailVerified) true else false } ?: false } var networkService : NetworkService val retrofit: Retrofit get() = Retrofit.Builder() .baseUrl("http://openapi.seoul.go.kr:8088/") .addConverterFactory(GsonConverterFactory.create()) .build() init{ networkService = retrofit.create(NetworkService::class.java)// ์ดˆ๊ธฐํ™” ํ•„์š” } } override fun onCreate() { super.onCreate() auth = Firebase.auth db = FirebaseFirestore.getInstance() storage = Firebase.storage } }
Helper_Subway/app/src/main/java/com/example/projectapplication/MyApplication.kt
1981859743
package com.example.projectapplication import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.graphics.drawable.Drawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.startActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.preference.PreferenceManager import androidx.viewpager2.adapter.FragmentStateAdapter import com.example.projectapplication.MyApplication.Companion.auth import com.example.projectapplication.databinding.ActivityMainBinding import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import com.google.firebase.auth.FirebaseAuth class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding var authMenuItem: MenuItem? = null private lateinit var fragmentTransaction: FragmentTransaction private var fragmentManager: FragmentManager = supportFragmentManager private val fragmentHome = HomeFragment() private val fragmentSubway = SubwayFragment() private val fragmentUser = UserFragment() lateinit var sharedPreferences: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val transaction: FragmentTransaction = fragmentManager.beginTransaction() transaction.replace(R.id.menu_frame_view,fragmentHome).commitAllowingStateLoss() sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigationview) bottomNavigationView.setOnNavigationItemSelectedListener { menuItem -> val transaction = fragmentManager.beginTransaction() when (menuItem.itemId) { R.id.menu_home -> transaction.replace(R.id.menu_frame_view, fragmentHome) .commitAllowingStateLoss() R.id.menu_subway -> transaction.replace(R.id.menu_frame_view, fragmentSubway) .commitAllowingStateLoss() R.id.menu_user -> transaction.replace(R.id.menu_frame_view, fragmentUser) .commitAllowingStateLoss() } true } } //add............................... override fun onResume() { super.onResume() val bgColor:String? = sharedPreferences.getString("bg_color", "") //binding.viewpager2.setBackgroundColor(Color.parseColor(bgColor)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) // ์˜ต์…˜ ๋ฉ”๋‰ด ์ถ”๊ฐ€ // ๋กœ๊ทธ์ธ ์˜ค๋ฅ˜๋ฐœ์ƒ authMenuItem = menu!!.findItem(R.id.menu_auth) if(MyApplication.checkAuth()){ // ๋กœ๊ทธ์ธ ์—ฌ๋ถ€ ํ™•์ธ authMenuItem!!.title = "${MyApplication.email}๋‹˜" } else{ // ๋กœ๊ทธ์ธ ์ธ์ฆ์ด ์•ˆ๋œ ๊ฒฝ์šฐ ์ธ์ฆ ๊ธ€์ž ๊ทธ๋Œ€๋กœ authMenuItem!!.title = "์ธ์ฆ" } return super.onCreateOptionsMenu(menu) } override fun onStart(){ // ์ž๋™์œผ๋กœ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜์ž„. ๊ทธ๋Ÿผ ์–ธ์ œ ๋ถˆ๋ ค์ง€๋ƒ? // Intent์—์„œ finish() ๋Œ์•„์˜ฌ ๋•Œ ์‹คํ–‰ // onCreate -> onStart -> onCreateOptionMenu super.onStart() if(authMenuItem != null) { if (MyApplication.checkAuth()) { authMenuItem!!.title = "${MyApplication.email}๋‹˜" } else { authMenuItem!!.title = "์ธ์ฆ" } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { // ๋ฉ”๋‰ด๋ฅผ ๋ˆŒ๋ €์„ ๋•Œ ๋ฐ˜์‘ if(item.itemId === R.id.menu_main_setting) { val intent = Intent(this, SettingActivity::class.java) // ์•ฝ 1์‹œ๊ฐ„ 30๋ถ„? startActivity(intent) return true } else if(item.itemId === R.id.menu_auth){ val intent = Intent(this,AuthActivity::class.java) if(authMenuItem!!.title!!.equals("์ธ์ฆ")){ // title๋„ null์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— !!๋ฅผ ๋ถ™์—ฌ์ค˜์•ผํ•จ. intent.putExtra("data", "logout") } else{ // ์ด๋ฉ”์ผ ๋˜๋Š” ๊ตฌ๊ธ€๋กœ ๋กœ๊ทธ์ธ ๋˜์–ด์žˆ๋Š” ์ƒํ™ฉ intent.putExtra("data", "login") // ๋กœ๊ทธ์ธ ์ƒํƒœ๋ผ๋Š” ๊ฒƒ์„ ์ „๋‹ฌ } startActivity(intent) // AuthActivity activity ์ƒ์„ฑ } return super.onOptionsItemSelected(item) } }
Helper_Subway/app/src/main/java/com/example/projectapplication/MainActivity.kt
1543501021