content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.yonatankarp.drools.model data class RiskRequest( val countryCode: String, val customerNumber: String, val email: String, )
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/model/RiskRequest.kt
3639503920
package com.yonatankarp.drools.model data class RiskResponse(val isRuleApplied: Boolean)
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/model/RiskResponse.kt
887888694
package com.yonatankarp.drools.rules import com.yonatankarp.drools.model.RiskRequest interface Rule { suspend operator fun invoke(request: RiskRequest) }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/rules/Rule.kt
1466001217
package com.yonatankarp.drools.rules import com.yonatankarp.drools.model.RiskRequest import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Component class CustomerNumberRule : Rule { override suspend fun invoke(request: RiskRequest) { logger.info("Customer number in request is: ${request.customerNumber}") } companion object { private val logger: Logger = LoggerFactory.getLogger(CustomerNumberRule::class.java) } }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/rules/CustomerNumberRule.kt
108018446
package com.yonatankarp.drools.rules import com.yonatankarp.drools.model.RiskRequest import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Component class EmailRule : Rule { override suspend fun invoke(request: RiskRequest) { logger.info("Age in request is: ${request.email}") } companion object { private val logger: Logger = LoggerFactory.getLogger(EmailRule::class.java) } }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/rules/EmailRule.kt
3884431933
package com.yonatankarp.drools.rules import com.yonatankarp.drools.model.RiskRequest import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Component class CountryCodeRule : Rule { override suspend fun invoke(request: RiskRequest) { logger.info("Age in request is: ${request.countryCode}") } companion object { private val logger: Logger = LoggerFactory.getLogger(CountryCodeRule::class.java) } }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/rules/CountryCodeRule.kt
1699246244
package com.yonatankarp.drools.service import com.yonatankarp.drools.model.RiskRequest import com.yonatankarp.drools.rules.Rule import org.kie.api.runtime.KieContainer import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Service @Service class RiskService( private val kieContainer: KieContainer, @Qualifier("rulesByName") private val rules: Map<String, Rule>, ) { suspend fun runRules(riskRequest: RiskRequest): Boolean { val ruleNames = getRulesNames(riskRequest) return ruleNames .takeIf { it.isNotEmpty() } ?.let { executeRules(riskRequest, ruleNames) } ?.let { true } ?: false } private suspend fun getRulesNames(riskRequest: RiskRequest): List<String> = mutableListOf<String>() .also { kieContainer.newKieSession() .apply { setGlobal("ruleNames", it) insert(riskRequest) fireAllRules() dispose() } } private suspend fun executeRules( riskRequest: RiskRequest, ruleNames: List<String>, ) = ruleNames.forEach { rules[it.lowercase()]?.let { it(request = riskRequest) } } }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/service/RiskService.kt
469678746
package com.yonatankarp.drools import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class DroolsApplication fun main(args: Array<String>) { runApplication<DroolsApplication>(*args) }
drools-rule-engine/src/main/kotlin/com/yonatankarp/drools/DroolsApplication.kt
1858971864
import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.work.ListenableWorker import androidx.work.testing.TestListenableWorkerBuilder import androidx.work.workDataOf import com.example.bluromatic.KEY_BLUR_LEVEL import com.example.bluromatic.KEY_IMAGE_URI import com.example.bluromatic.workers.BlurWorker import com.example.bluromatic.workers.CleanupWorker import com.example.bluromatic.workers.SaveImageToFileWorker import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class WorkerInstrumentationTest { lateinit var context: Context val mockUriInput = KEY_IMAGE_URI to "android.resource://com.example.bluromatic/drawable/android_cupcake" val mockBlurLevelInput = KEY_BLUR_LEVEL to 1 @Before fun setUp() { context = ApplicationProvider.getApplicationContext() } @Test fun cleanupWorker_doWork_resultSuccess() { val cleanupWorker = TestListenableWorkerBuilder<CleanupWorker>(context).build() runBlocking { val result = cleanupWorker.doWork() assertEquals(ListenableWorker.Result.success(), result) } } @Test fun blurWorker_doWork_resultSuccessReturnsUri() { val blurWorker = TestListenableWorkerBuilder<BlurWorker>(context) .setInputData(workDataOf(mockUriInput, mockBlurLevelInput)) .build() runBlocking { val result = blurWorker.doWork() assertTrue(result is ListenableWorker.Result.Success) val resultUri = result.outputData.getString(KEY_IMAGE_URI) assertTrue(result.outputData.keyValueMap.containsKey(KEY_IMAGE_URI)) assertTrue( resultUri?.startsWith("file:///data/user/0/com.example.bluromatic/files/blur_filter_outputs/blur-filter-output-") ?: false ) } } @Test fun saveFileWorker_doWork_resultSuccess() { val saveImageWorker = TestListenableWorkerBuilder<SaveImageToFileWorker>(context) .setInputData(workDataOf(mockUriInput)) .build() runBlocking { val result = saveImageWorker.doWork() val resultUri = result.outputData.getString(KEY_IMAGE_URI) assertTrue(result is ListenableWorker.Result.Success) assertTrue(result.outputData.keyValueMap.containsKey(KEY_IMAGE_URI)) assertTrue(resultUri?.startsWith("content://media/external/images/media/") ?: false) } } }
work-manager-learning/app/src/androidTest/java/WorkerInstrumentationTest.kt
1309125393
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006A68) val md_theme_light_secondaryContainer = Color(0xFFCCE8E6) val md_theme_light_background = Color(0xFFFAFDFC) val md_theme_dark_primary = Color(0xFF2EDCD8) val md_theme_dark_secondaryContainer = Color(0xFF324B4A) val md_theme_dark_background = Color(0xFF191C1C)
work-manager-learning/app/src/main/java/com/example/bluromatic/ui/theme/Color.kt
1317646161
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.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.Color 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 = md_theme_dark_primary, secondaryContainer = md_theme_dark_secondaryContainer, background = md_theme_dark_background, ) private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, secondaryContainer = md_theme_light_secondaryContainer, background = md_theme_light_background, ) @Composable fun BluromaticTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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.background.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, content = content ) }
work-manager-learning/app/src/main/java/com/example/bluromatic/ui/theme/Theme.kt
738232885
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.ui import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.foundation.Image 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.foundation.layout.width import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton import androidx.compose.material3.RadioButtonDefaults 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.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.example.bluromatic.R import com.example.bluromatic.data.BlurAmount import com.example.bluromatic.ui.theme.BluromaticTheme @Composable fun BluromaticScreen(blurViewModel: BlurViewModel = viewModel(factory = BlurViewModel.Factory)) { val uiState by blurViewModel.blurUiState.collectAsStateWithLifecycle() BluromaticTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { BluromaticScreenContent( blurUiState = uiState, blurAmountOptions = blurViewModel.blurAmount, applyBlur = blurViewModel::applyBlur, cancelWork = blurViewModel::cancelWork ) } } } @Composable fun BluromaticScreenContent( blurUiState: BlurUiState, blurAmountOptions: List<BlurAmount>, applyBlur: (Int) -> Unit, cancelWork: () -> Unit ) { var selectedValue by rememberSaveable { mutableStateOf(1) } val context = LocalContext.current Column(modifier = Modifier.padding(dimensionResource(R.dimen.padding_small))) { Image( painter = painterResource(R.drawable.android_cupcake), contentDescription = stringResource(R.string.description_image), modifier = Modifier .fillMaxWidth() .height(400.dp), contentScale = ContentScale.Fit, ) BlurAmountContent( selectedValue = selectedValue, blurAmounts = blurAmountOptions, modifier = Modifier.fillMaxWidth(), onSelectedValueChange = { selectedValue = it } ) BlurActions( blurUiState = blurUiState, onStartClick = { applyBlur(selectedValue) }, onSeeFileClick = {currentUri -> showBlurredImage(context, currentUri) }, onCancelClick = { cancelWork() }, modifier = Modifier.fillMaxWidth() ) } } @Composable private fun BlurActions( blurUiState: BlurUiState, onStartClick: () -> Unit, onSeeFileClick: (String) -> Unit, onCancelClick: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.Center ) { when (blurUiState) { is BlurUiState.Default -> { Button(onStartClick) { Text(stringResource(R.string.start)) } } is BlurUiState.Loading -> { FilledTonalButton(onClick = onCancelClick) { Text(text = stringResource(R.string.cancel_work)) } CircularProgressIndicator( modifier = Modifier.padding(dimensionResource(R.dimen.padding_small)) ) } is BlurUiState.Complete -> { Button(onStartClick) { Text(stringResource(R.string.start)) } Spacer( modifier = Modifier.width(dimensionResource(R.dimen.padding_small)) ) FilledTonalButton(onClick = { onSeeFileClick(blurUiState.outputUri) }) { Text(text = stringResource(R.string.see_file)) } } } } } @Composable private fun BlurAmountContent( selectedValue: Int, blurAmounts: List<BlurAmount>, modifier: Modifier = Modifier, onSelectedValueChange: (Int) -> Unit ) { Column( modifier = modifier.selectableGroup() ) { Text( text = stringResource(R.string.blur_title), style = MaterialTheme.typography.headlineSmall ) blurAmounts.forEach { amount -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .selectable( role = Role.RadioButton, selected = (selectedValue == amount.blurAmount), onClick = { onSelectedValueChange(amount.blurAmount) } ) .size(48.dp) ) { RadioButton( selected = (selectedValue == amount.blurAmount), onClick = null, modifier = Modifier.size(48.dp), colors = RadioButtonDefaults.colors( selectedColor = MaterialTheme.colorScheme.primary ) ) Text(stringResource(amount.blurAmountRes)) } } } } @Preview(showBackground = true) @Composable fun BluromaticScreenContentPreview() { BluromaticTheme { BluromaticScreenContent( blurUiState = BlurUiState.Default, blurAmountOptions = listOf(BlurAmount(R.string.blur_lv_1, 1)), {}, {} ) } } private fun showBlurredImage(context: Context, currentUri: String) { val uri = if (currentUri.isNotEmpty()) { Uri.parse(currentUri) } else { null } val actionView = Intent(Intent.ACTION_VIEW, uri) context.startActivity(actionView) }
work-manager-learning/app/src/main/java/com/example/bluromatic/ui/BluromaticScreen.kt
3627189314
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import androidx.work.WorkInfo import com.example.bluromatic.BluromaticApplication import com.example.bluromatic.KEY_IMAGE_URI import com.example.bluromatic.data.BlurAmountData import com.example.bluromatic.data.BluromaticRepository import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn /** * [BlurViewModel] starts and stops the WorkManger and applies blur to the image. Also updates the * visibility states of the buttons depending on the states of the WorkManger. */ class BlurViewModel(private val bluromaticRepository: BluromaticRepository) : ViewModel() { internal val blurAmount = BlurAmountData.blurAmount val blurUiState: StateFlow<BlurUiState> = bluromaticRepository.outputWorkInfo.map { info -> val outputImageUri = info.outputData.getString(KEY_IMAGE_URI) val state = info.state when { state.isFinished && !outputImageUri.isNullOrEmpty() -> BlurUiState.Complete( outputImageUri ) state == WorkInfo.State.CANCELLED -> BlurUiState.Default else -> BlurUiState.Loading } }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = BlurUiState.Default ) /** * Call the method from repository to create the WorkRequest to apply the blur * and save the resulting image * @param blurLevel The amount to blur the image */ fun applyBlur(blurLevel: Int) { bluromaticRepository.applyBlur(blurLevel) } fun cancelWork() { bluromaticRepository.cancelWork() } /** * Factory for [BlurViewModel] that takes [BluromaticRepository] as a dependency */ companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val bluromaticRepository = (this[APPLICATION_KEY] as BluromaticApplication).container.bluromaticRepository BlurViewModel( bluromaticRepository = bluromaticRepository ) } } } } sealed interface BlurUiState { object Default : BlurUiState object Loading : BlurUiState data class Complete(val outputUri: String) : BlurUiState }
work-manager-learning/app/src/main/java/com/example/bluromatic/ui/BlurViewModel.kt
1744344497
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic import android.app.Application import com.example.bluromatic.data.AppContainer import com.example.bluromatic.data.DefaultAppContainer class BluromaticApplication : Application() { /** AppContainer instance used by the rest of classes to obtain dependencies */ lateinit var container: AppContainer override fun onCreate() { super.onCreate() container = DefaultAppContainer(this) } }
work-manager-learning/app/src/main/java/com/example/bluromatic/BluromaticApplication.kt
1292810562
package com.example.bluromatic.workers import android.content.Context import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.example.bluromatic.DELAY_TIME_MILLIS import com.example.bluromatic.OUTPUT_PATH import com.example.bluromatic.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.io.File /** * Cleans up temporary files generated during blurring process */ private const val TAG = "CleanupWorker" class CleanupWorker( ctx: Context, params: WorkerParameters ) : CoroutineWorker(ctx, params) { override suspend fun doWork(): Result { /** Makes a notification when the work starts and slows down the work so that it's easier * to see each WorkRequest start, even on emulated devices */ makeStatusNotification( applicationContext.resources.getString(R.string.cleaning_up_files), applicationContext ) return withContext(Dispatchers.IO) { delay(DELAY_TIME_MILLIS) return@withContext try { val outputDirectory = File(applicationContext.filesDir, OUTPUT_PATH) if (outputDirectory.exists()) { val entries = outputDirectory.listFiles() entries?.forEach { entry -> val name = entry.name if (name.isNotEmpty() && name.endsWith(".png")) { val deleted = entry.delete() Log.i(TAG, "Deleted $name - $deleted") } } } Result.success() } catch (exception: Exception) { exception.printStackTrace() Result.failure() } } } }
work-manager-learning/app/src/main/java/com/example/bluromatic/workers/CleanupWorker.kt
483002820
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.workers import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.util.Log import androidx.annotation.WorkerThread import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.example.bluromatic.CHANNEL_ID import com.example.bluromatic.NOTIFICATION_ID import com.example.bluromatic.NOTIFICATION_TITLE import com.example.bluromatic.OUTPUT_PATH import com.example.bluromatic.R import com.example.bluromatic.VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION import com.example.bluromatic.VERBOSE_NOTIFICATION_CHANNEL_NAME import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.util.UUID private const val TAG = "WorkerUtils" /** * Create a Notification that is shown as a heads-up notification if possible. * * For this codelab, this is used to show a notification so that you know when different steps * of the background work chain are starting * * @param message Message shown on the notification * @param context Context needed to create Toast */ fun makeStatusNotification(message: String, context: Context) { // Make a channel if necessary if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library val name = VERBOSE_NOTIFICATION_CHANNEL_NAME val description = VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(CHANNEL_ID, name, importance) channel.description = description // Add the channel val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? notificationManager?.createNotificationChannel(channel) } // Create the notification val builder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle(NOTIFICATION_TITLE) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_HIGH) .setVibrate(LongArray(0)) // Show the notification NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build()) } /** * Blurs the given Bitmap image * @param bitmap Image to blur * @param blurLevel Blur level input * @return Blurred bitmap image */ @WorkerThread fun blurBitmap(bitmap: Bitmap, blurLevel: Int): Bitmap { val input = Bitmap.createScaledBitmap( bitmap, bitmap.width/(blurLevel*5), bitmap.height/(blurLevel*5), true ) return Bitmap.createScaledBitmap(input, bitmap.width, bitmap.height, true) } /** * Writes bitmap to a temporary file and returns the Uri for the file * @param applicationContext Application context * @param bitmap Bitmap to write to temp file * @return Uri for temp file with bitmap * @throws FileNotFoundException Throws if bitmap file cannot be found */ @Throws(FileNotFoundException::class) fun writeBitmapToFile(applicationContext: Context, bitmap: Bitmap): Uri { val name = String.format("blur-filter-output-%s.png", UUID.randomUUID().toString()) val outputDir = File(applicationContext.filesDir, OUTPUT_PATH) if (!outputDir.exists()) { outputDir.mkdirs() // should succeed } val outputFile = File(outputDir, name) var out: FileOutputStream? = null try { out = FileOutputStream(outputFile) bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* ignored for PNG */, out) } finally { out?.let { try { it.close() } catch (e: IOException) { Log.e(TAG, e.message.toString()) } } } return Uri.fromFile(outputFile) }
work-manager-learning/app/src/main/java/com/example/bluromatic/workers/WorkerUtils.kt
2124772596
package com.example.bluromatic.workers import android.content.Context import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import androidx.work.workDataOf import com.example.bluromatic.KEY_BLUR_LEVEL import com.example.bluromatic.KEY_IMAGE_URI import com.example.bluromatic.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private const val TAG = "BlurWorker" class BlurWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { override suspend fun doWork(): Result { val resourceUri = inputData.getString(KEY_IMAGE_URI) val blurLevel = inputData.getInt(KEY_BLUR_LEVEL, 1) makeStatusNotification( applicationContext.resources.getString(R.string.blurring_image), applicationContext ) return withContext(Dispatchers.IO) { return@withContext try { require(!resourceUri.isNullOrBlank()) { val errorMessage = applicationContext.resources.getString(R.string.invalid_input_uri) Log.e(TAG, errorMessage) errorMessage } val resolver = applicationContext.contentResolver val picture = BitmapFactory.decodeStream( resolver.openInputStream(Uri.parse(resourceUri)) ) val output = blurBitmap(picture, blurLevel) val outputUri = writeBitmapToFile(applicationContext, output) val outputData = workDataOf(KEY_IMAGE_URI to outputUri.toString()) Result.success(outputData) } catch (e: Exception) { Log.e( TAG, applicationContext.resources.getString(R.string.error_applying_blur), e ) Result.failure() } } } }
work-manager-learning/app/src/main/java/com/example/bluromatic/workers/BlurWorker.kt
3591842672
package com.example.bluromatic.workers import android.content.Context import android.graphics.BitmapFactory import android.net.Uri import android.provider.MediaStore import android.util.Log import androidx.annotation.StringRes import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import androidx.work.workDataOf import com.example.bluromatic.DELAY_TIME_MILLIS import com.example.bluromatic.KEY_IMAGE_URI import com.example.bluromatic.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.Date import java.util.Locale /** * Saves the image to a permanent file */ private const val TAG = "SaveImageToFileWorker" class SaveImageToFileWorker( ctx: Context, params: WorkerParameters ) : CoroutineWorker(ctx, params) { private val title = "Blurred Image" private val dateFormatter = SimpleDateFormat( "yyyy.MM.dd 'at' HH:mm:ss z", Locale.getDefault() ) override suspend fun doWork(): Result { // Makes a notification when the work starts and slows down the work so that // it's easier to see each WorkRequest start, even on emulated devices makeStatusNotification( applicationContext.resources.getString(R.string.saving_image), applicationContext ) return withContext(Dispatchers.IO) { delay(DELAY_TIME_MILLIS) val resolver = applicationContext.contentResolver return@withContext try { val resourceUri = inputData.getString(KEY_IMAGE_URI) val bitmap = BitmapFactory.decodeStream( resolver.openInputStream(Uri.parse(resourceUri)) ) val imageUrl = MediaStore.Images.Media.insertImage( resolver, bitmap, title, dateFormatter.format(Date()) ) if (!imageUrl.isNullOrEmpty()) { val output = workDataOf(KEY_IMAGE_URI to imageUrl) Result.success(output) } else { fail(R.string.writing_to_mediaStore_failed) } } catch (exception: Exception) { fail(R.string.error_saving_image) } } } private fun fail(@StringRes errMessageRes: Int): Result { Log.e(TAG, applicationContext.resources.getString(errMessageRes)) return Result.failure() } }
work-manager-learning/app/src/main/java/com/example/bluromatic/workers/SaveImageToFileWorker.kt
3955866380
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.data import android.content.Context interface AppContainer { val bluromaticRepository: BluromaticRepository } class DefaultAppContainer(context: Context) : AppContainer { override val bluromaticRepository = WorkManagerBluromaticRepository(context) }
work-manager-learning/app/src/main/java/com/example/bluromatic/data/AppContainer.kt
2520761453
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.data import androidx.annotation.StringRes data class BlurAmount( @StringRes val blurAmountRes: Int, val blurAmount: Int )
work-manager-learning/app/src/main/java/com/example/bluromatic/data/BlurAmount.kt
1711159105
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.data import android.content.Context import android.net.Uri import androidx.lifecycle.asFlow import androidx.work.Constraints import androidx.work.Data import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkInfo import androidx.work.WorkManager import com.example.bluromatic.IMAGE_MANIPULATION_WORK_NAME import com.example.bluromatic.KEY_BLUR_LEVEL import com.example.bluromatic.KEY_IMAGE_URI import com.example.bluromatic.TAG_OUTPUT import com.example.bluromatic.getImageUri import com.example.bluromatic.workers.BlurWorker import com.example.bluromatic.workers.CleanupWorker import com.example.bluromatic.workers.SaveImageToFileWorker import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapNotNull class WorkManagerBluromaticRepository(context: Context) : BluromaticRepository { private val workManager: WorkManager = WorkManager.getInstance(context) private var imageUri: Uri = context.getImageUri() override val outputWorkInfo: Flow<WorkInfo> = workManager.getWorkInfosByTagLiveData(TAG_OUTPUT) .asFlow() .mapNotNull { if (it.isNotEmpty()) it.first() else null } /** * Create the WorkRequests to apply the blur and save the resulting image * @param blurLevel The amount to blur the image */ override fun applyBlur(blurLevel: Int) { val cleanup = OneTimeWorkRequest.from(CleanupWorker::class.java) val constraints = Constraints.Builder() .setRequiresBatteryNotLow(true) .setRequiresStorageNotLow(true) .build() val blur = OneTimeWorkRequestBuilder<BlurWorker>() .setInputData(createInputDataForWorkRequest(blurLevel, imageUri)) .setConstraints(constraints) .build() val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>() .addTag(TAG_OUTPUT) .build() workManager.beginUniqueWork( IMAGE_MANIPULATION_WORK_NAME, ExistingWorkPolicy.REPLACE, cleanup ) .then(blur) .then(save) .enqueue() } /** * Cancel any ongoing WorkRequests * */ override fun cancelWork() { workManager.cancelUniqueWork(IMAGE_MANIPULATION_WORK_NAME) } /** * Creates the input data bundle which includes the blur level to * update the amount of blur to be applied and the Uri to operate on * @return Data which contains the Image Uri as a String and blur level as an Integer */ private fun createInputDataForWorkRequest(blurLevel: Int, imageUri: Uri): Data { val builder = Data.Builder() builder.putString(KEY_IMAGE_URI, imageUri.toString()).putInt(KEY_BLUR_LEVEL, blurLevel) return builder.build() } }
work-manager-learning/app/src/main/java/com/example/bluromatic/data/WorkManagerBluromaticRepository.kt
4252710517
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.data import com.example.bluromatic.R object BlurAmountData { val blurAmount = listOf( BlurAmount( blurAmountRes = R.string.blur_lv_1, blurAmount = 1 ), BlurAmount( blurAmountRes = R.string.blur_lv_2, blurAmount = 2 ), BlurAmount( blurAmountRes = R.string.blur_lv_3, blurAmount = 3 ) ) }
work-manager-learning/app/src/main/java/com/example/bluromatic/data/BlurAmountData.kt
4278066577
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic.data import androidx.work.WorkInfo import kotlinx.coroutines.flow.Flow interface BluromaticRepository { val outputWorkInfo: Flow<WorkInfo> fun applyBlur(blurLevel: Int) fun cancelWork() }
work-manager-learning/app/src/main/java/com/example/bluromatic/data/BluromaticRepository.kt
3659612947
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic // Notification Channel constants // Name of Notification Channel for verbose notifications of background work val VERBOSE_NOTIFICATION_CHANNEL_NAME: CharSequence = "Verbose WorkManager Notifications" const val VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION = "Shows notifications whenever work starts" val NOTIFICATION_TITLE: CharSequence = "WorkRequest Starting" const val CHANNEL_ID = "VERBOSE_NOTIFICATION" const val NOTIFICATION_ID = 1 // The name of the image manipulation work const val IMAGE_MANIPULATION_WORK_NAME = "image_manipulation_work" // Other keys const val OUTPUT_PATH = "blur_filter_outputs" const val KEY_IMAGE_URI = "KEY_IMAGE_URI" const val TAG_OUTPUT = "OUTPUT" const val KEY_BLUR_LEVEL = "KEY_BLUR_LEVEL" const val DELAY_TIME_MILLIS: Long = 3000
work-manager-learning/app/src/main/java/com/example/bluromatic/Constants.kt
377944630
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluromatic import android.content.ContentResolver import android.content.Context import android.net.Uri import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.example.bluromatic.ui.BluromaticScreen class BlurActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BluromaticScreen() } } } fun Context.getImageUri(): Uri { val resources = this.resources return Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(R.drawable.android_cupcake)) .appendPath(resources.getResourceTypeName(R.drawable.android_cupcake)) .appendPath(resources.getResourceEntryName(R.drawable.android_cupcake)) .build() }
work-manager-learning/app/src/main/java/com/example/bluromatic/BlurActivity.kt
1761719846
package contentgraph.datageneration data class CCReport( val content: CCContent ){ data class CCContent( val query: String ) }
error-import/src/gatling/kotlin/error/datageneration/CCReport.kt
56619142
import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import java.io.File object DataGeneration { private val objectMapper = ObjectMapper() @JvmStatic fun main(args: Array<String>) { val apiResponse=readMapObjectFromFile("test/optimal.json") val content=apiResponse["content"] as List<Map<String,Any>> val outputFile = File("optimalQueries.txt") content.forEach{ item -> val query = item["query"] as String val queryWithoutNewLine=query.replace("\n", " ") outputFile.appendText(queryWithoutNewLine+"\n") } } fun readFile(path: String): String { val fileContent= DataGeneration::class.java.classLoader.getResource(path)?.readText() ?: "" return fileContent } fun readMapObjectFromFile(path: String) = objectMapper.readValue( readFile(path), object : TypeReference<Map<String, Any>>() {} ) }
error-import/src/gatling/kotlin/error/datageneration/DataGeneration.kt
572521356
package computerdatabase import io.gatling.javaapi.core.* import io.gatling.javaapi.http.* import io.gatling.javaapi.core.CoreDsl.* import io.gatling.javaapi.http.HttpDsl.* import java.util.concurrent.ThreadLocalRandom /** * This sample is based on our official tutorials: * * - [Gatling quickstart tutorial](https://gatling.io/docs/gatling/tutorials/quickstart) * - [Gatling advanced tutorial](https://gatling.io/docs/gatling/tutorials/advanced) */ class ComputerDatabaseSimulation : Simulation() { val feeder = csv("search.csv").random() val search = exec( http("Home").get("/"), pause(1), feed(feeder), http("Search") .get("/computers?f=#{searchCriterion}") .check( css("a:contains('#{searchComputerName}')", "href").saveAs("computerUrl") ), pause(1), http("Select") .get("#{computerUrl}") .check(status().shouldBe(200)), pause(1) ) // repeat is a loop resolved at RUNTIME val browse = // Note how we force the counter name, so we can reuse it repeat(4, "i").on( http("Page #{i}").get("/computers?p=#{i}"), pause(1) ) // Note we should be using a feeder here // let's demonstrate how we can retry: let's make the request fail randomly and retry a given // number of times val edit = // let's try at max 2 times tryMax(2).on( http("Form").get("/computers/new"), pause(1), http("Post") .post("/computers") .formParam("name", "Beautiful Computer") .formParam("introduced", "2012-05-30") .formParam("discontinued", "") .formParam("company", "37") .check( status().shouldBe { session -> // we do a check on a condition that's been customized with // a lambda. It will be evaluated every time a user executes // the request 200 + ThreadLocalRandom.current().nextInt(2) } ) ) // if the chain didn't finally succeed, have the user exit the whole scenario .exitHereIfFailed() val httpProtocol = http.baseUrl("https://computer-database.gatling.io") .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") .acceptLanguageHeader("en-US,en;q=0.5") .acceptEncodingHeader("gzip, deflate") .userAgentHeader( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/119.0" ) val users = scenario("Users").exec(search, browse) val admins = scenario("Admins").exec(search, browse, edit) init { setUp( users.injectOpen(rampUsers(10).during(10)), admins.injectOpen(rampUsers(2).during(10)) ).protocols(httpProtocol) } }
error-import/src/gatling/kotlin/computerdatabase/ComputerDatabaseSimulation.kt
319449854
package com.example.recycleviewtest 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.recycleviewtest", appContext.packageName) } }
recycler-view-test/app/src/androidTest/java/com/example/recycleviewtest/ExampleInstrumentedTest.kt
940738857
package com.example.recycleviewtest 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) } }
recycler-view-test/app/src/test/java/com/example/recycleviewtest/ExampleUnitTest.kt
259470795
package com.example.recycleviewtest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
recycler-view-test/app/src/main/java/com/example/recycleviewtest/MainActivity.kt
857363869
package com.example.recycleviewtest import android.app.Activity import android.os.Bundle import android.text.Editable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class ContactSearchFragment : Fragment() { private val myAdapter by lazy { MyAdapter(getMessages()) } private fun getMessages(): ArrayList<Contact> { val list: ArrayList<Contact> = ArrayList() list.add(Contact("Mary")) list.add(Contact("John")) list.add(Contact("James")) list.add(Contact("David")) return list } private val TAG = this::class.simpleName override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerViewContact) recyclerView.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false) recyclerView.adapter = myAdapter val searchInput = view.findViewById<EditText>(R.id.searchInputContact) searchInput.requestFocus() val imm = requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0) searchInput.apply { doAfterTextChanged { filterItems(it) } } } private fun filterItems(query: Editable?) { query?.let { if (it.isNotEmpty()) { val searchQuery = it.toString().lowercase() myAdapter.updateItems(getMessages().filter { contact -> contact.name.lowercase().contains(searchQuery) }) } else { myAdapter.updateItems(getMessages()) } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_search, container, false) } }
recycler-view-test/app/src/main/java/com/example/recycleviewtest/ContactSearchFragment.kt
3295788098
package com.example.recycleviewtest data class Contact(val name: String)
recycler-view-test/app/src/main/java/com/example/recycleviewtest/Contact.kt
3937586338
package com.example.recycleviewtest import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText class SearchFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_contact, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fragment = ContactSearchFragment() val simpleName = fragment::class.simpleName val editText = view.findViewById<EditText>(R.id.searchInput) editText.apply { setOnClickListener { requireActivity().supportFragmentManager.apply { val hasFragment = findFragmentByTag(simpleName) beginTransaction().apply { if (hasFragment != null) { show(hasFragment) } else { replace(R.id.container, fragment, simpleName) } addToBackStack(null) commit() } } } } val button = view.findViewById<Button>(R.id.secondButton) button.setOnClickListener { requireActivity().supportFragmentManager.apply { val hasFragment = findFragmentByTag(simpleName) beginTransaction().apply { if (hasFragment != null) { show(hasFragment) } else { replace(R.id.container, fragment, simpleName) } addToBackStack(null) commit() } } } } }
recycler-view-test/app/src/main/java/com/example/recycleviewtest/SearchFragment.kt
259614466
package com.example.recycleviewtest import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class MyAdapter(private val mData: ArrayList<Contact>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return BodyViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false) ) } fun updateItems(newData: List<Contact>){ mData.clear() mData.addAll(newData) notifyDataSetChanged() } override fun getItemCount(): Int { return mData.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val data = mData[position] val bodyViewHolder = holder as BodyViewHolder bodyViewHolder.bind(data) } inner class BodyViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textViewContact: TextView = itemView.findViewById(R.id.textViewContact) fun bind(item: Contact) { textViewContact.text = item.name } } }
recycler-view-test/app/src/main/java/com/example/recycleviewtest/MyAdapter.kt
3033831808
package com.example.splashscreencompose 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.splashscreencompose", appContext.packageName) } }
Travel-Snap/app/src/androidTest/java/com/example/splashscreencompose/ExampleInstrumentedTest.kt
599897068
package com.example.splashscreencompose 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) } }
Travel-Snap/app/src/test/java/com/example/splashscreencompose/ExampleUnitTest.kt
1648300343
package com.example.splashscreencompose.viewModel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.splashscreencompose.model.ReviewRequest import com.example.splashscreencompose.repository.TravelRepository import com.example.splashscreencompose.travelResponse.TravelResponse import com.example.splashscreencompose.utils.NetworkResult import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch class TravelViewModel( private val travelRepository: TravelRepository ): ViewModel() { val getReviewResponse: LiveData<NetworkResult<TravelResponse>> get() = travelRepository.userResponse fun getReviews(apiKey: String, locationId: String, language: String, currency: String) { viewModelScope.launch { travelRepository.getReviews(apiKey,locationId,language, currency) } } /* fun getReviews(apiKey: String, requestBody: ReviewRequest): Flow<TravelResponse?> = flow { val response = travelRepository.getReviews(apiKey, requestBody) if (response.isSuccessful) { emit(response.body()) } else { // Handle error emit(null) } }*/ }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/viewModel/TravelViewModel.kt
4097653040
package com.example.splashscreencompose.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)
Travel-Snap/app/src/main/java/com/example/splashscreencompose/ui/theme/Color.kt
141943116
package com.example.splashscreencompose.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 SplashScreenComposeTheme( 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 ) }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/ui/theme/Theme.kt
3058490621
package com.example.splashscreencompose.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 ) */ )
Travel-Snap/app/src/main/java/com/example/splashscreencompose/ui/theme/Type.kt
680010370
package com.example.splashscreencompose import android.content.Intent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController @Composable fun SignupBoardingScreen(navController: NavController) { val context = LocalContext.current Box( modifier = Modifier.fillMaxSize() .background(Color(0xFF0FA3E2)) ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) .align(Alignment.Center), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.whitelogo), contentDescription = "pic", Modifier .padding(10.dp) .size(100.dp), contentScale = ContentScale.FillWidth, ) Text( text = "Successfully created an Account", fontSize = 24.sp, fontWeight = FontWeight.Bold, color = Color.White ) Spacer(modifier = Modifier.height(16.dp)) Text( text = "Thank you for signing up!", fontSize = 18.sp, fontWeight = FontWeight.Normal, color = Color.White ) Spacer(modifier = Modifier.height(15.dp)) } Button( onClick = { val intent = Intent(context, HomeActivity::class.java) context.startActivity(intent) }, modifier = Modifier .fillMaxWidth() .height(50.dp) .padding(horizontal = 16.dp) .padding(bottom = 10.dp) .align(Alignment.BottomCenter), colors = ButtonDefaults.buttonColors(Color.White) ) { Text( text = "Continue", color = Color(0xFF0FA3E2) ) } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/SignupBoardingScreen.kt
1744079693
package com.example.splashscreencompose.database import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "favorite_places") data class FavouritePlaces( @PrimaryKey(autoGenerate = true) val id: Long = 0, val placeId: String )
Travel-Snap/app/src/main/java/com/example/splashscreencompose/database/FavouritePlaces.kt
709814844
package com.example.splashscreencompose.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database(entities = [FavouritePlaces::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun favoritePlaceDao(): FavoritePlaceDao }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/database/AppDatabase.kt
2811440522
package com.example.splashscreencompose.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface FavoritePlaceDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavoriteSong(favouritePlaces: FavouritePlaces) @Query("DELETE FROM favorite_places WHERE placeId = :placeId") suspend fun deleteFavoriteSong(placeId: String) @Query("SELECT * FROM favorite_places") suspend fun getAllFavoriteSongs(): List<FavouritePlaces> @Query("SELECT * FROM favorite_places WHERE placeId = :placeId") fun isSongFavorite(placeId: String): FavouritePlaces? @Query("SELECT * FROM favorite_places WHERE placeId = :id") suspend fun getFavoriteSongById(id: Long) : FavouritePlaces }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/database/FavoritePlaceDao.kt
214214150
package com.example.splashscreencompose.repository import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.splashscreencompose.api.TravelApi import com.example.splashscreencompose.model.ReviewRequest import com.example.splashscreencompose.retrofit.RetrofitInstance import com.example.splashscreencompose.travelResponse.TravelResponse import com.example.splashscreencompose.utils.NetworkResult import org.json.JSONObject import retrofit2.Response class TravelRepository( ) { private val travelApi: TravelApi = RetrofitInstance.api /*suspend fun getReviews(apiKey: String, requestBody: ReviewRequest): Response<TravelResponse> { return travelApi.getReviews(apiKey, requestBody) }*/ /* private val _reviewsResponse = MutableLiveData<Response<TravelResponse>>() val reviewsResponse: LiveData<Response<TravelResponse>> get() = _reviewsResponse suspend fun getReviews(apiKey: String, locationId: String, language: String, currency: String) { try { val response = travelApi.getReviews(apiKey, ReviewRequest(locationId,language, currency)) _reviewsResponse.postValue(response) } catch (e: Exception) { // Handle errors } }*/ private val _userResponseReviews = MutableLiveData<NetworkResult<TravelResponse>>() val userResponse: LiveData<NetworkResult<TravelResponse>> get() = _userResponseReviews suspend fun getReviews(apiKey: String, locationId: String, language: String, currency: String) { _userResponseReviews.postValue(NetworkResult.Loading()) try { val response = travelApi.getReviews(apiKey, ReviewRequest(locationId,language, currency)) if (response.isSuccessful) { val data = response.body() Log.d("ResultRepository", "Success: ${data}") _userResponseReviews.value = NetworkResult.Success(data) } else { // Handle unsuccessful response val errorObj = response.errorBody()?.string()?.let { JSONObject(it) } Log.d("ResultRepository", "Failure: ${errorObj?.getString("error")}") _userResponseReviews.value = NetworkResult.Error(errorObj?.getString("error")) } } catch (e: Exception) { // Handle exceptions _userResponseReviews.value = NetworkResult.Error(e.message ?: "Something went wrong") } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/repository/TravelRepository.kt
2345080816
package com.example.splashscreencompose import android.annotation.SuppressLint import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.example.splashscreencompose.databinding.ActivityDetailBinding import com.example.splashscreencompose.travelResponse.Data import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnBack.setOnClickListener { finish() } var model = intent.extras?.getSerializable("model") as Data updateStatusOfFavouritePlace(model.id) binding.title.text = model.title binding.rating.text = "${model.rating}.0" binding.description.text = model.text binding.reviews.text = "${model.user.contributions.reviews} Reviews" binding.userLocation.text = model?.user?.user_location?.name ?: "Unknown User Location" val firstPhoto = model.photos?.firstOrNull() val locationName = firstPhoto?.locations?.firstOrNull()?.name ?: "Unknown Location" binding.location.text = locationName binding.publisher.text = model?.user?.name ?: "Publisher Not Found" if(!model.photos.isNullOrEmpty() && model.photos.firstOrNull()?.images?.original?.url != null) { Glide.with(this) .load(model.photos.firstOrNull()?.images?.original?.url!!) .placeholder(R.drawable.image) .centerCrop() .into(binding.image) } } private fun updateStatusOfFavouritePlace(placeId: String) { lifecycleScope.launch(Dispatchers.IO) { val isFavorite = SplashScreenCompose.database.favoritePlaceDao().isSongFavorite(placeId) withContext(Dispatchers.Main) { updateFavoriteButtonIcon(isFavorite != null) } } } private fun updateFavoriteButtonIcon(isFavorite: Boolean) { binding.btnFavorite.setImageResource( if (isFavorite) R.drawable.favorite else R.drawable.favorite_border ) } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/DetailActivity.kt
3038490830
package com.example.splashscreencompose import Home import android.content.Intent import android.net.Uri 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.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.core.net.toUri import androidx.navigation.NavType import androidx.navigation.activity import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.splashscreencompose.gesture.FullScreenImage import com.example.splashscreencompose.gesture.GalleryScreen import com.example.splashscreencompose.gesture.SwipeAblePages class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intentDestination = intent.getStringExtra("destination") setContent { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() NavHost(navController = navController, startDestination = getStartDestination(intentDestination)) { composable("Splash") { SplashScreen(navController = navController, context = this@MainActivity) } composable("Onboarding") { OnboardingScreen(navController = navController, context = this@MainActivity) } composable("Login") { LoginScreen(navController = navController) } composable("Home") { Home(navController = navController) } composable("Signup") { SignupScreen(navController = navController) } composable("SignupBoardingScreen") { SignupBoardingScreen(navController = navController) } composable("ForgetPassword") { ForgetPassword(navController = navController) } composable("CreatePassword") { CreatePassword(navController = navController) } activity("homeActivity") { Intent(this@MainActivity, HomeActivity::class.java) } composable("gallery") { GalleryScreen(navController) } composable( route = "imageDetail/{imageUrl}", arguments = listOf(navArgument("imageUrl") { type = NavType.LongType }) ) { backStackEntry -> val imageUrl = backStackEntry.arguments?.getLong("imageUrl") ?: 0L FullScreenImage(imageUrl) } composable("swipeAblePages") { SwipeAblePages() } } } } } } private fun getStartDestination(intentDestination: String?): String { return if (intentDestination != null && intentDestination == "gallery") { "gallery" } else { "splash" } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/MainActivity.kt
1758018201
package com.example.splashscreencompose import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.widget.Toast import android.window.OnBackInvokedDispatcher import androidx.activity.addCallback import androidx.appcompat.app.AlertDialog import androidx.compose.runtime.collectAsState import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.lifecycle.observe import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.LinearLayoutManager import com.example.splashscreencompose.adapter.TravelAdapter import com.example.splashscreencompose.databinding.ActivityHomeBinding import com.example.splashscreencompose.model.ReviewRequest import com.example.splashscreencompose.model.TravelModelDemo import com.example.splashscreencompose.repository.TravelRepository import com.example.splashscreencompose.travelResponse.Data import com.example.splashscreencompose.travelResponse.TravelResponse import com.example.splashscreencompose.utils.Constants import com.example.splashscreencompose.utils.NetworkResult import com.example.splashscreencompose.viewModel.TravelViewModel import com.google.android.material.button.MaterialButton import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class HomeActivity : AppCompatActivity() { private lateinit var binding: ActivityHomeBinding private lateinit var adapter: TravelAdapter private var travelList = ArrayList<Data>() private val repository = TravelRepository() private val travelViewModel = TravelViewModel(repository) private var isFirstTime = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) val locationIds = listOf("8797440", "47087", "45963", "562820", "187472", "259440", "150802", "3194809", "664450", "147288") var currentIndex = 0 fetchDataForLocationId(locationIds[currentIndex]) binding.swipe.setOnRefreshListener { isFirstTime = false // Increment the index cyclically currentIndex = (currentIndex + 1) % locationIds.size // Make API call with the location ID at the next index fetchDataForLocationId(locationIds[currentIndex]) Log.d("locationId", locationIds[currentIndex]) } // Configure the refreshing colors binding.swipe.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light) binding.images.setOnClickListener { navigateToMainActivity() } reviewObserver() } @SuppressLint("NotifyDataSetChanged") private fun reviewObserver() { travelViewModel.getReviewResponse.observe(this) { Log.d("observer", "reviewObserver: $it") when (it) { is NetworkResult.Success -> { Log.d("Result", "called") binding.progress.isVisible = false binding.swipe.isRefreshing = false // Add new data to the top of the travelList it.data?.results?.data?.let { newData -> travelList.addAll(0, newData) } Log.d("Result", travelList.toString()) if (travelList != null) { if(isFirstTime) { adapter = TravelAdapter(travelList, this) { position, model -> val bundle = Bundle() bundle.putSerializable("model", model) val intent = Intent(this, DetailActivity::class.java) intent.putExtras(bundle) startActivity(intent) } binding.travelRecyclerView.layoutManager = LinearLayoutManager(this) binding.travelRecyclerView.adapter = adapter } else { adapter.notifyDataSetChanged() } } } is NetworkResult.Error -> { Log.d("Result", it.message.toString()) Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show() binding.swipe.isRefreshing = false binding.progress.isVisible = false } is NetworkResult.Loading -> { binding.progress.isVisible = true } } } } private fun fetchDataForLocationId(locationId: String) { Log.d("API","API hitted.") travelViewModel.getReviews( Constants.API_KEY, locationId, language = "en_US", currency = "USD" ) } private fun navigateToMainActivity() { val intent = Intent(this, MainActivity::class.java) intent.putExtra("destination", "gallery") startActivity(intent) } override fun onBackPressed() { appExitDialog() } override fun getOnBackInvokedDispatcher(): OnBackInvokedDispatcher { onBackPressedDispatcher.addCallback { appExitDialog() } return super.getOnBackInvokedDispatcher() } private fun appExitDialog() { val dialogView = LayoutInflater.from(this).inflate(R.layout.exit_dialog, null) val dialogBuilder = AlertDialog.Builder(this) .setView(dialogView) val dialog = dialogBuilder.create() dialog.window?.setBackgroundDrawableResource(android.R.color.transparent) dialog.setCancelable(false) dialog.show() dialog.findViewById<MaterialButton>(R.id.btn_cancel)?.setOnClickListener { dialog.dismiss() } dialog.findViewById<MaterialButton>(R.id.btn_exit)?.setOnClickListener { finishAffinity() dialog.dismiss() } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/HomeActivity.kt
3926969196
package com.example.splashscreencompose.utils import java.io.Serializable data class LocalImages( val id: Long, val title: String?, val url: String?, val size: Float, val modifiedDate: String, val mimeType: String, var delete: Boolean = false ) : Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/utils/LocalImages.kt
3959791902
package com.example.splashscreencompose.utils sealed class NetworkResult<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T?): NetworkResult<T>(data) class Error<T>(message: String?, data: T? = null): NetworkResult<T>(data, message) class Loading<T>: NetworkResult<T>() }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/utils/NetworkResult.kt
1541115421
package com.example.splashscreencompose.utils import android.content.Context import android.provider.MediaStore object LocalFileProvider { /*suspend fun fetchLocalVideos(context: Context): List<LocalVideos> = withContext(Dispatchers.IO) { val localVideosList = mutableListOf<LocalVideos>() val projection = arrayOf( MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE, MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.ALBUM, MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media.MIME_TYPE ) val cursor = context.contentResolver.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null ) cursor?.use { val idColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media._ID) val titleColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE) val dataColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.DATA) val sizeColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE) val durationColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION) val folderColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM) val dateModifiedColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED) val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE) while (it.moveToNext()) { val id = it.getLong(idColumn) val title = it.getString(titleColumn) val data = it.getString(dataColumn) val size: Float = it.getFloat(sizeColumn) val duration = it.getLong(durationColumn) val folder = it.getString(folderColumn) val modifiedDate = it.getString(dateModifiedColumn) val mimeType = it.getString(mimeTypeColumn) val video = LocalVideos(id, title, data, size, duration, folder, modifiedDate, mimeType) localVideosList.add(video) } } return@withContext localVideosList }*/ fun fetchLocalImages(context: Context): List<LocalImages> // withContext(Dispatchers.IO) { val localImagesList = mutableListOf<LocalImages>() val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.TITLE, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.DATE_MODIFIED, MediaStore.Images.Media.MIME_TYPE ) val cursor = context.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null ) cursor?.use { val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID) val titleColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE) val dataColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) val sizeColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE) val dateModifiedColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED) val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE) while (it.moveToNext()) { val id = it.getLong(idColumn) val title = it.getString(titleColumn) val data = it.getString(dataColumn) val size: Float = it.getFloat(sizeColumn) val modifiedDate = it.getString(dateModifiedColumn) val mimeType = it.getString(mimeTypeColumn) val image = LocalImages(id, title, data, size, modifiedDate, mimeType) localImagesList.add(image) } } return localImagesList } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/utils/LocalFileProvider.kt
3983408188
package com.example.splashscreencompose.utils object Constants { const val BASE_URL_TRAVEL = "https://tourist-attraction.p.rapidapi.com/" const val END_POINT_REVIEWS = "reviews" const val API_KEY = "1e6d561424mshcac89b6a09fbed2p1619a0jsn7ff937645551" const val PREF_FIRST_TIME_OPENING_ONBOARDING = "pref_first_time_opening_onboarding" }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/utils/Constants.kt
727323743
package com.example.splashscreencompose.adapter import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.splashscreencompose.R import com.example.splashscreencompose.SplashScreenCompose import com.example.splashscreencompose.database.FavouritePlaces import com.example.splashscreencompose.databinding.TravelItemBinding import com.example.splashscreencompose.model.ReviewRequest import com.example.splashscreencompose.model.TravelModelDemo import com.example.splashscreencompose.travelResponse.Data import com.example.splashscreencompose.travelResponse.TravelResponse import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class TravelAdapter( private val travelList: ArrayList<Data>, val context: Context, private val click: (position: Int, data: Data) -> Unit ) : RecyclerView.Adapter<TravelAdapter.TravelViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TravelViewHolder { return TravelViewHolder( TravelItemBinding.inflate( LayoutInflater.from(context), parent, false ) ) } override fun onBindViewHolder(holder: TravelViewHolder, position: Int) { val travelItem = travelList[position] holder.bind(travelItem, position, click) } override fun getItemCount(): Int = travelList.size inner class TravelViewHolder(private val binding: TravelItemBinding) : RecyclerView.ViewHolder(binding.root) { val root = binding.root fun bind(data: Data, position: Int, click: (position: Int, data: Data) -> Unit) { binding.title.text = data.title binding.rating.text = "${data.rating}.0" binding.description.text = data.text CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) { val isFavorite = SplashScreenCompose.database.favoritePlaceDao().isSongFavorite(data.id) Log.d("favoriteSong", "song: $isFavorite id: ${isFavorite?.placeId}") withContext(Dispatchers.Main) { if(isFavorite != null) { binding.btnFavorite.setImageResource(R.drawable.favorite) } else { binding.btnFavorite.setImageResource(R.drawable.favorite_border) } } } if (!data.photos.isNullOrEmpty() && data.photos.firstOrNull()?.images?.original?.url != null) { Glide.with(context) .load(data.photos.firstOrNull()?.images?.original?.url) .placeholder(R.drawable.image_placeholder) .centerCrop() .into(binding.image) } root.setOnClickListener { click(position, data) } binding.btnFavorite.setOnClickListener { CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) { val songFavorite = SplashScreenCompose.database.favoritePlaceDao().isSongFavorite(data.id) Log.d("favoriteSong", "song: $songFavorite id: ${songFavorite?.placeId}") if (songFavorite != null) { SplashScreenCompose.database.favoritePlaceDao().deleteFavoriteSong(songFavorite.placeId) withContext(Dispatchers.Main) { binding.btnFavorite.setImageResource(R.drawable.favorite_border) /*FavouriteSongsFragment.favoriteSongs.remove(songFavorite) FavouriteSongsFragment.favouriteSongsAdapter?.notifyDataSetChanged() Log.e("index","$currentSongIndex") FavouriteSongsFragment.favouriteSongsAdapter?.updateFavoriteSongList()*/ Toast.makeText( context, "Removed from favorites", Toast.LENGTH_SHORT ).show() } } else { val favouritePlaces = FavouritePlaces( placeId = data.id ) SplashScreenCompose.database.favoritePlaceDao().insertFavoriteSong(favouritePlaces) withContext(Dispatchers.Main) { binding.btnFavorite.setImageResource(R.drawable.favorite) /*// Fetch all favorite songs and sort them by timestamp in descending order FavouriteSongsFragment.favoriteSongs.addAll( ApplicationClass.database.favoriteSongDao().getAllFavoriteSongs() .sortedByDescending { it.favouriteSongTimestamp } ) FavouriteSongsFragment.favouriteSongsAdapter?.updateFavoriteSongList()*/ Toast.makeText( context, "Added to favorites", Toast.LENGTH_SHORT ).show() } } } } } } /* private fun updateStatusOfFavouritePlace(placeId: String) { CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) { val isFavorite = SplashScreenCompose.database.favoritePlaceDao().isSongFavorite(placeId) withContext(Dispatchers.Main) { updateFavoriteButtonIcon(isFavorite != null) } } } private fun updateFavoriteButtonIcon(isFavorite: Boolean) { if (isFavorite) R.drawable.favorite else R.drawable.favorite_border }*/ }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/adapter/TravelAdapter.kt
976133825
package com.example.splashscreencompose import android.util.Log import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore @Composable fun SignupScreen(navController: NavController) { // Firebase Authentication instance val auth = FirebaseAuth.getInstance() // Firestore instance val db = FirebaseFirestore.getInstance() val context = LocalContext.current // State for user input fields var firstName by remember { mutableStateOf("") } var lastName by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var isLoading by remember { mutableStateOf(false) } // Handle user sign-up fun signUp() { isLoading = true auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { // User signed up successfully, store additional details in FireStore val user = auth.currentUser val userDetails = hashMapOf( "firstName" to firstName, "lastName" to lastName, "email" to email ) user?.uid?.let { userId -> db.collection("users").document(userId) .set(userDetails) .addOnSuccessListener { isLoading = false Log.d("status", "userId: $userId Success: $it") // Navigate to next screen after successful sign-up navController.navigate("SignupBoardingScreen") } .addOnFailureListener { e -> isLoading = false // Handle failure to store user details Toast.makeText(context, "$e", Toast.LENGTH_SHORT).show() Log.d("status", "Failure: $e") } } } else { // Handle sign-up failures isLoading = false Toast.makeText(context, task.toString(), Toast.LENGTH_SHORT).show() Log.d("status", "else Log: $task") } } } // Enable the button only when all fields are filled var isButtonEnabled by remember { mutableStateOf(false) } // Validation checks for all input fields // Enable the button only when all fields are filled if (firstName.isNotEmpty() && lastName.isNotEmpty() && email.isNotEmpty() && password.isNotEmpty()) { isButtonEnabled = true } else { isButtonEnabled = false } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "pic", Modifier .padding(10.dp) .size(100.dp), contentScale = ContentScale.FillWidth, ) Text( text = "Create an account", fontSize = 30.sp, fontWeight = FontWeight.Bold ) OutlinedTextField( value = firstName, onValueChange = { firstName = it }, label = { Text("First Name") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = lastName, onValueChange = { lastName = it }, label = { Text("Last Name") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = email, onValueChange = { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text("Password") }, modifier = Modifier.fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), trailingIcon = { IconButton(onClick = { /* Handle password visibility toggle */ }) { // Password visibility icon } }, visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { signUp() }, modifier = Modifier .fillMaxWidth() .height(58.dp) .padding(horizontal = 16.dp), colors = ButtonDefaults.buttonColors(Color(0xFF0FA3E2)), enabled = isButtonEnabled // Enable button only when all fields are filled ) { if (isLoading) { CircularProgressIndicator(color = Color.White) } else { Text("Sign Up", color = Color.White, fontSize = 16.sp) } } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/SignupScreen.kt
2252998890
package com.example.splashscreencompose 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.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController @Composable fun CreatePassword(navController: NavController) { var password by remember { mutableStateOf("") } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "pic", Modifier .padding(10.dp) .size(100.dp), contentScale = ContentScale.FillWidth, ) Text( text = "Create New Password", fontSize = 30.sp, fontWeight = FontWeight.Bold ) Text( text = "Keep your account secure by creating a strong password", fontSize = 18.sp, fontWeight = FontWeight.Light) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text("Password") }, modifier = Modifier.fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), trailingIcon = { IconButton(onClick = { /* Handle password visibility toggle */ }) { // Password visibility icon } }, visualTransformation = PasswordVisualTransformation() ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { navController.navigate("Login") }, modifier = Modifier .fillMaxWidth() .height(48.dp) .padding(horizontal = 16.dp), colors = ButtonDefaults.buttonColors(Color(0xFF0FA3E2)) ) { Text("Create New Password", color = Color.White) } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/CreatePassword.kt
580810641
package com.example.splashscreencompose import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.core.content.edit import androidx.navigation.NavController import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase private const val PREFS_NAME = "LoginPrefs" private const val PREF_EMAIL = "email" private const val PREF_PASSWORD = "password" private const val PREF_REMEMBER_ME = "rememberMe" @Composable fun LoginScreen(navController: NavController) { val context = LocalContext.current val sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) var passwordVisibility by remember { mutableStateOf(false) } var email by remember { mutableStateOf(sharedPreferences.getString(PREF_EMAIL, "") ?: "") } var password by remember { mutableStateOf(sharedPreferences.getString(PREF_PASSWORD, "") ?: "") } var rememberMe by remember { mutableStateOf(sharedPreferences.getBoolean(PREF_REMEMBER_ME, false)) } fun updateRememberMeState(value: Boolean) { rememberMe = value sharedPreferences.edit().putBoolean(PREF_REMEMBER_ME, value).apply() } var isLoading by remember { mutableStateOf(false) } // Enable the button only when all fields are filled var isButtonEnabled by remember { mutableStateOf(false) } // Validation checks for email and password fields // Enable the button only when all fields are filled if (email.isNotEmpty() && password.isNotEmpty()) { isButtonEnabled = true } else { isButtonEnabled = false } val emailError = remember { mutableStateOf<String?>(null) } val passwordError = remember { mutableStateOf<String?>(null) } fun validateFields(): Boolean { var isValid = true // Email validation if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { Toast.makeText(context, "Invalid email address", Toast.LENGTH_SHORT).show() // emailError.value = "Invalid email address" isValid = false } else { emailError.value = null } // Password validation if (password.isEmpty()) { Toast.makeText(context, "Password cannot be empty", Toast.LENGTH_SHORT).show() // passwordError.value = "Password cannot be empty" isValid = false } else { passwordError.value = null } return isValid } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "pic", modifier = Modifier .padding(10.dp) .size(100.dp), contentScale = ContentScale.FillWidth ) Text( text = "Welcome to Discover", fontSize = 30.sp, fontWeight = FontWeight.Bold ) OutlinedTextField( value = email, onValueChange = { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text("Password") }, modifier = Modifier.fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), trailingIcon = { IconButton(onClick = { passwordVisibility = !passwordVisibility }) { val eyeIcon: ImageVector = if (passwordVisibility) ImageVector.vectorResource(id = R.drawable.ic_eye_off) else ImageVector.vectorResource(id = R.drawable.ic_eye) Icon( imageVector = eyeIcon, contentDescription = "Toggle password visibility" ) } }, visualTransformation = if (passwordVisibility) { VisualTransformation.None } else { PasswordVisualTransformation() } ) Row( modifier = Modifier .fillMaxWidth() .padding(top = 20.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = rememberMe, onCheckedChange = { updateRememberMeState(it) }, modifier = Modifier .padding(end = 8.dp) .size(24.dp) ) Text("Remember me") } Text( text = "Forget password", color = Color.Blue, textDecoration = TextDecoration.Underline, modifier = Modifier.clickable { navController.navigate("ForgetPassword") } ) } Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { if (validateFields()) { isLoading = true val auth = Firebase.auth auth.signInWithEmailAndPassword(email, password).addOnCompleteListener { isLoading = false if (it.isSuccessful) { if (rememberMe) { sharedPreferences.edit { putString(PREF_EMAIL, email) putString(PREF_PASSWORD, password) } } else { sharedPreferences.edit { remove(PREF_EMAIL) remove(PREF_PASSWORD) } } //navController.navigate("swipeAblePages") val intent = Intent(context, HomeActivity::class.java) context.startActivity(intent) } }.addOnFailureListener { Toast.makeText(context, it.message, Toast.LENGTH_SHORT).show() } } }, modifier = Modifier .fillMaxWidth() .height(58.dp) .padding(horizontal = 16.dp), colors = ButtonDefaults.buttonColors(Color(0xFF0FA3E2)), enabled = isButtonEnabled // Enable button only when all fields are filled ) { if (isLoading) { CircularProgressIndicator(color = Color.White) } else { Text("Login", color = Color.White, fontSize = 16.sp) } } Spacer(modifier = Modifier.height(16.dp)) Row { Text("Don't have an account? ") Text( text = "Sign up", color = Color.Blue, textDecoration = TextDecoration.Underline, modifier = Modifier.clickable { navController.navigate("Signup") } ) } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/LoginScreen.kt
1000810182
package com.example.splashscreencompose.retrofit import com.example.splashscreencompose.api.TravelApi import com.example.splashscreencompose.utils.Constants.BASE_URL_TRAVEL import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitInstance { private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private val retrofit by lazy { Retrofit.Builder() .baseUrl(BASE_URL_TRAVEL) .addConverterFactory(GsonConverterFactory.create()) .build() } val api: TravelApi by lazy { retrofit.create(TravelApi::class.java) } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/retrofit/RetrofitInstance.kt
1195792672
import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedDispatcherOwner import androidx.activity.OnBackPressedCallback import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.sp import androidx.navigation.NavController @Composable fun Home(navController: NavController) { var showDialog by remember { mutableStateOf(false) } BackHandler { // Intercept back button press showDialog = true } Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text(text = "Home Screen", fontSize = 44.sp) } if (showDialog) { ExitConfirmationDialog( onConfirmExit = { showDialog = false android.os.Process.killProcess(android.os.Process.myPid()) }, onCancel = { showDialog = false } ) } } @Composable fun ExitConfirmationDialog( onConfirmExit: () -> Unit, onCancel: () -> Unit ) { AlertDialog( onDismissRequest = { onCancel() }, title = { Text("Exit Confirmation") }, text = { Text("Are you sure you want to exit the app?") }, confirmButton = { Button( onClick = { onConfirmExit() }, ) { Text("Exit") } }, dismissButton = { Button( onClick = { onCancel() }, ) { Text("Cancel") } } ) }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/Home.kt
2338794018
package com.example.splashscreencompose import android.content.Context import android.util.Log import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextDecoration import androidx.navigation.NavController import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase @Composable fun ForgetPassword(navController: NavController) { var email by remember { mutableStateOf("") } val context = LocalContext.current Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "pic", Modifier .padding(10.dp) .size(100.dp), contentScale = ContentScale.FillWidth, ) Text( text = "Forget Password", fontSize = 30.sp, fontWeight = FontWeight.Bold ) Text( text = "Welcome to Discover", fontSize = 25.sp, fontWeight = FontWeight.Light ) OutlinedTextField( value = email, onValueChange = { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { forgetPass(navController, context, email) }, modifier = Modifier .fillMaxWidth() .height(48.dp) .padding(horizontal = 16.dp), colors = ButtonDefaults.buttonColors(Color(0xFF0FA3E2)) ) { Text("Request Code", color = Color.White) } } } fun forgetPass(navController: NavController,context: Context, email: String) { Firebase.auth.sendPasswordResetEmail(email).addOnCompleteListener { if (it.isSuccessful) { Toast.makeText(context, "Link send to this email", Toast.LENGTH_SHORT).show() Log.d("lava", "forgetPass: ${it.exception}") navController.navigate("Login") } }.addOnFailureListener { } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/ForgetPasword.kt
2970443030
package com.example.splashscreencompose.gesture import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.AnchoredDraggableState import androidx.compose.foundation.gestures.DraggableAnchors import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.anchoredDraggable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PageSize import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState 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.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.navigation.NavController import coil.compose.rememberImagePainter import com.example.splashscreencompose.R import com.example.splashscreencompose.utils.LocalFileProvider.fetchLocalImages import com.example.splashscreencompose.utils.LocalImages import com.google.accompanist.pager.ExperimentalPagerApi import kotlin.math.roundToInt @Composable fun GalleryScreen(navController: NavController) { val context = LocalContext.current val permissionState = rememberPermissionState() val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_IMAGES } else { Manifest.permission.READ_EXTERNAL_STORAGE } val requestPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> permissionState.value = if (isGranted) PermissionState.Granted else PermissionState.Denied } Log.d("permissionValue","started: ${permissionState.value}") Box( modifier = Modifier .fillMaxSize() ) { when (permissionState.value) { PermissionState.Granted -> { Log.d("permissionValue","Granted: ${permissionState.value}") val images = fetchLocalImages(context) if (images.isNotEmpty()) { ImageGrid(images, navController) Log.d("Uri", "url: ${images.first().url} Uri: ${Uri.parse(images.first().url)}") } else { Text("No images found") } } PermissionState.Denied -> { Log.d("permissionValue","Denied: ${permissionState.value}") // Text("Permission denied") PermissionRequestButton(permissionState) } else -> { Log.d("permissionValue","Else: ${permissionState.value}") LaunchedEffect(permissionState) { requestPermissionLauncher.launch(permission) } } // PermissionRequestButton(permissionState) } } } @Composable fun ImageGrid(images: List<LocalImages>, navController: NavController) { LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 128.dp)) { items(images) { photo -> GalleryImage(imageUri = Uri.parse(photo.url)) { navController.navigate(route = "imageDetail/${photo.id}") } } } } @Composable fun GalleryImage(imageUri: Uri ,shape: Shape = RoundedCornerShape(8.dp), click: () -> Unit) { Image( painter = rememberImagePainter(imageUri), contentDescription = null, modifier = Modifier .padding(4.dp) .size(100.dp) .clip(shape) .clickable(onClick = click), contentScale = ContentScale.Crop // ) } @Preview(showBackground = true) @Composable fun PreviewGalleryImage() { // GalleryImage(Uri.parse("https://fastly.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI")) } @Preview(showBackground = true) @Composable fun PreviewGalleryScreen() { // Dummy list of images for preview val images = listOf( LocalImages( 1, "Image 1", "content://media/external/images/media/1", 100F, "2022-01-01", "image/jpeg" ), LocalImages( 2, "Image 2", "content://media/external/images/media/2", 150F, "2022-01-02", "image/jpeg" ), LocalImages( 3, "Image 3", "content://media/external/images/media/3", 200F, "2022-01-03", "image/jpeg" ) ) // GalleryScreen() } enum class PermissionState { Granted, Denied, Unknown } @Composable fun rememberPermissionState(): MutableState<PermissionState> { val context = LocalContext.current val permissionState = remember { mutableStateOf(PermissionState.Unknown) } val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_IMAGES } else { Manifest.permission.READ_EXTERNAL_STORAGE } DisposableEffect(context) { val permissionStatus = ContextCompat.checkSelfPermission( context, permission ) permissionState.value = if (permissionStatus == PackageManager.PERMISSION_GRANTED) { PermissionState.Granted } else { PermissionState.Unknown } onDispose { } } return permissionState } @Composable fun MutableState<PermissionState>.requestPermission(context: Context) { val requestPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> value = if (isGranted) PermissionState.Granted else PermissionState.Denied } val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_IMAGES } else { Manifest.permission.READ_EXTERNAL_STORAGE } requestPermissionLauncher.launch(permission) } @Composable fun FullScreenImage(url: Long) { Log.d("fHd", "FullScreenImage: $url") val imageList = fetchLocalImages(LocalContext.current) var uri: Uri?=null imageList.forEach { if (it.id ==url){ uri = Uri.parse(it.url) } } uri?.let { ImageWithZoom(it) } } @OptIn(ExperimentalFoundationApi::class) @Composable fun ImageWithZoom(uri: Uri) { val density = LocalDensity.current val state = remember { AnchoredDraggableState( initialValue = DragAnchors.Start, anchors = DraggableAnchors { DragAnchors.Start at 0f DragAnchors.End at 1000f }, positionalThreshold = { distance: Float -> distance * 0.5f }, velocityThreshold = { with(density) { 100.dp.toPx() } }, animationSpec = tween(), ) } var scale by remember { mutableStateOf(1f) } var offset by remember { mutableStateOf(Offset(0f, 0f)) } Image( painter = rememberImagePainter(uri), contentDescription = null, modifier = Modifier .pointerInput(Unit) { detectTransformGestures { _, pan, zoom, _ -> // Update the scale based on zoom gestures. scale *= zoom // Limit the zoom levels within a certain range (optional). scale = scale.coerceIn(0.5f, 3f) // Update the offset to implement panning when zoomed. offset = if (scale == 1f) Offset(0f, 0f) else offset + pan } } .graphicsLayer( scaleX = scale, scaleY = scale, translationX = offset.x, translationY = offset.y ) .offset { IntOffset( x = state .requireOffset() .roundToInt(), y = 0 ) } .anchoredDraggable(state = state, orientation = Orientation.Horizontal) ) } @Composable fun PermissionRequestButton(permissionState: MutableState<PermissionState>) { val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_IMAGES } else { Manifest.permission.READ_EXTERNAL_STORAGE } val requestPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> permissionState.value = if (isGranted) PermissionState.Granted else PermissionState.Denied } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Permission is Required for images", fontSize = 20.sp, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(20.dp)) Button( onClick = { requestPermissionLauncher.launch(permission) }, modifier = Modifier .fillMaxWidth() .wrapContentSize() .padding(horizontal = 16.dp), colors = ButtonDefaults.buttonColors(Color(0xFF0FA3E2)) ) { Text("Request Permission") } } } enum class DragAnchors { Start, End, } @OptIn(ExperimentalFoundationApi::class) @Composable fun SwipeAblePages() { val images = listOf( R.drawable.image, R.drawable.image2, R.drawable.image3 ) val pagerState = rememberPagerState { images.size} Box( modifier = Modifier.fillMaxSize() ) { HorizontalPager( state = pagerState, key = { images[it]}, pageSize = PageSize.Fill ) { index -> Image( painter = painterResource(images[index]), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier .fillMaxSize() ) } } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/gesture/AnchorDragableDemo.kt
1161239238
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Small( val height: String, val url: String, val width: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Small.kt
1779904298
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Images( val large: Large, val medium: Medium, val original: Original, val small: Small, val thumbnail: Thumbnail ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Images.kt
1629378216
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class AvatarX( val large: LargeXX, val small: SmallXX ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/AvatarX.kt
219137766
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Original( val height: String, val url: String, val width: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Original.kt
2433623772
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Contributions( val attraction_reviews: String, val badges_count: String, val helpful_votes: String, val hotel_reviews: String, val photos_count: String, val restaurant_reviews: String, val review_city_count: String, val reviews: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Contributions.kt
3547120642
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Large( val height: String, val url: String, val width: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Large.kt
1741860425
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Photo( val caption: String, val helpful_votes: String, val id: String, val images: Images, val is_blessed: Boolean, val locations: List<Location>, val published_date: String, val uploaded_date: String, val user: User ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Photo.kt
712139486
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Location( val id: String, val intent_url: String, val name: String, val parent_location_id: Int, val web_url: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Location.kt
3497790049
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Paging( val next: String, val previous: Any, val results: String, val skipped: String, val total_results: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Paging.kt
234768470
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Data( val helpful_votes: String, val id: String, val lang: String, val location_id: String, val machine_translatable: Boolean, val machine_translated: Boolean, val owner_response: Any, val photos: List<Photo?>, val published_date: String, val published_platform: String, val rating: String, val subratings: List<Any>, val text: String, val title: String, val travel_date: String, val type: String, val url: String, val user: UserX ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Data.kt
1030925464
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class LargeXX( val url: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/LargeXX.kt
721498738
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class ImagesX( val large: Large, val medium: Medium, val original: Original, val small: Small, val thumbnail: Thumbnail ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/ImagesX.kt
2756842964
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class SmallXX( val url: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/SmallXX.kt
448817235
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Results( val `data`: List<Data>, val paging: Paging ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Results.kt
3000869822
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class UserLocation( val id: String, val name: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/UserLocation.kt
3387629368
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class User( val avatar: Avatar, val member_id: String, val type: String, val user_id: String, val username: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/User.kt
3798194763
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Thumbnail( val height: String, val url: String, val width: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Thumbnail.kt
3896903282
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Avatar( val caption: String, val helpful_votes: String, val id: String, val images: ImagesX, val is_blessed: Boolean, val published_date: String, val uploaded_date: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Avatar.kt
3614763036
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class UserX( val avatar: AvatarX, val contributions: Contributions, val created_time: String, val first_name: String, val last_initial: String, val link: String, val locale: String, val member_id: String, val name: String, val points: String, val reviewer_type: Any, val type: String, val user_id: String, val user_location: UserLocation, val username: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/UserX.kt
4191313028
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class TravelResponse( val msg: Any, val results: Results, val status: Int ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/TravelResponse.kt
2045864468
package com.example.splashscreencompose.travelResponse import java.io.Serializable data class Medium( val height: String, val url: String, val width: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/travelResponse/Medium.kt
3172342623
package com.example.splashscreencompose import android.app.Application import androidx.room.Room import androidx.room.RoomDatabase import com.example.splashscreencompose.database.AppDatabase import com.google.firebase.FirebaseApp class SplashScreenCompose: Application() { companion object { lateinit var database: AppDatabase } override fun onCreate() { super.onCreate() FirebaseApp.initializeApp(this) database = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "TravelSnapDB") .fallbackToDestructiveMigration() .build() } }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/SplashScreenCompose.kt
3380468780
package com.example.splashscreencompose.model import java.io.Serializable data class TravelModelDemo( val image: String, val title: String, val description: String, val rating: String ): Serializable
Travel-Snap/app/src/main/java/com/example/splashscreencompose/model/TravelModelDemo.kt
4071933835
package com.example.splashscreencompose.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ReviewRequest( @Json(name = "location_id") val location_id: String, @Json(name = "language") val language: String, @Json(name = "currency") val currency: String )
Travel-Snap/app/src/main/java/com/example/splashscreencompose/model/ReviewRequest.kt
309597103
@file:Suppress("DEPRECATION") package com.example.splashscreencompose import android.content.Context import android.preference.PreferenceManager import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement 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.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.example.splashscreencompose.utils.Constants.PREF_FIRST_TIME_OPENING_ONBOARDING import kotlinx.coroutines.delay @Composable fun SplashScreen(navController: NavController, context: MainActivity) { val alpha = remember{ Animatable(0f) } LaunchedEffect(key1 = true) { alpha.animateTo(1f, animationSpec = tween(4000) ) delay(5000) if (isFirstTimeOpening(context)) { // Open OnBoarding screens if it's the first time opening navController.navigate("Onboarding") setFirstTimeOpening(context, false) } else { // Proceed without opening OnBoarding navController.navigate("Login") } /*if (onBoardingIsFinished(context = context)) { navController.popBackStack() navController.navigate("Home") } else { navController.popBackStack() navController.navigate("Onboarding") } navController.popBackStack() navController.navigate("Onboarding")*/ } Column (modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally){ LoaderAnimation( modifier=Modifier.size(400.dp), anim=R.raw.splash ) Spacer(modifier = Modifier.height(25.dp)) Text(text = "Travel Snap", modifier = Modifier.alpha(alpha.value), fontSize = 52.sp, fontWeight = FontWeight.Bold, ) } } @Composable fun LoaderAnimation(modifier: Modifier, anim: Int) { val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(anim)) LottieAnimation(composition = composition, iterations = LottieConstants.IterateForever, modifier = modifier) } private fun onBoardingIsFinished(context: MainActivity): Boolean { val sharedPreferences = context.getSharedPreferences("onBoarding", Context.MODE_PRIVATE) return sharedPreferences.getBoolean("isFinished", false) } fun isFirstTimeOpening(context: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(context).getBoolean( PREF_FIRST_TIME_OPENING_ONBOARDING, true) } fun setFirstTimeOpening(context: Context, isFirstTimeOpening: Boolean) { PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean( PREF_FIRST_TIME_OPENING_ONBOARDING, isFirstTimeOpening).apply() }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/SplashScreen.kt
3223195135
package com.example.splashscreencompose.api import com.example.splashscreencompose.model.ReviewRequest import com.example.splashscreencompose.travelResponse.TravelResponse import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Header import retrofit2.http.POST interface TravelApi { @POST("reviews") suspend fun getReviews( @Header("X-RapidAPI-Key") apiKey: String, @Body requestBody: ReviewRequest ): Response<TravelResponse> }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/api/TravelApi.kt
2661205349
package com.example.splashscreencompose import android.content.Context import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.PagerState import com.google.accompanist.pager.rememberPagerState import kotlinx.coroutines.launch @OptIn(ExperimentalPagerApi::class) @Composable fun OnboardingScreen(navController: NavHostController, context: MainActivity) { val animations = listOf( R.raw.intro1, R.raw.intro2, R.raw.intro3 ) val titles = listOf( "Explore the Skies", "Seaside Escapes", "Garden Getaways" ) val descriptions = listOf( "Discover unbeatable deals on air travel to destinations around the globe.", "Embark on unforgettable journeys to renowned beachfront destinations.", "Experience the finest city and garden tours right at your fingertips with our app." ) val pagerState = rememberPagerState( pageCount = animations.size ) Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { HorizontalPager( state = pagerState, Modifier.wrapContentSize() ) { currentPage -> Column( Modifier .wrapContentSize() .padding(26.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(animations[currentPage])) LottieAnimation( composition = composition, iterations = LottieConstants.IterateForever, modifier = Modifier.size(400.dp) ) Text( text = titles[currentPage], textAlign = TextAlign.Center, fontSize = 44.sp, fontWeight = FontWeight.Bold ) Text( text = descriptions[currentPage], Modifier.padding(top = 45.dp), textAlign = TextAlign.Center, fontSize = 20.sp ) } } PageIndicator( pageCount = animations.size, currentPage = pagerState.currentPage, modifier = Modifier.padding(60.dp) ) } ButtonsSection( pagerState = pagerState, navController = navController, context = context ) } @OptIn(ExperimentalPagerApi::class) @Composable fun ButtonsSection(pagerState: PagerState, navController: NavHostController, context: MainActivity) { val scope = rememberCoroutineScope() Box(modifier = Modifier .fillMaxSize() .padding(30.dp)){ if (pagerState.currentPage != 2){ Text(text = "Next", modifier = Modifier .align(Alignment.BottomEnd) .clickable { scope.launch { val nextPage = pagerState.currentPage + 1 pagerState.scrollToPage(nextPage) } }, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = Color.Black ) Text(text = "Back", modifier = Modifier .align(Alignment.BottomStart) .clickable { scope.launch { val prevPage = pagerState.currentPage - 1 if (prevPage >= 0) { pagerState.scrollToPage(prevPage) } } }, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = Color.Black ) }else{ OutlinedButton(onClick = { onBoardingIsFinished(context = context) navController.popBackStack() navController.navigate("Login") }, modifier = Modifier .fillMaxWidth() .align(Alignment.BottomCenter) , colors = ButtonDefaults.buttonColors(containerColor = Color(0x25E92F1E)) ) { Text( text = "Get Started", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = Color.Black ) } } } } @Composable fun PageIndicator(pageCount: Int, currentPage: Int, modifier: Modifier) { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = modifier ) { repeat(pageCount){ IndicatorSingleDot(isSelected = it == currentPage ) } } } @Composable fun IndicatorSingleDot(isSelected: Boolean) { val width = animateDpAsState(targetValue = if (isSelected) 35.dp else 15.dp, label = "") Box(modifier = Modifier .padding(2.dp) .height(15.dp) .width(width.value) .clip(CircleShape) .background(if (isSelected) Color(0xFFE92F1E) else Color(0x25E92F1E)) ) } private fun onBoardingIsFinished(context: MainActivity) { val sharedPreferences = context.getSharedPreferences("onBoarding", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putBoolean("isFinished", true) editor.apply() }
Travel-Snap/app/src/main/java/com/example/splashscreencompose/OnboardingScreen.kt
941180171
package mx.edu.potros.theguessnumber 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("mx.edu.potros.theguessnumber", appContext.packageName) } }
Asignacion3TheGuessNumber/TheGuessNumber/app/src/androidTest/java/mx/edu/potros/theguessnumber/ExampleInstrumentedTest.kt
557137741
package mx.edu.potros.theguessnumber 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) } }
Asignacion3TheGuessNumber/TheGuessNumber/app/src/test/java/mx/edu/potros/theguessnumber/ExampleUnitTest.kt
3195816779
package mx.edu.potros.theguessnumber import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import kotlin.random.Random class MainActivity : AppCompatActivity() { private var minValue = 0 private var maxValue = 100 private var num: Int = 0 private var won = false private lateinit var title: TextView private lateinit var guessings: TextView private lateinit var down: Button private lateinit var up: Button private lateinit var generate: Button private lateinit var guessed: Button private lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = findViewById(R.id.title) guessings = findViewById(R.id.guessings) down = findViewById(R.id.down) up = findViewById(R.id.up) generate = findViewById(R.id.generate) guessed = findViewById(R.id.guessed) imageView = findViewById(R.id.imageView) generate.setOnClickListener { resetGame() generate.visibility = View.INVISIBLE guessed.visibility = View.VISIBLE } down.setOnClickListener { handleGuess(false) } guessed.setOnClickListener { if (!won) { guessings.text = getString(R.string.guess_result, num) guessed.text = getString(R.string.play_again) won = true } else { resetGame() } } up.setOnClickListener { handleGuess(true) } } private fun resetGame() { minValue = 0 maxValue = 100 num = Random.nextInt(minValue, maxValue) guessings.text = getString(R.string.tap_to_generate) imageView.setImageResource(R.drawable.ic_eyeball) won = false } private fun handleGuess(isHigher: Boolean) { if (!won) { if (isHigher) { minValue = num } else { maxValue = num } if (isGuessingValid()) { num = Random.nextInt(minValue, maxValue) guessings.text = num.toString() } else { guessings.text = getString(R.string.lost_message) } } } private fun isGuessingValid(): Boolean { return minValue < maxValue } }
Asignacion3TheGuessNumber/TheGuessNumber/app/src/main/java/mx/edu/potros/theguessnumber/MainActivity.kt
1891738165
package com.example.todolist 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.todolist", appContext.packageName) } }
Basic-To-do-App/app/src/androidTest/java/com/example/todolist/ExampleInstrumentedTest.kt
534842961
package com.example.todolist import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Basic-To-do-App/app/src/test/java/com/example/todolist/ExampleUnitTest.kt
1029007278
package com.example.todolist import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import com.example.todolist.databinding.ActivityMainBinding /*import kotlinx.android.synthetic.main.activity_main.btnAddTodo import kotlinx.android.synthetic.main.activity_main.btnDeleteDoneTodos import kotlinx.android.synthetic.main.activity_main.etTodoTitle import kotlinx.android.synthetic.main.activity_main.rvTodoItems*/ class MainActivity : AppCompatActivity() { private lateinit var todoAdapter: TodoAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) todoAdapter = TodoAdapter(mutableListOf()) binding.rvTodoItems.adapter = todoAdapter binding.rvTodoItems.layoutManager = LinearLayoutManager(this) binding.btnAddTodo.setOnClickListener { val todoTitle = binding.etTodoTitle.text.toString() if(todoTitle.isNotEmpty()){ val todo = Todo(todoTitle) todoAdapter.addTodo(todo) binding.etTodoTitle.text.clear() } } binding.btnDeleteDoneTodos.setOnClickListener { todoAdapter.deleteDoneTodos() } } }
Basic-To-do-App/app/src/main/java/com/example/todolist/MainActivity.kt
2451379561
package com.example.todolist data class Todo(val title: String, var isChecked: Boolean = false)
Basic-To-do-App/app/src/main/java/com/example/todolist/Todo.kt
198537546
package com.example.todolist import android.graphics.Paint.STRIKE_THRU_TEXT_FLAG import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.todolist.databinding.ItemTodoBinding class TodoAdapter ( private val todos: MutableList<Todo> ): RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() { class TodoViewHolder(private val binding: ItemTodoBinding): RecyclerView.ViewHolder(binding.root) { fun bind(todo: Todo) { binding.tvTodoTitle.text = todo.title binding.cbDone.isChecked = todo.isChecked toggleStrikeThrough(binding.tvTodoTitle, todo.isChecked) binding.cbDone.setOnCheckedChangeListener { _, isChecked -> toggleStrikeThrough(binding.tvTodoTitle, isChecked) todo.isChecked = !todo.isChecked } } private fun toggleStrikeThrough(tvTodoTitle: TextView, isChecked: Boolean) { if(isChecked){ tvTodoTitle.paintFlags = tvTodoTitle.paintFlags or STRIKE_THRU_TEXT_FLAG }else{ tvTodoTitle.paintFlags = tvTodoTitle.paintFlags and STRIKE_THRU_TEXT_FLAG.inv() } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder { val binding = ItemTodoBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return TodoViewHolder(binding) } override fun onBindViewHolder(holder: TodoViewHolder, position: Int) { val curTodo = todos[position] holder.bind(curTodo) } override fun getItemCount(): Int { return todos.size } fun addTodo(todo: Todo) { todos.add(todo) notifyItemInserted(todos.size - 1) } fun deleteDoneTodos() { todos.removeAll{todo -> todo.isChecked } notifyDataSetChanged() } }
Basic-To-do-App/app/src/main/java/com/example/todolist/TodoAdapter.kt
4234873261
package com.example.sozlukuygulamasideneme 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.sozlukuygulamasideneme", appContext.packageName) } }
dictonaryAppWithRetrofit/SozlukUygulamasiRetrofit/app/src/androidTest/java/com/example/sozlukuygulamasideneme/ExampleInstrumentedTest.kt
4255984296
package com.example.sozlukuygulamasideneme 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) } }
dictonaryAppWithRetrofit/SozlukUygulamasiRetrofit/app/src/test/java/com/example/sozlukuygulamasideneme/ExampleUnitTest.kt
489303102
package com.example.sozlukuygulamasideneme import androidx.appcompat.app.AppCompatActivity import android.os.Bundle //import android.telecom.Call import android.util.Log import android.view.Menu import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import com.example.sozlukuygulamasideneme.databinding.ActivityMainBinding import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() , SearchView.OnQueryTextListener{ private lateinit var ulas : ActivityMainBinding private lateinit var kelimelistesi: ArrayList<Kelimeler> private lateinit var adapter : KelimelerAdapter private lateinit var kdi : KelimelerDaoInterface override fun onCreate(savedInstanceState: Bundle?) { ulas = ActivityMainBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(ulas.root) ulas.toolbar.title="Sözlük Uygulaması" setSupportActionBar(ulas.toolbar) ulas.rv.setHasFixedSize(true) ulas.rv.layoutManager = LinearLayoutManager(this) kdi = ApiUtils.getKelimelerDaoInterface() tum_kelimeler() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_arama,menu) val item = menu.findItem(R.id.action_ara) val searchView = item.actionView as SearchView searchView.setOnQueryTextListener(this) return super.onCreateOptionsMenu(menu) } override fun onQueryTextSubmit(query: String): Boolean { kelime_ara(query) Log.e("aranan yer",query) return true } override fun onQueryTextChange(newText: String): Boolean { kelime_ara(newText) return true } fun tum_kelimeler(){ kdi.tumKelimeler().enqueue(object : Callback<KelimelerCevap>{ override fun onResponse(call: Call<KelimelerCevap>?, response: Response<KelimelerCevap>?) { if(response != null){ val liste = response.body().kelimeler adapter = KelimelerAdapter(this@MainActivity,liste) ulas.rv.adapter = adapter } } override fun onFailure(call: Call<KelimelerCevap>?, t: Throwable?) { } }) } fun kelime_ara(aramaKelime : String){ kdi.kelimeAra(aramaKelime).enqueue(object : Callback<KelimelerCevap>{ override fun onResponse(call: Call<KelimelerCevap>?, response: Response<KelimelerCevap>?) { if(response != null){ val liste = response.body().kelimeler adapter = KelimelerAdapter(this@MainActivity,liste) ulas.rv.adapter = adapter } } override fun onFailure(call: Call<KelimelerCevap>?, t: Throwable?) { } }) } }
dictonaryAppWithRetrofit/SozlukUygulamasiRetrofit/app/src/main/java/com/example/sozlukuygulamasideneme/MainActivity.kt
347745334
package com.example.sozlukuygulamasideneme import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST interface KelimelerDaoInterface { @GET("sozlukUygulamasi/tum_kelimeler.php") fun tumKelimeler() : Call<KelimelerCevap> @POST("sozlukUygulamasi/kelime_ara.php") @FormUrlEncoded fun kelimeAra(@Field("ingilizce") ingilizce:String): Call<KelimelerCevap> }
dictonaryAppWithRetrofit/SozlukUygulamasiRetrofit/app/src/main/java/com/example/sozlukuygulamasideneme/KelimelerDaoInterface.kt
2363122484