content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
MP_Tugas02/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MP_Tugas02/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
MP_Tugas02/app/src/main/java/com/example/myapplication/ui/theme/Color.kt
2513741509
package com.example.myapplication.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MyApplicationTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
MP_Tugas02/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt
196007232
package com.example.myapplication.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
MP_Tugas02/app/src/main/java/com/example/myapplication/ui/theme/Type.kt
3481532690
package com.example.myapplication import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import com.example.myapplication.ui.theme.MyApplicationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Dillon Carol Heatubun Bonay") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Box( modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { Box( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.primary), contentAlignment = Alignment.Center ) { Text( text = "Halo $name! How are you ?", fontSize = 24.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyApplicationTheme { Greeting("Dillon Carol Heatubun Bonay") } }
MP_Tugas02/app/src/main/java/com/example/myapplication/MainActivity.kt
3305576967
import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.window.Window import androidx.compose.ui.window.application @Composable @Preview fun App() { var text by remember { mutableStateOf("Hello, World!") } MaterialTheme { Button(onClick = { text = "Hello, Desktop!" }) { Text(text) } } } fun main() = application { Window(onCloseRequest = ::exitApplication) { App() } }
ekstrakto/src/main/kotlin/Main.kt
440970822
import kotlinx.css.* import styled.StyleSheet object GlobalStyles : StyleSheet("GlobalStyles", isStatic = true) { private val styles = CSSBuilder(allowClasses = false).apply { body { fontFamily = "Rajdhani, sans-serif" } h1 { fontSize = 3.75.rem } margin(bottom = 0.px, top = 0.px) p { color = hex(0x62676c) fontSize = 1.2.rem } a { color = hex(0x3884ff) fontSize = 1.2.rem } } fun applyGlobalStyle() { styled.injectGlobal(styles.toString()) } }
rterwgtdf/src/main/ui/src/main/kotlin/GlobalStyles.kt
1546127131
import kotlinx.css.* import kotlinx.css.properties.TextDecoration import styled.StyleSheet object Styles : StyleSheet("Styles", isStatic = true) { val container by css { width = 100.pct display = Display.flex flexDirection = FlexDirection.column alignItems = Align.center textAlign = TextAlign.center padding(top = 0.px); } val logo by css { height = 300.px; width = 300.px; } val usefulLinks by css { alignItems = Align.center; display = Display.flex; flexDirection = FlexDirection.row; cursor = Cursor.pointer; } val usefulMinicard by css { display = Display.flex; alignItems = Align.center; justifyContent = JustifyContent.center; borderColor = rgba(150, 121, 255, 0.377) borderWidth = 1.px borderStyle = BorderStyle.solid borderRadius = 10.px; height = 80.px; width = 350.px; padding(25.px); margin(15.px) hover { backgroundColor = hex(0x3884ff) } } val link by css { alignItems = Align.center; color = Color.black; display = Display.flex; justifyContent = JustifyContent.center; textDecoration = TextDecoration.none; } val arrowIcon by css { height = 30.px; margin(left = 10.px) } }
rterwgtdf/src/main/ui/src/main/kotlin/Styles.kt
1530066974
import kotlinx.html.DIV import react.RBuilder import react.RComponent import react.RProps import react.RState import react.dom.* import styled.StyledDOMBuilder import styled.css import styled.styledDiv import styled.styledImg external val EquoCommService : EquoComm val cards = listOf( MinicardData( "Development guides", "https://docs.equo.dev/sdk/1.0.x/developing/getting-started/creating.html", null ), MinicardData( "Web UI frameworks Development", "https://docs.equo.dev/sdk/1.0.x/developing/hot-reload.html", null ), MinicardData( "Javascript API documentation", "https://docs.equo.dev/sdk/1.0.x/index-api-javascript.html", null ), MinicardData("Java API documentation", "https://docs.equo.dev/sdk/1.0.x/index-api-java.html", null), MinicardData("Click me!", "") { minicard -> val comm = EquoCommService comm.on("MyKotlinEvent") { response -> console.log(response) minicard.setState(MinicardState(response = response)) } comm.send("MyEventHandler", "Message from the frontend") } ) @JsExport class MainPage(props: RProps) : RComponent<RProps, RState>(props) { override fun RBuilder.render() { styledDiv { css { +Styles.container } styledImg( alt = "logo equo", src = "https://sfo2.digitaloceanspaces.com/equo-cms/2020/08/28/5f495e535cda5Isotipo.png" ) { css { +Styles.logo } } h1 { +"Welcome to your first Equo App" } p { +"For a guide and recipes on how to configure / customize an Equo App, check out the " a( href = "https://docs.equo.dev", target = "_blank" ) { +"SDK Documentation" } } h2 { +"Useful Links" } generateCards() h2 { +"Ecosystem" } p { +"Learn Equo " a(href = "https://equo.dev", target = "_blank") { +"here!" } } } } private fun StyledDOMBuilder<DIV>.generateCards() { var i = 0 var minicardList: MutableList<MinicardData> = mutableListOf() cards.forEach { minicard -> minicardList.add(minicard) if (i++ % 2 == 1 || cards.size == i) { child(Minicard::class) { attrs { list = minicardList } } minicardList = mutableListOf() } } } }
rterwgtdf/src/main/ui/src/main/kotlin/MainPage.kt
3872382213
import kotlinx.html.js.onClickFunction import react.* import react.dom.attrs import styled.css import styled.styledA import styled.styledDiv import styled.styledImg data class MinicardData(val name: String, val link: String, val onSelect: ((Minicard) -> Unit)?) external interface MinicardProps : RProps { var list: List<MinicardData> } data class MinicardState(val response: String) : RState @JsExport class Minicard(props: MinicardProps) : RComponent<MinicardProps, MinicardState>(props) { init { state = MinicardState("") } override fun RBuilder.render() { styledDiv { css { +Styles.usefulLinks } props.list.forEach { currentProp -> styledDiv { css { +Styles.usefulMinicard } if (currentProp.onSelect == null) { styledA(href = currentProp.link, target = "_blank") { css { +Styles.link } +currentProp.name styledImg(alt = "arrow icon", src = "arrow-icon.png") { css { +Styles.arrowIcon } } } } else { styledDiv { css { +Styles.link } +currentProp.name } attrs { onClickFunction = { currentProp.onSelect.invoke(this@Minicard) } } } +state.response } } } } }
rterwgtdf/src/main/ui/src/main/kotlin/Minicard.kt
3722843043
@JsModule("@equo/comm") @JsNonModule external class EquoComm { fun send(actionId: String, payload: String?) fun on(actionId: String, callback: (result: String) -> Unit) }
rterwgtdf/src/main/ui/src/main/kotlin/equo/EquoComm.kt
1588819062
import react.dom.render import kotlinx.browser.document import kotlinx.browser.window fun main() { GlobalStyles.applyGlobalStyle() window.onload = { render(document.getElementById("root")) { child(MainPage::class) { } } } }
rterwgtdf/src/main/ui/src/main/kotlin/Client.kt
1185271758
package ghjhgjh import com.equo.application.api.IEquoApplication import com.equo.application.model.EquoApplicationBuilder import com.equo.dev.EquoApp import org.osgi.service.component.annotations.Component fun main(args: Array<String>) { EquoApp.launch() } @Component class GhjhgjhApplication : IEquoApplication { override fun buildApp(appBuilder: EquoApplicationBuilder?): EquoApplicationBuilder { return appBuilder!!.withUI("index.html").start(); } }
rterwgtdf/src/main/kotlin/ghjhgjh/GhjhgjhApplication.kt
3499893105
package ghjhgjh import com.equo.comm.api.ICommService import com.equo.comm.api.actions.IActionHandler import com.equo.comm.api.annotations.EventName import org.osgi.service.component.annotations.Component import org.osgi.service.component.annotations.Reference @Component class MyEventHandler : IActionHandler { @Reference private lateinit var commService: ICommService @EventName("MyEventHandler") fun myFirstEvent(payload: String): String { println("First event: $payload"); commService.send("MyKotlinEvent", "This is your first message received from Kotlin"); return payload } }
rterwgtdf/src/main/kotlin/ghjhgjh/MyEventHandler.kt
3632816676
package com.example.swipestore 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.swipestore", appContext.packageName) } }
SwipeStore/app/src/androidTest/java/com/example/swipestore/ExampleInstrumentedTest.kt
3422875789
package com.example.swipestore 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) } }
SwipeStore/app/src/test/java/com/example/swipestore/ExampleUnitTest.kt
2736461490
package com.example.swipestore.ui.uistates sealed class UiState { object Loading : UiState() data class Success<T>(val data: T) : UiState() data class Error(val message: String) : UiState() }
SwipeStore/app/src/main/java/com/example/swipestore/ui/uistates/UiState.kt
690350159
package com.example.swipestore.ui.uistates import com.example.swipestore.data.entities.Product data class ProductListUiState( val products: ArrayList<Product>, var uiState: UiState )
SwipeStore/app/src/main/java/com/example/swipestore/ui/uistates/ProductListUiState.kt
2555955444
package com.example.swipestore.ui.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel open class BaseViewModel<T> : ViewModel() { fun uiState(): LiveData<T> = uiState protected val uiState: MutableLiveData<T> = MutableLiveData() }
SwipeStore/app/src/main/java/com/example/swipestore/ui/viewmodels/BaseViewModel.kt
3417552098
package com.example.swipestore.ui.viewmodels import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.swipestore.data.entities.Product import com.example.swipestore.data.entities.ProductRequest import com.example.swipestore.data.repositories.ProductRepository import com.example.swipestore.data.repositories.Repository import com.example.swipestore.ui.uistates.UiState import kotlinx.coroutines.launch import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import java.io.File class ProductViewModel( val repository: Repository ): ViewModel() { private val TAG = ProductViewModel::class.simpleName private val _uiState: MutableLiveData<UiState> = MutableLiveData() private val _products: MutableLiveData<ArrayList<Product>?> = MutableLiveData() val uiState: LiveData<UiState> = _uiState val products: MutableLiveData<ArrayList<Product>?> = _products fun fetchProducts(){ viewModelScope.launch { if(repository is ProductRepository){ try{ _uiState.value = UiState.Loading val products = repository.fetchProducts() _products.value = products _uiState.value = UiState.Success(products) } catch (e: Exception) { _uiState.value = UiState.Error(e.message.toString()) } } } } fun createProduct(request: ProductRequest) { viewModelScope.launch { if(repository is ProductRepository){ try{ _uiState.value = UiState.Loading val response = repository.createProduct(request) _uiState.value = UiState.Success(response?.product_details) } catch (e: Exception) { _uiState.value = UiState.Error(e.message.toString()) } } } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/viewmodels/ProductViewModel.kt
1605048627
package com.example.swipestore.ui.di import com.example.swipestore.data.repositories.ProductRepository import com.example.swipestore.data.repositories.Repository import com.example.swipestore.data.services.AppDatabase import com.example.swipestore.data.services.ProductService import com.example.swipestore.data.services.RetrofitClient import com.example.swipestore.data.sources.LocalProductDataSource import com.example.swipestore.data.sources.RemoteProductDataSource import com.example.swipestore.ui.viewmodels.ProductViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.qualifier.named import org.koin.dsl.module val productModule = module { single{ RetrofitClient.getRetrofit() .create(ProductService::class.java) } single{ LocalProductDataSource(get()) } single{ RemoteProductDataSource(get()) } factory<Repository> { ProductRepository(get(), get()) } viewModel { ProductViewModel(get()) } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/di/ProductModule.kt
3626614390
package com.example.swipestore.ui.di import android.content.Context import androidx.room.Room import com.example.swipestore.data.services.AppDatabase import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module val roomDbModule = module { single { provideDatabase(androidApplication()) } single{ provideDao(get()) } } fun provideDatabase(context: Context) = run { Room.databaseBuilder(context, AppDatabase::class.java, "products") .allowMainThreadQueries() .fallbackToDestructiveMigration() .build() } fun provideDao(db: AppDatabase) = db.productDao()
SwipeStore/app/src/main/java/com/example/swipestore/ui/di/RoomDbModule.kt
644137604
package com.example.swipestore.ui.utils import android.content.BroadcastReceiver import android.content.Context import android.content.Intent class NetworkChangeReceiver(val onNetworkChange: (status: Boolean) -> Unit) : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val status: Int = NetworkUtil.getConnectivityStatusString(context) if (intent.action == "android.net.conn.CONNECTIVITY_CHANGE") { if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) { onNetworkChange(false) } else { onNetworkChange(true) } } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/utils/NetworkChangeListener.kt
4000832835
package com.example.swipestore.ui.utils import android.content.Context import android.net.ConnectivityManager object NetworkUtil { const val TYPE_WIFI = 1 const val TYPE_MOBILE = 2 const val TYPE_NOT_CONNECTED = 0 const val NETWORK_STATUS_NOT_CONNECTED = 0 const val NETWORK_STATUS_WIFI = 1 const val NETWORK_STATUS_MOBILE = 2 private fun getConnectivityStatus(context: Context): Int { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo if (null != activeNetwork) { if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE } return TYPE_NOT_CONNECTED } fun getConnectivityStatusString(context: Context): Int { val conn = getConnectivityStatus(context) var status = 0 if (conn == TYPE_WIFI) { status = NETWORK_STATUS_WIFI } else if (conn == TYPE_MOBILE) { status = NETWORK_STATUS_MOBILE } else if (conn == TYPE_NOT_CONNECTED) { status = NETWORK_STATUS_NOT_CONNECTED } return status } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/utils/NetworkUtil.kt
2460717461
package com.example.swipestore.ui.utils import android.app.Activity import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.ImageView import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.example.swipestore.R import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar object UiComponentUtils { fun showToast(context: Context, message: String) { Toast.makeText(context, message, Toast.LENGTH_LONG).show() } fun showCancelDialog(context: Context, onSheetDiscard: () -> Unit) { MaterialAlertDialogBuilder( context, R.style.ThemeOverlay_App_MaterialAlertDialog1 ) .setTitle("${context.getString(R.string.discard_changes)}?") .setMessage(context.getString(R.string.discard_detail_message)) .setNegativeButton(context.getString(R.string.cancel_btn)) { dialog, _ -> dialog.dismiss() } .setPositiveButton("Discard") { dialog, _ -> dialog.dismiss() onSheetDiscard() } .show() } fun showSnackBar(view: View, message: String){ Snackbar.make( view, message, Snackbar.LENGTH_SHORT ).show() } fun hideSoftKeyboard(view : View, activity: Activity) { if (view != null) { val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? imm!!.hideSoftInputFromWindow(view.windowToken, 0) } } fun loadImageFromUrl( context: Context, imageUrl: String, imageContainer: ImageView, defaultImageId: Int ){ if(imageUrl.isNullOrEmpty()){ imageContainer.setImageResource(defaultImageId) } else { Glide.with(context) .load(imageUrl) .diskCacheStrategy(DiskCacheStrategy.DATA) .centerCrop() .into(imageContainer) } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/utils/UiComponentUtils.kt
2233767374
package com.example.swipestore.ui.utils import android.app.Dialog import android.content.Context import android.view.Window import android.widget.TextView import com.example.swipestore.R object ProgressLoaderDialog { private var loader: Dialog? = null fun showLoader(context: Context, message: String) { if(loader?.isShowing == true) return loader = Dialog(context) loader?.requestWindowFeature(Window.FEATURE_NO_TITLE) loader?.setContentView(R.layout.layout_loader_dialog) loader?.window?.setBackgroundDrawableResource(android.R.color.transparent) loader?.setCancelable(false) val tvMessage = loader?.findViewById<TextView>(R.id.tv_message) tvMessage?.text = message loader?.show() } fun hideLoader() { if(loader?.isShowing == false) return loader?.dismiss() } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/utils/ProgressLoaderDialog.kt
2876380917
package com.example.swipestore.ui.screens import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.swipestore.R import com.example.swipestore.ui.viewmodels.ProductViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class ProductHostActivity : AppCompatActivity() { private val viewModel by viewModel<ProductViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_product_host) } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/screens/ProductHostActivity.kt
714173228
package com.example.swipestore.ui.screens import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Spinner import androidx.navigation.fragment.findNavController import com.example.swipestore.R import com.example.swipestore.data.entities.Product import com.example.swipestore.data.entities.ProductRequest import com.example.swipestore.databinding.FragmentCreateProductBinding import com.example.swipestore.ui.utils.ProgressLoaderDialog import com.example.swipestore.ui.utils.UiComponentUtils import com.example.swipestore.ui.uistates.UiState import com.example.swipestore.ui.viewmodels.ProductViewModel import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import org.koin.androidx.viewmodel.ext.android.viewModel import java.io.File import java.io.FileOutputStream class CreateProductFragment : BottomSheetDialogFragment() { private val binding by lazy { FragmentCreateProductBinding.inflate(layoutInflater) } private var productToUpload: Product? = null private var fileToUpload: File? = null private val viewmodel by viewModel<ProductViewModel>() private val navController by lazy { findNavController() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { isCancelable = false val sheetBehavior = BottomSheetBehavior.from(binding.bottomSheetCreateProduct) sheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setToolbar() setUpProductTypeDropdown() setUpViewListeners() } private fun setUpViewListeners() { binding.ivAdd.setOnClickListener{ pickImageFromGallery() } binding.btnAddProduct.setOnClickListener { UiComponentUtils.hideSoftKeyboard(it, requireActivity()) saveProduct() } viewmodel.uiState.observe(viewLifecycleOwner){ result -> when (result) { is UiState.Success<*> -> { ProgressLoaderDialog.hideLoader() val product = result.data as? Product if(product != null){ UiComponentUtils.showSnackBar(binding.root, "${product.name} added successfully") val direction = CreateProductFragmentDirections.actionCreateProductFragmentToProductListFragment() navController.navigate(direction) } else { ProgressLoaderDialog.hideLoader() UiComponentUtils.showSnackBar(binding.root, "Please try again, failed to upload the product..") dismiss() } } is UiState.Error -> { UiComponentUtils.showSnackBar(binding.root, "Please try again, failed to upload the product..") dismiss() } else -> { ProgressLoaderDialog.showLoader(requireContext(), "Uploading...") } } } } private fun setToolbar() { val toolbar = binding.customToolbar toolbar.toolbarIcBack.visibility = View.VISIBLE toolbar.toolbarTitle.text = resources.getText(R.string.toolbar_title_product_create) toolbar.toolbarIcBack.setOnClickListener{ val (productName, productType, _, productPrice, tax) = getProductFormData() if(isFormInProgress(productName, productType, productPrice, tax)){ UiComponentUtils.showCancelDialog(requireActivity()){ dismiss() } } else { dismiss() } } } private fun setUpProductTypeDropdown(){ val productTypeSpinner: Spinner = binding.ddProductType val productTypes = resources.getStringArray(R.array.spinner_items) val productTypeAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, productTypes) productTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) productTypeSpinner.adapter = productTypeAdapter } private fun saveProduct() { val product = getProductFormData() val (productName, productType, _, productPrice, tax) = product if(!isMandatoryAttributeFilled(productName, productType, productPrice, tax)){ UiComponentUtils.showToast(requireActivity(), "Please fill all mandatory fields") }else{ postProductData(product, fileToUpload) } } private fun isMandatoryAttributeFilled(productName: String, productType: String, productPrice: String, tax: String): Boolean { if(productName.isNullOrEmpty() || productType == "Select Product Type" || productPrice.isNullOrEmpty() || tax.isNullOrEmpty()){ return false } return true } private fun isFormInProgress(productName: String, productType: String, productPrice: String, tax: String): Boolean { if(productName.isNullOrEmpty() && (productType == "Select Product Type") && productPrice.isNullOrEmpty() && tax.isNullOrEmpty()){ return false } return true } private fun postProductData(product: Product, file: File?) { val request = getRequestParams(product, fileToUpload) viewmodel.createProduct(request) } private fun pickImageFromGallery(){ val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, REQUEST_PICK_IMAGE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { when (requestCode) { REQUEST_PICK_IMAGE -> { try { val selectedImageUri = data?.data selectedImageUri?.let { val bitmap = MediaStore.Images.Media.getBitmap( requireActivity().contentResolver, it ) val resizedBitmap = Bitmap.createScaledBitmap(bitmap, 240, 240, true) binding.ivAdd.setImageBitmap(resizedBitmap) } fileToUpload = selectedImageUri?.let { uri -> val file = File(requireContext().filesDir, "image.jpg") val inputStream = requireContext().contentResolver.openInputStream(uri) val outputStream = FileOutputStream(file) inputStream?.copyTo(outputStream) file } UiComponentUtils.showToast(requireActivity(), "Image selected") } catch (e: Exception) { UiComponentUtils.showToast(requireActivity(), "Failed to select the image") } } } } } private fun getRequestParams(product: Product, fileToUpload: File?): ProductRequest { val nameRequestBody = product.name.toRequestBody("text/plain".toMediaTypeOrNull()) val typeRequestBody = product.type.toRequestBody("text/plain".toMediaTypeOrNull()) val priceRequestBody = product.price.toRequestBody("text/plain".toMediaTypeOrNull()) val taxRequestBody = product.tax.toRequestBody("text/plain".toMediaTypeOrNull()) val filePart: MultipartBody.Part? = fileToUpload?.let { val fileRequestBody: RequestBody = it.asRequestBody("image/*".toMediaTypeOrNull()) MultipartBody.Part.createFormData("files[]", it.name ?: "", fileRequestBody) } return ProductRequest( mutableMapOf( "product_name" to nameRequestBody, "product_type" to typeRequestBody, "price" to priceRequestBody, "tax" to taxRequestBody ), filePart ) } private fun getProductFormData(): Product { val productName = binding.etProductName.text.toString() val productType = binding.ddProductType.selectedItem.toString() val productPrice = binding.etProductPrice.text.toString() val tax = binding.etTax.text.toString() return Product(productName, productType, "", productPrice, tax) } companion object { private const val REQUEST_PICK_IMAGE = 1 @JvmStatic fun newInstance(param1: String, param2: String) = CreateProductFragment().apply { arguments = Bundle().apply { } } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/screens/CreateProductFragment.kt
3469138913
package com.example.swipestore.ui.screens import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SearchView import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.swipestore.data.entities.Product import com.example.swipestore.databinding.FragmentSearchBinding import com.example.swipestore.ui.adapters.SearchAdapter import com.example.swipestore.ui.viewmodels.ProductViewModel import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.qualifier.named class SearchFragment : Fragment() { private val binding by lazy { FragmentSearchBinding.inflate(layoutInflater) } private lateinit var products: ArrayList<Product> private lateinit var searchAdapter: SearchAdapter private val viewModel: ProductViewModel by sharedViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) products = viewModel.products.value ?: ArrayList() setUpSearchAdapter() setSearchQueryChangeListener() } private fun setUpSearchAdapter() { searchAdapter = SearchAdapter(requireActivity(),products){data -> viewModel.products.value = products val direction = SearchFragmentDirections.actionSearchToProduct(data) findNavController().navigate(direction) } binding.recyclerPr.apply { adapter = searchAdapter layoutManager = LinearLayoutManager(requireActivity()) } } private fun setSearchQueryChangeListener(){ binding.etSearch.setOnClickListener{ binding.etSearch.isIconified = false } binding.etSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { searchAdapter.filter.filter(newText) return true } }) } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/screens/SearchFragment.kt
2039548641
package com.example.swipestore.ui.screens import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.swipestore.R import com.example.swipestore.data.entities.Product import com.example.swipestore.databinding.FragmentProductListBinding import com.example.swipestore.ui.utils.NetworkChangeReceiver import com.example.swipestore.ui.utils.ProgressLoaderDialog import com.example.swipestore.ui.utils.UiComponentUtils import com.example.swipestore.ui.adapters.ProductAdapter import com.example.swipestore.ui.uistates.UiState import com.example.swipestore.ui.viewmodels.ProductViewModel import org.koin.androidx.viewmodel.ext.android.sharedViewModel class ProductListFragment : Fragment() { private lateinit var networkChangeReceiver: NetworkChangeReceiver private val navController by lazy { findNavController() } private val binding by lazy { FragmentProductListBinding.inflate(layoutInflater) } private val viewmodel: ProductViewModel by sharedViewModel() private var products: ArrayList<Product>? = null private lateinit var productAdapter: ProductAdapter private var isNetworkAvailable: Boolean = true override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setNetworkChangeListener() setToolbar() setViewListeners() observeData() fetchProductApiCall() } private fun setNetworkChangeListener() { // Registering broadcast receiver for network change networkChangeReceiver = NetworkChangeReceiver { isConnected -> isNetworkAvailable = isConnected if(isNetworkAvailable){ binding.noInternetIv.visibility = View.GONE fetchProductApiCall() } } // Todo: update the deprecated attribute requireActivity().registerReceiver( networkChangeReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) ) } // Todo: make it abstract and add in the BaseFragment, to make it dynamic and reusable private fun setToolbar() { val toolbar = binding.customToolbar toolbar.toolbarIcSearch.visibility = View.VISIBLE toolbar.toolbarTitle.text = resources.getText(R.string.toolbar_title_product_list) toolbar.toolbarIcSearch.setOnClickListener{ // Todo: Instead of replace operation on the destination, add destination to preserve the state of current screen val direction = ProductListFragmentDirections.actionProductListToSearch() navController.navigate(direction) } } private fun setViewListeners() { binding.fabCreateProduct.setOnClickListener { val direction = ProductListFragmentDirections.actionProductListToCreateProduct() navController.navigate(direction) } } private fun fetchProductApiCall() { viewmodel.fetchProducts() } private fun observeData() { viewmodel.uiState.observe(viewLifecycleOwner){ result -> when (result) { is UiState.Success<*> -> { ProgressLoaderDialog.hideLoader() products = result.data as? ArrayList<Product> if(!products.isNullOrEmpty()){ updateUI(products!!) } else { setNetworkNotAvailable() } } is UiState.Error -> { ProgressLoaderDialog.hideLoader() setNetworkNotAvailable() } else -> { ProgressLoaderDialog.showLoader(requireContext(), "Fetching Products...") } } } } private fun setNetworkNotAvailable(){ // Internet connection not available if(!isNetworkAvailable){ binding.noInternetIv.visibility = View.VISIBLE } else { UiComponentUtils.showSnackBar(binding.root, "Please try again, failed to fetch the product..") } } private fun updateUI(data: ArrayList<Product>) { productAdapter = ProductAdapter(requireActivity(), products!!){ data -> val direction = ProductListFragmentDirections.actionProductListToProduct(data) navController.navigate(direction) } binding.rvProducts.apply { layoutManager = LinearLayoutManager(requireActivity()) adapter = productAdapter } } override fun onDestroyView() { super.onDestroyView() requireActivity().unregisterReceiver(networkChangeReceiver) } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/screens/ProductListFragment.kt
1139938680
package com.example.swipestore.ui.screens import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import com.example.swipestore.R import com.example.swipestore.data.entities.Product import com.example.swipestore.databinding.FragmentProductBinding import com.example.swipestore.ui.utils.UiComponentUtils import com.example.swipestore.ui.viewmodels.ProductViewModel import org.koin.androidx.viewmodel.ext.android.sharedViewModel class ProductFragment : Fragment() { private val binding by lazy { FragmentProductBinding.inflate(layoutInflater) } private val viewmodel by sharedViewModel<ProductViewModel>() private val args: ProductFragmentArgs by navArgs() private var selectedPrduct: Product? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setToolbar() selectedPrduct = args.keyProduct setProductData(selectedPrduct) } private fun setProductData(product: Product?) { val productView = binding.itemviewProduct productView.tvProductName.text = product?.name productView.tvProductType.text = product?.type productView.tvProductPrice.text = product?.price productView.tvProductTax.text = product?.tax UiComponentUtils.loadImageFromUrl(requireContext(), product?.image ?: "", productView.ivProductImage, R.drawable.ic_default_product) } private fun setToolbar() { val toolbar = binding.customToolbar toolbar.toolbarIcBack.visibility = View.VISIBLE toolbar.toolbarTitle.text = resources.getText(R.string.toolbar_title_product_view) toolbar.toolbarIcBack.setOnClickListener{ activity?.supportFragmentManager?.popBackStack() } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/screens/ProductFragment.kt
1677293206
package com.example.swipestore.ui.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.swipestore.R import com.example.swipestore.data.entities.Product import com.example.swipestore.databinding.ItemviewProductBinding import com.example.swipestore.ui.utils.UiComponentUtils class ProductAdapter( private val context: Context, private val products: ArrayList<Product>, private val onItemClick: (data: Product) -> Unit ): RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder { val binding = ItemviewProductBinding.inflate(LayoutInflater.from(context), parent, false) return ProductViewHolder(binding) } override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { val product = products[position] holder.bind(product) holder.itemView.setOnClickListener{ val position = holder.adapterPosition if (position != RecyclerView.NO_POSITION) { onItemClick(products[position]) } } } override fun getItemCount(): Int { return products.size } inner class ProductViewHolder(private val binding: ItemviewProductBinding): RecyclerView.ViewHolder(binding.root){ fun bind(product: Product){ binding.apply { tvProductName.text = product.name tvProductType.text = product.type tvProductPrice.text = String.format("%.2f", product.price.toDoubleOrNull()) tvProductTax.text = "tax: ${String.format("%.2f", product.tax.toDoubleOrNull())}" UiComponentUtils.loadImageFromUrl(context, product.image, ivProductImage, R.drawable.ic_default_product) } } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/adapters/ProductAdapter.kt
1197291775
package com.example.swipestore.ui.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import com.example.swipestore.data.entities.Product import com.example.swipestore.databinding.ItemviewProductSearchBinding import java.io.File class SearchAdapter( private val context: Context, private val products: ArrayList<Product>, private val onItemClick: (data: Product) -> Unit ): RecyclerView.Adapter<SearchAdapter.SearchViewHolder>(),Filterable { var filterList:ArrayList<Product> = products override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder { val binding = ItemviewProductSearchBinding.inflate(LayoutInflater.from(context), parent, false) return SearchViewHolder(binding) } override fun onBindViewHolder(holder: SearchViewHolder, position: Int) { val product = filterList[position] holder.bind(product) holder.itemView.setOnClickListener{ onItemClick(product) } } override fun getItemCount(): Int { return filterList.size } inner class SearchViewHolder(private val binding: ItemviewProductSearchBinding): RecyclerView.ViewHolder(binding.root){ fun bind(product: Product){ binding.apply { nameProduct.text = product.name priceProduct.text = "\u20B9 ${String.format("%.2f", product.price.toDoubleOrNull())}" val imgString = product.image Glide.with(context).asFile() .load(imgString) .into(object : SimpleTarget<File>() { override fun onResourceReady( resource: File, transition: Transition<in File>? ) { val filePath = resource.absolutePath Glide.with(context).load(filePath).into(productImg) } }) } } } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(constraint: CharSequence?): FilterResults { val filterResults = FilterResults() if (constraint.isNullOrBlank()|| constraint.length < 3) { filterResults.values = products } else { val filteredItems = products.filter { it.name.contains(constraint, ignoreCase = true) } filterResults.values = filteredItems } return filterResults } @Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence?, results: FilterResults?) { filterList = (results?.values as? List<Product> ?: emptyList()) as ArrayList<Product> notifyDataSetChanged() } } } }
SwipeStore/app/src/main/java/com/example/swipestore/ui/adapters/SearchAdapter.kt
2874189030
package com.example.swipestore import android.app.Application import com.example.swipestore.ui.di.productModule import com.example.swipestore.ui.di.roomDbModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class BaseApplication: Application() { override fun onCreate() { super.onCreate() startKoin{ androidLogger(Level.ERROR) androidContext(this@BaseApplication) modules(listOf(productModule, roomDbModule)) } } }
SwipeStore/app/src/main/java/com/example/swipestore/BaseApplication.kt
1513774278
package com.example.swipestore.data.repositories interface Repository { }
SwipeStore/app/src/main/java/com/example/swipestore/data/repositories/Repository.kt
2394072951
package com.example.swipestore.data.repositories import android.util.Log import com.example.swipestore.data.entities.Product import com.example.swipestore.data.entities.ProductRequest import com.example.swipestore.data.entities.ProductResponse import com.example.swipestore.data.sources.LocalProductDataSource import com.example.swipestore.data.sources.RemoteProductDataSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import retrofit2.Response class ProductRepository( val localSource: LocalProductDataSource, val remoteSource: RemoteProductDataSource ) : Repository { private val TAG = ProductRepository::class.simpleName suspend fun fetchProducts(): ArrayList<Product>? = withContext(Dispatchers.IO) { try { val products = remoteSource.getProducts() // Todo: Optimize this conflict resolution strategy localSource.updateProducts(products!!) } catch (e: Exception) { Log.d(TAG, e.message.toString()) } return@withContext localSource.fetchProducts() as? ArrayList<Product> } suspend fun createProduct(request: ProductRequest): ProductResponse? = withContext(Dispatchers.IO){ var response: ProductResponse? = null try { response = remoteSource.createProduct(request) } catch (e: Exception) { Log.d(TAG, e.message.toString()) } return@withContext response } }
SwipeStore/app/src/main/java/com/example/swipestore/data/repositories/ProductRepository.kt
3694017472
package com.example.swipestore.data.sources import com.example.swipestore.data.entities.Product import com.example.swipestore.data.entities.ProductRequest import com.example.swipestore.data.entities.ProductResponse import com.example.swipestore.data.services.ProductService import retrofit2.Response class RemoteProductDataSource(private val api: ProductService) { suspend fun getProducts(): List<Product>? { return api.getProducts() } suspend fun createProduct(request: ProductRequest): ProductResponse { return api.createProduct( request.requestMap, request.file ) } }
SwipeStore/app/src/main/java/com/example/swipestore/data/sources/RemoteProductDataSource.kt
3436653768
package com.example.swipestore.data.sources import com.example.swipestore.data.entities.Product import com.example.swipestore.data.services.ProductDao class LocalProductDataSource( private val dao: ProductDao ) { suspend fun fetchProducts(): List<Product> { return dao.getAllProducts() } suspend fun updateProducts(products: List<Product>){ dao.insertAll(products) } }
SwipeStore/app/src/main/java/com/example/swipestore/data/sources/LocalProductDataSource.kt
2951029895
package com.example.swipestore.data.services import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClient { private const val BASE_URL = "https://app.getswipe.in/" fun getRetrofit(): Retrofit { val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() return Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } }
SwipeStore/app/src/main/java/com/example/swipestore/data/services/RetrofitClient.kt
1537673576
package com.example.swipestore.data.services import androidx.room.Database import androidx.room.RoomDatabase import com.example.swipestore.data.entities.Product @Database(entities = [Product::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun productDao(): ProductDao }
SwipeStore/app/src/main/java/com/example/swipestore/data/services/AppDatabase.kt
697432242
package com.example.swipestore.data.services import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.swipestore.data.entities.Product @Dao interface ProductDao { @Query("SELECT * FROM products") suspend fun getAllProducts(): List<Product> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(products: List<Product>) }
SwipeStore/app/src/main/java/com/example/swipestore/data/services/ProductDao.kt
1241249865
package com.example.swipestore.data.services import com.example.swipestore.data.entities.Product import com.example.swipestore.data.entities.ProductRequest import com.example.swipestore.data.entities.ProductResponse import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.PartMap interface ProductService { @GET("api/public/get") suspend fun getProducts(): List<Product> @Multipart @POST("api/public/add") suspend fun createProduct( @PartMap partMap: MutableMap<String,@JvmSuppressWildcards RequestBody>, @Part file: MultipartBody.Part? ): ProductResponse }
SwipeStore/app/src/main/java/com/example/swipestore/data/services/ProductService.kt
1849981108
package com.example.swipestore.data.entities data class ProductResponse( val message: String, val product_details: Product, val product_id: Int, val success: Boolean )
SwipeStore/app/src/main/java/com/example/swipestore/data/entities/ProductResponse.kt
2113641271
package com.example.swipestore.data.entities import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import java.io.Serializable @Entity(tableName = "products", primaryKeys = ["name", "type", "price", "tax"]) data class Product( @SerializedName("product_name") val name: String, @SerializedName("product_type") val type: String, val image: String, val price: String, val tax: String ): Serializable
SwipeStore/app/src/main/java/com/example/swipestore/data/entities/Product.kt
1846407243
package com.example.swipestore.data.entities import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File data class ProductRequest( val requestMap: MutableMap<String, RequestBody> = mutableMapOf(), var file: MultipartBody.Part? = null )
SwipeStore/app/src/main/java/com/example/swipestore/data/entities/ProductRequest.kt
428166424
package com.snick55.vkmessagertestapp 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.snick55.vkmessagertestapp", appContext.packageName) } }
VkMessagerTestApp/app/src/androidTest/java/com/snick55/vkmessagertestapp/ExampleInstrumentedTest.kt
2139189964
package com.snick55.vkmessagertestapp 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) } }
VkMessagerTestApp/app/src/test/java/com/snick55/vkmessagertestapp/ExampleUnitTest.kt
4036147900
package com.snick55.vkmessagertestapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import com.snick55.vkmessagertestapp.databinding.ActivityMainBinding import java.util.Locale import java.util.TimeZone class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onStart() { super.onStart() binding.clockView.startClock() } override fun onStop() { super.onStop() binding.clockView.stopClock() } }
VkMessagerTestApp/app/src/main/java/com/snick55/vkmessagertestapp/MainActivity.kt
3169945594
package com.snick55.vkmessagertestapp import android.annotation.SuppressLint import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Handler import android.os.Looper import android.util.AttributeSet import android.util.Log import android.view.View import java.text.SimpleDateFormat import java.util.* import kotlin.math.cos import kotlin.math.min import kotlin.math.sin class ClockView : View { constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) { setupAttributes(attrs) } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr, 0 ) { setupAttributes(attrs) } private var handler: Handler = Handler(Looper.getMainLooper()) private var timeUpdater: Runnable private var dialColor: Int = Color.GRAY private var pointsColor: Int = Color.WHITE private var hourHandColor: Int = Color.BLACK private var minuteHandColor: Int = Color.BLACK private var secondHandColor: Int = Color.BLACK private var hourHandWidth: Float = 24f private var minuteHandWidth: Float = 12f private var secondHandWidth: Float = 6f private var textPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private lateinit var dialPaint: Paint private lateinit var pointerPaint: Paint private var strokePaint = Paint() private var hourData = 0f private var minuteData = 0f private var secondData = 0 private var mWidth = 0.0f private var mHeight = 0.0f private var mRadius = 0.0f init { initParameters() timeUpdater = startCounting() } private fun startCounting(): Runnable { timeUpdater = object : Runnable { override fun run() { val currentTime: String = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date()) setClockTime( currentTime.substring(0, 2).toFloat() % 12, currentTime.substring(3, 5).toFloat(), currentTime.substring(6, 8).toInt() ) handler.postDelayed(this, 1000) } } return timeUpdater } @SuppressLint("DrawAllocation") override fun onDraw(canvas: Canvas) { super.onDraw(canvas) initParameters() drawBaseCircles(canvas) val numberCircleRadius = mRadius / 1.2f val numberLinesRadius = mRadius / 1.2f val pointRadius = mRadius / 15 val minutesRadius = mRadius / 150 drawNumbers(canvas,numberCircleRadius, pointRadius) drawMinutes(canvas,numberLinesRadius,minutesRadius) drawHandWithPaint( canvas, hourHandColor, hourHandWidth, calcXYForPosition(hourData, numberCircleRadius - 130, 30) ) drawHandWithPaint( canvas, minuteHandColor, minuteHandWidth, calcXYForPosition(minuteData, numberCircleRadius - 90, 6) ) drawHandWithPaint( canvas, secondHandColor, secondHandWidth, calcXYForPosition(secondData.toFloat(), numberCircleRadius - 30, 6) ) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) mWidth = w.toFloat() mHeight = h.toFloat() mRadius = ((min(mWidth, mHeight)) / 2) } private fun calcXYForPosition(pos: Float, rad: Float, skipAngle: Int): ArrayList<Float> { val result = ArrayList<Float>(2) val startAngle = 270f val angle = startAngle + (pos * skipAngle) result.add(0, (rad * cos(angle * Math.PI / 180) + width / 2).toFloat()) result.add(1, (height / 2 + rad * sin(angle * Math.PI / 180)).toFloat()) return result } private fun drawHandWithPaint( canvas: Canvas, handColor: Int, strokeWidth: Float, xyData: ArrayList<Float> ) { val handPaint = Paint(Paint.ANTI_ALIAS_FLAG) handPaint.color = handColor handPaint.strokeWidth = strokeWidth canvas.drawLine(mWidth / 2, mHeight / 2, xyData[0], xyData[1], handPaint) } private fun setupAttributes(attrs: AttributeSet?) { val typedArray: TypedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.ClockView, 0, 0) dialColor = typedArray.getColor(R.styleable.ClockView_dialColor, dialColor) pointsColor = typedArray.getColor(R.styleable.ClockView_pointsColor, pointsColor) hourHandColor = typedArray.getColor(R.styleable.ClockView_hourHandColor, hourHandColor) minuteHandColor = typedArray.getColor(R.styleable.ClockView_minuteHandColor, minuteHandColor) secondHandColor = typedArray.getColor(R.styleable.ClockView_secondHandColor, secondHandColor) hourHandWidth = typedArray.getFloat(R.styleable.ClockView_hourHandWidth, hourHandWidth) minuteHandWidth = typedArray.getFloat(R.styleable.ClockView_minuteHandWidth, minuteHandWidth) secondHandWidth = typedArray.getFloat(R.styleable.ClockView_secondHandWidth, secondHandWidth) typedArray.recycle() } private fun drawNumbers(canvas: Canvas,numberCircleRadius: Float,pointRadius:Float){ var num = 12 for (i in 0..11) { Log.d("TAG","num = $num") val xyData = calcXYForPosition(i.toFloat(), numberCircleRadius, 30) val yPadding = if (mRadius > 200) xyData[1] + pointRadius - 10 else xyData[1] - pointRadius + 10 canvas.drawText("$num", xyData[0], yPadding, textPaint) num = i + 1 } } private fun drawMinutes(canvas: Canvas,numberLinesRadius:Float,minutesRadius: Float){ for (i in 0..59) { val xyData = calcXYForPosition(i.toFloat(), numberLinesRadius, 6) canvas.drawCircle(xyData[0], xyData[1], minutesRadius, pointerPaint) } } private fun drawBaseCircles(canvas: Canvas) { canvas.drawCircle(mWidth / 2, mHeight / 2, mRadius, dialPaint) canvas.drawCircle(mWidth / 2, mHeight / 2, mRadius - 10, strokePaint) } private fun setClockTime(hour: Float, minute: Float, second: Int) { hourData = hour + (minute / 60) minuteData = minute secondData = second invalidate() } private fun initParameters(){ textPaint.color = Color.BLACK textPaint.style = Paint.Style.FILL_AND_STROKE textPaint.textAlign = Paint.Align.CENTER textPaint.textSize = 40f dialPaint = Paint() dialPaint.color = dialColor strokePaint.color = Color.BLACK strokePaint.strokeWidth = 20f strokePaint.style = Paint.Style.STROKE pointerPaint = Paint(Paint.ANTI_ALIAS_FLAG) pointerPaint.color = pointsColor textPaint.color = Color.BLACK textPaint.textSize = mRadius / 8 } fun startClock() { handler.post(timeUpdater) } fun stopClock() { handler.removeCallbacks(timeUpdater) } }
VkMessagerTestApp/app/src/main/java/com/snick55/vkmessagertestapp/ClockView.kt
2885593728
package util fun main() { }
project_euler/src/main/kotlin/util/_template.kt
3281759089
package solutions fun main() { val input = """ 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690 """.trimIndent() input .lines() .map { it.trim().toBigDecimal() } .sumOf { it } .let { println(it) } }
project_euler/src/main/kotlin/solutions/_13.kt
1639951489
package solutions fun main() { val res = 3 * uSum(999 / 3) + 5 * uSum(999 / 5) - 15 * uSum(999 / 15) assert(res == 233168) println("$res") } private fun uSum(n: Int): Int = (n * (n + 1)) / 2
project_euler/src/main/kotlin/solutions/_1.kt
2057307873
package solutions import kotlin.math.abs fun main() { val lcm = lcm(*(1L until 20L).toList().toLongArray()) println(lcm) } private fun lcm(vararg nums: Long): Long { var s = 1L for (i in nums) { s = lcm(s, i) } return s } private fun lcm(i: Long, j: Long): Long { if (i == 0L && j == 0L) return 0L return abs(i * j) / gcd(i, j) } private fun gcd(i: Long, j: Long): Long { if (i == 0L) return j if (j == 0L) return i return gcd(j, i % j) }
project_euler/src/main/kotlin/solutions/_5.kt
3153951531
package solutions fun main() { var max = 0 for (i in 100..999) { for (j in 100..999) { val res = i * j if (isPalindrome(res) && res > max) max = res } } println("$max") } private fun isPalindrome(num: Int): Boolean { var tmp = num var rev = 0; while (tmp > 0) { val dig = tmp % 10; rev = rev * 10 + dig; tmp /= 10; } return rev == num }
project_euler/src/main/kotlin/solutions/_4.kt
2601683212
package solutions import kotlin.math.sqrt fun main() { var sum = 1L (2..Int.MAX_VALUE).find { sum += it findDivisors(sum) > 500 }.let { println(sum) } } fun findDivisors(n: Long): Int { var counter = 0 var i = 2L while (i <= sqrt(n.toDouble())) { if (n % i == 0L) { counter++ if (i != (n / i)) { counter++ } } i++; } if (n > 1) { counter++ } if (n >= 1) { counter++ } return counter }
project_euler/src/main/kotlin/solutions/_12.kt
3438313141
package solutions import kotlin.math.sqrt fun main() { for (b in 1..500) { for (a in 1 until b) { if (a + b + sqrt((a * a + b * b).toDouble()) == 1000.0) { println("$a $b ${sqrt((a * a + b * b).toDouble())}") println("${a * b * sqrt((a * a + b * b).toDouble()).toInt()}") } } } }
project_euler/src/main/kotlin/solutions/_9.kt
3295586799
package solutions fun main() { val num = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" + "12540698747158523863050715693290963295227443043557" + "66896648950445244523161731856403098711121722383113" + "62229893423380308135336276614282806444486645238749" + "30358907296290491560440772390713810515859307960866" + "70172427121883998797908792274921901699720888093776" + "65727333001053367881220235421809751254540594752243" + "52584907711670556013604839586446706324415722155397" + "53697817977846174064955149290862569321978468622482" + "83972241375657056057490261407972968652414535100474" + "82166370484403199890008895243450658541227588666881" + "16427171479924442928230863465674813919123162824586" + "17866458359124566529476545682848912883142607690042" + "24219022671055626321111109370544217506941658960408" + "07198403850962455444362981230987879927244284909188" + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725" + "71636269561882670428252483600823257530420752963450" val size = 13 var max = 0L for (i in 0 .. num.length - size) { val nums = num.subSequence(i until i + size).fold(1L) { acc, c -> acc * c.digitToInt() } if (nums > max) { max = nums } } //23514624000 println(max) }
project_euler/src/main/kotlin/solutions/_8.kt
537568454
package solutions import kotlin.math.sqrt fun main() { val max = Int.MAX_VALUE / 100 val values = MutableList(max) { true } for (i in 2..(sqrt(max.toDouble()).toInt() + 1)) { if (values[i]) { for (p in ((i * i)until max).step(i)) { values[p] = false } } } println(values.drop(1).mapIndexed { index, b -> index to b }.filter { it.second }[10001]) }
project_euler/src/main/kotlin/solutions/_7.kt
3521190571
package solutions fun main() { val grid = """ 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 99 67 99 """.trimIndent().lines().map { it.trim().split(' ').map { it.trim().toLong() } } var max = 0L for (y in grid.indices) { for (x in grid.first().indices) { val vert = grid[y][x] * grid.getSafe(y + 1, x) * grid.getSafe(y + 2, x) * grid.getSafe(y + 3, x) val hor = grid[y][x] * grid.getSafe(y, x + 1) * grid.getSafe(y, x + 2) * grid.getSafe(y, x + 3) val dir = grid[y][x] * grid.getSafe(y + 1, x + 1) * grid.getSafe(y + 2, x + 2) * grid.getSafe(y + 3, x + 3) val dil = grid[y][x] * grid.getSafe(y + 1, x - 1) * grid.getSafe(y + 2, x - 2) * grid.getSafe(y + 3, x - 3) max = maxOf(vert, hor, dir, dil, max) } } println(max) } private fun List<List<Long>>.getSafe(y: Int, x: Int) = getOrElse(y) { emptyList() }.getOrElse(x) { 0L }
project_euler/src/main/kotlin/solutions/_11.kt
3116212011
package solutions fun main() { var target = 600851475143L //13195 var i = 2L while (i * i < target) { if (target % i != 0L) { i++ } else { target /= i } } println(target) }
project_euler/src/main/kotlin/solutions/_3.kt
3016154661
package solutions import kotlin.math.sqrt fun main() { val max = 2_000_000 val values = MutableList(max) { true } for (i in 2..(sqrt(max.toDouble()).toInt())) { if (values[i]) { for (p in ((i * i)until max).step(i)) { values[p] = false } } } println(values.mapIndexed { index, b -> index.toLong() to b }.drop(2).filter { it.second }.sumOf { it.first }) }
project_euler/src/main/kotlin/solutions/_10.kt
2501436269
package solutions // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 fun main() { var i = 1 var j = 2 var sum = 0 while(j < 4_000_000) { if(j % 2 == 0) sum += j val tmp = j j += i i = tmp } println(sum) }
project_euler/src/main/kotlin/solutions/_2.kt
3504045427
package solutions fun main() { val cache = mutableMapOf<Long, Long>() (1L..1_000_000L).asSequence().maxBy { chainLenght(it, cache) }.let { println(it) } } fun chainLenght(n: Long, cache: MutableMap<Long, Long>): Long { if (n in cache) return cache[n]!! if (n == 1L) return 1L val res = if (n % 2L == 0L) chainLenght(n / 2, cache) + 1 else chainLenght(n * 3 + 1, cache) + 1 cache[n] = res return res }
project_euler/src/main/kotlin/solutions/_14.kt
2777237547
package solutions fun main() { val i = 100 println(sumSquared(i) - squareSum(i)) } private fun sumSquared(n: Int) = (1..n).sum().let { it * it } private fun squareSum(n: Int) = (1..n).sumOf { it * it }
project_euler/src/main/kotlin/solutions/_6.kt
1565453907
package air.texnodev.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("air.texnodev.todolist", appContext.packageName) } }
To-Do-List-/app/src/androidTest/java/air/texnodev/todolist/ExampleInstrumentedTest.kt
56367688
package air.texnodev.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) } }
To-Do-List-/app/src/test/java/air/texnodev/todolist/ExampleUnitTest.kt
878174620
package air.texnodev.todolist import air.texnodev.todolist.databinding.ActivityMainBinding import android.content.Intent import android.graphics.* import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.lifecycle.Observer import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val list = arrayListOf<TodoModel>() var adapter = TodoAdapter(list) private lateinit var binding: ActivityMainBinding private lateinit var db:AppDatabase // val db by lazy { // AppDatabase.getDatabase(this) // } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) db = AppDatabase.getDatabase(baseContext) binding.todoRv.apply { layoutManager = LinearLayoutManager(this@MainActivity) adapter = [email protected] } initSwipe() db.todoDao().getTask().observe(this, Observer { if (!it.isNullOrEmpty()) { list.clear() list.addAll(it) adapter.notifyDataSetChanged() }else{ list.clear() adapter.notifyDataSetChanged() } }) } fun initSwipe() { val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition if (direction == ItemTouchHelper.LEFT) { GlobalScope.launch(Dispatchers.IO) { db.todoDao().deleteTask(adapter.getItemId(position)) } } else if (direction == ItemTouchHelper.RIGHT) { GlobalScope.launch(Dispatchers.IO) { db.todoDao().finishTask(adapter.getItemId(position)) } } } override fun onChildDraw( canvas: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val itemView = viewHolder.itemView val paint = Paint() val icon: Bitmap if (dX > 0) { icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_check_white_png) paint.color = Color.parseColor("#388E3C") canvas.drawRect( itemView.left.toFloat(), itemView.top.toFloat(), itemView.left.toFloat() + dX, itemView.bottom.toFloat(), paint ) canvas.drawBitmap( icon, itemView.left.toFloat(), itemView.top.toFloat() + (itemView.bottom.toFloat() - itemView.top.toFloat() - icon.height.toFloat()) / 2, paint ) } else { icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_delete_white_png) paint.color = Color.parseColor("#D32F2F") canvas.drawRect( itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat(), paint ) canvas.drawBitmap( icon, itemView.right.toFloat() - icon.width, itemView.top.toFloat() + (itemView.bottom.toFloat() - itemView.top.toFloat() - icon.height.toFloat()) / 2, paint ) } viewHolder.itemView.translationX = dX } else { super.onChildDraw( canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive ) } } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(binding.todoRv) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) val item = menu.findItem(R.id.search) val searchView = item.actionView as SearchView item.setOnActionExpandListener(object :MenuItem.OnActionExpandListener{ override fun onMenuItemActionExpand(p0: MenuItem): Boolean { displayTodo() return true } override fun onMenuItemActionCollapse(p0: MenuItem): Boolean { displayTodo() return true } }) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { if(!newText.isNullOrEmpty()){ displayTodo(newText) } return true } }) return super.onCreateOptionsMenu(menu) } fun displayTodo(newText: String = "") { db.todoDao().getTask().observe(this, Observer { if(it.isNotEmpty()){ list.clear() list.addAll( it.filter { todo -> todo.title.contains(newText,true) } ) adapter.notifyDataSetChanged() } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.history -> { startActivity(Intent(this, HistoryActivity::class.java)) } } return super.onOptionsItemSelected(item) } fun openNewTask(view: View) { startActivity(Intent(this, TaskActivity::class.java)) } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/MainActivity.kt
630294460
package air.texnodev.todolist import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [TodoModel::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun todoDao(): TodoDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, DB_NAME ).build() INSTANCE = instance return instance } } } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/AppDatabase.kt
1662845286
package air.texnodev.todolist import air.texnodev.todolist.databinding.ItemTodoBinding import air.texnodev.todolist.databinding.ItemTodoHistoryBinding import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import java.text.SimpleDateFormat import java.util.* class TodoHistoryAdapter(val list: List<TodoModel>) : RecyclerView.Adapter<TodoHistoryAdapter.TodoViewHolder>() { inner class TodoViewHolder(val binding: ItemTodoHistoryBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder { val binding = ItemTodoHistoryBinding.inflate(LayoutInflater.from(parent.context), parent, false) return TodoViewHolder(binding) } override fun getItemCount() = list.size override fun onBindViewHolder(holder: TodoViewHolder, position: Int) { with(holder) { with(list[position]) { val colors = holder.itemView.resources.getIntArray(R.array.random_color) val randomColor = colors[Random().nextInt(colors.size)] binding.viewColorTag.setBackgroundColor(randomColor) binding.txtShowTitle.text = this.title binding.txtShowTask.text = this.description binding.txtShowCategory.text = this.category val myformatt = "h:mm a" val sdff = SimpleDateFormat(myformatt) binding.txtShowTime.text = sdff.format(Date(time)) val myformat = "EEE, d MMM yyyy" val sdf = SimpleDateFormat(myformat) binding.txtShowDate.text = sdf.format(Date(time)) if (this.isFinished == 1){ binding.status.text = "Success" binding.status.setTextColor(Color.GREEN) }else if (this.isFinished == 2){ binding.status.text = "Delete" binding.status.setTextColor(Color.RED) } } } } override fun getItemId(position: Int): Long { return list[position].id } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/TodoHistoryAdapter.kt
3219089393
package air.texnodev.todolist import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class TodoModel( var title:String, var description:String, var category: String, var date:Long, var time:Long, var isFinished : Int = 0, @PrimaryKey(autoGenerate = true) var id:Long = 0 )
To-Do-List-/app/src/main/java/air/texnodev/todolist/TodoModel.kt
2551092858
package air.texnodev.todolist import air.texnodev.todolist.databinding.ActivityTaskBinding import android.app.DatePickerDialog import android.app.TimePickerDialog import android.os.Bundle import android.os.Handler import android.view.View import android.widget.ArrayAdapter import android.widget.DatePicker import android.widget.TimePicker import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.Calendar const val DB_NAME = "todo.db" class TaskActivity : AppCompatActivity(), View.OnClickListener { lateinit var myCalendar: Calendar lateinit var dateSetListener: DatePickerDialog.OnDateSetListener lateinit var timeSetListener: TimePickerDialog.OnTimeSetListener var finalDate = 0L var finalTime = 0L private lateinit var binding: ActivityTaskBinding private val labels = arrayListOf("Personal", "Business", "Insurance", "Shopping", "Banking") val db by lazy { AppDatabase.getDatabase(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTaskBinding.inflate(layoutInflater) setContentView(binding.root) binding.dateEdt.setOnClickListener(this) binding.timeEdt.setOnClickListener(this) binding.saveBtn.setOnClickListener(this) setUpSpinner() } private fun setUpSpinner() { val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, labels) labels.sort() binding.spinnerCategory.adapter = adapter } override fun onClick(v: View) { when (v.id) { R.id.dateEdt -> { setListener() } R.id.timeEdt -> { setTimeListener() } R.id.saveBtn -> { saveTodo() } } } private fun saveTodo() { val category = binding.spinnerCategory.selectedItem.toString() val title = binding.titleInpLay.editText?.text.toString() val description = binding.taskInpLay.editText?.text.toString() GlobalScope.launch(Dispatchers.Main) { val id = withContext(Dispatchers.IO) { return@withContext db.todoDao().insertTask( TodoModel( title, description, category, finalDate, finalTime ) ) } finish() } } private fun setTimeListener() { myCalendar = Calendar.getInstance() timeSetListener = TimePickerDialog.OnTimeSetListener() { _: TimePicker, hourOfDay: Int, min: Int -> myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay) myCalendar.set(Calendar.MINUTE, min) updateTime() } val timePickerDialog = TimePickerDialog( this, timeSetListener, myCalendar.get(Calendar.HOUR_OF_DAY), myCalendar.get(Calendar.MINUTE), false ) timePickerDialog.show() } private fun updateTime() { //Mon, 5 Jan 2020 val myformat = "h:mm a" val sdf = SimpleDateFormat(myformat) finalTime = myCalendar.time.time binding.timeEdt.setText(sdf.format(myCalendar.time)) } private fun setListener() { myCalendar = Calendar.getInstance() dateSetListener = DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, month: Int, dayOfMonth: Int -> myCalendar.set(Calendar.YEAR, year) myCalendar.set(Calendar.MONTH, month) myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) updateDate() } val datePickerDialog = DatePickerDialog( this, dateSetListener, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH) ) datePickerDialog.datePicker.minDate = System.currentTimeMillis() datePickerDialog.show() } private fun updateDate() { //Mon, 5 Jan 2020 val myformat = "EEE, d MMM yyyy" val sdf = SimpleDateFormat(myformat) finalDate = myCalendar.time.time binding.dateEdt.setText(sdf.format(myCalendar.time)) binding.timeInptLay.visibility = View.VISIBLE } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/TaskActivity.kt
1575461647
package air.texnodev.todolist import air.texnodev.todolist.databinding.ActivityHistoryBinding import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer class HistoryActivity : AppCompatActivity() { private lateinit var binding: ActivityHistoryBinding val list = arrayListOf<TodoModel>() private lateinit var db:AppDatabase override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHistoryBinding.inflate(layoutInflater) setContentView(binding.root) db = AppDatabase.getDatabase(baseContext) db.todoDao().getFinished().observe(this, Observer { if (!it.isNullOrEmpty()) { Log.d("LOG_APP", " Lo "+it.size) list.clear() list.addAll(it) binding.todoRv.adapter = TodoHistoryAdapter(it) }else{ binding.todoRv.adapter = TodoHistoryAdapter(list) } }) } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/HistoryActivity.kt
198933110
package air.texnodev.todolist import air.texnodev.todolist.databinding.ItemTodoBinding import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import java.text.SimpleDateFormat import java.util.* class TodoAdapter(val list: List<TodoModel>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() { inner class TodoViewHolder(val binding: ItemTodoBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder { val binding = ItemTodoBinding.inflate(LayoutInflater.from(parent.context), parent, false) return TodoViewHolder(binding) } override fun getItemCount() = list.size override fun onBindViewHolder(holder: TodoViewHolder, position: Int) { with(holder) { with(list[position]) { val colors = holder.itemView.resources.getIntArray(R.array.random_color) val randomColor = colors[Random().nextInt(colors.size)] binding.viewColorTag.setBackgroundColor(randomColor) binding.txtShowTitle.text = this.title binding.txtShowTask.text = this.description binding.txtShowCategory.text = this.category val myformatt = "h:mm a" val sdff = SimpleDateFormat(myformatt) binding.txtShowTime.text = sdff.format(Date(time)) val myformat = "EEE, d MMM yyyy" val sdf = SimpleDateFormat(myformat) binding.txtShowDate.text = sdf.format(Date(time)) } } } override fun getItemId(position: Int): Long { return list[position].id } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/TodoAdapter.kt
1542667726
package air.texnodev.todolist import air.texnodev.todolist.TodoModel import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface TodoDao { @Insert() suspend fun insertTask(todoModel: TodoModel):Long @Query("Select * from TodoModel where isFinished == 0") fun getTask():LiveData<List<TodoModel>> @Query("Select * from TodoModel where isFinished > 0") fun getFinished():LiveData<List<TodoModel>> @Query("Update TodoModel Set isFinished = 1 where id=:uid") fun finishTask(uid:Long) @Query("Update TodoModel Set isFinished = 2 where id=:uid") fun deleteTask(uid:Long) }
To-Do-List-/app/src/main/java/air/texnodev/todolist/TodoDao.kt
857635145
package air.texnodev.todolist import air.texnodev.todolist.databinding.ActivitySplashBinding import android.animation.Animator import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SplashActivity : AppCompatActivity() { private lateinit var binding: ActivitySplashBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySplashBinding.inflate(layoutInflater) setContentView(binding.root) binding.animationView.addAnimatorListener( object : Animator.AnimatorListener{ override fun onAnimationStart(p0: Animator) { } override fun onAnimationEnd(p0: Animator) { startActivity(Intent(this@SplashActivity, MainActivity::class.java)) finish() } override fun onAnimationCancel(p0: Animator) { } override fun onAnimationRepeat(p0: Animator) { } }) } }
To-Do-List-/app/src/main/java/air/texnodev/todolist/SplashActivity.kt
3359391111
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class RefreshMainDataWorkTest { @Test fun testRefreshMainDataWork() { // TODO: Write this test } }
corutinesCodelab/start/src/androidTest/java/com/example/android/kotlincoroutines/main/RefreshMainDataWorkTest.kt
3415621901
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.android.kotlincoroutines.fakes.MainNetworkFake import com.example.android.kotlincoroutines.fakes.TitleDaoFake import com.example.android.kotlincoroutines.main.utils.MainCoroutineScopeRule import com.example.android.kotlincoroutines.main.utils.getValueForTest import com.google.common.truth.Truth import org.junit.Before import org.junit.Rule import org.junit.Test class MainViewModelTest { @get:Rule val coroutineScope = MainCoroutineScopeRule() @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() lateinit var subject: MainViewModel @Before fun setup() { subject = MainViewModel( TitleRepository( MainNetworkFake("OK"), TitleDaoFake("initial") )) } @Test fun whenMainClicked_updatesTaps() { subject.onMainViewClicked() Truth.assertThat(subject.taps.getValueForTest()).isEqualTo("0 taps") coroutineScope.advanceTimeBy(1000) Truth.assertThat(subject.taps.getValueForTest()).isEqualTo("1 taps") } }
corutinesCodelab/start/src/test/java/com/example/android/kotlincoroutines/main/MainViewModelTest.kt
2307668526
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main.utils import androidx.lifecycle.LiveData import androidx.lifecycle.Observer /** * Represents a list of capture values from a LiveData. */ class LiveDataValueCapture<T> { val lock = Any() private val _values = mutableListOf<T?>() val values: List<T?> get() = synchronized(lock) { _values.toList() // copy to avoid returning reference to mutable list } fun addValue(value: T?) = synchronized(lock) { _values += value } } /** * Extension function to capture all values that are emitted to a LiveData<T> during the execution of * `captureBlock`. * * @param captureBlock a lambda that will */ inline fun <T> LiveData<T>.captureValues(block: LiveDataValueCapture<T>.() -> Unit) { val capture = LiveDataValueCapture<T>() val observer = Observer<T> { capture.addValue(it) } observeForever(observer) try { capture.block() } finally { removeObserver(observer) } } /** * Get the current value from a LiveData without needing to register an observer. */ fun <T> LiveData<T>.getValueForTest(): T? { var value: T? = null var observer = Observer<T> { value = it } observeForever(observer) removeObserver(observer) return value }
corutinesCodelab/start/src/test/java/com/example/android/kotlincoroutines/main/utils/LiveDataTestExtensions.kt
724531286
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main.utils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.TestCoroutineScope import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description /** * MainCoroutineRule installs a TestCoroutineDispatcher for Disptachers.Main. * * Since it extends TestCoroutineScope, you can directly launch coroutines on the MainCoroutineRule * as a [CoroutineScope]: * * ``` * mainCoroutineRule.launch { aTestCoroutine() } * ``` * * All coroutines started on [MainCoroutineScopeRule] must complete (including timeouts) before the test * finishes, or it will throw an exception. * * When using MainCoroutineRule you should always invoke runBlockingTest on it to avoid creating two * instances of [TestCoroutineDispatcher] or [TestCoroutineScope] in your test: * * ``` * @Test * fun usingRunBlockingTest() = mainCoroutineRule.runBlockingTest { * aTestCoroutine() * } * ``` * * You may call [DelayController] methods on [MainCoroutineScopeRule] and they will control the * virtual-clock. * * ``` * mainCoroutineRule.pauseDispatcher() * // do some coroutines * mainCoroutineRule.advanceUntilIdle() // run all pending coroutines until the dispatcher is idle * ``` * * By default, [MainCoroutineScopeRule] will be in a *resumed* state. * * @param dispatcher if provided, this [TestCoroutineDispatcher] will be used. */ @ExperimentalCoroutinesApi class MainCoroutineScopeRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) : TestWatcher(), TestCoroutineScope by TestCoroutineScope(dispatcher) { override fun starting(description: Description?) { super.starting(description) // If your codebase allows the injection of other dispatchers like // Dispatchers.Default and Dispatchers.IO, consider injecting all of them here // and renaming this class to `CoroutineScopeRule` // // All injected dispatchers in a test should point to a single instance of // TestCoroutineDispatcher. Dispatchers.setMain(dispatcher) } override fun finished(description: Description?) { super.finished(description) cleanupTestCoroutines() Dispatchers.resetMain() } }
corutinesCodelab/start/src/test/java/com/example/android/kotlincoroutines/main/utils/MainCoroutineScopeRule.kt
3657878335
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.android.kotlincoroutines.fakes.MainNetworkCompletableFake import com.example.android.kotlincoroutines.fakes.MainNetworkFake import com.example.android.kotlincoroutines.fakes.TitleDaoFake import com.google.common.truth.Truth import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.test.runBlockingTest import org.junit.Rule import org.junit.Test class TitleRepositoryTest { @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @Test fun whenRefreshTitleSuccess_insertsRows() = runBlockingTest { val titleDao = TitleDaoFake("title") val subject = TitleRepository( MainNetworkFake("OK"), titleDao ) subject.refreshTitle() Truth.assertThat(titleDao.nextInsertedOrNull()).isEqualTo("OK") } @Test(expected = TitleRefreshError::class) fun whenRefreshTitleTimeout_throws() = runBlockingTest { val network = MainNetworkCompletableFake() val subject = TitleRepository( network, TitleDaoFake("title") ) launch { subject.refreshTitle() } advanceTimeBy(5_000) } }
corutinesCodelab/start/src/test/java/com/example/android/kotlincoroutines/main/TitleRepositoryTest.kt
646747357
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.util import java.util.concurrent.Executors /** * An executor service that can run [Runnable]s off the main thread. */ val BACKGROUND = Executors.newFixedThreadPool(2)
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/util/Executors.kt
3095478019
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.util import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider /** * Convenience factory to handle ViewModels with one parameter. * * Make a factory: * ``` * // Make a factory * val FACTORY = viewModelFactory(::MyViewModel) * ``` * * Use the generated factory: * ``` * ViewModelProviders.of(this, FACTORY(argument)) * * ``` * * @param constructor A function (A) -> T that returns an instance of the ViewModel (typically pass * the constructor) * @return a function of one argument that returns ViewModelProvider.Factory for ViewModelProviders */ fun <T : ViewModel, A> singleArgViewModelFactory(constructor: (A) -> T): (A) -> ViewModelProvider.NewInstanceFactory { return { arg: A -> object : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <V : ViewModel> create(modelClass: Class<V>): V { return constructor(arg) as V } } } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/util/ViewModelHelpers.kt
3093216056
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.util import com.google.gson.Gson import okhttp3.* /** * A list of fake results to return. */ private val FAKE_RESULTS = listOf( "Hello, coroutines!", "My favorite feature", "Async made easy", "Coroutines by example", "Check out the Advanced Coroutines codelab next!" ) /** * This class will return fake [Response] objects to Retrofit, without actually using the network. */ class SkipNetworkInterceptor: Interceptor { private var lastResult: String = "" val gson = Gson() private var attempts = 0 /** * Return true iff this request should error. */ private fun wantRandomError() = attempts++ % 5 == 0 /** * Stop the request from actually going out to the network. */ override fun intercept(chain: Interceptor.Chain): Response { pretendToBlockForNetworkRequest() return if (wantRandomError()) { makeErrorResult(chain.request()) } else { makeOkResult(chain.request()) } } /** * Pretend to "block" interacting with the network. * * Really: sleep for 500ms. */ private fun pretendToBlockForNetworkRequest() = Thread.sleep(500) /** * Generate an error result. * * ``` * HTTP/1.1 500 Bad server day * Content-type: application/json * * {"cause": "not sure"} * ``` */ private fun makeErrorResult(request: Request): Response { return Response.Builder() .code(500) .request(request) .protocol(Protocol.HTTP_1_1) .message("Bad server day") .body(ResponseBody.create( MediaType.get("application/json"), gson.toJson(mapOf("cause" to "not sure")))) .build() } /** * Generate a success response. * * ``` * HTTP/1.1 200 OK * Content-type: application/json * * "$random_string" * ``` */ private fun makeOkResult(request: Request): Response { var nextResult = lastResult while (nextResult == lastResult) { nextResult = FAKE_RESULTS.random() } lastResult = nextResult return Response.Builder() .code(200) .request(request) .protocol(Protocol.HTTP_1_1) .message("OK") .body(ResponseBody.create( MediaType.get("application/json"), gson.toJson(nextResult))) .build() } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/util/SkipNetworkInterceptor.kt
2595393461
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines import android.app.Application import androidx.work.Configuration import androidx.work.Constraints import androidx.work.ExistingPeriodicWorkPolicy.KEEP import androidx.work.NetworkType.UNMETERED import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import com.example.android.kotlincoroutines.main.RefreshMainDataWork import java.util.concurrent.TimeUnit /** * Override application to setup background work via [WorkManager] */ class KotlinCoroutinesApp : Application() { /** * onCreate is called before the first screen is shown to the user. * * Use it to setup any background tasks, running expensive setup operations in a background * thread to avoid delaying app start. */ override fun onCreate() { super.onCreate() setupWorkManagerJob() } /** * Setup WorkManager background job to 'fetch' new network data daily. */ private fun setupWorkManagerJob() { // initialize WorkManager with a Factory val workManagerConfiguration = Configuration.Builder() .setWorkerFactory(RefreshMainDataWork.Factory()) .build() WorkManager.initialize(this, workManagerConfiguration) // Use constraints to require the work only run when the device is charging and the // network is unmetered val constraints = Constraints.Builder() .setRequiresCharging(true) .setRequiredNetworkType(UNMETERED) .build() // Specify that the work should attempt to run every day val work = PeriodicWorkRequestBuilder<RefreshMainDataWork>(1, TimeUnit.DAYS) .setConstraints(constraints) .build() // Enqueue it work WorkManager, keeping any previously scheduled jobs for the same // work. WorkManager.getInstance(this) .enqueueUniquePeriodicWork(RefreshMainDataWork::class.java.name, KEEP, work) } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/KotlinCoroutinesApp.kt
1512256766
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.kotlincoroutines.util.BACKGROUND import com.example.android.kotlincoroutines.util.singleArgViewModelFactory import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * MainViewModel designed to store and manage UI-related data in a lifecycle conscious way. This * allows data to survive configuration changes such as screen rotations. In addition, background * work such as fetching network results can continue through configuration changes and deliver * results after the new Fragment or Activity is available. * * @param repository the data source this ViewModel will fetch results from. */ class MainViewModel(private val repository: TitleRepository) : ViewModel() { companion object { /** * Factory for creating [MainViewModel] * * @param arg the repository to pass to [MainViewModel] */ val FACTORY = singleArgViewModelFactory(::MainViewModel) } /** * Request a snackbar to display a string. * * This variable is private because we don't want to expose MutableLiveData * * MutableLiveData allows anyone to set a value, and MainViewModel is the only * class that should be setting values. */ private val _snackBar = MutableLiveData<String?>() /** * Request a snackbar to display a string. */ val snackbar: LiveData<String?> get() = _snackBar /** * Update title text via this LiveData */ val title = repository.title private val _spinner = MutableLiveData<Boolean>(false) /** * Show a loading spinner if true */ val spinner: LiveData<Boolean> get() = _spinner /** * Count of taps on the screen */ private var tapCount = 0 /** * LiveData with formatted tap count. */ private val _taps = MutableLiveData<String>("$tapCount taps") /** * Public view of tap live data. */ val taps: LiveData<String> get() = _taps /** * Respond to onClick events by refreshing the title. * * The loading spinner will display until a result is returned, and errors will trigger * a snackbar. */ fun onMainViewClicked() { refreshTitle() updateTaps() } /** * Wait one second then update the tap count. */ private fun updateTaps() { viewModelScope.launch { tapCount++ delay(1000L) _taps.postValue("${tapCount} taps") } } /** * Called immediately after the UI shows the snackbar. */ fun onSnackbarShown() { _snackBar.value = null } /** * Refresh the title, showing a loading spinner while it refreshes and errors via snackbar. */ fun refreshTitle() { launchDataLoad { repository.refreshTitle() } // _spinner.value = true // repository.refreshTitleWithCallbacks(object : TitleRefreshCallback { // override fun onCompleted() { // _spinner.postValue(false) // } // // override fun onError(cause: Throwable) { // _snackBar.postValue(cause.message) // _spinner.postValue(false) // } // }) } private fun launchDataLoad(block: suspend () -> Unit): Unit { viewModelScope.launch { try { _spinner.value = true block() } catch (error: TitleRefreshError) { _snackBar.value = error.message } finally { _spinner.value = false } } } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainViewModel.kt
3544183399
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import androidx.lifecycle.LiveData import androidx.lifecycle.map import com.example.android.kotlincoroutines.util.BACKGROUND import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout /** * TitleRepository provides an interface to fetch a title or request a new one be generated. * * Repository modules handle data operations. They provide a clean API so that the rest of the app * can retrieve this data easily. They know where to get the data from and what API calls to make * when data is updated. You can consider repositories to be mediators between different data * sources, in our case it mediates between a network API and an offline database cache. */ class TitleRepository(val network: MainNetwork, val titleDao: TitleDao) { /** * [LiveData] to load title. * * This is the main interface for loading a title. The title will be loaded from the offline * cache. * * Observing this will not cause the title to be refreshed, use [TitleRepository.refreshTitleWithCallbacks] * to refresh the title. */ val title: LiveData<String?> = titleDao.titleLiveData.map { it?.title } suspend fun refreshTitle() { try { val result = withTimeout(5000L) { network.fetchNextTitle() } titleDao.insertTitle(Title(result)) } catch (cause: Throwable) { throw TitleRefreshError("unable to refresh", cause) } } /** * Refresh the current title and save the results to the offline cache. * * This method does not return the new title. Use [TitleRepository.title] to observe * the current tile. */ // fun refreshTitleWithCallbacks(titleRefreshCallback: TitleRefreshCallback) { // // This request will be run on a background thread by retrofit // BACKGROUND.submit { // try { // // Make network request using a blocking call // val result = network.fetchNextTitle().execute() // if (result.isSuccessful) { // // Save it to database // titleDao.insertTitle(Title(result.body()!!)) // // Inform the caller the refresh is completed // titleRefreshCallback.onCompleted() // } else { // // If it's not successful, inform the callback of the error // titleRefreshCallback.onError( // TitleRefreshError("Unable to refresh title", null)) // } // } catch (cause: Throwable) { // // If anything throws an exception, inform the caller // titleRefreshCallback.onError( // TitleRefreshError("Unable to refresh title", cause)) // } // } // } } /** * Thrown when there was a error fetching a new title * * @property message user ready error message * @property cause the original cause of this exception */ class TitleRefreshError(message: String, cause: Throwable?) : Throwable(message, cause) interface TitleRefreshCallback { fun onCompleted() fun onError(cause: Throwable) }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/TitleRepository.kt
837922728
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import android.content.Context import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Database import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.PrimaryKey import androidx.room.Query import androidx.room.Room import androidx.room.RoomDatabase /** * Title represents the title fetched from the network */ @Entity data class Title constructor(val title: String, @PrimaryKey val id: Int = 0) /*** * Very small database that will hold one title */ @Dao interface TitleDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertTitle(title: Title) @get:Query("select * from Title where id = 0") val titleLiveData: LiveData<Title?> } /** * TitleDatabase provides a reference to the dao to repositories */ @Database(entities = [Title::class], version = 1, exportSchema = false) abstract class TitleDatabase : RoomDatabase() { abstract val titleDao: TitleDao } private lateinit var INSTANCE: TitleDatabase /** * Instantiate a database from a context. */ fun getDatabase(context: Context): TitleDatabase { synchronized(TitleDatabase::class) { if (!::INSTANCE.isInitialized) { INSTANCE = Room .databaseBuilder( context.applicationContext, TitleDatabase::class.java, "titles_db" ) .fallbackToDestructiveMigration() .build() } } return INSTANCE }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainDatabase.kt
412325288
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import android.os.Bundle import android.view.View import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.lifecycle.ViewModelProvider import com.example.android.kotlincoroutines.R import com.google.android.material.snackbar.Snackbar /** * Show layout.activity_main and setup data binding. */ class MainActivity : AppCompatActivity() { /** * Inflate layout.activity_main and setup data binding. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rootLayout: ConstraintLayout = findViewById(R.id.rootLayout) val title: TextView = findViewById(R.id.title) val taps: TextView = findViewById(R.id.taps) val spinner: ProgressBar = findViewById(R.id.spinner) // Get MainViewModel by passing a database to the factory val database = getDatabase(this) val repository = TitleRepository(getNetworkService(), database.titleDao) val viewModel = ViewModelProvider(this, MainViewModel.FACTORY(repository)) .get(MainViewModel::class.java) // When rootLayout is clicked call onMainViewClicked in ViewModel rootLayout.setOnClickListener { viewModel.onMainViewClicked() } // update the title when the [MainViewModel.title] changes viewModel.title.observe(this) { value -> value?.let { title.text = it } } viewModel.taps.observe(this) { value -> taps.text = value } // show the spinner when [MainViewModel.spinner] is true viewModel.spinner.observe(this) { value -> value.let { show -> spinner.visibility = if (show) View.VISIBLE else View.GONE } } // Show a snackbar whenever the [ViewModel.snackbar] is updated a non-null value viewModel.snackbar.observe(this) { text -> text?.let { Snackbar.make(rootLayout, text, Snackbar.LENGTH_SHORT).show() viewModel.onSnackbarShown() } } } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainActivity.kt
2450682549
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import android.content.Context import androidx.work.CoroutineWorker import androidx.work.ListenableWorker import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerFactory import androidx.work.WorkerParameters /** * Worker job to refresh titles from the network while the app is in the background. * * WorkManager is a library used to enqueue work that is guaranteed to execute after its constraints * are met. It can run work even when the app is in the background, or not running. */ class RefreshMainDataWork(context: Context, params: WorkerParameters, private val network: MainNetwork) : CoroutineWorker(context, params) { /** * Refresh the title from the network using [TitleRepository] * * WorkManager will call this method from a background thread. It may be called even * after our app has been terminated by the operating system, in which case [WorkManager] will * start just enough to run this [Worker]. */ override suspend fun doWork(): Result { val database = getDatabase(applicationContext) val repository = TitleRepository(network, database.titleDao) return try { repository.refreshTitle() Result.success() } catch (error: TitleRefreshError) { Result.failure() } } class Factory(val network: MainNetwork = getNetworkService()) : WorkerFactory() { override fun createWorker(appContext: Context, workerClassName: String, workerParameters: WorkerParameters): ListenableWorker? { return RefreshMainDataWork(appContext, workerParameters, network) } } }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/RefreshMainDataWork.kt
1967649236
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.main import com.example.android.kotlincoroutines.util.SkipNetworkInterceptor import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET private val service: MainNetwork by lazy { val okHttpClient = OkHttpClient.Builder() .addInterceptor(SkipNetworkInterceptor()) .build() val retrofit = Retrofit.Builder() .baseUrl("http://localhost/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() retrofit.create(MainNetwork::class.java) } fun getNetworkService() = service /** * Main network interface which will fetch a new welcome title for us */ interface MainNetwork { @GET("next_title.json") suspend fun fetchNextTitle(): String }
corutinesCodelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainNetwork.kt
2014421954
/* * Copyright (C) 2019 Google LLC * * 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 * * http://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.android.kotlincoroutines.fakes import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.android.kotlincoroutines.main.MainNetwork import com.example.android.kotlincoroutines.main.Title import com.example.android.kotlincoroutines.main.TitleDao import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import okhttp3.Request import okio.Timeout import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Fake [TitleDao] for use in tests. */ class TitleDaoFake(initialTitle: String) : TitleDao { /** * A channel is a Coroutines based implementation of a blocking queue. * * We're using it here as a buffer of inserted elements. * * This uses a channel instead of a list to allow multiple threads to call insertTitle and * synchronize the results with the test thread. */ private val insertedForNext = Channel<Title>(capacity = Channel.BUFFERED) override fun insertTitle(title: Title) { insertedForNext.trySend(title) _titleLiveData.value = title } private val _titleLiveData = MutableLiveData<Title?>(Title(initialTitle)) override val titleLiveData: LiveData<Title?> get() = _titleLiveData /** * Assertion that the next element inserted has a title of expected * * If the element was previously inserted and is currently the most recent element * this assertion will also match. This allows tests to avoid synchronizing calls to insert * with calls to assertNextInsert. * * If multiple items were inserted, this will always match the first item that was not * previously matched. * * @param expected the value to match * @param timeout duration to wait (this is provided for instrumentation tests that may run on * multiple threads) * @param unit timeunit * @return the next value that was inserted into this dao, or null if none found */ fun nextInsertedOrNull(timeout: Long = 2_000): String? { var result: String? = null runBlocking { // wait for the next insertion to complete try { withTimeout(timeout) { result = insertedForNext.receive().title } } catch (ex: TimeoutCancellationException) { // ignore } } return result } } /** * Testing Fake implementation of MainNetwork */ class MainNetworkFake(var result: String) : MainNetwork { override suspend fun fetchNextTitle() = result } /** * Testing Fake for MainNetwork that lets you complete or error all current requests */ class MainNetworkCompletableFake() : MainNetwork { private var completable = CompletableDeferred<String>() override suspend fun fetchNextTitle() = completable.await() fun sendCompletionToAllCurrentRequests(result: String) { completable.complete(result) completable = CompletableDeferred() } fun sendErrorToCurrentRequests(throwable: Throwable) { completable.completeExceptionally(throwable) completable = CompletableDeferred() } } typealias MakeCompilerHappyForStarterCode = FakeCallForRetrofit<String> /** * This class only exists to make the starter code compile. Remove after refactoring retrofit to use * suspend functions. */ class FakeCallForRetrofit<T> : Call<T> { override fun enqueue(callback: Callback<T>) { // nothing } override fun isExecuted() = false override fun clone(): Call<T> { return this } override fun isCanceled() = true override fun cancel() { // nothing } override fun execute(): Response<T> { TODO("Not implemented") } override fun request(): Request { TODO("Not implemented") } override fun timeout(): Timeout { TODO("Not yet implemented") } }
corutinesCodelab/start/src/debug/java/com/example/android/kotlincoroutines/fakes/TestingFakes.kt
1925096558
package com.example.appmarvels 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.appmarvels", appContext.packageName) } }
appMarvels/app/src/androidTest/java/com/example/appmarvels/ExampleInstrumentedTest.kt
2192627106
package com.example.appmarvels import com.example.appmarvels.framework.useCase.base.CoroutinesDispatchers import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.* import kotlinx.coroutines.Dispatchers import org.junit.rules.TestWatcher import org.junit.runner.Description @ExperimentalCoroutinesApi class MainCoroutineRule( val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(TestCoroutineScheduler()) ) : TestWatcher() { val testDispatcherProvider = object : CoroutinesDispatchers { override fun default(): CoroutineDispatcher = testDispatcher override fun io(): CoroutineDispatcher = testDispatcher override fun main(): CoroutineDispatcher = testDispatcher override fun unconfined(): CoroutineDispatcher = testDispatcher } override fun starting(description: Description) { super.starting(description) Dispatchers.setMain(testDispatcher) } override fun finished(description: Description) { super.finished(description) Dispatchers.resetMain() } }
appMarvels/app/src/test/java/com/example/appmarvels/MainCoroutineRule.kt
4079597082
package com.example.appmarvels.framework.paging import androidx.paging.PagingSource import com.example.appmarvels.MainCoroutineRule import com.example.appmarvels.framework.repository.CharactersRemoteDataSource import com.example.appmarvels.model.CharacterFactory import com.example.appmarvels.model.CharacterPagingFactory import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import java.lang.RuntimeException import com.example.appmarvels.framework.model.Character @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class CharactersPagingSourceTest { @get:Rule var mainCoroutineRule = MainCoroutineRule() @Mock lateinit var remoteDataSource: CharactersRemoteDataSource private val characterPagingFactory = CharacterPagingFactory() private val characterFactory = CharacterFactory() private lateinit var charactersPagingSource: CharactersPagingSource @Before fun setUp() { charactersPagingSource = CharactersPagingSource(remoteDataSource, "") } @Test fun `should return a success load result when load is called`() = runTest { // Arrange whenever(remoteDataSource.fetchCharacters(any())).thenReturn(characterPagingFactory.create()) // Act val result = charactersPagingSource.load( PagingSource.LoadParams.Refresh(null, loadSize = 2, false) ) // Assert val expected = listOf( characterFactory.create(CharacterFactory.Hero.ThreeDMan), characterFactory.create(CharacterFactory.Hero.ABomb) ) assertEquals( PagingSource.LoadResult.Page( data = expected, prevKey = null, nextKey = 20 ), result ) } @Test fun `should return a error load when load is called`() = runTest { //Arrange val exception = RuntimeException() whenever(remoteDataSource.fetchCharacters(any())).thenThrow(exception) //Act val result = charactersPagingSource.load( PagingSource.LoadParams.Refresh( key = null, loadSize = 2, placeholdersEnabled = false )) //Assert assertEquals( PagingSource.LoadResult.Error<Int, Character>(exception), result ) } }
appMarvels/app/src/test/java/com/example/appmarvels/framework/paging/CharactersPagingSourceTest.kt
1916971387
package com.example.appmarvels 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) } }
appMarvels/app/src/test/java/com/example/appmarvels/ExampleUnitTest.kt
4151691601
package com.example.appmarvels.model import com.example.appmarvels.framework.model.CharacterPaging import com.example.appmarvels.framework.model.Character class CharacterPagingFactory { fun create() = CharacterPaging( offset = 0, total = 2, characters = listOf( Character( id = 1011334, name = "3-D Man", imageUrl = "https://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784.jpg" ), Character( id = 1017100, name = "A-Bomb (HAS)", imageUrl = "https://i.annihil.us/u/prod/marvel/i/mg/3/20/5232158de5b16.jpg" ) ) ) }
appMarvels/app/src/test/java/com/example/appmarvels/model/CharacterPagingFactory.kt
2225042384
package com.example.appmarvels.model import com.example.appmarvels.framework.model.Comic class ComicFactory { fun create(comic: FakeComic) = when (comic) { FakeComic.FakeComic1 -> Comic( 2211506, "http://fakecomigurl.jpg" ) } sealed class FakeComic { object FakeComic1 : FakeComic() } }
appMarvels/app/src/test/java/com/example/appmarvels/model/ComicFactory.kt
3895788016
package com.example.appmarvels.model import com.example.appmarvels.framework.model.Character class CharacterFactory { fun create(hero: Hero) = when(hero) { Hero.ThreeDMan -> Character( 1011334, "3-D Man", "https://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784.jpg" ) Hero.ABomb -> Character( 1017100, "A-Bomb (HAS)", "https://i.annihil.us/u/prod/marvel/i/mg/3/20/5232158de5b16.jpg" ) } sealed class Hero { object ThreeDMan : Hero() object ABomb : Hero() } }
appMarvels/app/src/test/java/com/example/appmarvels/model/CharacterFactory.kt
3042055772
package com.example.appmarvels.model import com.example.appmarvels.framework.model.Event class EventFactory { fun create(event: FakeEvent) = when (event) { FakeEvent.FakeEvent1 -> Event( 1, "http://fakeurl.jpg" ) } sealed class FakeEvent { object FakeEvent1 : FakeEvent() } }
appMarvels/app/src/test/java/com/example/appmarvels/model/EventFactory.kt
1636894609