content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.homeworkkotlin6n import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.homeworkkotlin6n.databinding.FragmentFirstBinding class FirstFragment : Fragment() { private var _binding: FragmentFirstBinding? = null private val binding: FragmentFirstBinding get() = _binding!! private var count = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFirstBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.tvCounterZer.text = count.toString() setupCount() savedInstanceState?.let { count = it.getInt(NUMBER, 0) binding.tvCounterZer.text = count.toString() } } private fun setupCount() = with(binding) { btnIncrement.setOnClickListener { if (count < 10) { count++ tvCounterZer.text = count.toString() } else { parentFragmentManager.beginTransaction() .add(R.id.fragment_container_view2, LastFragment()) .addToBackStack("Last Fragment") .commit() } } btnDecrement.setOnClickListener { if (count > 0) { count-- tvCounterZer.text = count.toString() } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.apply { putInt(NUMBER, count) } } companion object { const val NUMBER = "count" } }
HomeWorkKotlin6n/app/src/main/java/com/example/homeworkkotlin6n/FirstFragment.kt
1363669810
package com.example.homeworkkotlin6n import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.homeworkkotlin6n.databinding.FragmentLastBinding class LastFragment : Fragment() { private var _binding: FragmentLastBinding? = null private val binding: FragmentLastBinding get() = _binding!! private val animalsLisiAdapter = AnimalsListAdapter() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLastBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fillAnimalsList() setupRecycleView() } private fun fillAnimalsList() { val animalsList = listOf( Animals(R.drawable.arel1, "ะั€ะตะป", "5ัะผ", "3ัะผ"), Animals(R.drawable.arel2, "ะั€ะตะป", "6ัะผ", "4ัะผ"), Animals(R.drawable.arel3, "ะั€ะตะป", "4ัะผ", "5ัะผ"), Animals(R.drawable.arel4, "ะั€ะตะป", "6ัะผ", "6ัะผ"), Animals(R.drawable.arel5, "ะะฐะฑัะฐะฝ", "6ัะผ", "4ัะผ"), Animals(R.drawable.arel6, "ะะฐะฑัะฐะฝ", "6ัะผ", "5ัะผ"), Animals(R.drawable.arel7, "ะะฐะฑัะฐะฝ", "3ัะผ", "6ัะผ"), Animals(R.drawable.arel8, "ะะฐะฑัะฐะฝ", "6ัะผ", "5ัะผ") ) animalsLisiAdapter.setData(animalsList) } private fun setupRecycleView() { binding.rvAnimal.adapter = animalsLisiAdapter } }
HomeWorkKotlin6n/app/src/main/java/com/example/homeworkkotlin6n/LastFragment.kt
578952548
package com.example.homeworkkotlin6n import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.homeworkkotlin6n.databinding.AnimalsItemBinding class AnimalsListAdapter : RecyclerView.Adapter<AnimalsListAdapter.AnimalViewHolder>() { private var animals = listOf<Animals>() fun setData(data: List<Animals>) { animals = data } class AnimalViewHolder(private val binding: AnimalsItemBinding) : RecyclerView.ViewHolder(binding.root) { fun onBind(animals: Animals) = with(binding) { ivGaller.setImageResource(animals.animalImage) tvText.text = animals.name tvWool.text = animals.claws tvEars.text = animals.beak } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnimalViewHolder { val binding = AnimalsItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return AnimalViewHolder(binding) } override fun getItemCount(): Int { return animals.size } override fun onBindViewHolder(holder: AnimalViewHolder, position: Int) { holder.onBind(animals[position]) } }
HomeWorkKotlin6n/app/src/main/java/com/example/homeworkkotlin6n/AnimalsListAdapter.kt
1866260811
package com.android.fortune 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.android.fortune", appContext.packageName) } }
fortune-android/app/src/androidTest/java/com/android/fortune/ExampleInstrumentedTest.kt
113529026
package com.android.fortune 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) } }
fortune-android/app/src/test/java/com/android/fortune/ExampleUnitTest.kt
3353785165
package com.android.fortune import android.Manifest import android.animation.ValueAnimator import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.flowWithLifecycle import com.android.fortune.presentation.main.component.PayFortuneCircleOverlay import com.android.fortune.presentation.require.location.PayFortuneLocationFragment import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapNotNull import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Marker import timber.log.Timber import kotlin.math.cos import kotlin.math.sin object PayFortuneExt { const val initialZoomLevel = 19.0 const val deltaThreshold = 600 const val deltaThresholdBase = 111000.0 const val mapMoveAnimationSpeed = 500L const val minZoomLevel = 18.0 const val maxZoomLevel = 19.0 } fun getRandomLocation(currentLocation: GeoPoint): GeoPoint { // 10๋ฏธํ„ฐ ๋žœ๋ค ์ด๋™ ๊ณ„์‚ฐ val randomAngle = Math.random() * 2 * Math.PI val deltaLatitude = 100 * sin(randomAngle) / 111320 val deltaLongitude = 100 * cos(randomAngle) / (111320 * cos(Math.toRadians(currentLocation.latitude))) return GeoPoint( currentLocation.latitude + deltaLatitude, currentLocation.longitude + deltaLongitude ) } fun isMarkerInsideCircle( marker: GeoPoint, circleOverlay: PayFortuneCircleOverlay ): Boolean { // ๋งˆ์ปค ์œ„์น˜์™€ ์› ์ค‘์‹ฌ์  ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐ val distance = marker.distanceToAsDouble(circleOverlay.center) Timber.tag("FortuneTest").d("ํด๋ฆญํ•œ ๋งˆ์ปค๊นŒ์ง€ ๊ฑฐ๋ฆฌ: $distance") // ๊ฑฐ๋ฆฌ๊ฐ€ ์›์˜ ๋ฐ˜๊ฒฝ ์ด๋‚ด์ธ์ง€ ํ™•์ธ return distance <= circleOverlay.radiusInMeters } // onStop()์—์„œ ์ปฌ๋ ‰ํŠธ๋ฅผ ์ทจ์†Œํ•˜๊ณ , onStart()์—์„œ ์ปฌ๋ ‰ํŠธ๋ฅผ ์‹œ์ž‘ํ•จ. @Composable fun <T> rememberFlowWithLifecycle( flow: Flow<T>, lifecycleOwner: LifecycleOwner ): Flow<T> { return remember(flow, lifecycleOwner) { flow.flowWithLifecycle( lifecycleOwner.lifecycle, Lifecycle.State.STARTED ) } } // ํ”Œ๋กœ์šฐ๊ฐ€ ๋ณ€๊ฒฝ๋ฌ์„ ๊ฒฝ์šฐ๋งŒ ์‹œ์ž‘ํ•จ. @Composable fun <T> LaunchSingleEvent( flow: Flow<T?>, // 1 function: suspend (value: T) -> Unit // 2 ) { val effectFlow = rememberFlowWithLifecycle(flow, LocalLifecycleOwner.current) // 3 LaunchedEffect(effectFlow) { // 4 effectFlow.mapNotNull { it }.collect(function) // 5 } } // ๋งˆ์ปค์— '๋›ฐ๋Š”' ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ์ ์šฉํ•˜๋Š” ํ•จ์ˆ˜ fun applySmoothBounceAnimationToMarker( marker: Marker, initialPosition: GeoPoint, onEnd: () -> Unit ) { val animator = ValueAnimator.ofFloat(0f, 1f).apply { duration = 2000 // ์• ๋‹ˆ๋ฉ”์ด์…˜ ์ง€์† ์‹œ๊ฐ„ repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.REVERSE addUpdateListener { animation -> val progress = animation.animatedValue as Float val delta = Math.sin(progress * Math.PI) * 0.00010 // ์• ๋‹ˆ๋ฉ”์ด์…˜ ๋ณ€ํ™”๋Ÿ‰ val newLatitude = initialPosition.latitude + delta marker.position = GeoPoint(newLatitude, initialPosition.longitude) onEnd() } } animator.start() } // ๋งˆ์ปค ์œ„์น˜๋ฅผ ํ™”๋ฉด ์ขŒํ‘œ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ fun getScreenPositionFromMarker(marker: Marker, mapView: MapView): Offset { val projection = mapView.projection val point = projection.toPixels(marker.position, null) return Offset(point.x.toFloat(), point.y.toFloat()) } @Composable fun Drawable.asImageBitmap(): ImageBitmap { val context = LocalContext.current return this.toBitmap().asImageBitmap() } fun Context.checkPermissionGranted(): Boolean { val permissions = PayFortuneLocationFragment.requirePermission val allPermissionsGranted = permissions.all { permission -> val granted = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED granted } return allPermissionsGranted }
fortune-android/app/src/main/java/com/android/fortune/PayFortuneExt.kt
3458716398
package com.android.fortune.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
fortune-android/app/src/main/java/com/android/fortune/theme/Color.kt
1058394766
package com.android.fortune.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun AndroidFortuneTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
fortune-android/app/src/main/java/com/android/fortune/theme/Theme.kt
437733588
package com.android.fortune.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 ) */ )
fortune-android/app/src/main/java/com/android/fortune/theme/Type.kt
20585732
package com.android.fortune.domain import android.os.Parcelable import kotlinx.parcelize.Parcelize import org.osmdroid.util.GeoPoint @Parcelize data class PayFortuneMarker( val id: String, val name: String, val location: GeoPoint, val imageUrl: String, val type: Type ) : Parcelable { enum class Type { COIN, NORMAL, RANDOM_BOX, NONE, } }
fortune-android/app/src/main/java/com/android/fortune/domain/PayFortuneMarker.kt
2369228344
package com.android.fortune.presentation.require import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.fragment.NavHostFragment import com.android.fortune.R import com.android.fortune.checkPermissionGranted import com.android.fortune.databinding.ActivityFortuneRequireBinding import com.android.fortune.presentation.main.PayFortuneMainActivity import timber.log.Timber class PayFortuneRequireActivity : AppCompatActivity() { private lateinit var binding: ActivityFortuneRequireBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.plant(Timber.DebugTree()); binding = ActivityFortuneRequireBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_fortune_require) as NavHostFragment val navController = navHostFragment.navController val isPermissionGranted = checkPermissionGranted() val isTermsGranted = true val startDestinationId = if (!isTermsGranted) { R.id.payFortuneTermsFragment } else if (!isPermissionGranted) { R.id.payFortuneLocationFragment } else { R.id.payFortuneRequireStartMainFragment } val inflater = navController.navInflater val graph = inflater.inflate(R.navigation.nav_fortune_require) graph.setStartDestination(startDestinationId) navController.graph = graph } fun landingToMainActivity() { startActivity(PayFortuneMainActivity.newIntent(this)) finish() } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/PayFortuneRequireActivity.kt
1042401780
package com.android.fortune.presentation.require.location import android.Manifest import android.annotation.SuppressLint import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.android.fortune.LaunchSingleEvent import com.android.fortune.checkPermissionGranted import com.android.fortune.presentation.main.PayFortuneMainActivity import com.android.fortune.presentation.require.PayFortuneRequireActivity import com.android.fortune.presentation.require.location.component.PayFortuneLocationPermissionDialog import timber.log.Timber @SuppressLint("ClickableViewAccessibility") @Composable fun PayFortuneLocationDestination( viewModel: PayFortuneLocationViewModel, ) { val context = LocalContext.current val activity = context as? PayFortuneRequireActivity val viewState by viewModel.viewState.collectAsStateWithLifecycle() val lifecycle = LocalLifecycleOwner.current.lifecycle val permissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> if (permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true) { activity?.landingToMainActivity() } else { viewModel.setPermissionState(true) } } // ๊ถŒํ•œ ๊ฑฐ๋ถ€ ๋‹ค์ด์–ผ๋กœ๊ทธ ํ‘œ์‹œ if (viewState.isPermissionGranted) { PayFortuneLocationPermissionDialog(activity) } DisposableEffect(lifecycle) { val lifecycleObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_PAUSE -> Timber.tag("FortuneTest").d("onPause") Lifecycle.Event.ON_RESUME -> { if (context.checkPermissionGranted()) { activity?.landingToMainActivity() } else { permissionLauncher.launch(PayFortuneLocationFragment.requirePermission) } } Lifecycle.Event.ON_STOP -> Timber.tag("FortuneTest").d("onStop") else -> Unit } } lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) } } LaunchSingleEvent(flow = viewModel.singleEvent) { event -> when (event) { PayFortuneLocationSingleEvent.Loading -> { } } } Box( modifier = Modifier.fillMaxSize() ) { Text(text = "์—ฌ๊ธฐ๋Š” ์œ„์น˜๊ถŒํ•œ ํ™”๋ฉด์ž…๋‹ˆ๋‹ค") Button(onClick = { activity?.startActivity(PayFortuneMainActivity.newIntent(context)) activity?.finish() }) { } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/location/PayFortuneLocationDestination.kt
828151458
package com.android.fortune.presentation.require.location.component import android.app.Activity import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @Composable fun PayFortuneLocationPermissionDialog( activity: Activity?, ) = activity?.let { AlertDialog( onDismissRequest = { }, title = { Text("๊ถŒํ•œ ํ•„์š”") }, text = { Text("์ด ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ์œ„์น˜ ๊ถŒํ•œ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์„ค์ • ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ•˜์—ฌ ๊ถŒํ•œ์„ ํ—ˆ์šฉํ•ด์ฃผ์„ธ์š”.") }, confirmButton = { TextButton( onClick = { // ์‚ฌ์šฉ์ž๋ฅผ ์•ฑ ์„ค์ • ํ™”๋ฉด์œผ๋กœ ์ด๋™ val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri = Uri.fromParts("package", it.packageName, null) intent.data = uri it.startActivity(intent) } ) { Text("์„ค์ •") } }, dismissButton = { TextButton(onClick = { /* ๋‹ค์ด์–ผ๋กœ๊ทธ ๋‹ซ๊ธฐ */ }) { Text("์ทจ์†Œ") } } ) }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/location/component/PayFortuneLocationPermissionDialog.kt
3488171840
package com.android.fortune.presentation.require.location import com.android.fortune.domain.PayFortuneMarker data class PayFortuneLocationViewState( val isPermissionGranted: Boolean, ) { companion object { fun initial() = PayFortuneLocationViewState( isPermissionGranted = false, ) } } sealed interface PayFortuneLocationSingleEvent { object Loading : PayFortuneLocationSingleEvent }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/location/PayFortuneLocationViewState.kt
667734936
package com.android.fortune.presentation.require.location import android.Manifest import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import com.android.fortune.R import com.android.fortune.theme.AndroidFortuneTheme class PayFortuneLocationFragment : Fragment() { private val viewModel = PayFortuneLocationViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_fortune_location, container, false).apply { findViewById<ComposeView>(R.id.compose_view).apply { setContent { AndroidFortuneTheme { PayFortuneLocationDestination( viewModel = viewModel, ) } } } } } companion object { val requirePermission = mutableListOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, ).apply { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { // Android 10 (API ๋ ˆ๋ฒจ 29) ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ add(Manifest.permission.READ_EXTERNAL_STORAGE) add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/location/PayFortuneLocationFragment.kt
1346155422
package com.android.fortune.presentation.require.location import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.fortune.domain.PayFortuneMarker import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PayFortuneLocationViewModel : ViewModel() { private val _viewState = MutableStateFlow(PayFortuneLocationViewState.initial()) val viewState = _viewState.asStateFlow() private val _singleEvent = Channel<PayFortuneLocationSingleEvent>(Channel.BUFFERED) val singleEvent = _singleEvent.receiveAsFlow() fun setPermissionState(flag: Boolean) { _viewState.update { prevState -> prevState.copy( isPermissionGranted = flag ) } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/location/PayFortuneLocationViewModel.kt
1456007048
package com.android.fortune.presentation.require.terms import android.annotation.SuppressLint import android.app.Activity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.android.fortune.LaunchSingleEvent import com.android.fortune.R import com.android.fortune.checkPermissionGranted import com.android.fortune.presentation.require.PayFortuneRequireActivity import timber.log.Timber @SuppressLint("ClickableViewAccessibility") @Composable fun PayFortuneTermsDestination( viewModel: PayFortuneTermsViewModel, navigator: NavController, ) { val context = LocalContext.current val activity = context as? PayFortuneRequireActivity val viewState by viewModel.viewState.collectAsStateWithLifecycle() val lifecycle = LocalLifecycleOwner.current.lifecycle DisposableEffect(lifecycle) { val lifecycleObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_PAUSE -> Timber.tag("FortuneTest").d("onPause") Lifecycle.Event.ON_RESUME -> { Timber.tag("FortuneTest").d("onPause") } Lifecycle.Event.ON_STOP -> Timber.tag("FortuneTest").d("onStop") else -> Unit } } lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) } } LaunchSingleEvent(flow = viewModel.singleEvent) { event -> when (event) { PayFortuneTermsSingleEvent.Loading -> { } } } Box( modifier = Modifier.fillMaxSize() ) { Text(text = "์—ฌ๊ธฐ๋Š” ์•ฝ๊ด€๋™์˜ ํ™”๋ฉด์ž…๋‹ˆ๋‹ค") Button(onClick = { if (!context.checkPermissionGranted()) { navigator.navigate(R.id.payFortuneLocationFragment) } else { activity?.landingToMainActivity() } }) { } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/terms/PayFortuneTermsDestination.kt
3353119841
package com.android.fortune.presentation.require.terms import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import androidx.navigation.findNavController import com.android.fortune.R import com.android.fortune.theme.AndroidFortuneTheme class PayFortuneTermsFragment : Fragment() { private val viewModel = PayFortuneTermsViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_fortune_terms, container, false).apply { findViewById<ComposeView>(R.id.compose_view).apply { setContent { AndroidFortuneTheme { PayFortuneTermsDestination( navigator = findNavController(), viewModel = viewModel, ) } } } } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/terms/PayFortuneTermsFragment.kt
2546127093
package com.android.fortune.presentation.require.terms import androidx.lifecycle.ViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow class PayFortuneTermsViewModel : ViewModel() { private val _viewState = MutableStateFlow(PayFortuneTermsViewState.initial()) val viewState = _viewState.asStateFlow() private val _singleEvent = Channel<PayFortuneTermsSingleEvent>(Channel.BUFFERED) val singleEvent = _singleEvent.receiveAsFlow() init { } }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/terms/PayFortuneTermsViewModel.kt
4270805557
package com.android.fortune.presentation.require.terms data class PayFortuneTermsViewState( val isLoading: Boolean, ) { companion object { fun initial() = PayFortuneTermsViewState( isLoading = false, ) } } sealed interface PayFortuneTermsSingleEvent { object Loading : PayFortuneTermsSingleEvent }
fortune-android/app/src/main/java/com/android/fortune/presentation/require/terms/PayFortuneTermsViewState.kt
4146831752
package com.android.fortune.presentation.require import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.android.fortune.R class PayFortuneRequireStartMainFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_fortune_require_empty, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { (requireActivity() as? PayFortuneRequireActivity)?.landingToMainActivity() } } class PayFortuneRequireEmptyFragment() : Fragment()
fortune-android/app/src/main/java/com/android/fortune/presentation/require/PayFortuneRequireStartMainFragment.kt
2724822403
package com.android.fortune.presentation.obtain import com.android.fortune.domain.PayFortuneMarker data class PayFortuneMarkerObtainViewState( val targetMarker: PayFortuneMarker?, val isObtaining: Boolean, val isShowScratchDialog: Boolean, val isCloseScratchBox: Boolean, ) { companion object { fun initial() = PayFortuneMarkerObtainViewState( targetMarker = null, isObtaining = false, isShowScratchDialog = false, isCloseScratchBox = false, ) } } sealed interface PayFortuneMarkerObtainSingleEvent { data class ObtainSuccess( val marker: PayFortuneMarker, ) : PayFortuneMarkerObtainSingleEvent data class ShowScratchMarkerDialog( val marker: PayFortuneMarker, ) : PayFortuneMarkerObtainSingleEvent }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/PayFortuneMarkerObtainViewState.kt
3177643907
package com.android.fortune.presentation.obtain import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.fortune.domain.PayFortuneMarker import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PayFortuneMarkerObtainViewModel : ViewModel() { private val _viewState = MutableStateFlow(PayFortuneMarkerObtainViewState.initial()) val viewState = _viewState.asStateFlow() private val _singleEvent = Channel<PayFortuneMarkerObtainSingleEvent>(Channel.BUFFERED) val singleEvent = _singleEvent.receiveAsFlow() // todo ์ด๊ฑฐ Init ๋ธ”๋Ÿญ์œผ๋กœ ์˜ฎ๊ฒจ์•ผ๋จ. fun initProcessMarkerObtain(args: PayFortuneMarkerObtainArgs) = viewModelScope.launch { args.marker?.let { _viewState.update { prevState -> prevState.copy( targetMarker = args.marker, isObtaining = true, ) } when (it.type) { PayFortuneMarker.Type.NORMAL, PayFortuneMarker.Type.COIN -> { obtainMarker(it) } PayFortuneMarker.Type.RANDOM_BOX -> { } else -> Unit } } } fun obtainMarker(marker: PayFortuneMarker) = viewModelScope.launch { // ๋žœ๋ค๋ฐ•์Šค ์ผ ๊ฒฝ์šฐ ์Šคํฌ๋ž˜์น˜ ํ™”๋ฉด ์ œ๊ฑฐ. if (marker.type == PayFortuneMarker.Type.RANDOM_BOX) { _viewState.update { prevState -> prevState.copy( isCloseScratchBox = true, isShowScratchDialog = false, ) } } // todo ์„œ๋ฒ„์—์„œ ๋งˆ์ปค ํš๋“ api ์ฒ˜๋ฆฌํ•˜๋Š” ์‹œ๊ฐ„. delay(1000) _viewState.update { prevState -> prevState.copy( isObtaining = false, ) } _singleEvent.trySend(PayFortuneMarkerObtainSingleEvent.ObtainSuccess(marker = marker)) } fun scratchEnd() = viewModelScope.launch { _viewState.update { prevState -> prevState.copy( isShowScratchDialog = true, ) } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/PayFortuneMarkerObtainViewModel.kt
1980539540
package com.android.fortune.presentation.obtain.component import android.content.Context import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf 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.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.core.graphics.drawable.toBitmap import coil.Coil import coil.request.ImageRequest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext data class DraggedPath( val path: Path, val points: MutableList<Offset> = mutableListOf() ) @Composable fun PayFortuneScratchCard( overlayImage: ImageBitmap, baseImage: ImageBitmap, onScratchEnd: () -> Unit, isCloseScratchBox: Boolean, ) { val density = LocalDensity.current var currentPathState by remember { mutableStateOf(DraggedPath(path = Path())) } val radiusPixels = with(density) { 32.dp.toPx() } var scratchedArea by remember { mutableFloatStateOf(0f) } val circleArea = Math.PI.toFloat() * radiusPixels val totalArea = overlayImage.width * overlayImage.height.toFloat() // ํ”ฝ์…€ ๋‹จ์œ„๋กœ ๊ณ„์‚ฐ LaunchedEffect(scratchedArea) { val scratchedPercentage = (scratchedArea / totalArea) * 100 if (scratchedPercentage >= 70) { onScratchEnd() } } AnimatedVisibility( visible = !isCloseScratchBox, enter = fadeIn(initialAlpha = 0f, animationSpec = tween(durationMillis = 300)), exit = fadeOut(targetAlpha = 0f, animationSpec = tween(durationMillis = 300)) ) { Box( modifier = Modifier .fillMaxSize() .background(color = Color.DarkGray) ) { Canvas( modifier = Modifier .size(300.dp) .fillMaxSize() .align(alignment = Alignment.Center) .pointerInput(Unit) { detectDragGestures { change, _ -> val position = change.position if (!currentPathState.points.any { it.distance(position) < radiusPixels / 7 }) { scratchedArea += circleArea } currentPathState = currentPathState.copy( path = Path().also { it.addPath(currentPathState.path) it.addOval( oval = Rect( left = position.x - radiusPixels, top = position.y - radiusPixels, right = position.x + radiusPixels, bottom = position.y + radiusPixels ) ) }, points = mutableListOf<Offset>().apply { addAll(currentPathState.points) add(position) } ) } } ) { val imageSize = IntSize(width = size.width.toInt(), height = size.height.toInt()) val padding = with(density) { 24.dp.toPx() } val paddedSize = IntSize( width = (imageSize.width - padding * 2).toInt(), height = (imageSize.height - padding * 2).toInt() ) val paddedOffset = IntOffset(padding.toInt(), padding.toInt()) clipPath( path = currentPathState.path, clipOp = ClipOp.Difference, ) { // ๋ฒ ์ด์Šค ์ด๋ฏธ์ง€๋ฅผ ํŒจ๋”ฉ์„ ์ ์šฉํ•˜์—ฌ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค. drawImage( image = overlayImage, dstSize = imageSize ) } clipPath( path = currentPathState.path, clipOp = ClipOp.Intersect ) { drawImage( baseImage, dstOffset = paddedOffset, dstSize = paddedSize ) } } } } } fun Offset.distance(to: Offset): Float { return (this - to).getDistance() } @Composable fun loadNetworkImage(url: String): ImageBitmap? { var image by remember { mutableStateOf<ImageBitmap?>(null) } val context = LocalContext.current LaunchedEffect(url) { image = context.loadNetworkImage(url) } return image } suspend fun Context.loadNetworkImage(url: String): ImageBitmap? { return withContext(Dispatchers.IO) { try { Coil.imageLoader(this@loadNetworkImage).execute( ImageRequest.Builder(this@loadNetworkImage) .data(url) .build() ).drawable?.toBitmap()?.asImageBitmap() } catch (e: Exception) { null } } } @Composable @Preview(device = Devices.PIXEL_4) fun ImageScratchPreview() { val overlayImageUrl = "https://picsum.photos/128/128/?random" val baseImageUrl = "https://hcpyrleocxaejkqqibik.supabase.co/storage/v1/object/public/ingredients/fortune_cookie.webp" val overlayImage = loadNetworkImage(overlayImageUrl) val baseImage = loadNetworkImage(baseImageUrl) if (overlayImage != null && baseImage != null) { PayFortuneScratchCard( overlayImage = overlayImage, baseImage = baseImage, onScratchEnd = {}, isCloseScratchBox = false ) } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/component/PayFortuneScratchCard.kt
1792267646
package com.android.fortune.presentation.obtain.component import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.CachePolicy import coil.request.ImageRequest import com.android.fortune.R import com.android.fortune.theme.AndroidFortuneTheme @Composable fun PayFortuneObtainingView( modifier: Modifier = Modifier, visible: Boolean, imageUrl: String?, name: String?, ) { val alphaAnimation = animateFloatAsState( targetValue = if (visible) 1f else 0f, animationSpec = tween(durationMillis = 500), label = "" ) Box( modifier = modifier .fillMaxSize() .graphicsLayer { alpha = alphaAnimation.value } .background( color = Color.Black.copy( alpha = 0.5f ) ), contentAlignment = Alignment.Center, ) { if (visible) { Column( verticalArrangement = Arrangement.Center, // ์ˆ˜์ง ๋ฐฉํ–ฅ์œผ๋กœ ์ค‘์•™ ์ •๋ ฌ horizontalAlignment = Alignment.CenterHorizontally // ์ˆ˜ ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .size(64) .crossfade(true) // ๋ถ€๋“œ๋Ÿฌ์šด ์ด๋ฏธ์ง€ ์ „ํ™˜ ํšจ๊ณผ .diskCachePolicy(CachePolicy.ENABLED) // ๋””์Šคํฌ ์บ์‹ฑ ํ™œ์„ฑํ™” .memoryCachePolicy(CachePolicy.ENABLED) // ๋ฉ”๋ชจ๋ฆฌ ์บ์‹ฑ ํ™œ์„ฑํ™” .build(), contentDescription = null, placeholder = painterResource(R.drawable.ic_launcher_background), error = painterResource(R.drawable.ic_launcher_background) ) Spacer(modifier = Modifier.height(8.dp)) Text("$name ์ค์ค ์ค‘..", style = TextStyle(color = Color.White)) } } } } @Preview @Composable private fun MarkerObtainingPreview() { AndroidFortuneTheme { PayFortuneObtainingView( modifier = Modifier, imageUrl = "https://picsum.photos/128/128/?random", name = "์ฝ”์ธ", visible = true, ) } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/component/PayFortuneObtainingView.kt
4183086875
package com.android.fortune.presentation.obtain import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import com.android.fortune.R import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity.Companion.ARGS_FORTUNE_OPTAIN import com.android.fortune.theme.AndroidFortuneTheme class PayFortuneMarkerObtainFragment() : Fragment() { private val viewModel = PayFortuneMarkerObtainViewModel() private lateinit var args: PayFortuneMarkerObtainArgs override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_fortune_marker_obtain, container, false).apply { findViewById<ComposeView>(R.id.compose_view).apply { setContent { AndroidFortuneTheme { PayFortuneMarkerObtainDestination( args = args, viewModel = viewModel, ) } } } } } companion object { fun newInstance( args: PayFortuneMarkerObtainArgs ): PayFortuneMarkerObtainFragment { return PayFortuneMarkerObtainFragment().apply { this.args = args } } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/PayFortuneMarkerObtainFragment.kt
618874121
package com.android.fortune.presentation.obtain import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Parcelable import androidx.appcompat.app.AppCompatActivity import com.android.fortune.R import com.android.fortune.databinding.ActivityFortuneObtainBinding import com.android.fortune.domain.PayFortuneMarker import com.android.fortune.presentation.main.PayFortuneMainFragment import kotlinx.parcelize.Parcelize import timber.log.Timber @Parcelize data class PayFortuneMarkerObtainArgs( val marker: PayFortuneMarker? ) : Parcelable { companion object { fun initial() = PayFortuneMarkerObtainArgs( marker = null, ) } } class PayFortuneMarkerObtainActivity : AppCompatActivity() { private lateinit var binding: ActivityFortuneObtainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFortuneObtainBinding.inflate(layoutInflater) setObtainFragment() setContentView(binding.root) } private fun setObtainFragment() { supportFragmentManager .beginTransaction() .replace( R.id.fortune_obtain_container, PayFortuneMarkerObtainFragment.newInstance( args = intent.getParcelableExtra(ARGS_FORTUNE_OPTAIN) ?: PayFortuneMarkerObtainArgs.initial() ) ) .commit() } companion object { const val ARGS_FORTUNE_OPTAIN = "ARGS_FORTUNE_OPTAIN" const val KEY_RESULT_OBTAIN_SUCCESS = "KEY_RESULT_OBTAIN_SUCCESS" const val CODE_RESULT_OBTAIN_SUCCESS = 1004 fun newIntent( context: Context, args: PayFortuneMarkerObtainArgs ) = Intent(context, PayFortuneMarkerObtainActivity::class.java).apply { putExtra(ARGS_FORTUNE_OPTAIN, args) } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/PayFortuneMarkerObtainActivity.kt
1895283924
package com.android.fortune.presentation.obtain import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.android.fortune.LaunchSingleEvent import com.android.fortune.domain.PayFortuneMarker import com.android.fortune.presentation.obtain.component.PayFortuneObtainingView import com.android.fortune.presentation.obtain.component.PayFortuneScratchCard import com.android.fortune.presentation.obtain.component.loadNetworkImage import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity.Companion.KEY_RESULT_OBTAIN_SUCCESS import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity.Companion.CODE_RESULT_OBTAIN_SUCCESS import timber.log.Timber @SuppressLint("ClickableViewAccessibility") @Composable fun PayFortuneMarkerObtainDestination( args: PayFortuneMarkerObtainArgs, viewModel: PayFortuneMarkerObtainViewModel, ) { val context = LocalContext.current val activity = context as? Activity val viewState by viewModel.viewState.collectAsStateWithLifecycle() val lifecycle = LocalLifecycleOwner.current.lifecycle DisposableEffect(lifecycle) { val lifecycleObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_PAUSE -> Timber.tag("FortuneTest").d("onPause") Lifecycle.Event.ON_RESUME -> { viewModel.initProcessMarkerObtain(args) } Lifecycle.Event.ON_STOP -> Timber.tag("FortuneTest").d("onStop") else -> Unit } } lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) } } LaunchSingleEvent(flow = viewModel.singleEvent) { event -> when (event) { is PayFortuneMarkerObtainSingleEvent.ObtainSuccess -> { val returnIntent = Intent() returnIntent.putExtra(KEY_RESULT_OBTAIN_SUCCESS, event.marker) activity?.setResult(CODE_RESULT_OBTAIN_SUCCESS, returnIntent) activity?.finish() } is PayFortuneMarkerObtainSingleEvent.ShowScratchMarkerDialog -> { } else -> {} } } if (viewState.isShowScratchDialog) { AlertDialog( onDismissRequest = { }, title = { Text("์Šคํฌ๋ž˜์น˜ ๊ธ๊ธฐ ์™„๋ฃŒ") }, text = { Text("ํ™•์ธ ๋ˆ„๋ฅด๊ณ  ํš๋“") }, confirmButton = { Button( onClick = { val targetMarker = viewState.targetMarker targetMarker?.let { viewModel.obtainMarker(it) } } ) { Text("ํ™•์ธ") } }, ) } args.marker?.let { targetMarker -> PayFortuneObtainingView( visible = viewState.isObtaining, imageUrl = targetMarker.imageUrl, name = targetMarker.name ) when (targetMarker.type) { PayFortuneMarker.Type.RANDOM_BOX -> { val sampleBaseImageUrl = "https://picsum.photos/128/128/?random" val overlayImage = loadNetworkImage(sampleBaseImageUrl) val baseImage = loadNetworkImage(targetMarker.imageUrl) val isCloseScratchBox = viewState.isCloseScratchBox if (overlayImage != null && baseImage != null) { PayFortuneScratchCard( overlayImage = overlayImage, baseImage = baseImage, isCloseScratchBox = isCloseScratchBox, onScratchEnd = { viewModel.scratchEnd() }, ) } } else -> Unit } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/obtain/PayFortuneMarkerObtainDestination.kt
4066026173
package com.android.fortune.presentation.main import android.content.Context import android.graphics.Bitmap.Config import android.os.Bundle import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import android.preference.PreferenceManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import com.android.fortune.R import com.android.fortune.theme.AndroidFortuneTheme import org.osmdroid.config.Configuration import org.osmdroid.library.BuildConfig import org.osmdroid.tileprovider.util.StorageUtils.getStorage class PayFortuneMainFragment : Fragment() { private val viewModel = PayFortuneMainViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_fortune_main, container, false).apply { findViewById<ComposeView>(R.id.compose_view).apply { val context = requireContext() val mapProvider = Configuration.getInstance() mapProvider.userAgentValue = BuildConfig.APPLICATION_ID mapProvider.load(context, PreferenceManager.getDefaultSharedPreferences(context)) setContent { AndroidFortuneTheme { PayFortuneMainDestination( viewModel = viewModel ) } } } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/PayFortuneMainFragment.kt
3700381494
package com.android.fortune.presentation.main.component import android.graphics.Canvas import android.view.MotionEvent import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay class PayFortuneDisableDoubleTabOverlay : Overlay() { override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) { } override fun onDoubleTap(e: MotionEvent?, mapView: MapView?): Boolean { return true } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneDisableDoubleTabOverlay.kt
4133334856
package com.android.fortune.presentation.main.component import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.tooling.preview.Preview import com.android.fortune.theme.AndroidFortuneTheme import kotlin.math.absoluteValue import kotlin.math.cos import kotlin.math.sin @Composable fun PayFortuneDirectionPainter() { val infiniteTransition = rememberInfiniteTransition(label = "") val rotation by infiniteTransition.animateFloat( initialValue = 0f, targetValue = 360f, animationSpec = infiniteRepeatable( animation = tween(2000, easing = LinearEasing), repeatMode = RepeatMode.Restart ), label = "" ) Canvas(modifier = Modifier.fillMaxSize()) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = 420f // ์•„ํฌ์˜ ๋ฐ˜์ง€๋ฆ„ // ๋ถ€์ฑ„๊ผด์˜ ์‹œ์ž‘์ ๊ณผ ๋์  ๊ณ„์‚ฐ val startAngle = 145f // ์‹œ์ž‘ ๊ฐ๋„ val sweepAngle = 75f // ์Šค์œ• ๊ฐ๋„ val endAngle = startAngle + sweepAngle val gradientStart = Offset( x = centerX + radius * cos(Math.toRadians(startAngle.toDouble())).toFloat(), y = centerY + radius * sin(Math.toRadians(startAngle.toDouble())).toFloat() ) val gradientEnd = Offset( x = centerX + radius * cos(Math.toRadians(endAngle.toDouble())).toFloat(), y = centerY + radius * sin(Math.toRadians(endAngle.toDouble())).toFloat() ) val gradient = Brush.linearGradient( colors = listOf( Color.Green.copy(alpha = 0.00f), // ์•„๋ž˜์ชฝ: ์™„์ „ ํˆฌ๋ช… Color.Green.copy(alpha = 0.005f), Color.Green.copy(alpha = 0.01f), Color.Green.copy(alpha = 0.03f), Color.Green.copy(alpha = 0.05f), Color.Green.copy(alpha = 0.1f), Color.Green.copy(alpha = 0.2f), // ์ค‘๊ฐ„: ์•ฝ๊ฐ„ ๋ถˆํˆฌ๋ช… Color.Green.copy(alpha = 0.3f), // ์ค‘๊ฐ„: ๋” ๋ถˆํˆฌ๋ช… Color.Green.copy(alpha = 0.4f), // ์œ„์ชฝ: ๋” ๋ถˆํˆฌ๋ช… Color.Green.copy(alpha = 0.5f) // ์œ„์ชฝ: ๊ฐ€์žฅ ์ง„ํ•˜๊ณ  ๋ถˆํˆฌ๋ช… ), start = gradientStart, end = gradientEnd ) // ์บ”๋ฒ„์Šค ํšŒ์ „ rotate(degrees = rotation, pivot = Offset(centerX, centerY)) { drawArc( brush = gradient, startAngle = startAngle, sweepAngle = sweepAngle, useCenter = true, topLeft = Offset(centerX - radius, centerY - radius), size = Size(radius * 2, radius * 2) ) } } } @Preview @Composable private fun PayFortuneDirectionPainterPreview() { AndroidFortuneTheme { PayFortuneDirectionPainter() } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneDirectionPainter.kt
2034665778
package com.android.fortune.presentation.main.component import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.os.Build import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay class PayFortuneGridOverlay(private val gridSpacing: Float = 50f) : Overlay() { private val primaryColor = Color.parseColor("#FF45E2AA") // Define or fetch your primary color private val backgroundPaint: Paint = Paint().apply { color = Color.parseColor("#FF1A1A1E") style = Paint.Style.FILL } private val gridPaint: Paint = Paint().apply { color = primaryColor style = Paint.Style.STROKE strokeWidth = 0.2f } private val thickCrossPaint: Paint = Paint().apply { color = primaryColor style = Paint.Style.STROKE strokeWidth = 0.4f } override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) { if (shadow) return val projection = mapView.projection val screenRect = projection.screenRect val left = screenRect.left.toFloat() val top = screenRect.top.toFloat() val right = screenRect.right.toFloat() val bottom = screenRect.bottom.toFloat() // Draw background canvas.drawRect( Rect(screenRect.left, screenRect.top, screenRect.right, screenRect.bottom), backgroundPaint ) // Draw grid lines for (i in left.toInt()..right.toInt() step gridSpacing.toInt()) { canvas.drawLine(i.toFloat(), top, i.toFloat(), bottom, gridPaint) } for (j in top.toInt()..bottom.toInt() step gridSpacing.toInt()) { canvas.drawLine(left, j.toFloat(), right, j.toFloat(), gridPaint) } // Draw thick crosses at intersections val crossHalfLength = gridSpacing / 5 for (i in left.toInt()..right.toInt() step (gridSpacing * 3).toInt()) { for (j in top.toInt()..bottom.toInt() step (gridSpacing * 3).toInt()) { canvas.drawLine( i - crossHalfLength, j.toFloat(), i + crossHalfLength, j.toFloat(), thickCrossPaint ) canvas.drawLine( i.toFloat(), j - crossHalfLength, i.toFloat(), j + crossHalfLength, thickCrossPaint ) } } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneGridOverlay.kt
2709291200
package com.android.fortune.presentation.main.component import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Color import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.MotionEvent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.viewinterop.AndroidView import com.android.fortune.PayFortuneExt import com.android.fortune.applySmoothBounceAnimationToMarker import com.android.fortune.domain.PayFortuneMarker import com.android.fortune.isMarkerInsideCircle import com.bumptech.glide.Glide import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import kotlinx.collections.immutable.ImmutableList import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Marker import org.osmdroid.views.overlay.Overlay import timber.log.Timber @Composable fun PayFortuneMainMap( context: Context, mapView: MapView, headings: Float, markers: ImmutableList<PayFortuneMarker>, currentLocation: GeoPoint?, onMarkerClick: (PayFortuneMarker) -> Unit, ) { var previousLocation by remember { mutableStateOf<GeoPoint?>(null) } LaunchedEffect(currentLocation, markers) { if (currentLocation != null && currentLocation != previousLocation) { previousLocation = currentLocation updateMarkersOnMap( currentLocation = currentLocation, markers = markers, mapView = mapView, context = context, onMarkerClick = onMarkerClick ) } } Box { AndroidView( modifier = Modifier.fillMaxSize(), factory = { _ -> mapView.apply { minZoomLevel = PayFortuneExt.minZoomLevel maxZoomLevel = PayFortuneExt.maxZoomLevel setTileSource(TileSourceFactory.MAPNIK) setupNightMode(mapView) controller.setZoom(PayFortuneExt.initialZoomLevel) zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER) zoomController.setZoomInEnabled(false) isFlingEnabled = false setMultiTouchControls(true) } }, ) PayFortuneDirectionPainter() FortuneMainRippleBackground( modifier = Modifier.align(Alignment.Center) ) } } @SuppressLint("ClickableViewAccessibility") fun updateMarkersOnMap( currentLocation: GeoPoint, markers: ImmutableList<PayFortuneMarker>, mapView: MapView, context: Context, onMarkerClick: (PayFortuneMarker) -> Unit ) { // ์ด ๋ฆฌ์Šค๋„ˆ๋Š” ๋‚ด ์œ„์น˜๊ฐ€ ๋ฐ”๋€” ๋•Œ๋งˆ๋‹ค ์ค‘์•™์œผ๋กœ ์คŒ์ธ์‹œ์ผœ์•ผ๋˜๊ธฐ๋•Œ๋ฌธ์— ์—ฌ๊ธฐ์žˆ๋Š”๊ฑฐ์ž„. mapView.setOnTouchListener { _, event -> when (event.action) { MotionEvent.ACTION_UP -> { if (mapView.zoomLevelDouble != PayFortuneExt.initialZoomLevel) { mapView.controller.animateTo( currentLocation, PayFortuneExt.initialZoomLevel, 200L ) } // true๋กœ ํ•˜๋ฉด ๋งˆ์ปคํด๋ฆญ์ด ์•ˆ๋จ. // ํ„ฐ์น˜์—์„œ ์†์„๋• ์„ ๊ฒฝ์šฐ ๊ธฐ์ค€. false } // ์†๊ฐ€๋ฝ ํ•˜๋‚˜๋กœ ์Šคํฌ๋กค ๋ฐฉ์ง€ MotionEvent.ACTION_MOVE -> { event.pointerCount == 1 } else -> false } } currentLocation.let { mapView.overlays.clear() mapView.overlays.add(PayFortuneDisableDoubleTabOverlay()) val newCircleOverlay = PayFortuneCircleOverlay(currentLocation, 100F) val newOverlays = ArrayList<Overlay>() for (overlay in mapView.overlays) { if (overlay !is PayFortuneCircleOverlay) { newOverlays.add(overlay) } } newOverlays.add(newCircleOverlay) mapView.overlays.addAll(newOverlays) markers.forEach { fortuneMarker -> Glide.with(context) .asBitmap() .load(fortuneMarker.imageUrl) .into(object : CustomTarget<Bitmap>() { override fun onResourceReady( resource: Bitmap, transition: Transition<in Bitmap>? ) { val marker = Marker(mapView).apply { id = fortuneMarker.id title = fortuneMarker.name icon = BitmapDrawable(context.resources, resource) position = fortuneMarker.location setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) } marker.setOnMarkerClickListener { marker, mapView -> if (isMarkerInsideCircle(marker.position, newCircleOverlay)) { Timber.tag("FortuneTest").d("ํš๋“ ๊ฐ€๋Šฅํ•œ ๋งˆ์ปค") onMarkerClick(fortuneMarker) } else { Timber.tag("FortuneTest").d("ํš๋“ ๋ถˆ๊ฐ€๋Šฅํ•œ ๋งˆ์ปค") } true } applySmoothBounceAnimationToMarker( marker = marker, initialPosition = fortuneMarker.location, onEnd = { mapView.invalidate() } ) mapView.overlays.add(marker) } override fun onLoadCleared(placeholder: Drawable?) = Unit }) } } } fun setupNightMode(mapView: MapView) { // ์ƒ‰์ƒ ๋ฐ˜์ „ ํ–‰๋ ฌ val inverseMatrix = ColorMatrix( floatArrayOf( -1.0f, 0.0f, 0.0f, 0.0f, 255f, 0.0f, -1.0f, 0.0f, 0.0f, 255f, 0.0f, 0.0f, -1.0f, 0.0f, 255f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f ) ) // ๋ชฉํ‘œ ์ƒ‰์ƒ ์„ค์ • val destinationColor = Color.parseColor("#FF2A2A2A") val lr = (255.0f - Color.red(destinationColor)) / 255.0f val lg = (255.0f - Color.green(destinationColor)) / 255.0f val lb = (255.0f - Color.blue(destinationColor)) / 255.0f // ํšŒ์ƒ‰์กฐ ํ–‰๋ ฌ ์ƒ์„ฑ val grayscaleMatrix = ColorMatrix( floatArrayOf( lr, lg, lb, 0F, 0F, lr, lg, lb, 0F, 0F, lr, lg, lb, 0F, 0F, 0F, 0F, 0F, 1F, 0F ) ) grayscaleMatrix.preConcat(inverseMatrix) // ์ƒ‰์กฐ ํ–‰๋ ฌ ์ƒ์„ฑ val drf = Color.red(destinationColor) / 255f val dgf = Color.green(destinationColor) / 255f val dbf = Color.blue(destinationColor) / 255f val tintMatrix = ColorMatrix( floatArrayOf( drf, 0F, 0F, 0F, 0F, 0F, dgf, 0F, 0F, 0F, 0F, 0F, dbf, 0F, 0F, 0F, 0F, 0F, 1F, 0F ) ) tintMatrix.preConcat(grayscaleMatrix) // ์ตœ์ข… ์Šค์ผ€์ผ ํ–‰๋ ฌ ์ƒ์„ฑ ๋ฐ ์ ์šฉ val lDestination = drf * lr + dgf * lg + dbf * lb val scale = 1f - lDestination val translate = 1 - scale * 0.5f val scaleMatrix = ColorMatrix( floatArrayOf( scale, 0F, 0F, 0F, Color.red(destinationColor) * translate, 0F, scale, 0F, 0F, Color.green(destinationColor) * translate, 0F, 0F, scale, 0F, Color.blue(destinationColor) * translate, 0F, 0F, 0F, 1F, 0F ) ) scaleMatrix.preConcat(tintMatrix) // ColorMatrixColorFilter ์ƒ์„ฑ ๋ฐ ์ ์šฉ val filter = ColorMatrixColorFilter(scaleMatrix) mapView.overlayManager.tilesOverlay.setColorFilter(filter) }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneMainMap.kt
2287752526
package com.android.fortune.presentation.main.component import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import org.osmdroid.util.GeoPoint class PayFortuneCircleOverlay( val center: GeoPoint, val radiusInMeters: Float ) : Overlay() { private val paint: Paint = Paint().apply { style = Paint.Style.FILL color = Color.GREEN // ์ ์ ˆํ•œ ์ƒ‰์ƒ ์„ค์ • alpha = 30 // ํˆฌ๋ช…๋„ ์„ค์ • } override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) { if (!shadow) { val projectedCenter = mapView.projection.toPixels(center, null) val radiusInPixels = mapView.projection.metersToPixels(radiusInMeters) canvas.drawCircle( projectedCenter.x.toFloat(), projectedCenter.y.toFloat(), radiusInPixels, paint ) } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneCircleOverlay.kt
2840879323
package com.android.fortune.presentation.main.component import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.InfiniteRepeatableSpec import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.android.fortune.theme.AndroidFortuneTheme @Composable fun FortuneMainRippleBackground( modifier: Modifier, rippleColor: Color = Color.Green, rippleCount: Int = 3, rippleDurationTime: Int = 5000, rippleScale: Float = 6.0f, initialAlpha: Float = 0.2f, // ์‹œ์ž‘ ํˆฌ๋ช…๋„ initialScale: Float = 0f // ์‹œ์ž‘ ํฌ๊ธฐ ) { val minSize = 50.dp // ์ง€์ •ํ•œ ํฌ๊ธฐ for (i in 0 until rippleCount) { val delay = (rippleDurationTime / rippleCount) * i val animationSpec = infiniteRepeatable<Float>( animation = tween( rippleDurationTime, easing = FastOutSlowInEasing, delayMillis = delay ), repeatMode = RepeatMode.Restart ) RippleEffect( modifier = modifier, rippleColor = rippleColor, rippleScale = rippleScale, minSize = minSize, animationSpec = animationSpec, initialAlpha = initialAlpha, initialScale = initialScale ) } } @Composable private fun RippleEffect( modifier: Modifier, rippleColor: Color, rippleScale: Float, minSize: Dp, animationSpec: InfiniteRepeatableSpec<Float>, initialAlpha: Float, initialScale: Float ) { val infiniteTransition = rememberInfiniteTransition(label = "") val animation = infiniteTransition.animateFloat( initialValue = initialScale, targetValue = rippleScale, animationSpec = animationSpec, label = "" ) Canvas(modifier = modifier.size(minSize)) { val scale = animation.value val alpha = (1 - (scale - initialScale) / (rippleScale - initialScale)) * initialAlpha drawCircle( color = rippleColor.copy(alpha = alpha), radius = (minSize.toPx() / 2) * scale, center = Offset(size.width / 2, size.height / 2) ) } } @Preview @Composable private fun RippleEffectPreview() { AndroidFortuneTheme { FortuneMainRippleBackground( modifier = Modifier .fillMaxSize(), ) } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/component/PayFortuneRippleBackground.kt
725690917
package com.android.fortune.presentation.main import com.android.fortune.domain.PayFortuneMarker import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import org.osmdroid.util.GeoPoint data class PayFortuneMainViewState( val markers: ImmutableList<PayFortuneMarker>, val myLocation: GeoPoint?, val headings: Float, val isShowRequestObtainDialog: Boolean, val currentObtainMarker: PayFortuneMarker?, ) { companion object { fun initial() = PayFortuneMainViewState( markers = persistentListOf(), myLocation = null, isShowRequestObtainDialog = false, headings = 0F, currentObtainMarker = null, ) } } sealed interface PayFortuneSingleEvent { data class ChangeMyLocation( val geoPoint: GeoPoint ) : PayFortuneSingleEvent data class NavigateProcessObtain( val marker: PayFortuneMarker ) : PayFortuneSingleEvent data class ObtainMarkerAction( val marker: PayFortuneMarker ) : PayFortuneSingleEvent }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/PayFortuneMainViewState.kt
61313200
package com.android.fortune.presentation.main import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.android.fortune.R import com.android.fortune.databinding.ActivityFortuneMainBinding import timber.log.Timber class PayFortuneMainActivity : AppCompatActivity() { private lateinit var binding: ActivityFortuneMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.plant(Timber.DebugTree()); binding = ActivityFortuneMainBinding.inflate(layoutInflater) setMainFragment() setContentView(binding.root) } private fun setMainFragment() { supportFragmentManager .beginTransaction() .replace(R.id.fortune_main_container, PayFortuneMainFragment()) .commit() } companion object { fun newIntent( context: Context, ) = Intent(context, PayFortuneMainActivity::class.java).apply { } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/PayFortuneMainActivity.kt
3330104836
package com.android.fortune.presentation.main import android.annotation.SuppressLint import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.android.fortune.LaunchSingleEvent import com.android.fortune.PayFortuneExt import com.android.fortune.PayFortuneExt.deltaThresholdBase import com.android.fortune.PayFortuneExt.initialZoomLevel import com.android.fortune.PayFortuneExt.mapMoveAnimationSpeed import com.android.fortune.domain.PayFortuneMarker import com.android.fortune.presentation.main.component.PayFortuneMainMap import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity.Companion.CODE_RESULT_OBTAIN_SUCCESS import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainActivity.Companion.KEY_RESULT_OBTAIN_SUCCESS import com.android.fortune.presentation.obtain.PayFortuneMarkerObtainArgs import org.osmdroid.util.BoundingBox import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Marker import timber.log.Timber @SuppressLint("ClickableViewAccessibility") @Composable fun PayFortuneMainDestination( viewModel: PayFortuneMainViewModel, ) { val context = LocalContext.current val viewState by viewModel.viewState.collectAsStateWithLifecycle() val mapView = remember { MapView(context) } val lifecycle = LocalLifecycleOwner.current.lifecycle val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val rotationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION) val rotationListener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent) { viewModel.updateCompass(event.values[0]) } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { // ์ •ํ™•๋„ ๋ณ€๊ฒฝ ์‹œ ์ฒ˜๋ฆฌ } } // ๋งˆ์ปค ํš๋“ ํ›„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜. val startObtainActivityForResult = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == CODE_RESULT_OBTAIN_SUCCESS) { val data = result.data // Intent ๊ฐ์ฒด val resultData = data?.getParcelableExtra<PayFortuneMarker>(KEY_RESULT_OBTAIN_SUCCESS) resultData?.let { viewModel.obtainSuccess(it) } } } DisposableEffect(lifecycle) { val lifecycleObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_PAUSE -> { // ์„ผ์„œ ๋งค๋‹ˆ์ € ๋“ฑ๋ก ํ•ด์ œ. sensorManager.unregisterListener(rotationListener) } Lifecycle.Event.ON_RESUME -> { // ์„ผ์„œ ๋งค๋‹ˆ์ € ๋“ฑ๋ก. sensorManager.registerListener( rotationListener, rotationSensor, SensorManager.SENSOR_DELAY_UI ) } Lifecycle.Event.ON_STOP -> { Timber.tag("FortuneTest").d("onStop") } else -> Unit } } lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) sensorManager.unregisterListener(rotationListener) } } LaunchSingleEvent(flow = viewModel.singleEvent) { event -> when (event) { is PayFortuneSingleEvent.ChangeMyLocation -> { val mapController = mapView.controller val currentLocation = event.geoPoint val deltaThreshold = PayFortuneExt.deltaThreshold val deltaLatitude = deltaThreshold / deltaThresholdBase val deltaLongitude = deltaThreshold / (deltaThresholdBase * kotlin.math.cos( Math.toRadians(currentLocation.latitude) )) mapView.setScrollableAreaLimitDouble( BoundingBox( currentLocation.latitude + deltaLatitude, currentLocation.longitude + deltaLongitude, currentLocation.latitude - deltaLatitude, currentLocation.longitude - deltaLongitude, ) ) mapController.animateTo(currentLocation, initialZoomLevel, mapMoveAnimationSpeed) } is PayFortuneSingleEvent.NavigateProcessObtain -> { startObtainActivityForResult.launch( PayFortuneMarkerObtainActivity.newIntent( context = context, args = PayFortuneMarkerObtainArgs( marker = event.marker ) ) ) } is PayFortuneSingleEvent.ObtainMarkerAction -> { val markerToRemove = mapView.overlays.find { overlay -> overlay is Marker && overlay.id == event.marker.id } as? Marker markerToRemove?.let { mapView.overlays.remove(markerToRemove) mapView.invalidate() } } } } if (viewState.isShowRequestObtainDialog) { AlertDialog( onDismissRequest = { }, text = { Text("๋งˆ์ปค๋ฅผ ํš๋“ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?") }, confirmButton = { Button( onClick = { val targetMarker = viewState.currentObtainMarker targetMarker?.let { viewModel.startObtainProcess(targetMarker) } } ) { Text("ํ™•์ธ") } }, ) } Box { PayFortuneMainMap( context = context, mapView = mapView, headings = viewState.headings, markers = viewState.markers, currentLocation = viewState.myLocation, onMarkerClick = { viewModel.onMarkerClick(it) } ) } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/PayFortuneMainDestination.kt
105389030
package com.android.fortune.presentation.main import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.fortune.domain.PayFortuneMarker import com.android.fortune.getRandomLocation import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.osmdroid.util.GeoPoint class PayFortuneMainViewModel : ViewModel() { private val _viewState = MutableStateFlow(PayFortuneMainViewState.initial()) val viewState = _viewState.asStateFlow() private val _singleEvent = Channel<PayFortuneSingleEvent>(Channel.BUFFERED) val singleEvent = _singleEvent.receiveAsFlow() init { viewModelScope.launch { // ํ˜„์žฌ ์œ„์น˜๋ฅผ ๋ถˆ๋Ÿฌ์˜ด. val centerGeoPoint = GeoPoint(37.39481622873532, 127.1112430592695) // ๋งˆ์ปค ๋ฆฌ์ŠคํŠธ. val sampleList = (0..9).map { val id = "$it" val angle = 2 * Math.PI / 10 * it // ๊ฐ ๋งˆ์ปค์˜ ๊ฐ๋„ val offsetX = 100 * kotlin.math.cos(angle) / 110540 // ๊ฒฝ๋„ ์˜คํ”„์…‹ (๋Œ€๋žต์ ์ธ ๊ณ„์‚ฐ) val offsetY = 100 * kotlin.math.sin(angle) / 111320 // ์œ„๋„ ์˜คํ”„์…‹ (๋Œ€๋žต์ ์ธ ๊ณ„์‚ฐ) val markerPoint = GeoPoint(centerGeoPoint.latitude + offsetY, centerGeoPoint.longitude + offsetX) PayFortuneMarker( id = id, name = when (it) { 0 -> PayFortuneMarker.Type.COIN.name 1 -> PayFortuneMarker.Type.NORMAL.name 2 -> PayFortuneMarker.Type.RANDOM_BOX.name 3 -> PayFortuneMarker.Type.COIN.name 4 -> PayFortuneMarker.Type.NORMAL.name 5 -> PayFortuneMarker.Type.RANDOM_BOX.name else -> PayFortuneMarker.Type.RANDOM_BOX.name }, location = markerPoint, imageUrl = "https://hcpyrleocxaejkqqibik.supabase.co/storage/v1/object/public/ingredients/green_clover.webp?t=2023-12-15T03%3A36%3A26.315Z", type = when (it) { 0 -> PayFortuneMarker.Type.COIN 1 -> PayFortuneMarker.Type.NORMAL 2 -> PayFortuneMarker.Type.RANDOM_BOX 3 -> PayFortuneMarker.Type.COIN 4 -> PayFortuneMarker.Type.NORMAL 5 -> PayFortuneMarker.Type.RANDOM_BOX else -> PayFortuneMarker.Type.RANDOM_BOX }, ) }.toImmutableList() // ๋‚ด ์œ„์น˜๋ฅผ ๋ณด๋ƒ„. _singleEvent.trySend(PayFortuneSingleEvent.ChangeMyLocation(centerGeoPoint)) _viewState.update { prevState -> prevState.copy( myLocation = centerGeoPoint, markers = sampleList ) } startLocationUpdates(centerGeoPoint) } } private fun startLocationUpdates(centerGeoPoint: GeoPoint) { viewModelScope.launch { while (true) { // ํ˜„์žฌ ๋‚ด ์œ„์น˜๋ฅผ ๊ฐ€์ ธ์˜ด.(์„œ๋ฒ„์—์„œ ๊ฐ€์ ธ์˜จ๊ฑธ๋กœ) val newLocation = getRandomLocation(centerGeoPoint) // ์ƒˆ๋กœ์šด ๋งˆ์ปค ๋“ค์„ ๊ฐ€์ ธ์˜ด. (์„œ๋ฒ„์—์„œ ๊ฐ€์ ธ์˜จ๊ฑธ๋กœ) val nextList = (0..9).map { val id = "${System.currentTimeMillis()}-$it" val angle = 2 * Math.PI / 10 * it // ๊ฐ ๋งˆ์ปค์˜ ๊ฐ๋„ val offsetX = 200 * kotlin.math.cos(angle) / 110540 // ๊ฒฝ๋„ ์˜คํ”„์…‹ (๋Œ€๋žต์ ์ธ ๊ณ„์‚ฐ) val offsetY = 200 * kotlin.math.sin(angle) / 111320 // ์œ„๋„ ์˜คํ”„์…‹ (๋Œ€๋žต์ ์ธ ๊ณ„์‚ฐ) val markerPoint = GeoPoint(newLocation.latitude + offsetY, newLocation.longitude + offsetX) PayFortuneMarker( id = id, name = when (it) { 0 -> PayFortuneMarker.Type.COIN.name 1 -> PayFortuneMarker.Type.NORMAL.name 2 -> PayFortuneMarker.Type.RANDOM_BOX.name 3 -> PayFortuneMarker.Type.COIN.name 4 -> PayFortuneMarker.Type.NORMAL.name 5 -> PayFortuneMarker.Type.RANDOM_BOX.name else -> PayFortuneMarker.Type.RANDOM_BOX.name }, location = markerPoint, imageUrl = "https://picsum.photos/128/128/?random", type = when (it) { 0 -> PayFortuneMarker.Type.COIN 1 -> PayFortuneMarker.Type.NORMAL 2 -> PayFortuneMarker.Type.RANDOM_BOX 3 -> PayFortuneMarker.Type.COIN 4 -> PayFortuneMarker.Type.NORMAL 5 -> PayFortuneMarker.Type.RANDOM_BOX else -> PayFortuneMarker.Type.RANDOM_BOX }, ) }.toImmutableList() _viewState.update { currentState -> currentState.copy( myLocation = newLocation, markers = nextList ) } _singleEvent.send(PayFortuneSingleEvent.ChangeMyLocation(newLocation)) delay(10000) } } } fun onMarkerClick(marker: PayFortuneMarker) { _viewState.update { prevState -> prevState.copy( isShowRequestObtainDialog = true, currentObtainMarker = marker, ) } } fun startObtainProcess(marker: PayFortuneMarker) { _viewState.update { prevState -> prevState.copy( isShowRequestObtainDialog = false, ) } _singleEvent.trySend(PayFortuneSingleEvent.NavigateProcessObtain(marker)) } fun obtainSuccess(marker: PayFortuneMarker) = viewModelScope.launch { _singleEvent.trySend(PayFortuneSingleEvent.ObtainMarkerAction(marker)) } fun updateCompass(azimuth: Float) { _viewState.update { prevState -> prevState.copy( headings = azimuth ) } } }
fortune-android/app/src/main/java/com/android/fortune/presentation/main/PayFortuneMainViewModel.kt
2353856321
package com.example.herbalappviewer 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.herbalappviewer", appContext.packageName) } }
Herbal_Plants_Viewer_Application/app/src/androidTest/java/com/example/herbalappviewer/ExampleInstrumentedTest.kt
3977651390
package com.example.herbalappviewer 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) } }
Herbal_Plants_Viewer_Application/app/src/test/java/com/example/herbalappviewer/ExampleUnitTest.kt
3668477482
package com.example.herbalappviewer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.content.Intent import android.widget.EditText import android.widget.ImageButton import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { private lateinit var plants: MutableList<HerbalPlant> private lateinit var adapter: HerbalPlantAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) plants = createHerbalPlants() adapter = HerbalPlantAdapter(this, plants) { plant -> showPlantDetail(plant) } val recyclerView: RecyclerView = findViewById(R.id.rvplants) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) // Image button to add a new herbal plant val btnAdd: ImageButton = findViewById(R.id.btn_add) btnAdd.setOnClickListener { showAddPlantDialog() } } private fun createHerbalPlants(): MutableList<HerbalPlant> { val plants = mutableListOf<HerbalPlant>() // Populate with initial data, you can replace this with actual data source plants.add(HerbalPlant("Gotu Kola (Centella asiatica)", "Gotu kola is a small, perennial herbaceous plant that grows in damp, marshy areas. It's renowned for its medicinal properties, particularly for improving memory and cognition.Neem is a versatile tree native to the Indian subcontinent, including Sri Lanka. Its leaves, seeds, and bark are all used for medicinal purposes. In Sri Lankan herbal medicine, neem is valued for its antibacterial, antiviral, and antifungal properties. It's commonly used to treat skin disorders, digestive issues, and as an insect repellent. In Sri Lankan traditional medicine, it's often used to treat various ailments including anxiety, skin conditions, and wounds.", R.drawable.plant_1)) plants.add(HerbalPlant("Neem (Azadirachta indica):", "Neem is a versatile tree native to the Indian subcontinent, including Sri Lanka. Its leaves, seeds, and bark are all used for medicinal purposes. In Sri Lankan herbal medicine, neem is valued for its antibacterial, antiviral, and antifungal properties. Sri Lankan cardamom, also known as \"true cardamom\" or \"green cardamom,\" is a perennial herbaceous plant native to the country. It's highly prized for its culinary uses as a spice, particularly in curries and desserts. In addition to its aromatic flavor, cardamom also possesses medicinal properties and is used in traditional medicine to aid digestion, freshen breath, and alleviate respiratory ailments.It's commonly used to treat skin disorders, digestive issues, and as an insect repellent.",R.drawable.plant_2)) plants.add(HerbalPlant("Sri Lankan Cardamom (Elettaria cardamomum):", "Ginger is a flowering plant native to Southeast Asia, including Sri Lanka. It's widely cultivated for its rhizome, which is commonly used as a spice and for its medicinal properties. In Sri Lankan herbal medicine, ginger is valued for its ability to alleviate nausea, aid digestion, and reduce inflammation. It's often consumed as a tea or added to various dishes for flavor and health benefits.Sri Lankan cardamom, also known as \"true cardamom\" or \"green cardamom,\" is a perennial herbaceous plant native to the country. It's highly prized for its culinary uses as a spice, particularly in curries and desserts. In addition to its aromatic flavor, cardamom also possesses medicinal properties and is used in traditional medicine to aid digestion, freshen breath, and alleviate respiratory ailments.",R.drawable.plant_3)) plants.add(HerbalPlant("Ginger (Zingiber officinale):", "Ginger is a flowering plant native to Southeast Asia, including Sri Lanka. It's widely cultivated for its rhizome, which is commonly used as a spice and for its medicinal properties. In Sri Lankan herbal medicine, ginger is valued for its ability to alleviate nausea, aid digestion, and reduce inflammation. It's often consumed as a tea or added to various dishes for flavor and health benefits.",R.drawable.plant_4)) plants.add(HerbalPlant("Turmeric (Curcuma longa):", "Turmeric is a member of the ginger family and is native to South Asia, including Sri Lanka. It's well-known for its bright yellow color and culinary uses as a spice, particularly in curries. In addition to its culinary applications, turmeric is highly valued in traditional medicine for its anti-inflammatory and antioxidant properties. It's used to treat various ailments including arthritis, digestive issues, and skin conditions.Turmeric is a member of the ginger family and is native to South Asia, including Sri Lanka. It's well-known for its bright yellow color and culinary uses as a spice, particularly in curries. In addition to its culinary applications, turmeric is highly valued in traditional medicine for its anti-inflammatory and antioxidant properties. It's used to treat various ailments including arthritis, digestive issues, and skin conditions.",R.drawable.plant_5)) // Add more plants as needed return plants } private fun showAddPlantDialog() { val dialogBuilder = AlertDialog.Builder(this) val inflater = layoutInflater val dialogView = inflater.inflate(R.layout.dialog_add_plant, null) dialogBuilder.setView(dialogView) val etName = dialogView.findViewById<EditText>(R.id.et_plant_name) val etDescription = dialogView.findViewById<EditText>(R.id.et_plant_description) dialogBuilder.setTitle("Add New Plant") dialogBuilder.setMessage("Enter the details for the new plant:") dialogBuilder.setPositiveButton("Add") { dialog, _ -> val name = etName.text.toString() val description = etDescription.text.toString() if (name.isNotEmpty() && description.isNotEmpty()) { // Assuming you have a function to get the background image resource ID based on the plant name val backgroundImageResId = getBackgroundImageResId(name) val newPlant = HerbalPlant(name, description, backgroundImageResId) plants.add(newPlant) adapter.notifyDataSetChanged() Toast.makeText(this, "New herbal plant added", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Please enter both name and description", Toast.LENGTH_SHORT).show() } dialog.dismiss() } dialogBuilder.setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() } val dialog = dialogBuilder.create() dialog.show() } private fun getBackgroundImageResId(plantName: String): Int { // Assuming you have a map or another data structure to store the background image resource IDs for each plant name val backgroundImageResIds = mapOf( "Gotu Kola (Centella asiatica)" to R.drawable.plant_1, "Basil" to R.drawable.plant_2 // Add more mappings as needed ) // Return the background image resource ID corresponding to the plant name return backgroundImageResIds[plantName] ?: R.drawable.plant_11 // Default background image if not found } private fun showPlantDetail(plant: HerbalPlant) { val intent = Intent(this, PlantDetailActivity::class.java) intent.putExtra("plant", plant) startActivity(intent) } }
Herbal_Plants_Viewer_Application/app/src/main/java/com/example/herbalappviewer/MainActivity.kt
1148532524
package com.example.herbalappviewer import android.os.Bundle import android.widget.TextView import android.widget.ImageButton import androidx.appcompat.app.AppCompatActivity class PlantDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_plant_detail) val plant = intent.getParcelableExtra<HerbalPlant>("plant") // Set the title of the activity to the plant name setTitle(plant?.name) val tvDescription: TextView = findViewById(R.id.tv_description) tvDescription.text = plant?.description supportActionBar?.setDisplayHomeAsUpEnabled(true) // Enable back button val backButton = findViewById<ImageButton>(R.id.btn_back) backButton.setOnClickListener { onBackPressed() // Navigate back when the back button is clicked } } override fun onSupportNavigateUp(): Boolean { onBackPressed() // Navigate back when the back button in the action bar is clicked return true } }
Herbal_Plants_Viewer_Application/app/src/main/java/com/example/herbalappviewer/PlantDetailActivity.kt
2862364216
package com.example.herbalappviewer import android.os.Parcel import android.os.Parcelable data class HerbalPlant( val name: String, val description: String, val backgroundImageResId: Int ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString() ?: "", parcel.readString() ?: "", parcel.readInt() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(name) parcel.writeString(description) parcel.writeInt(backgroundImageResId) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<HerbalPlant> { override fun createFromParcel(parcel: Parcel): HerbalPlant { return HerbalPlant(parcel) } override fun newArray(size: Int): Array<HerbalPlant?> { return arrayOfNulls(size) } } }
Herbal_Plants_Viewer_Application/app/src/main/java/com/example/herbalappviewer/HerbalPlant.kt
3949015442
package com.example.herbalappviewer import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView import com.example.herbalappviewer.R class HerbalPlantAdapter( private val context: Context, private val plants: MutableList<HerbalPlant>, private val onItemClick: (HerbalPlant) -> Unit ) : RecyclerView.Adapter<HerbalPlantAdapter.ViewHolder>() { inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val tvPlantName: TextView = itemView.findViewById(R.id.tvplantname) val cardView: CardView = itemView.findViewById(R.id.rvcard) init { itemView.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { onItemClick(plants[position]) } } itemView.setOnLongClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { showDeleteConfirmationDialog(plants[position]) true // Indicate that the long click event is consumed } else { false } } } private fun showDeleteConfirmationDialog(plant: HerbalPlant) { val builder = AlertDialog.Builder(context) builder.setTitle("Confirm Deletion") builder.setMessage("Are you sure you want to delete ${plant.name}?") builder.setPositiveButton("Delete") { _, _ -> plants.remove(plant) notifyDataSetChanged() Toast.makeText(context, "${plant.name} deleted", Toast.LENGTH_SHORT).show() } builder.setNegativeButton("Cancel", null) builder.show() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val plant = plants[position] holder.tvPlantName.text = plant.name holder.cardView.setBackgroundResource(plant.backgroundImageResId) } override fun getItemCount() = plants.size }
Herbal_Plants_Viewer_Application/app/src/main/java/com/example/herbalappviewer/HerbalPlantAdapter.kt
4265981232
package com.example.historyageapp 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.historyageapp", appContext.packageName) } }
HistoryAgeApp_ST10451565/app/src/androidTest/java/com/example/historyageapp/ExampleInstrumentedTest.kt
964396994
package com.example.historyageapp import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class UnitTest { @Before fun setUp() { // Start the MainActivity before each test ActivityScenario.launch(MainActivity::class.java) } @Test fun calculateButtonClicked_showResult() { // Input age into the EditText field onView(withId(R.id.edtAge)) .perform(typeText("30"), closeSoftKeyboard()) // Click the Calculate button onView(withId(R.id.btnResults)) .perform(click()) // Check if the result TextView displays the expected text onView(withId(R.id.txtResult)) .check(matches(withText("Your 30: Martin Luther King Jr. was a historical figure what at the age died 39"))) } @Test fun clearButtonClicked_clearFields() { // Input age into the EditText field onView(withId(R.id.edtAge)) .perform(typeText("30"), closeSoftKeyboard()) // Click the Clear button onView(withId(R.id.btnClear)) .perform(click()) // Check if the EditText field is empty onView(withId(R.id.edtAge)) .check(matches(withText(""))) // Check if the result TextView is empty onView(withId(R.id.txtResult)) .check(matches(withText(""))) } }
HistoryAgeApp_ST10451565/app/src/androidTest/java/com/example/historyageapp/UnitTest.kt
890479846
package com.example.historyageapp 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) } }
HistoryAgeApp_ST10451565/app/src/test/java/com/example/historyageapp/ExampleUnitTest.kt
1610090123
package com.example.historyageapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { enum class HistoricalEvent(val age: Int, val description: String) { EVENT_1(95,"Nelson Mandela is a historical figure what died at the age 95 "), EVENT_2(76,"Albert Einstein is a historical figure what died at the age 97"), EVENT_3(56,"Abraham Lincoln is a historical figure what died at the age 56"), EVENT_4(39,"Martin Luther King Jr. was a historical figure what at the age died 39"), EVENT_5(67,"George Washington was a historical figure what died at the age 67"), EVENT_6(81,"Muhammad Ali was a historical figure what died at the age 81"), EVENT_7(35,"Wolfgang Amadeus Mozart was a historical figure what died at the age 35"), EVENT_8(40,"Edgar Allan Poe was a historical figure what died at the age 40"), EVENT_9(22,"Buddy Holly was a historical figure what died at the age 22"), EVENT_10(26,"Otis Redding was a historical figure what died at the age 26"), } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnResult = findViewById<Button>(R.id.btnResults) val btnClear = findViewById<Button>(R.id.btnClear) val txtResult = findViewById<TextView>(R.id.txtResult) val edtBirthAge = findViewById<EditText>(R.id.edtAge) btnResult?.setOnClickListener() { val birthAge = edtBirthAge.text.toString().toIntOrNull() if (birthAge != null && birthAge in 20..100){ val eventAge = HistoricalEvent.values().map{it.age } val events = when (birthAge) { in eventAge -> { val event = HistoricalEvent.values().find {it.age == birthAge} listOf("Your $birthAge: ${event?.description ?: "event"}") } in eventAge.map { it - 1 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 1 } listOf("Your age is one year before ${event?.description ?: "event"}") } in eventAge.map { it + 1 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 1 } listOf("Your age is one years after ${event?.description ?: "event"}") } in eventAge.map { it - 2 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 2 } listOf("Your age is two years before ${event?.description ?: "event"}") } in eventAge.map { it + 2 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 2 } listOf("Your age is two years after ${event?.description ?: "event"}") } in eventAge.map { it - 3 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 3 } listOf("Your age is three years before ${event?.description ?: "event"}") } in eventAge.map { it + 3 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 3 } listOf("Your age is three years after ${event?.description ?: "event"}") } in eventAge.map { it - 4 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 4 } listOf("Your age is four years before ${event?.description ?: "event"}") } in eventAge.map { it + 4 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 4 } listOf("Your age is four years after ${event?.description ?: "event"}") } in eventAge.map { it - 5 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 5 } listOf("Your age is five years before ${event?.description ?: "event"}") } in eventAge.map { it + 5 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 5 } listOf("Your age is five years after ${event?.description ?: "event"}") } in eventAge.map { it - 6 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 6 } listOf("Your age is six years before ${event?.description ?: "event"}") } in eventAge.map { it + 6 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 6 } listOf("Your age is six years after ${event?.description ?: "event"}") } in eventAge.map { it - 7 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 7 } listOf("Your age is seven years before ${event?.description ?: "event"}") } in eventAge.map { it + 7 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 7 } listOf("Your age is seven years after ${event?.description ?: "event"}") } in eventAge.map { it - 8 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 7 } listOf("Your age is eight years before ${event?.description ?: "event"}") } in eventAge.map { it + 8 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 7 } listOf("Your age is eight years after ${event?.description ?: "event"}") } in eventAge.map { it - 9 } -> { val event = HistoricalEvent.values().find { it.age == birthAge + 7 } listOf("Your age is nine years before ${event?.description ?: "event"}") } in eventAge.map { it + 9 } -> { val event = HistoricalEvent.values().find { it.age == birthAge - 7 } listOf("Your age is nine years after ${event?.description ?: "event"}") } else -> listOf("No ages found for $birthAge") } txtResult.text = events.joinToString( "\n") } else { txtResult.text ="Please enter age from 20 to 100" } } btnClear?.setOnClickListener() { edtBirthAge.text.clear() txtResult.text = "" } } }
HistoryAgeApp_ST10451565/app/src/main/java/com/example/historyageapp/MainActivity.kt
4031639339
package com.example.hellojetpack 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.hellojetpack", appContext.packageName) } }
HelloJetpack/app/src/androidTest/java/com/example/hellojetpack/ExampleInstrumentedTest.kt
3622447203
package com.example.hellojetpack 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) } }
HelloJetpack/app/src/test/java/com/example/hellojetpack/ExampleUnitTest.kt
3064311636
package com.example.hellojetpack.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
HelloJetpack/app/src/main/java/com/example/hellojetpack/ui/theme/Color.kt
743952249
package com.example.hellojetpack.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun HelloJetpackTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
HelloJetpack/app/src/main/java/com/example/hellojetpack/ui/theme/Theme.kt
216471124
package com.example.hellojetpack.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 ) */ )
HelloJetpack/app/src/main/java/com/example/hellojetpack/ui/theme/Type.kt
3961262152
package com.example.hellojetpack import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.hellojetpack.ui.theme.HelloJetpackTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HelloJetpackTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { var number by remember { mutableStateOf(0) } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { TextResult("$number") Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround ) { MyButton("+") { number++ } MyButton("-") { number-- } } } } } } } @Composable private fun TextResult(text: String) { Text( text = text, fontSize = 30.sp, fontWeight = FontWeight.Bold ) } @Composable private fun MyButton(text: String, function: () -> Unit) { Button(onClick = function) { Text(text = text) } } }
HelloJetpack/app/src/main/java/com/example/hellojetpack/MainActivity.kt
772604044
package com.example.activitylifecycle 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.activitylifecycle", appContext.packageName) } }
Activity-Life-Cycle/app/src/androidTest/java/com/example/activitylifecycle/ExampleInstrumentedTest.kt
2128741437
package com.example.activitylifecycle 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) } }
Activity-Life-Cycle/app/src/test/java/com/example/activitylifecycle/ExampleUnitTest.kt
2377769495
package com.example.activitylifecycle import android.nfc.Tag import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) Toast.makeText(this, "onCreate",Toast.LENGTH_SHORT).show() Log.d("Tag", "onCreate I'm Running") } override fun onStart() { super.onStart() Toast.makeText(this, "onStart",Toast.LENGTH_SHORT).show() Log.d("Tag", "onStart I'm Running") } override fun onResume() { super.onResume() Toast.makeText(this, "onResume",Toast.LENGTH_SHORT).show() Log.d("Tag", "onResume I'm Running") } override fun onPause() { super.onPause() Toast.makeText(this, "onPause",Toast.LENGTH_SHORT).show() Log.d("Tag", "onPause I'm Running") } override fun onStop() { super.onStop() Toast.makeText(this, "onStop",Toast.LENGTH_SHORT).show() Log.d("Tag", "onStop I'm Running") } override fun onRestart() { super.onRestart() Toast.makeText(this, "onRestart",Toast.LENGTH_SHORT).show() Log.d("Tag", "onRestart I'm Running") } override fun onDestroy() { super.onDestroy() Toast.makeText(this, "onDestroy",Toast.LENGTH_SHORT).show() Log.d("Tag", "onDestroy I'm Running") } }
Activity-Life-Cycle/app/src/main/java/com/example/activitylifecycle/MainActivity.kt
3076538552
package ir.dunijet.material_you_xml 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("ir.dunijet.material_you_xml", appContext.packageName) } }
WikiPedia_Material3/app/src/androidTest/java/ir/dunijet/material_you_xml/ExampleInstrumentedTest.kt
212662194
package ir.dunijet.material_you_xml 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) } }
WikiPedia_Material3/app/src/test/java/ir/dunijet/material_you_xml/ExampleUnitTest.kt
2749659689
package ir.dunijet.wikipedia_m3.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import ir.dunijet.wikipedia_m3.databinding.FragmentTestBinding class TestFragment :Fragment() { lateinit var binding :FragmentTestBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentTestBinding.inflate(layoutInflater , container , false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/fragments/TestFragment.kt
3269353240
package ir.dunijet.wikipedia_m3.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.bumptech.glide.Glide import ir.dunijet.wikipedia_m3.R import ir.dunijet.wikipedia_m3.databinding.FragmentPhotographerBinding import jp.wasabeef.glide.transformations.RoundedCornersTransformation class FragmentPhotographer : Fragment() { lateinit var binding: FragmentPhotographerBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentPhotographerBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Glide .with(requireContext()) .load(R.drawable.img_photographer) .transform(RoundedCornersTransformation(32, 8)) .into(binding.imgPhotographer) } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/fragments/FragmentPhotographer.kt
1051732832
package ir.dunijet.wikipedia_m3.fragments import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ir.dunijet.wikipedia_m3.activity.MainActivity2 import ir.dunijet.wikipedia_m3.adapter.ExploreAdapter import ir.dunijet.wikipedia_m3.adapter.ItemEvents import ir.dunijet.wikipedia_m3.data.ItemPost import ir.dunijet.wikipedia_m3.databinding.FragmentExploreBinding const val SEND_DATA_TO_SECOND_ACTIVITY = "sendData" class FragmentExplore : Fragment(), ItemEvents { lateinit var binding: FragmentExploreBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentExploreBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val dataExplore = listOf( // Explore Section => ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/jamiroquai.jpg", "Jamiroquai", "British acid jazz band", "Jamiroquai are an English funk and acid jazz band from London. Formed in 1992, they are fronted by vocalist Jay Kay, and were prominent in the London-based funk and acid jazz movement of the 1990s. They built on their acid jazz sound in their early releases and later drew from rock, disco, electronic and Latin music genres. Lyrically, the group has addressed social and environmental justice. Kay has remained as the only original member through several line-up changes.\n" + "The band made their debut under Acid Jazz Records, but they subsequently found mainstream success under Sony. While under this label, three of their albums have charted at number one in the UK, including Emergency on Planet Earth (1993), Synkronized (1999) and A Funk Odyssey (2001). The band's 1998 single, \"Deeper Underground\", was also number one in their native country.\n" + "As of 2017, Jamiroquai had sold more than 26 million albums worldwide. Their third album, Travelling Without Moving (1996), received a Guinness World Record as the best-selling funk album in history. The music video for its lead single, \"Virtual Insanity\", also contributed to the band's success. The song was named Video of the Year at the 1997 MTV Video Music Awards and earned the band a Grammy Award in 1998.\n" + "\n" + "History\n" + "1992โ€“1993: Formation and Emergency on Planet Earth\n" + "Jay Kay was sending songs to record companies, including a hip-hop single released in 1986 under the label StreetSounds. During this time, Kay was influenced by Native American and First Nation peoples and their philosophies; this led to the creation of \"When You Gonna Learn\", a song covering social issues. After he had it recorded, Kay fought with his producer, who took out half the lyrics and produced the song based on what was charting at the time. With the track restored to his preference, the experience helped Kay realise he \"wanted a proper live band with a proper live sound\". The band would be named \"Jamiroquai\", a portmanteau of the words \"jam\" and the name of a Native American confederacy, the Iroquois. He was signed to Acid Jazz Records in 1991 after he sent a demo tape of himself covering a song by the Brand New Heavies. Kay gradually gathered band members, including Wallis Buchanan, who played the didgeridoo. Kay's manager scouted keyboardist Toby Smith, who joined the group as Kay's songwriting partner. In 1992, Jamiroquai began their career by performing in the British club scene. They released \"When You Gonna Learn\" as their debut single, charting outside the UK Top 50 on its initial release. In the following year, Stuart Zender became the band's bassist by audition.\n", false, "" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/ezra_meeker.jpg", "Ezra Meeker", "American pioneer (1830-1928)", "Ezra Manning Meeker (December 29, 1830 โ€“ December 3, 1928) was an American pioneer who traveled the Oregon Trail by ox-drawn wagon as a young man, migrating from Iowa to the Pacific Coast. Later in life he worked to memorialize the Trail, repeatedly retracing the trip of his youth. Once known as the \"Hop King of the World\", he was the first mayor of Puyallup, Washington.\n" + "\n" + "Meeker was born in Butler County, Ohio, to Jacob and Phoebe Meeker. His family relocated to Indiana when he was a boy. He married Eliza Jane Sumner in 1851; the following year the couple, with Ezra's brother and with their newborn son, set out for the Oregon Territory, where land could be claimed and settled on. Although they endured hardships on the Trail in the journey of nearly six months, the entire party survived the trek. Meeker and his family briefly stayed near Portland, then journeyed north to live in the Puget Sound region. They settled at what is now Puyallup in 1862, where Meeker grew hops for use in brewing beer. By 1887, his business had made him wealthy, and his wife built a large mansion for the family. In 1891, an infestation of hop aphids destroyed his crops and took much of his fortune. He later tried his hand at a number of ventures, and made four largely unsuccessful trips to the Klondike, taking groceries and hoping to profit from the gold rush.\n" + "\n" + "Meeker became convinced that the Oregon Trail was being forgotten, and he determined to bring it publicity so it could be marked and monuments erected. In 1906โ€“1908, while in his late 70s, he retraced his steps along the Oregon Trail by wagon, seeking to build monuments in communities along the way. His trek reached New York City, and in Washington, D.C., he met President Theodore Roosevelt. He traveled the Trail again several times in the final two decades of this life, including by oxcart in 1910โ€“1912 and by airplane in 1924. During another such trip, in 1928, Meeker fell ill but was succored by Henry Ford. On his return to Washington state, Meeker became ill again and died there on December 3, 1928, at the age of 97. Meeker wrote several books; his work has continued through the activities of such groups as the Oregon-California Trails Association.\n" + "\n", false, "" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/piano_beethoven.jpg", "Piano Beethoven", "1822 piano sonata by Ludwig Beethoven", "Ludwig van Beethoven baptised 17 December 1770 โ€“ 26 March 1827 was a German composer and pianist. Beethoven remains one of the most admired composers in the history of Western music; his works rank amongst the most performed of the classical music repertoire and span the transition from the Classical period to the Romantic era in classical music. His career has conventionally been divided into early, middle, and late periods. His early period, during which he forged his craft, is typically considered to have lasted until 1802. From 1802 to around 1812, his middle period showed an individual development from the styles of Joseph Haydn and Wolfgang Amadeus Mozart, and is sometimes characterized as heroic. During this time, he began to suffer increasingly from deafness. In his late period, from 1812 to 1827, he extended his innovations in musical form and expression.\n" + "\n" + "Born in Bonn, Beethoven's musical talent was obvious at an early age, and he was initially harshly and intensively taught by his father Johann van Beethoven. Beethoven was later taught by the composer and conductor Christian Gottlob Neefe, under whose tutelage he published his first work, a set of keyboard variations, in 1783. He found relief from a dysfunctional home life with the family of Helene von Breuning, whose children he loved, befriended, and taught piano. At age 21, he moved to Vienna, which subsequently became his base, and studied composition with Haydn. Beethoven then gained a reputation as a virtuoso pianist, and he was soon patronized by Karl Alois, Prince Lichnowsky for compositions, which resulted in his three Opus 1 piano trios (the earliest works to which he accorded an opus number) in 1795.\n" + "\n" + "His first major orchestral work, the First Symphony, premiered in 1800, and his first set of string quartets was published in 1801. Despite his hearing deteriorating during this period, he continued to conduct, premiering his Third and Fifth Symphonies in 1804 and 1808, respectively. His Violin Concerto appeared in 1806. His last piano concerto (No. 5, Op. 73, known as the Emperor), dedicated to his frequent patron Archduke Rudolf of Austria, was premiered in 1811, without Beethoven as soloist. He was almost completely deaf by 1814, and he then gave up performing and appearing in public. He described his problems with health and his unfulfilled personal life in two letters, his Heiligenstadt Testament (1802) to his brothers and his unsent love letter to an unknown \"Immortal Beloved\" (1812).\n" + "\n" + "After 1810, increasingly less socially involved, Beethoven composed many of his most admired works, including later symphonies, mature chamber music and the late piano sonatas. His only opera, Fidelio, first performed in 1805, was revised to its final version in 1814. He composed Missa solemnis between 1819 and 1823 and his final Symphony, No. 9, one of the first examples of a choral symphony, between 1822 and 1824. Written in his last years, his late string quartets, including the Grosse Fuge, of 1825โ€“1826 are among his final achievements. After some months of bedridden illness, he died in 1827. Beethoven's works remain mainstays of the classical music repertoire.\n" + "\n", false, "" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/surrogate.jpg", "Surrogate's Courthouse", "Historic courthouse in Manhattan", "The Surrogate's Courthouse (also the Hall of Records and 31 Chambers Street) is a historic building at the northwest corner of Chambers and Centre Streets in the Civic Center of Manhattan in New York City. Completed in 1907, it was designed in the Beaux Arts style. John Rochester Thomas created the original plans while Arthur J. Horgan and Vincent J. Slattery oversaw the building's completion. The building faces City Hall Park and the Tweed Courthouse to the south and the Manhattan Municipal Building to the east.\n" + "\n" + "The Surrogate's Courthouse is a seven-story, steel-framed structure with a granite facade and elaborate marble interiors. The fireproof frame was designed to safely accommodate the city's paper records. The exterior is decorated with 54 sculptures by Philip Martiny and Henry Kirke Bush-Brown, as well as a three-story Corinthian order colonnade on Chambers and Reade Streets. The basement houses the New York City Municipal Archives. The fifth floor contains the New York Surrogate's Court for New York County, which handles probate and estate proceedings for the New York State Unified Court System.\n" + "\n" + "The Hall of Records building had been planned since the late 19th century to replace an outdated building in City Hall Park; plans for the current building were approved in 1897. Construction took place between 1899 and 1907, having been subject to several delays because of controversies over funding, sculptures, and Horgan and Slattery's involvement after Thomas's death in 1901. Renamed the Surrogate's Courthouse in 1962, the building has undergone few alterations over the years. The Surrogate's Courthouse is listed on the National Register of Historic Places as a National Historic Landmark, and its facade and interior are both New York City designated landmarks.\n" + "\n", false, "" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/texas_hurricane.jpg", "1916 Texas hurricane", "Category 4 Atlantic hurricane", "The 1916 Texas hurricane was an intense and quick-moving tropical cyclone that caused widespread damage in Jamaica and South Texas in August 1916. A Category 4 hurricane upon landfall in Texas, it was the strongest tropical cyclone to strike the United States in three decades. Throughout its eight-day trek across the Caribbean Sea and Gulf of Mexico, the hurricane caused 37 fatalities and inflicted \$11.8 million in damage.\n" + "\n" + "Weather observations were limited for most of the storm's history, so much of its growth has been inferred from scant data analyzed by the Atlantic hurricane reanalysis project in 2008. The precursor disturbance organized into a small tropical storm by August 12, shortly before crossing the Lesser Antilles into the Caribbean Sea. The storm skirted the southern coast of Jamaica as a hurricane on August 15, killing 17 people along the way. No banana plantation was left unscathed by the hours-long onslaught of strong winds. Coconut and cocoa trees also sustained severe losses. The southern parishes saw the severest effects, incurring extensive damage to crops and buildings; damage in Jamaica amounted to \$10 million (equivalent to \$238 million in 2020). The storm then traversed the Yucatรกn Channel into the Gulf of Mexico and intensified further into the equivalent of a major hurricane on the modern-day Saffirโ€“Simpson scale.\n" + "\n" + "On the evening of August 16, the hurricane struck southern Texas near Baffin Bay with winds of 130 mph (215 km/h). Buildings were razed at many coastal cities, the worst impacts being felt in Corpus Christi and surrounding communities. Beachfront structures were destroyed by a 9.2-foot (2.8 m) storm surge. Strong gusts and heavy rainfall spread farther inland across mainly rural sectors of southern Texas, damaging towns and their outlying agricultural districts alike. Railroads and other public utilities were disrupted across the region, with widespread power outages. Eight locations set 24-hour rainfall records; among them was Harlingen, which recorded the storm's rainfall maximum with 6 inches (150 mm) of precipitation. The deluge wrought havoc on military camps along the Mexicoโ€“United States border, forcing 30,000 garrisoned militiamen to evacuate. Aggregate property damage across Texas reached \$1.8 million (equivalent to \$43 million in 2020), and 20 people were killed. The hurricane quickly weakened over southwestern Texas and dissipated near New Mexico by August 20.\n" + "\n", false, "" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/australian_boobook.jpg", "Australian boobook", "species of owl native to Australia", "The Australian boobook (Ninox boobook), which is known in some regions as the mopoke, is a species of owl native to mainland Australia, southern New Guinea, the island of Timor, and the Sunda Islands. Described by John Latham in 1801, it was generally considered to be the same species as the morepork of New Zealand until 1999. Its name is derived from its two-tone boo-book call. Eight subspecies of the Australian boobook are recognized, with three further subspecies being reclassified as separate species in 2019 due to their distinctive calls and genetics.\n" + "\n" + "The smallest owl on the Australian mainland, the Australian boobook is 27 to 36 cm (10.5 to 14 in) long, with predominantly dark-brown plumage with prominent pale spots. It has grey-green or yellow-green eyes. It is generally nocturnal, though is sometimes active at dawn and dusk, retiring to roost in secluded spots in the foliage of trees. The Australian boobook feeds on insects and small vertebrates, hunting by pouncing on them from tree perches. Breeding takes place from late winter to early summer, using tree hollows as nesting sites. The International Union for Conservation of Nature has assessed the Australian boobook as being of least concern on account of its large range and apparently stable population.\n" + "\n", false, "" ) ) val myAdapter = ExploreAdapter(dataExplore, this) binding.recyclerExplore.adapter = myAdapter binding.recyclerExplore.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) } override fun onItemClicked(itemPost: ItemPost) { val intent = Intent(activity , MainActivity2::class.java) intent.putExtra( SEND_DATA_TO_SECOND_ACTIVITY , itemPost ) startActivity( intent ) } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/fragments/FragmentExplore.kt
252199387
package ir.dunijet.wikipedia_m3.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import ir.dunijet.wikipedia_m3.databinding.FragmentProfileBinding class FragmentProfile : Fragment() { lateinit var binding: FragmentProfileBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentProfileBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // val card = view.findViewById<MaterialCardView>(R.id.cardMain) //// card.isChecked = true //// //// card.setOnClickListener { //// //// if (card.isChecked) { //// card.isChecked = false //// } else { //// card.isChecked = true //// } //// //// } } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/fragments/FragmentProfile.kt
1736794228
package ir.dunijet.wikipedia_m3.fragments import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ir.dunijet.wikipedia_m3.activity.MainActivity2 import ir.dunijet.wikipedia_m3.adapter.ItemEvents import ir.dunijet.wikipedia_m3.adapter.TrendAdapter import ir.dunijet.wikipedia_m3.data.ItemPost import ir.dunijet.wikipedia_m3.databinding.FragmentTrendBinding class FragmentTrend : Fragment(), ItemEvents { lateinit var binding: FragmentTrendBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentTrendBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val dataTrend = arrayListOf<ItemPost>( // Trend Section => ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/john.jpg", "John Madden", "American football\ncoach and commentator\n(1936-2021)", "John Earl Madden (April 10, 1936 โ€“ December 28, 2021) was an American football coach and sportscaster. He was the head coach of the Oakland Raiders of the National Football League (NFL) for ten seasons (1969โ€“1978), and guided them to a championship in Super Bowl XI (1977). After retiring from coaching, he served as a color commentator for NFL telecasts until 2009, work for which he won 16 Sports Emmy Awards. From 1988 he lent his name, expertise and color commentary to the John Madden Football (later Madden NFL) video game series.\n" + "\n" + "Madden never had a losing season as a coach, and his overall win percentage is second in NFL history.[1] In recognition of his coaching career, Madden was inducted into the Pro Football Hall of Fame in 2006. As a broadcaster, Madden commentated on all four of the major American television networks: CBS (1979โ€“1993), Fox (1994โ€“2001), ABC (2002โ€“2005), and NBC (2006โ€“2008). He also served as a commercial pitchman for various products and retailers.\n" + "\n" + "A football star in high school, Madden played one season at the College of San Mateo, in 1954, before he was given a football scholarship to the University of Oregon, studying pre-law, and playing football with boyhood friend John Robinson. He was redshirted because of a knee injury and had a knee operation. Then he attended the College of San Mateo in 1955, then Grays Harbor College playing in the fall of 1956, before transferring to Cal Poly in San Luis Obispo, where he played both offense and defense for the Mustangs in 1957 while earning a Bachelor of Science in education in 1959 and a Master of Arts in education in 1961. He won all-conference honors at offensive tackle, and was a catcher on Cal Poly's baseball team.\n" + "\n" + "Madden was drafted in the 21st round (244th overall) by the NFL's Philadelphia Eagles in 1958, but in his first training camp suffered an injury on his other knee, ending his playing career before having had an opportunity to play professionally.\n" + "\n", true, "+1 M" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/dont_look_up.jpg", "Don't Look Up (2021 film)", "2021 American satirical\nscience fiction film", "Don't Look Up is a 2021 American satirical science fiction film written, produced, and directed by Adam McKay. It stars Leonardo DiCaprio and Jennifer Lawrence as two astronomers attempting to warn humanity, via a media horror, about an approaching comet that will destroy human civilization. Supporting them are Rob Morgan, Jonah Hill, Mark Rylance, Tyler Perry, Timothรฉe Chalamet, Ron Perlman, Ariana Grande, Scott Mescudi, Himesh Patel, Melanie Lynskey, with Cate Blanchett and Meryl Streep.[4] The film is a satire of government and media indifference to the climate crisis.[4][5] Grande and Mescudi also collaborated on the song \"Just Look Up\" as part of the film's soundtrack.[6] The film is dedicated to Hal Willner who died in 2020.\n" + "\n" + "Produced by Hyperobject Industries and Bluegrass Films, the film was announced in November 2019, and sold by Paramount Pictures to Netflix several months later. Lawrence became the first member of the cast to join, with DiCaprio signing on after his discussions with McKay on adjustments to the script; the rest of the cast was added through the rest of 2020. Filming was originally set to begin in April 2020 around the U.S. state of Massachusetts, but was delayed until November due to the ongoing COVID-19 pandemic, and then lasted through February 2021.\n" + "\n" + "Don't Look Up began a limited theatrical release on December 10, 2021, prior to streaming on Netflix on December 24, 2021. It received mixed reviews from critics, who praised the cast but found McKay's approach to the subject heavy handed. Despite the reviews, it was named one of the top ten films of 2021 by the National Board of Review and American Film Institute, and received four nominations at the 79th Golden Globe Awards, including Best Picture โ€“ Musical or Comedy, and six at the 27th Critics' Choice Awards, including Best Picture.\n" + "\n", true, "+362 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/harry.jpg", "Harry Reid", "American politician\n(1939-2021)", "Harry Mason Reid Jr , was an American lawyer and politician who served as a United States senator from Nevada from 1987 to 2017. He led the Senate Democratic Caucus from 2005 to 2017 and was the Senate Majority Leader from 2007 to 2015.\n" + "\n" + "Reid began his public career as the city attorney for Henderson, Nevada, before being elected to the Nevada Assembly in 1968. Reid's former boxing coach, Mike O'Callaghan, chose Reid as his running mate in the 1970 Nevada gubernatorial election, and Reid served as Lieutenant Governor of Nevada from 1971 to 1975. After being defeated in races for the United States Senate and mayor of Las Vegas, Reid served as chairman of the Nevada Gaming Commission from 1977 to 1981. From 1983 to 1987, Reid represented Nevada's 1st district in the United States House of Representatives.\n" + "\n" + "Reid was elected to the United States Senate in 1986 and served in the Senate from 1987 to 2017. He served as the Senate Democratic Whip from 1999 to 2005 before succeeding Tom Daschle as Senate Minority Leader. The Democrats won control of the Senate after the 2006 United States Senate elections, and Reid became the Senate Majority Leader in 2007. He held that position for the final two years of George W. Bush's presidency and for the first six years of Barack Obama's presidency. As Majority Leader, Reid helped pass major legislation of the Obama administration, such as the Affordable Care Act, the Doddโ€“Frank Act, and the American Recovery and Reinvestment Act of 2009. In 2013, under Reid's leadership, the Senate Democratic majority controversially invoked the \"nuclear option\" to eliminate the 60-vote requirement to end a filibuster for presidential nominations, other than nominations to the U.S. Supreme Court.[1] Republicans took control of the Senate following the 2014 United States Senate elections, and Reid served as Senate Minority Leader from 2015 until his retirement in 2017.\n" + "\n" + "Reid was succeeded as the Senate Democratic leader by Chuck Schumer, whose leadership bid had been endorsed by Reid. Along with Alben W. Barkley and Mike Mansfield, Reid was one of only three senators to have served at least eight years as majority leader.\n" + "\n", true, "+326 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/no_way_home.jpg", "No Way Home", "2021 American\nsuperhero film", "Spider-Man: No Way Home is a 2021 American superhero film based on the Marvel Comics character Spider-Man, co-produced by Columbia Pictures and Marvel Studios and distributed by Sony Pictures Releasing. It is the sequel to Spider-Man: Homecoming (2017) and Spider-Man: Far From Home (2019), and the 27th film in the Marvel Cinematic Universe (MCU). The film was directed by Jon Watts and written by Chris McKenna and Erik Sommers. It stars Tom Holland as Peter Parker / Spider-Man alongside Zendaya, Benedict Cumberbatch, Jacob Batalon, Jon Favreau, Jamie Foxx, Willem Dafoe, Alfred Molina, Benedict Wong, Tony Revolori, Marisa Tomei, Andrew Garfield, and Tobey Maguire. In the film, Parker asks Dr. Stephen Strange (Cumberbatch) to make his identity as Spider-Man a secret again with magic after its public revelation in Far From Home, but this breaks open the multiverse and allows supervillains from alternate realities to enter Parker's universe.\n" + "\n" + "A third MCU Spider-Man film was planned during the production of Homecoming in 2017. By August 2019, negotiations between Sony and Marvel Studios to alter their dealโ€”in which they produce the Spider-Man films togetherโ€”ended with Marvel Studios leaving the project; however, a negative fan reaction led to a new deal between the companies a month later. Watts, McKenna, Sommers, and Holland were set to return at that time. Filming began in October 2020 in New York City before moving to Atlanta that month and wrapping in March 2021. No Way Home explores the concept of the multiverse and ties the MCU to past Spider-Man film series, with numerous actors reprising their roles from the Spider-Man films directed by Sam Raimi and Marc Webb. The return of previous Spider-Man actors Maguire and Garfield was the subject of speculation, and Sony, Marvel, and the cast attempted to conceal their involvement despite numerous leaks.\n" + "\n" + "Spider-Man: No Way Home premiered at the Fox Village Theatre in Los Angeles on December 13, 2021, and was theatrically released in the United States on December 17, as part of Phase Four of the MCU. The film received positive reviews from critics, who praised the story, direction, action sequences, and the cast's performances and chemistry. No Way Home has grossed over \$1.1 billion worldwide, surpassing Spider-Man: Far From Home as the highest-grossing film released by Sony Pictures, in addition to becoming the highest-grossing film of 2021, and the 21st highest-grossing film of all time, and setting several box office records, partly for films released after the onset of the COVID-19 pandemic. A sequel is in development.\n" + "\n", true, "+302 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/matrix.jpg", "Matrix Resurrections", "2021 American science\nfiction action film", "The Matrix Resurrections is a 2021 American science fiction action film produced, co-written, and directed by Lana Wachowski. It is the sequel to The Matrix Revolutions (2003) and the fourth and final installment in The Matrix film franchise. Keanu Reeves, Carrie-Anne Moss, Lambert Wilson, and Jada Pinkett Smith reprise their roles from the previous films, and they are joined by Yahya Abdul-Mateen II, Jessica Henwick, Jonathan Groff, Neil Patrick Harris, and Priyanka Chopra Jonas. The film is set sixty years after the events of Revolutions and follows Neo, who lives a seemingly ordinary life as a video game developer troubled with distinguishing dreams from reality. A group of rebels, with the help of a programmed version of Morpheus, free Neo from an altered Matrix and fight a new enemy that holds Trinity captive.\n" + "\n" + "Following the release of Revolutions, the Wachowskis denied the possibility of another Matrix film, though rumors emerged since then about a possible fourth Matrix film and the studio constantly expressed interest in reviving the franchise, hiring Zak Penn to write a new screenplay after the Wachowskis refused every offer to create more sequels. In late 2019, a fourth Matrix film was finally announced, with Lana Wachowski returning as director without her sister and Reeves and Moss reprising their roles. Filming started in February 2020 but was halted the next month by the COVID-19 pandemic. Wachowski toyed with the possibility of shelving the project and leaving the film unfinished, but the cast insisted that she finish it. Filming resumed in August 2020, concluding three months later.\n" + "\n" + "The Matrix Resurrections premiered in Toronto on December 16, 2021, and was released by Warner Bros. Pictures on December 22, 2021, both theatrically and via the HBO Max streaming service. It has grossed over \$68 million. Critics praised the performances of the cast, though the writing, action scenes, and visuals received some criticism.\n" + "\n", true, "+198 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/margaret.jpg", "Margaret Campbell", "British socialite", "Ethel Margaret Campbell, Duchess of Argyll (nรฉe Whigham, thereafter Sweeny; 1 December 1912 โ€“ 25 July 1993), was a British socialite best remembered for her much-publicised divorce from her second husband, Ian Campbell, 11th Duke of Argyll, in 1963, which featured salacious photographs and scandalous stories.\n" + "\n" + "Margaret was the only child of Helen Mann Hannay and George Hay Whigham, a Scottish millionaire who was chairman of the Celanese Corporation of Britain and North America. She spent the first 14 years of her life in New York City, where she was educated privately at the Hewitt School. Her beauty was much spoken of, and she had youthful romances with Prince Aly Khan, millionaire aviator Glen Kidston and publishing heir Max Aitken, later the second Lord Beaverbrook.\n" + "\n" + "In 1928 the future actor David Niven, then 18, had sex with 15-year-old Margaret Whigham during a holiday at Bembridge on the Isle of Wight. To the fury of her father, she became pregnant as a result. She was taken into a London nursing home for a secret abortion. \"All hell broke loose,\" remembered her family cook, Elizabeth Duckworth. Margaret did not mention the episode in her 1975 memoirs, but she continued to adore Niven until the day he died. She was among the VIP guests at his London memorial service.\n" + "\n", true, "+344 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/encanto.jpg", "Encanto", "2021 American animated\nfilm", "Encanto is a 2021 American computer-animated musical fantasy comedy film produced by Walt Disney Animation Studios and distributed by Walt Disney Studios Motion Pictures. The 60th film produced by the studio, it was directed by Jared Bush and Byron Howard, co-directed by writer Charise Castro Smith who co-wrote the screenplay with Bush, and produced by Yvett Merino and Clark Spencer, with original songs written by Lin-Manuel Miranda. The film stars the voices of Stephanie Beatriz, Marรญa Cecilia Botero, John Leguizamo, Mauro Castillo, Jessica Darrow, Angie Cepeda, Carolina Gaitรกn, Diane Guerrero, and Wilmer Valderrama. The film premiered at the El Capitan Theatre in Los Angeles on November 3, 2021, and was theatrically released in the United States on November 24 over a 30-day theatrical run, in response to the COVID-19 pandemic. It received positive reviews from critics but has so far underperformed commercially as of December 2021 due to the shortened release frame, grossing over \$194 million.\n" + "\n" + "Forced by an armed conflict to flee her home, young Alma Madrigal loses her husband Pedro but saves her triplet infant children: Julieta, Pepa, and Bruno. Her candle attains magical qualities, and blasts away their pursuers and creates a sentient house, the \"Casita\", for the Madrigals to live in. Fifty years later, a village has grown up under the candle's protection, and the Madrigals are gifted superhuman abilities they use to help the villagers. However, Bruno's gift of precognition causes multiple conflicts that makes the family vilify him, while Mirabel, Julieta's youngest daughter, is treated differently for having no gift at all.\n" + "\n" + "During the evening when Pepa's youngest son Antonio is gifted the ability to speak to animals, Mirabel suddenly sees cracks in the Casita, but her warnings go unheeded when the Casita appears undamaged to the others. Mirabel resolves to save the magic of the Casita. Her super-strong older sister Luisa suggests that Bruno's room, which is located in a forbidden tower in the Casita, may hold some clues to the phenomenon. Inside, Mirabel discovers a cave and recovers pieces of a slab of opaque jade glass which form an image showing her causing the Casita to fall apart. After Mirabel narrowly escapes the cave, Luisa realizes that her family's gifts are starting to weaken.\n" + "\n", true, "+164 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/boxing.jpg", "Boxing Day", "Commonwealth nations\nholiday on 26 December", "Boxing Day is a holiday celebrated after Christmas Day, occurring on the second day of Christmastide.[1] Though it originated as a holiday to give gifts to the poor, today Boxing Day is primarily known as a shopping holiday. It originated in Great Britain and is celebrated in a number of countries that previously formed part of the British Empire. The attached bank holiday or public holiday may take place either on that day or one or two days later (if necessary to ensure it falls on a weekday). Boxing Day is also concurrent with the Catholic holiday Saint Stephen's Day.\n" + "\n" + "In parts of Europe, such as several regions of Spain, Czech Republic, Germany, Hungary, the Netherlands, Italy, Poland, Slovakia, Croatia, Denmark, Finland, Sweden, Belgium, Norway and the Republic of Ireland, 26 December is Saint Stephen's Day, which is considered the second day of Christmas.\n" + "\n", true, "+430 K" ), ItemPost( "https://dunijet.ir/YaghootAndroidFiles/Wikipedia/james_webb.jpg", "James Webb Space", "NASA/ESA space\ntelescope launched in\n2021", "The James Webb Space Telescope (JWST) is a space telescope developed by NASA with contributions from the European Space Agency (ESA), and the Canadian Space Agency (CSA). The telescope is named after James E. Webb, who was the administrator of NASA from 1961 to 1968 and played an integral role in the Apollo program. It is intended to succeed the Hubble Space Telescope as NASA's flagship mission in astrophysics. JWST was launched on 25 December 2021 on Ariane flight VA256. It is designed to provide improved infrared resolution and sensitivity over Hubble, and will enable a broad range of investigations across the fields of astronomy and cosmology, including observations of some of the most distant events and objects in the Universe such as the formation of the first galaxies, and allowing detailed atmospheric characterization of potentially habitable exoplanets.\n" + "\n" + "The primary mirror of JWST, the Optical Telescope Element, consists of 18 hexagonal mirror segments made of gold-plated beryllium, which combine to create a 6.5 m (21 ft)-diameter mirror โ€“ considerably larger than Hubble's 2.4 m (7.9 ft) mirror. Unlike the Hubble telescope, which observes in the near ultraviolet, visible, and near infrared (0.1โ€“1.0 ฮผm) spectra, JWST will observe in a lower frequency range, from long-wavelength visible light (red) through mid-infrared (0.6โ€“28.3 ฮผm). This will enable it to observe high-redshift objects that are too old and too distant for Hubble. The telescope must be kept very cold to observe in the infrared without interference, so it will be deployed in space near the Sunโ€“Earth L2 Lagrange point, about 1.5 million kilometers (930,000 mi) from Earth (0.01 au โ€“ 3.9 times the average distance to the Moon).\n" + "\n", true, "+372 K" ) ) val myAdapter = TrendAdapter(dataTrend, this) binding.recyclerTrend.adapter = myAdapter binding.recyclerTrend.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) } override fun onItemClicked(itemPost: ItemPost) { val intent = Intent(activity, MainActivity2::class.java) intent.putExtra(SEND_DATA_TO_SECOND_ACTIVITY, itemPost) startActivity(intent) } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/fragments/FragmentTrend.kt
2157329219
package ir.dunijet.wikipedia_m3.activity import android.annotation.SuppressLint import android.graphics.Bitmap import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import im.delight.android.webview.AdvancedWebView import ir.dunijet.wikipedia_m3.R import ir.dunijet.wikipedia_m3.databinding.ActivityWebViewBinding import ir.dunijet.wikipedia_m3.ext.copyToClipboard class WebViewActivity : AppCompatActivity() , AdvancedWebView.Listener { lateinit var binding :ActivityWebViewBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityWebViewBinding.inflate(layoutInflater) setContentView(binding.root) enableEdgeToEdge() ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets -> val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) v.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = insets.top bottomMargin = insets.bottom } WindowInsetsCompat.CONSUMED } val bundle = intent.getBundleExtra("url_data")!! val url = bundle.getString("url")!! val title = bundle.getString("title")!! binding.webViewMain.setListener(this, this) binding.webViewMain.setMixedContentAllowed(false) binding.webViewMain.loadUrl(url) binding.toolbarWebview.title = title binding.toolbarWebview.setNavigationOnClickListener { finish() } binding.toolbarWebview.setOnMenuItemClickListener { when (it.itemId) { R.id.menu_copy_address -> { val currentUrl = binding.webViewMain.url!! copyToClipboard(currentUrl) } } true } } fun copyUrl() { } override fun onPageStarted(url: String?, favicon: Bitmap?) { binding.progressBar.visibility = View.VISIBLE } override fun onPageFinished(url: String?) { binding.progressBar.visibility = View.GONE } override fun onPageError(errorCode: Int, description: String?, failingUrl: String?) { } override fun onDownloadRequested( url: String?, suggestedFilename: String?, mimeType: String?, contentLength: Long, contentDisposition: String?, userAgent: String? ) { } override fun onExternalPageRequest(url: String?) { } override fun onBackPressed() { if (!binding.webViewMain.onBackPressed()) { return } super.onBackPressed() } override fun onResume() { super.onResume() binding.webViewMain.onResume() } @SuppressLint("NewApi") override fun onPause() { binding.webViewMain.onPause() super.onPause() } override fun onDestroy() { binding.webViewMain.onDestroy() super.onDestroy() } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/activity/WebViewActivity.kt
4160540238
package ir.dunijet.wikipedia_m3.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.bumptech.glide.Glide import ir.dunijet.wikipedia_m3.R import ir.dunijet.wikipedia_m3.databinding.ActivityMain3Binding import jp.wasabeef.glide.transformations.RoundedCornersTransformation class MainActivity3 : AppCompatActivity() { lateinit var binding: ActivityMain3Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMain3Binding.inflate(layoutInflater) setContentView(binding.root) enableEdgeToEdge() ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } Glide .with(this) .load(R.drawable.img_translatore) .transform(RoundedCornersTransformation(32, 8)) .into(binding.imgTranslator) } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/activity/MainActivity3.kt
1147565320
package ir.dunijet.wikipedia_m3.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.ViewGroup import android.widget.ImageView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatDelegate import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.GravityCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import ir.dunijet.wikipedia_m3.R import ir.dunijet.wikipedia_m3.databinding.ActivityMainBinding import ir.dunijet.wikipedia_m3.ext.Constant import ir.dunijet.wikipedia_m3.ext.Keys import ir.dunijet.wikipedia_m3.ext.readPref import ir.dunijet.wikipedia_m3.ext.setNavigationColor import ir.dunijet.wikipedia_m3.ext.showDialog import ir.dunijet.wikipedia_m3.ext.showSnackbar import ir.dunijet.wikipedia_m3.ext.writePref import ir.dunijet.wikipedia_m3.fragments.FragmentExplore import ir.dunijet.wikipedia_m3.fragments.FragmentProfile import ir.dunijet.wikipedia_m3.fragments.FragmentTrend import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var changeThemeButton: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initialize() changeThemeButton.setOnClickListener { toggleTheme() } binding.navigationViewMain.setNavigationItemSelectedListener { when (it.itemId) { // R.id.temenu_writer -> { // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // val dialog = SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE) // dialog.titleText = "Alert!" // dialog.confirmText = "Confirm" // dialog.cancelText = "Cancel" // dialog.contentText = "Wanna be a Writer?" // dialog.setCancelClickListener { // dialog.dismiss() // } // dialog.setConfirmClickListener { // dialog.dismiss() // Toast.makeText(this, "you can be a writer just work :)", Toast.LENGTH_SHORT) // .show() // } // dialog.show() // // } // // R.id.menu_photograph -> { // // // load fragment => // val transaction = supportFragmentManager.beginTransaction() // transaction.add(R.id.frame_main_container, FragmentPhotographer()) // transaction.addToBackStack(null) // transaction.commit() // // // check menu item => // binding.navigationViewMain.menu.getItem(1).isChecked = true // // // close drawer => // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // } // // R.id.menu_vieo_maker -> { // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // Snackbar // .make(binding.root, "No Internet!", Snackbar.LENGTH_LONG) // .setAction("Retry") { // Toast.makeText(this, "checking network", Toast.LENGTH_SHORT).show() // } //// .setActionTextColor(ContextCompat.getColor(this, R.color.white)) //// .setBackgroundTint(ContextCompat.getColor(this, R.color.blue)) // .show() // // } R.id.menu_writer -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) val intent = Intent(this, MainActivity3::class.java) startActivity(intent) } // --------------------------------- R.id.menu_open_wikipedia -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) openWebsite("https://www.wikipedia.org/") } R.id.openWikimedia -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) openWebsite("https://www.wikimedia.org/") } } true } binding.toolbarMain.setOnMenuItemClickListener { when (it.itemId) { R.id.menu_info -> { showDialog( "About us", "Wikipedia is a free, web-based, collaborative, multilingual encyclopedia project launched in 2001 supported by the non-profit Wikimedia Foundation. \n\nIt is one of the largest and most popular general reference works on the internet. Wikipedia's articles are written collaboratively by volunteers around the world, and almost all of its articles can be edited by anyone with internet access." ) } R.id.menu_writer -> { openWebsite("https://en.wikipedia.org/wiki/Wikipedia:How_to_create_a_page") } } true } binding.bottomNavigationMain.setOnItemSelectedListener { when (it.itemId) { R.id.menu_explore -> { replaceFragment(FragmentExplore()) } R.id.menu_trend -> { replaceFragment(FragmentTrend()) } R.id.menu_profile -> { replaceFragment(FragmentProfile()) } } true } binding.bottomNavigationMain.setOnItemReselectedListener {} } private fun openWebsite(url: String) { val intent = Intent(this, WebViewActivity::class.java) val bundle = Bundle() bundle.putString("title", "be a writer") bundle.putString("url", url) intent.putExtra("url_data", bundle) startActivity(intent) } private fun replaceFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.frame_main_container, fragment) transaction.commit() } fun initTheme() { val theme = runBlocking { readPref(Keys.appTheme) } if (theme == null) { runBlocking { writePref(Keys.appTheme, Constant.light) } AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } else { if (theme == Constant.light) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } } } private fun initialize() { enableEdgeToEdge() ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets -> val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) v.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = insets.top bottomMargin = insets.bottom } WindowInsetsCompat.CONSUMED } setNavigationColor() val actionBarDrawerToggle = ActionBarDrawerToggle( this, binding.drawerLayoutMain, binding.toolbarMain, R.string.openDrawer, R.string.closeDrawer ) binding.drawerLayoutMain.addDrawerListener(actionBarDrawerToggle) actionBarDrawerToggle.syncState() replaceFragment(FragmentExplore()) binding.bottomNavigationMain.selectedItemId = R.id.menu_explore changeThemeButton = binding.navigationViewMain.getHeaderView(0).findViewById(R.id.btnChangeTheme) } private fun toggleTheme() { lifecycleScope.launch { val currentTheme = readPref(Keys.appTheme) if (currentTheme == Constant.light) { writePref(Keys.appTheme, Constant.dark) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { writePref(Keys.appTheme, Constant.light) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/activity/MainActivity.kt
2211996263
package ir.dunijet.wikipedia_m3.activity import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import androidx.activity.enableEdgeToEdge import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.bumptech.glide.Glide import ir.dunijet.wikipedia_m3.data.ItemPost import ir.dunijet.wikipedia_m3.databinding.ActivityMain2Binding import ir.dunijet.wikipedia_m3.fragments.SEND_DATA_TO_SECOND_ACTIVITY class MainActivity2 : AppCompatActivity() { lateinit var binding: ActivityMain2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMain2Binding.inflate(layoutInflater) setContentView(binding.root) enableEdgeToEdge() ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } setSupportActionBar(binding.toolbarAsli) binding.collapsingMain.setExpandedTitleColor( ContextCompat.getColor( this, android.R.color.transparent ) ) supportActionBar!!.setHomeButtonEnabled(true) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val dataPost = intent.getParcelableExtra<ItemPost>(SEND_DATA_TO_SECOND_ACTIVITY) if (dataPost != null) { showData(dataPost) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() } return true } private fun showData(itemPost: ItemPost) { Glide .with(this) .load( itemPost.imgUrl ) .into( binding.imgDetail ) binding.txtDetailTitle.text = itemPost.txtTitle binding.txtDetailSubtitle.text = itemPost.txtSubtitle binding.txtDetailText.text = itemPost.txtDetail binding.fabDetailOpenWikipedia.setOnClickListener { // open wikipedia val url = "https://en.wikipedia.org/wiki/Main_Page" val intent = Intent( Intent.ACTION_VIEW , Uri.parse(url) ) startActivity(intent) } } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/activity/MainActivity2.kt
3537582812
package ir.dunijet.wikipedia_m3.ext import android.app.Activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Build import android.view.View import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.datastore.dataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.viewbinding.ViewBinding import com.google.android.material.color.MaterialColors import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import ir.dunijet.wikipedia_m3.databinding.ActivityMainBinding import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map val Context.dataStore by preferencesDataStore(name = "Pref") suspend fun Context.writePref(key: String, value: String) { val preferenceKey = stringPreferencesKey(key) dataStore.edit { it[preferenceKey] = value } } suspend fun Context.readPref(key: String) :String? { val preferenceKey = stringPreferencesKey(key) val preference = dataStore.data.first() return preference[preferenceKey] } fun Context.showSnackbar(view: View, str: String) { Snackbar.make(view, str, Snackbar.LENGTH_SHORT).show() } fun Context.showDialog(title: String, detail: String) { MaterialAlertDialogBuilder(this) .setTitle(title) .setMessage(detail) .setPositiveButton("Submit") { dialog, which -> dialog.dismiss() } .show() } fun Context.copyToClipboard(text: String) { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("url", text) clipboard.setPrimaryClip(clip) } fun AppCompatActivity.setNavigationColor() { val colorSurface = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurface, null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { this.window.navigationBarColor = colorSurface } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/ext/extension.kt
3685399829
package ir.dunijet.wikipedia_m3.ext object Keys { val appTheme = "appTheme" } object Constant { val light = "light" val dark = "dark" }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/ext/constants.kt
3032675026
package ir.dunijet.wikipedia_m3.adapter import ir.dunijet.wikipedia_m3.data.ItemPost interface ItemEvents { fun onItemClicked( itemPost: ItemPost ) }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/adapter/ItemEvents.kt
3706216468
package ir.dunijet.wikipedia_m3.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ir.dunijet.wikipedia_m3.data.ItemPost import ir.dunijet.wikipedia_m3.databinding.ItemTrendBinding import jp.wasabeef.glide.transformations.RoundedCornersTransformation class TrendAdapter(val data: List<ItemPost>, val itemEvents: ItemEvents) : RecyclerView.Adapter<TrendAdapter.TrendViewHolder>() { lateinit var binding: ItemTrendBinding inner class TrendViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindViews(itemPost: ItemPost) { binding.txtTrendTitle.text = itemPost.txtTitle binding.txtTrendSubtitle.text = itemPost.txtSubtitle binding.txtTrendInsight.text = itemPost.insight binding.txtTrendNumber.text = (adapterPosition + 1).toString() Glide .with(binding.root) .load(itemPost.imgUrl) .transform(RoundedCornersTransformation(24, 8)) .into(binding.imgTrendMain) itemView.setOnClickListener { itemEvents.onItemClicked(itemPost) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrendViewHolder { binding = ItemTrendBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return TrendViewHolder(binding.root) } override fun onBindViewHolder(holder: TrendViewHolder, position: Int) { holder.bindViews(data[position]) } override fun getItemCount(): Int { return data.size } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/adapter/TrendAdapter.kt
2133543131
package ir.dunijet.wikipedia_m3.adapter import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ir.dunijet.wikipedia_m3.data.ItemPost import ir.dunijet.wikipedia_m3.databinding.ItemExploreBinding class ExploreAdapter(val data: List<ItemPost> , val itemEvents: ItemEvents) : RecyclerView.Adapter<ExploreAdapter.ExploreViewHolder>() { lateinit var binding: ItemExploreBinding inner class ExploreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindViews(itemPost: ItemPost) { Glide .with(itemView.context) .load(itemPost.imgUrl) .into(binding.imgExploreMain) binding.txtExploreTitle.text = itemPost.txtTitle binding.txtExploreSubtitle.text = itemPost.txtSubtitle binding.txtExploreDetail.text = itemPost.txtDetail itemView.setOnClickListener { itemEvents.onItemClicked( itemPost ) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExploreViewHolder { binding = ItemExploreBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ExploreViewHolder(binding.root) } override fun onBindViewHolder(holder: ExploreViewHolder, position: Int) { holder.bindViews(data[position]) Log.v("testApp", position.toString()) } override fun getItemCount(): Int { return data.size } }
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/adapter/ExploreAdapter.kt
868793102
package ir.dunijet.wikipedia_m3.data import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ItemPost( val imgUrl: String, val txtTitle: String, val txtSubtitle: String, val txtDetail: String , // for trend fragment => val isTrend :Boolean , val insight :String ) :Parcelable
WikiPedia_Material3/app/src/main/java/ir/dunijet/wikipedia_m3/data/ItemPost.kt
866100935
package com.example.mylogin 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.mylogin", appContext.packageName) } }
simple-login-app/app/src/androidTest/java/com/example/mylogin/ExampleInstrumentedTest.kt
3897671064
package com.example.mylogin 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) } }
simple-login-app/app/src/test/java/com/example/mylogin/ExampleUnitTest.kt
1005316773
package com.example.mylogin.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
simple-login-app/app/src/main/java/com/example/mylogin/ui/theme/Color.kt
165185323
package com.example.mylogin.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MyLoginTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
simple-login-app/app/src/main/java/com/example/mylogin/ui/theme/Theme.kt
3548161825
package com.example.mylogin.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 ) */ )
simple-login-app/app/src/main/java/com/example/mylogin/ui/theme/Type.kt
3916911538
package com.example.mylogin import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.mylogin.ui.theme.MyLoginTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoginScreen() } } }
simple-login-app/app/src/main/java/com/example/mylogin/MainActivity.kt
4104189914
package com.example.mylogin import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun LoginScreen(){ var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image(painter = painterResource(id = R.drawable.a), contentDescription = "Login image", modifier = Modifier.size(150.dp)) Spacer(modifier = Modifier.height(8.dp)) Text(text = "Welcome Back", fontSize = 25.sp, fontWeight = FontWeight.Bold) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Login to your account") Spacer(modifier = Modifier.height(15.dp)) OutlinedTextField(value = email, onValueChange = { email = it }, label = { Text(text = "Email address") }) Spacer(modifier = Modifier.height(15.dp)) OutlinedTextField(value = password, onValueChange = { password = it }, label = { Text(text = "Password") }, visualTransformation = PasswordVisualTransformation()) Spacer(modifier = Modifier.height(15.dp)) Button(onClick = { Log.i("Credential", "Email : $email Password : $password") }) { Text(text = "Login") } Spacer(modifier = Modifier.height(30.dp)) Text(text = "Forgot Password?", modifier = Modifier.clickable { }) Spacer(modifier = Modifier.height(30.dp)) Text(text = "Or sign in with") Row( modifier = Modifier .fillMaxWidth() .padding(30.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { Image(painter = painterResource(id = R.drawable.google), contentDescription = "Google", modifier = Modifier .size(40.dp) .clickable { //Google clicked }) Image(painter = painterResource(id = R.drawable.facebook), contentDescription = "Facebook", modifier = Modifier .size(40.dp) .clickable { //Facebook clicked }) Image(painter = painterResource(id = R.drawable.linkedin), contentDescription = "Linkedin", modifier = Modifier .size(40.dp) .clickable { //Linkedin clicked }) } } }
simple-login-app/app/src/main/java/com/example/mylogin/LoginScreen.kt
1093342122
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Product import de.maibornwolff.alabenkhlifa.monolith.repository.ProductRepository import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.* class ProductServiceTest { private lateinit var mockProductRepository: ProductRepository @BeforeEach fun setUp() { mockProductRepository = mockk() } @Test fun `getProductById should return the product with the given id`() { // given val productService = createProductService() val productId = 1L val product = Product(productId = productId, name = "Product 1", description = "Description 1") every { mockProductRepository.findById(productId) } returns Optional.of(product) // when val result = productService.getProductById(productId) // then assertTrue(result.isPresent) assertEquals(product, result.get()) } @Test fun `getProductById should return null if product not found`() { // given val productService = createProductService() val productId = 1L every { mockProductRepository.findById(productId) } returns Optional.empty() // when val result = productService.getProductById(productId) // then assertTrue(result.isEmpty) } @Test fun `getAllProducts should return all products`() { // given val productService = createProductService() val products = listOf( Product(productId = 1, name = "Product 1", description = "Description 1"), Product(productId = 2, name = "Product 2", description = "Description 2") ) every { mockProductRepository.findAll() } returns products // when val result = productService.getAllProducts() // then assertEquals(products, result) } @Test fun `createOrUpdateProduct should return the created product`() { // given val productService = createProductService() val product = Product(productId = 1, name = "Product 1", description = "Description 1") every { mockProductRepository.save(product) } returns product // when val result = productService.createOrUpdateProduct(product) // then assertEquals(product, result) } @Test fun `deleteProduct should delete the product with the given id`() { // given val productService = createProductService() val productId = 1L every { mockProductRepository.deleteById(productId) } returns Unit // when productService.deleteProduct(productId) // then verify { mockProductRepository.deleteById(productId) } } private fun createProductService() = ProductService(mockProductRepository) }
monolith/src/test/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/ProductServiceTest.kt
313745038
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Pricing import de.maibornwolff.alabenkhlifa.monolith.repository.PricingRepository import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.util.Optional class PricingServiceTest { private lateinit var mockPricingRepository: PricingRepository @BeforeEach fun setUp() { mockPricingRepository = mockk() } @Test fun `getItemPriceById should return the price after discount`() { // given val pricingService = createPricingService() val productId = 1L val pricing = Pricing(productId = productId, basePrice = 100.0, discount = 10.0) every { mockPricingRepository.findById(productId) } returns Optional.of(pricing) // when val price = pricingService.getItemPriceById(productId) // then assertEquals(90.0, price) } @Test fun `getItemPriceById should throw IllegalArgumentException if item not found`() { // given val pricingService = createPricingService() val productId = 1L every { mockPricingRepository.findById(productId) } returns Optional.empty() // when val exception = assertThrows<IllegalArgumentException> { pricingService.getItemPriceById(productId) } // then assertEquals("Item not found with id $productId", exception.message) } @Test fun `getItemPriceById should throw IllegalArgumentException if base price is negative`() { // given val pricingService = createPricingService() val productId = 1L val pricing = Pricing(productId = productId, basePrice = -100.0, discount = 10.0) every { mockPricingRepository.findById(productId) } returns Optional.of(pricing) // when val exception = assertThrows<IllegalArgumentException> { pricingService.getItemPriceById(productId) } // then assertEquals("Base price of the item with id $productId is negative", exception.message) } @Test fun `getItemPriceByIds should return the price after discount for each item`() { // given val pricingService = createPricingService() val productIds = listOf(1L, 2L, 3L) val pricing1 = Pricing(productId = 1L, basePrice = 100.0, discount = 10.0) val pricing2 = Pricing(productId = 2L, basePrice = 200.0, discount = 20.0) val pricing3 = Pricing(productId = 3L, basePrice = 300.0, discount = 30.0) every { mockPricingRepository.findById(1L) } returns Optional.of(pricing1) every { mockPricingRepository.findById(2L) } returns Optional.of(pricing2) every { mockPricingRepository.findById(3L) } returns Optional.of(pricing3) // when val prices = pricingService.getItemPriceByIds(productIds) // then val expectedResult = mapOf( 1L to 90.0, 2L to 160.0, 3L to 210.0 ) assertEquals(expectedResult, prices) } private fun createPricingService() = PricingService(mockPricingRepository) }
monolith/src/test/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/PricingServiceTest.kt
1812469953
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Order import de.maibornwolff.alabenkhlifa.monolith.entity.OrderStatus import de.maibornwolff.alabenkhlifa.monolith.repository.OrderRepository import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.* class OrderServiceTest { private lateinit var mockOrderRepository: OrderRepository @BeforeEach fun setUp() { mockOrderRepository = mockk() } @Test fun `getOrders should return all orders`() { // given val orderService = createOrderService() val orders = listOf( Order(orderId = 1, status = OrderStatus.PENDING), Order(orderId = 2, status = OrderStatus.SHIPPED), Order(orderId = 3, status = OrderStatus.DELIVERED) ) every { mockOrderRepository.findAll() } returns orders // when val result = orderService.getOrders() // then assertEquals(3, result.size) } @Test fun `getPendingOrders should return all pending orders`() { // given val orderService = createOrderService() val orders = listOf( Order(orderId = 1, status = OrderStatus.PENDING), Order(orderId = 2, status = OrderStatus.PENDING) ) every { mockOrderRepository.findByStatus(OrderStatus.PENDING) } returns orders // when val result = orderService.getPendingOrders() // then assertEquals(2, result.size) } @Test fun `getShippedOrders should return all shipped orders`() { // given val orderService = createOrderService() val orders = listOf( Order(orderId = 1, status = OrderStatus.SHIPPED), Order(orderId = 2, status = OrderStatus.SHIPPED) ) every { mockOrderRepository.findByStatus(OrderStatus.SHIPPED) } returns orders // when val result = orderService.getShippedOrders() // then assertEquals(2, result.size) } @Test fun `getDeliveredOrders should return all delivered orders`() { // given val orderService = createOrderService() val orders = listOf( Order(orderId = 1, status = OrderStatus.DELIVERED), Order(orderId = 2, status = OrderStatus.DELIVERED) ) every { mockOrderRepository.findByStatus(OrderStatus.DELIVERED) } returns orders // when val result = orderService.getDeliveredOrders() // then assertEquals(2, result.size) } @Test fun `getOrderById should return the order`() { // given val orderService = createOrderService() val orderId = 1L val order = Order(orderId = orderId, status = OrderStatus.PENDING) every { mockOrderRepository.findById(orderId) } returns Optional.of(order) // when val result = orderService.getOrderById(orderId) // then assertTrue(result.isPresent) assertEquals(order, result.get()) } @Test fun `getOrderById should return null if order not found`() { // given val orderService = createOrderService() val orderId = 1L every { mockOrderRepository.findById(orderId) } returns Optional.empty() // when val result = orderService.getOrderById(orderId) // then assertTrue(result.isEmpty) } @Test fun `createOrUpdateOrder should return the created order`() { // given val orderService = createOrderService() val order = Order(orderId = 1, status = OrderStatus.PENDING) every { mockOrderRepository.save(order) } returns order // when val result = orderService.createOrUpdateOrder(order) // then assertEquals(order, result) } @Test fun `deleteOrder should delete the order`() { // given val orderService = createOrderService() val orderId = 1L every { mockOrderRepository.deleteById(orderId) } returns Unit // when orderService.deleteOrder(orderId) // then verify { mockOrderRepository.deleteById(orderId) } } private fun createOrderService() = OrderService(mockOrderRepository) }
monolith/src/test/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/OrderServiceTest.kt
631750910
package de.maibornwolff.alabenkhlifa.monolith.repository import de.maibornwolff.alabenkhlifa.monolith.entity.Order import de.maibornwolff.alabenkhlifa.monolith.entity.OrderStatus import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface OrderRepository: JpaRepository<Order, Long> { fun findByStatus(orderStatus: OrderStatus): List<Order> }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/repository/OrderRepository.kt
1067027772
package de.maibornwolff.alabenkhlifa.monolith.repository import de.maibornwolff.alabenkhlifa.monolith.entity.Pricing import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface PricingRepository: JpaRepository<Pricing, Long>
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/repository/PricingRepository.kt
201357264
package de.maibornwolff.alabenkhlifa.monolith.repository import de.maibornwolff.alabenkhlifa.monolith.entity.Product import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface ProductRepository: JpaRepository<Product, Long>
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/repository/ProductRepository.kt
3295187958
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id import java.time.LocalDate @Entity class Pricing( @Id val pricingId: Long = 0, val productId: Long = 0, val basePrice: Double = 0.0, val discount: Double = 0.0 )
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/Pricing.kt
975358386
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id @Entity class Product( @Id val productId: Long = 0, val name: String = "", val description: String? = null, )
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/Product.kt
3199795515
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id import java.time.LocalDate @Entity class Inventory( @Id val inventoryId: Long = 0, val productId: Long = 0, val quantityOnHand: Long = 0 )
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/Inventory.kt
62360920
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id import java.time.LocalDate @Entity class OrderItem( @Id val orderItemId: Long = 0, val orderId: Long = 0, val productId: Long = 0, val quantity: Long = 0, val price: Double = 0.0 )
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/OrderItem.kt
1264007961
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id import java.time.LocalDate @Entity class Customer( @Id val customerId: Long = 0, val firstname: String = "", val lastname: String = "", val email: String = "" )
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/Customer.kt
1234224008
package de.maibornwolff.alabenkhlifa.monolith.entity import jakarta.persistence.Entity import jakarta.persistence.Id import java.time.LocalDate @Entity class Order( @Id val orderId: Long = 0, val customerId: Long = 0, val orderDate: LocalDate = LocalDate.now(), val status: OrderStatus = OrderStatus.PENDING, ) enum class OrderStatus { PENDING, SHIPPED, DELIVERED }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/entity/Order.kt
147600824
package de.maibornwolff.alabenkhlifa.monolith.controller import de.maibornwolff.alabenkhlifa.monolith.entity.Product import de.maibornwolff.alabenkhlifa.monolith.service.ProductService import org.springframework.web.bind.annotation.* @RestController class ProductController(private val productService: ProductService) { @GetMapping("/products") fun getProducts() = productService.getAllProducts() @GetMapping("/products/{productId}") fun getProductById(@PathVariable productId: Long) = productService.getProductById(productId) @PostMapping("/product") fun createProduct(product: Product) = productService.createOrUpdateProduct(product) @PutMapping("/product") fun updateProduct(product: Product) = productService.createOrUpdateProduct(product) @DeleteMapping("/product/{productId}") fun deleteProduct(@PathVariable productId: Long) = productService.deleteProduct(productId) }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/controller/ProductController.kt
2891232722
package de.maibornwolff.alabenkhlifa.monolith.controller import de.maibornwolff.alabenkhlifa.monolith.entity.Order import de.maibornwolff.alabenkhlifa.monolith.service.OrderService import org.springframework.web.bind.annotation.* @RestController class OrderController(private val orderService: OrderService) { @GetMapping("/orders") fun getOrders() = orderService.getOrders() @GetMapping("/orders/{orderId}") fun getOrderById(@PathVariable orderId: Long) = orderService.getOrderById(orderId) @PostMapping("/order") fun createOrder(order: Order) = orderService.createOrUpdateOrder(order) @PutMapping("/order") fun updateOrder(order: Order) = orderService.createOrUpdateOrder(order) @DeleteMapping("/order/{orderId}") fun deleteOrder(@PathVariable orderId: Long) = orderService.deleteOrder(orderId) @GetMapping("/orders/pending") fun getPendingOrders() = orderService.getPendingOrders() @GetMapping("/orders/shipped") fun getShippedOrders() = orderService.getShippedOrders() @GetMapping("/orders/delivered") fun getDeliveredOrders() = orderService.getDeliveredOrders() }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/controller/OrderController.kt
2237758558
package de.maibornwolff.alabenkhlifa.monolith import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class EnsitMonolithApplication fun main(args: Array<String>) { runApplication<EnsitMonolithApplication>(*args) }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/EnsitMonolithApplication.kt
1849358489
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Order import de.maibornwolff.alabenkhlifa.monolith.entity.OrderStatus import de.maibornwolff.alabenkhlifa.monolith.repository.OrderRepository import org.springframework.stereotype.Service @Service class OrderService(private val orderRepository: OrderRepository) { fun getOrders() = orderRepository.findAll() fun getPendingOrders() = orderRepository.findByStatus(OrderStatus.PENDING) fun getShippedOrders() = orderRepository.findByStatus(OrderStatus.SHIPPED) fun getDeliveredOrders() = orderRepository.findByStatus(OrderStatus.DELIVERED) fun getOrderById(orderId: Long) = orderRepository.findById(orderId) fun createOrUpdateOrder(order: Order) = orderRepository.save(order) fun deleteOrder(orderId: Long) = orderRepository.deleteById(orderId) }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/OrderService.kt
3767016473
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Pricing import de.maibornwolff.alabenkhlifa.monolith.repository.PricingRepository import org.springframework.stereotype.Service @Service class PricingService(private val pricingRepository: PricingRepository) { fun getItemPriceByIds(itemIds: List<Long>): Map<Long, Double> { val prices = mutableMapOf<Long, Double>() itemIds.forEach { itemId -> prices[itemId] = getItemPriceById(itemId) } return prices } fun getItemPriceById(itemId: Long): Double { val pricing = pricingRepository.findById(itemId) if(pricing.isEmpty) { throw IllegalArgumentException("Item not found with id $itemId") } if(pricing.get().basePrice < 0) { throw IllegalArgumentException("Base price of the item with id $itemId is negative") } return calculatePriceAfterDiscount(pricing.get()) } private fun calculatePriceAfterDiscount(pricing: Pricing): Double { val basePrice = pricing.basePrice val discount = pricing.discount return basePrice - (basePrice * discount / 100) } }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/PricingService.kt
747537304
package de.maibornwolff.alabenkhlifa.monolith.service import de.maibornwolff.alabenkhlifa.monolith.entity.Product import de.maibornwolff.alabenkhlifa.monolith.repository.ProductRepository import org.springframework.stereotype.Service @Service class ProductService(private val productRepository: ProductRepository) { fun getProductById(productId: Long) = productRepository.findById(productId) fun getAllProducts(): MutableList<Product> = productRepository.findAll() fun createOrUpdateProduct(product: Product) = productRepository.save(product) fun deleteProduct(productId: Long) = productRepository.deleteById(productId) }
monolith/src/main/kotlin/de/maibornwolff/alabenkhlifa/monolith/service/ProductService.kt
2989704129