content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.ktlintstudy.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 KtlintStudyTheme(
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
)
}
|
KtlintStudy/app/src/main/java/com/example/ktlintstudy/ui/theme/Theme.kt
|
2328214413
|
package com.example.ktlintstudy.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
)
*/
)
|
KtlintStudy/app/src/main/java/com/example/ktlintstudy/ui/theme/Type.kt
|
2197122170
|
package com.example.ktlintstudy
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.ktlintstudy.ui.theme.KtlintStudyTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KtlintStudyTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
KtlintStudyTheme {
Greeting("Android")
}
}
|
KtlintStudy/app/src/main/java/com/example/ktlintstudy/MainActivity.kt
|
524545674
|
package com.josesorli.dibuja3
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.josesorli.dibuja3", appContext.packageName)
}
}
|
AppDibujar/app/src/androidTest/java/com/josesorli/dibuja3/ExampleInstrumentedTest.kt
|
4032185090
|
package com.josesorli.dibuja3
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)
}
}
|
AppDibujar/app/src/test/java/com/josesorli/dibuja3/ExampleUnitTest.kt
|
375850829
|
package com.josesorli.dibuja3
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class DrawingView(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
private val paint = Paint()
private val path = Path()
init {
paint.color = Color.BLACK
paint.isAntiAlias = true
paint.strokeWidth = 10f
paint.style = Paint.Style.STROKE
paint.strokeJoin = Paint.Join.ROUND
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas?.drawPath(path, paint)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
path.moveTo(event.x, event.y)
return true
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(event.x, event.y)
invalidate()
}
}
return false
}
fun clearDrawing() {
path.reset()
invalidate()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val drawingView = findViewById<DrawingView>(R.id.drawingView)
// Example: Clear the drawing when a button is clicked
val clearButton = findViewById<Button>(R.id.clearButton)
clearButton.setOnClickListener {
drawingView.clearDrawing()
}
}
}
|
AppDibujar/app/src/main/java/com/josesorli/dibuja3/MainActivity.kt
|
3635246955
|
package ge.edu.btu.imdb.di.viewmodel
import ge.edu.btu.imdb.presentation.splash.vm.SplashViewModel
import ge.edu.btu.imdb.presentation.favorites.vm.FavoritesViewModel
import ge.edu.btu.imdb.presentation.home.vm.HomeViewModel
import ge.edu.btu.imdb.presentation.details.vm.DetailViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelModule = module {
viewModel { SplashViewModel(navigationApi = get()) }
viewModel {
DetailViewModel(
addFavoriteMovieUseCase = get(),
checkIfMovieIsFavoritesUseCase = get(),
deleteFavoriteMovieUseCase = get(),
navigationApi = get()
)
}
viewModel {
HomeViewModel(
navigationApi = get(),
getMovieUseCase = get(),
searchMovieUseCase = get(),
addFavoriteMovieUseCase = get(),
checkIfMovieIsFavoritesUseCase = get(),
deleteFavoriteMovieUseCase = get(),
getAllFavoriteMovieIdsUseCase = get()
)
}
viewModel {
FavoritesViewModel(
navigationApi = get(),
getFavoriteMoviesUseCase = get(),
deleteFavoriteMovieUseCase = get()
)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/viewmodel/ViewModelModule.kt
|
1182790961
|
package ge.edu.btu.imdb.di.network
import ge.edu.btu.imdb.common.constants.Constants.BASE_URL
import ge.edu.btu.imdb.data.remote.network.AuthInterceptor
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
val networkModule = module {
/**
* Provides an instance of OkHttpClient configured with various interceptors.
*/
single {
OkHttpClient.Builder()
.addInterceptor(getLoggingInterceptor())
.addInterceptor(AuthInterceptor())
.build()
}
/**
* Provides an instance of Moshi JSON converter with KotlinJsonAdapterFactory.
*/
single {
Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
}
/**
* Provides an instance of Retrofit with the configured base URL, Moshi converter, and OkHttpClient.
*/
single {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(get()))
.client(get())
.build()
}
}
/**
* Creates an instance of HttpLoggingInterceptor configured with the desired log level.
*
* @return The configured HttpLoggingInterceptor instance.
*/
private fun getLoggingInterceptor() = HttpLoggingInterceptor().apply {
setLevel(HttpLoggingInterceptor.Level.BODY)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/network/NetworkModule.kt
|
4207433862
|
package ge.edu.btu.imdb.di.navigation
import ge.edu.btu.imdb.navigation.NavControllerManager
import ge.edu.btu.imdb.navigation.dashboard.DashboardNavigationImpl
import ge.edu.btu.imdb.navigation.dashboard.DashboardNavigationApi
import ge.edu.btu.imdb.navigation.detail.DetailNavigationApi
import ge.edu.btu.imdb.navigation.detail.DetailNavigationImpl
import ge.edu.btu.imdb.navigation.NavControllerManagerImpl
import ge.edu.btu.imdb.navigation.splash.SplashNavigationImpl
import ge.edu.btu.imdb.navigation.splash.SplashNavigationApi
import org.koin.dsl.module
val navigationModule = module {
single<NavControllerManager> { NavControllerManagerImpl() }
single<SplashNavigationApi> { SplashNavigationImpl(get()) }
single<DetailNavigationApi> { DetailNavigationImpl(get()) }
single<DashboardNavigationApi> { DashboardNavigationImpl(navControllerManager = get()) }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/navigation/NavigationModule.kt
|
1508863246
|
package ge.edu.btu.imdb.di.dashboard
import ge.edu.btu.imdb.domain.mapper.MoviesDTOToDomainMapper
import org.koin.dsl.module
val dashboardMapperModule = module {
single { MoviesDTOToDomainMapper() }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/dashboard/DashboardMapperModule.kt
|
539245886
|
package ge.edu.btu.imdb.di.dashboard
import ge.edu.btu.imdb.data.repository.remote.MoviesRepositoryImpl
import ge.edu.btu.imdb.domain.repository.remote.MoviesRepository
import org.koin.dsl.module
val dashboardRepositoryModule = module {
single<MoviesRepository> {
MoviesRepositoryImpl(
moviesApiService = get(), mapper =get()
)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/dashboard/DashboardRepositoryModule.kt
|
3851806094
|
package ge.edu.btu.imdb.di.dashboard
import ge.edu.btu.imdb.domain.usecase.remote.GetMovieUseCase
import ge.edu.btu.imdb.dashboardimpl.container.domain.usecase.remote.SearchMovieUseCase
import org.koin.dsl.module
val dashboardUseCaseModule = module {
single { GetMovieUseCase(moviesRepository = get()) }
single { SearchMovieUseCase(repository = get()) }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/dashboard/DashboardUseCaseModule.kt
|
1161931991
|
package ge.edu.btu.imdb.di.db
import ge.edu.btu.imdb.data.mapper.DomainToEntityMapper
import ge.edu.btu.imdb.domain.mapper.EntityToDomainMapper
import org.koin.dsl.module
val coreDBMapperModule = module {
single { DomainToEntityMapper() }
single { EntityToDomainMapper() }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/db/CoreDBMapperModule.kt
|
2422940649
|
package ge.edu.btu.imdb.di.db
import ge.edu.btu.imdb.domain.usecase.local.AddFavoriteMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.CheckIfMovieIsFavoritesUseCase
import ge.edu.btu.imdb.domain.usecase.local.DeleteFavoriteMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.GetAllFavoriteMovieIdsUseCase
import ge.edu.btu.imdb.domain.usecase.local.GetFavoriteMoviesUseCase
import org.koin.dsl.module
val coreDBUseCaseModule = module {
single { AddFavoriteMovieUseCase(favoritesRepository = get()) }
single { DeleteFavoriteMovieUseCase(favoritesRepository = get()) }
single { GetFavoriteMoviesUseCase(favoritesRepository = get()) }
single { CheckIfMovieIsFavoritesUseCase(favoritesRepository = get()) }
single { GetAllFavoriteMovieIdsUseCase(favoritesRepository = get()) }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/db/CoreDBUseCaseModule.kt
|
691741235
|
package ge.edu.btu.imdb.di.db
import android.app.Application
import androidx.room.Room
import ge.edu.btu.imdb.data.local.database.FavoriteMoviesDatabase
import org.koin.android.ext.koin.androidApplication
import org.koin.dsl.module
const val FAVORITE_MOVIES_DATABASE_NAME = "favorite_movies_database"
private fun provideAppDatabase(application: Application): FavoriteMoviesDatabase {
return Room.databaseBuilder(
application,
FavoriteMoviesDatabase::class.java,
FAVORITE_MOVIES_DATABASE_NAME
)
.fallbackToDestructiveMigration()
.build()
}
private fun provideUserDao(database: FavoriteMoviesDatabase) = database.favoriteMoviesDao()
val databaseModule = module {
single { provideAppDatabase(androidApplication()) }
single { provideUserDao(database = get()) }
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/db/DatabaseModule.kt
|
2420288954
|
package ge.edu.btu.imdb.di.db
import ge.edu.btu.imdb.data.repository.local.FavoritesRepositoryImpl
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
import org.koin.dsl.module
val coreDBRepositoryModule = module {
single<FavoritesRepository> {
FavoritesRepositoryImpl(
favoriteMoviesDao = get(),
domainToEntityMapper = get(),
entityToDomainMapper = get()
)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/db/CoreDBRepositoryModule.kt
|
3940096210
|
package ge.edu.btu.imdb.di.service
import ge.edu.btu.imdb.data.remote.network.MoviesApiService
import org.koin.dsl.module
import retrofit2.Retrofit
val serviceModule = module {
single {
get<Retrofit>().create(MoviesApiService::class.java)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/di/service/ServiceModule.kt
|
2514149982
|
package ge.edu.btu.imdb
import android.app.Application
import ge.edu.btu.imdb.di.dashboard.dashboardMapperModule
import ge.edu.btu.imdb.di.dashboard.dashboardRepositoryModule
import ge.edu.btu.imdb.di.dashboard.dashboardUseCaseModule
import ge.edu.btu.imdb.di.service.serviceModule
import ge.edu.btu.imdb.di.db.coreDBMapperModule
import ge.edu.btu.imdb.di.db.coreDBRepositoryModule
import ge.edu.btu.imdb.di.db.coreDBUseCaseModule
import ge.edu.btu.imdb.di.db.databaseModule
import ge.edu.btu.imdb.di.navigation.navigationModule
import ge.edu.btu.imdb.di.viewmodel.viewModelModule
import ge.edu.btu.imdb.di.network.networkModule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.GlobalContext.startKoin
class MovieApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MovieApp)
modules(
navigationModule, viewModelModule, networkModule, serviceModule,
dashboardMapperModule, dashboardRepositoryModule, dashboardUseCaseModule,
databaseModule, coreDBRepositoryModule, coreDBMapperModule,
coreDBUseCaseModule
)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/MovieApp.kt
|
2924757595
|
package ge.edu.btu.imdb.navigation
import androidx.navigation.NavController
interface NavControllerManager {
fun setNavController(navController: NavController)
fun getNavController():NavController
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/NavControllerManager.kt
|
3468082583
|
package ge.edu.btu.imdb.navigation.splash
interface SplashNavigationApi {
fun navigateToSplash()
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/splash/SplashNavigationApi.kt
|
1905122770
|
package ge.edu.btu.imdb.navigation.splash
import ge.edu.btu.imdb.navigation.NavControllerManager
import ge.edu.btu.imdb.R
class SplashNavigationImpl(private val navControllerManager: NavControllerManager) :
SplashNavigationApi {
override fun navigateToSplash() {
navControllerManager.getNavController().navigate(R.id.splash_nav_graph)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/splash/SplashNavigationImpl.kt
|
581818626
|
package ge.edu.btu.imdb.navigation.dashboard
interface DashboardNavigationApi {
fun navigateToDashboard()
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/dashboard/DashboardNavigationApi.kt
|
1372364569
|
package ge.edu.btu.imdb.navigation.dashboard
import ge.edu.btu.imdb.navigation.NavControllerManager
import ge.edu.btu.imdb.R
class DashboardNavigationImpl (private val navControllerManager: NavControllerManager) :
DashboardNavigationApi {
override fun navigateToDashboard() {
navControllerManager.getNavController().navigate(R.id.dashboard_nav_graph)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/dashboard/DashboardNavigationImpl.kt
|
2110216227
|
package ge.edu.btu.imdb.navigation.detail
import android.os.Bundle
interface DetailNavigationApi {
fun navigateToDetail(bundle: Bundle)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/detail/DetailNavigationApi.kt
|
385395109
|
package ge.edu.btu.imdb.navigation.detail
import android.os.Bundle
import ge.edu.btu.imdb.navigation.NavControllerManager
import ge.edu.btu.imdb.R
class DetailNavigationImpl (private val navControllerManager: NavControllerManager) :
DetailNavigationApi {
override fun navigateToDetail(bundle: Bundle) {
navControllerManager.getNavController().navigate(R.id.detail_nav_graph,bundle)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/detail/DetailNavigationImpl.kt
|
1825181687
|
package ge.edu.btu.imdb.navigation
import androidx.navigation.NavController
import ge.edu.btu.imdb.navigation.NavControllerManager
class NavControllerManagerImpl(): NavControllerManager {
private lateinit var navController: NavController
override fun setNavController(navController: NavController) {
this.navController = navController
}
override fun getNavController(): NavController {
return navController
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/navigation/NavControllerManagerImpl.kt
|
1601513217
|
package ge.edu.btu.imdb.common.extension
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
fun TextView.setTextColorCompat(@ColorRes colorResource: Int) {
val colorValue = ContextCompat.getColor(context, colorResource)
setTextColor(colorValue)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/TextViewExtension.kt
|
552293432
|
package ge.edu.btu.imdb.common.extension
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/** Activity binding delegate, may be used since onCreate up to onDestroy (inclusive) */
inline fun <T : ViewBinding> AppCompatActivity.viewBinding(crossinline factory: (LayoutInflater) -> T) =
lazy(LazyThreadSafetyMode.NONE) {
factory(layoutInflater)
}
/** Fragment binding delegate, may be used since onViewCreated up to onDestroyView (inclusive) */
fun <T : ViewBinding> Fragment.viewBinding(factory: (View) -> T): ReadOnlyProperty<Fragment, T> =
object : ReadOnlyProperty<Fragment, T>, DefaultLifecycleObserver {
private var binding: T? = null
override fun getValue(thisRef: Fragment, property: KProperty<*>): T =
binding ?: factory(requireView()).also {
// if binding is accessed after Lifecycle is DESTROYED, create new instance, but don't cache it
if (viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
viewLifecycleOwner.lifecycle.addObserver(this)
binding = it
}
}
override fun onDestroy(owner: LifecycleOwner) {
binding = null
}
}
/** Not really a delegate, just a small helper for RecyclerView.ViewHolders */
inline fun <T : ViewBinding> ViewGroup.viewBinding(factory: (LayoutInflater, ViewGroup, Boolean) -> T) =
factory(LayoutInflater.from(context), this, false)
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/ViewBindingDelegates.kt
|
1116088927
|
package ge.edu.btu.imdb.common.extension
import android.widget.ImageView
import com.bumptech.glide.Glide
import ge.edu.btu.imdb.R
fun ImageView.setImage(url: String?){
Glide.with(this.context)
.load(url)
.placeholder(R.drawable.ic_no_data)
.error(R.drawable.ic_no_data)
.into(this)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/ImageViewExtension.kt
|
2245422237
|
package ge.edu.btu.imdb.common.extension
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
fun Context.isNetworkAvailable(): Boolean {
val connectivityManager =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
capabilities?.run {
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
) || hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
} ?: false
} else {
false
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/InternetExtension.kt
|
244132714
|
package ge.edu.btu.imdb.common.extension
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
/**
* Extension functions for simplifying common coroutine operations related to ViewModels and Fragments.
*/
/**
* Launches a coroutine within the ViewModel's scope with the provided coroutine context.
*
* @param coroutineContext The coroutine context in which the coroutine should run. Default is Dispatchers.IO.
* @param block The suspend block of code to be executed within the coroutine.
*/
fun ViewModel.viewModelScope(
coroutineContext: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> Unit
) {
viewModelScope.launch(coroutineContext) {
block()
}
}
/**
* Launches a coroutine within the fragment's lifecycle scope, with the provided coroutine context,
* and repeats the execution when the lifecycle state changes to the specified state.
*
* @param coroutineContext The coroutine context in which the coroutine should run. Default is Dispatchers.Main.
* @param lifecycleState The desired lifecycle state at which to start and repeat the coroutine. Default is RESUMED.
* @param block The suspend block of code to be executed within the coroutine.
*/
fun Fragment.lifecycleScope(
coroutineContext: CoroutineContext = Dispatchers.Main,
lifecycleState: Lifecycle.State = Lifecycle.State.RESUMED,
block: suspend CoroutineScope.() -> Unit
) {
viewLifecycleOwner.lifecycleScope.launch(coroutineContext) {
repeatOnLifecycle(lifecycleState) {
this.block()
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/ScopesExtensions.kt
|
4152967257
|
package ge.edu.btu.imdb.common.extension
import android.view.View
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/extension/ViewExtension.kt
|
1197052857
|
package ge.edu.btu.imdb.common.constants
/**
* Object containing constant keys for passing movie item data between components.
*/
object MovieItemKeyConstant {
/**
* Key for the movie item data in a Bundle.
*/
const val MOVIE_ITEM_KEY = "movieItem"
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/constants/MovieItemKeyConstant.kt
|
413462643
|
package ge.edu.btu.imdb.common.constants
object Constants {
const val BASE_URL = "https://api.themoviedb.org/3/"
const val API_KEY = "4eab185902b1e54632f0336964e8904d"
const val IMG_BASE_URL = "https://image.tmdb.org/t/p/w342"
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/constants/Constants.kt
|
2774981877
|
package ge.edu.btu.imdb.common.mapper
interface ModelMapper<in ModelA, out ModelB> {
operator fun invoke(model: ModelA): ModelB
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/common/mapper/ModelMapper.kt
|
211255639
|
package ge.edu.btu.imdb.data.repository.local
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.data.local.dao.FavoriteMoviesDao
import ge.edu.btu.imdb.data.mapper.DomainToEntityMapper
import ge.edu.btu.imdb.domain.mapper.EntityToDomainMapper
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class FavoritesRepositoryImpl(
private val favoriteMoviesDao: FavoriteMoviesDao,
private val domainToEntityMapper: DomainToEntityMapper,
private val entityToDomainMapper: EntityToDomainMapper,
) : FavoritesRepository {
override suspend fun addFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
val favoriteMovieEntity = domainToEntityMapper(movie)
favoriteMoviesDao.insert(favoriteMovieEntity)
}
override fun getAllFavoriteMovies(): Flow<List<MoviesDomainModel.ResultDomain>> {
return favoriteMoviesDao.getAllFavoriteMovies()
.map {
it.map {
entityToDomainMapper(it)
}
}
}
override suspend fun deleteFavoriteMovieById(movieId: Int) {
favoriteMoviesDao.deleteMovieById(movieId)
}
override suspend fun isMovieFavorite(id: Int): Boolean {
return favoriteMoviesDao.isMovieFavorite(id)
}
override fun getAllFavoriteMovieIds(): Flow<List<Int>> {
return favoriteMoviesDao.getAllFavoriteMovieIds()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/repository/local/FavoritesRepositoryImpl.kt
|
1193960233
|
package ge.edu.btu.imdb.data.repository.remote
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.data.paging.MoviesPagingSource
import ge.edu.btu.imdb.data.paging.SearchPagingSource
import ge.edu.btu.imdb.data.remote.network.MoviesApiService
import ge.edu.btu.imdb.domain.mapper.MoviesDTOToDomainMapper
import ge.edu.btu.imdb.domain.repository.remote.MoviesRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class MoviesRepositoryImpl(
private val moviesApiService: MoviesApiService,
private val mapper: MoviesDTOToDomainMapper
) : MoviesRepository {
private suspend fun getGenresMap(): Map<Int, String> {
try {
val genresResponse = moviesApiService.getGenres()
val genres = genresResponse.body()?.genres ?: emptyList()
return genres.associate { it.id to it.name }
} catch (e: Exception) {
return emptyMap()
}
}
override fun getMoviesByCategory(category: String): Flow<PagingData<MoviesDomainModel.ResultDomain>> {
return Pager(
config = PagingConfig(pageSize = PAGE_SIZE, enablePlaceholders = false),
pagingSourceFactory = { MoviesPagingSource(moviesApiService, category) }
).flow
.map {
val genreMap = getGenresMap()
it.map { movie ->
mapper.mapToDomainModel(movie, genreMap)
}
}
}
override fun searchMovies(query: String): Flow<PagingData<MoviesDomainModel.ResultDomain>> {
return Pager(
config = PagingConfig(pageSize = PAGE_SIZE, enablePlaceholders = false),
pagingSourceFactory = { SearchPagingSource(moviesApiService, query) }
).flow
.map {
val genreMap = getGenresMap()
it.map { movie ->
mapper.mapToDomainModel(movie, genreMap)
}
}
}
companion object {
private const val PAGE_SIZE = 20
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/repository/remote/MoviesRepositoryImpl.kt
|
3929086256
|
package ge.edu.btu.imdb.data.mapper
import ge.edu.btu.imdb.common.mapper.ModelMapper
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.data.model.local.FavoriteMoviesEntity
class DomainToEntityMapper : ModelMapper<MoviesDomainModel.ResultDomain, FavoriteMoviesEntity> {
override operator fun invoke(model: MoviesDomainModel.ResultDomain): FavoriteMoviesEntity {
with(model) {
return FavoriteMoviesEntity(
id = id,
title = title,
overview = overview,
posterPath = posterPath,
adult = adult,
backdropPath = backdropPath,
genreIds = genreIds,
originalLanguage = originalLanguage,
originalTitle = originalTitle,
popularity = popularity,
releaseDate = releaseDate,
video = video,
voteAverage = voteAverage,
voteCount = voteCount,
)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/mapper/DomainToEntityMapper.kt
|
1632795355
|
package ge.edu.btu.imdb.data.local.database
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import ge.edu.btu.imdb.data.local.dao.FavoriteMoviesDao
import ge.edu.btu.imdb.data.local.database.FavoriteMoviesDatabase.Companion.DB_VERSION
import ge.edu.btu.imdb.data.model.local.FavoriteMoviesEntity
import ge.edu.btu.imdb.data.local.typeconverter.Converters
@Database(
entities = [FavoriteMoviesEntity::class], version = DB_VERSION, exportSchema = false
)
@TypeConverters(Converters::class)
abstract class FavoriteMoviesDatabase : RoomDatabase() {
abstract fun favoriteMoviesDao(): FavoriteMoviesDao
companion object {
const val DB_VERSION = 6
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/local/database/FavoriteMoviesDatabase.kt
|
2837758226
|
package ge.edu.btu.imdb.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import ge.edu.btu.imdb.data.model.local.FavoriteMoviesEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface FavoriteMoviesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(movie: FavoriteMoviesEntity)
@Query("SELECT * FROM favorite_movies")
fun getAllFavoriteMovies(): Flow<List<FavoriteMoviesEntity>>
@Query("DELETE FROM favorite_movies WHERE id = :id")
suspend fun deleteMovieById(id: Int): Int
@Query("SELECT EXISTS(SELECT * FROM favorite_movies WHERE id=:id)")
suspend fun isMovieFavorite(id: Int): Boolean
@Query("SELECT id FROM favorite_movies")
fun getAllFavoriteMovieIds(): Flow<List<Int>>
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/local/dao/FavoriteMoviesDao.kt
|
1004958146
|
package ge.edu.btu.imdb.data.local.typeconverter
import androidx.room.TypeConverter
/**
* A class containing TypeConverter methods for converting between List<String> and String.
*/
class Converters {
/**
* Converts a List of Strings to a single comma-separated String.
*
* @param list The List of Strings to be converted.
* @return A comma-separated String representation of the input List.
*/
@TypeConverter
fun fromStringList(list: List<String>): String {
return list.joinToString(",")
}
/**
* Converts a comma-separated String to a List of Strings.
*
* @param data The comma-separated String to be converted.
* @return A List of Strings extracted from the input comma-separated String.
*/
@TypeConverter
fun toStringList(data: String): List<String> {
return data.split(",")
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/local/typeconverter/Converters.kt
|
2550358956
|
package ge.edu.btu.imdb.data.paging
import androidx.paging.PagingSource
import androidx.paging.PagingState
import ge.edu.btu.imdb.dashboardimpl.remote.model.dto.MoviesDTOModel
import ge.edu.btu.imdb.data.remote.network.MoviesApiService
import retrofit2.HttpException
/**
* A PagingSource class for loading paginated search results based on a specified query.
*
* @param moviesApiService The MoviesApiService instance used for making API calls.
* @param query The search query string.
*/
class SearchPagingSource(
private val moviesApiService: MoviesApiService,
private val query: String
) : PagingSource<Int, MoviesDTOModel.ResultDTO>() {
/**
* Loads the requested page of search results from the API.
*
* @param params The LoadParams object containing information about the requested load.
* @return A LoadResult containing the loaded data or an error if the load operation fails.
*/
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MoviesDTOModel.ResultDTO> {
return try {
val currentPage = params.key ?: 1
val response = moviesApiService.searchMovies(query, currentPage)
val data = response.body()!!
val totalPages = response.body()!!.totalPages
LoadResult.Page(
data = data.results,
prevKey = if (currentPage == 1) null else currentPage - 1,
nextKey = if (currentPage == totalPages) null else currentPage + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
} catch (exception: HttpException) {
LoadResult.Error(exception)
}
}
/**
* Returns the key that should be used to refresh the currently loaded data.
*
* @param state The current state of the PagingSource, containing information about the loaded data.
* @return The key to be used for refreshing the data, or null if a refresh is not supported.
*/
override fun getRefreshKey(state: PagingState<Int, MoviesDTOModel.ResultDTO>): Int? {
return state.anchorPosition
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/paging/SearchPagingSource.kt
|
826570356
|
package ge.edu.btu.imdb.data.paging
import androidx.paging.PagingSource
import androidx.paging.PagingState
import ge.edu.btu.imdb.data.remote.network.MoviesApiService
import ge.edu.btu.imdb.dashboardimpl.remote.model.dto.MoviesDTOModel
import retrofit2.HttpException
/**
* A PagingSource class for loading paginated movies data based on a specified category.
*
* @param moviesApiService The MoviesApiService instance used for making API calls.
* @param category The category of movies to load (e.g., "popular", "top_rated", "upcoming").
*/
class MoviesPagingSource(
private val moviesApiService: MoviesApiService,
private val category: String,
) : PagingSource<Int, MoviesDTOModel.ResultDTO>() {
/**
* Loads the requested page of movies data from the API.
*
* @param params The LoadParams object containing information about the requested load.
* @return A LoadResult containing the loaded data or an error if the load operation fails.
*/
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MoviesDTOModel.ResultDTO> {
return try {
val currentPage = params.key ?: 1
val response = moviesApiService.getMoviesByCategory(category, currentPage)
val data = response.body()!!
val totalPages = response.body()!!.totalPages
LoadResult.Page(
data = data.results,
prevKey = if (currentPage == 1) null else currentPage - 1,
nextKey = if (currentPage == totalPages) null else currentPage + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
} catch (exception: HttpException) {
LoadResult.Error(exception)
}
}
/**
* Returns the key that should be used to refresh the currently loaded data.
*
* @param state The current state of the PagingSource, containing information about the loaded data.
* @return The key to be used for refreshing the data, or null if a refresh is not supported.
*/
override fun getRefreshKey(state: PagingState<Int, MoviesDTOModel.ResultDTO>): Int? {
return state.anchorPosition
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/paging/MoviesPagingSource.kt
|
2770572801
|
package ge.edu.btu.imdb.data.model.local
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "favorite_movies")
data class FavoriteMoviesEntity (
@PrimaryKey(autoGenerate = false)
val id: Int = 0,
val adult: Boolean?,
val backdropPath: String?,
val genreIds: List<String>?,
val originalLanguage: String?,
val originalTitle: String?,
val overview: String?,
val popularity: Double?,
val posterPath: String?,
val releaseDate: String?,
val title: String?,
val video: Boolean?,
val voteAverage: Double?,
val voteCount: Int?
)
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/model/local/FavoriteMoviesEntity.kt
|
821242713
|
package ge.edu.btu.imdb.data.model.remote.dto
data class MoviesGenresDTO(
val genres: List<Genre>
) {
data class Genre(
val id: Int,
val name: String
)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/model/remote/dto/MoviesGenresDTO.kt
|
2723989352
|
package ge.edu.btu.imdb.dashboardimpl.remote.model.dto
import com.squareup.moshi.Json
data class MoviesDTOModel(
val page: Int,
val results: List<ResultDTO>,
@Json(name = "total_pages")
val totalPages: Int,
@Json(name = "total_results")
val totalResults: Int
) {
data class ResultDTO(
val adult: Boolean?,
@Json(name = "backdrop_path")
val backdropPath: String?,
@Json(name = "genre_ids")
val genreIds: List<Int>?,
val id: Int,
@Json(name = "original_language")
val originalLanguage: String?,
@Json(name = "original_title")
val originalTitle: String?,
val overview: String?,
val popularity: Double?,
@Json(name = "poster_path")
val posterPath: String?,
@Json(name = "release_date")
val releaseDate: String?,
val title: String?,
val video: Boolean?,
@Json(name = "vote_average")
val voteAverage: Double?,
@Json(name = "vote_count")
val voteCount: Int?
)
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/model/remote/dto/MoviesDTOModel.kt
|
1835835404
|
package ge.edu.btu.imdb.data.remote.network
import ge.edu.btu.imdb.common.constants.Constants
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Response
/**
* Interceptor implementation for adding an authentication query parameter to outgoing requests.
*/
class AuthInterceptor : Interceptor {
/**
* Intercepts the request and adds the authentication query parameter before proceeding.
*
* @param chain The interceptor chain.
* @return The response from the intercepted request.
*/
override fun intercept(chain: Interceptor.Chain): Response {
// Get the original request
val original = chain.request()
// Extract the original URL
val originalHttpUrl: HttpUrl = original.url
// Build the new URL with added authentication query parameter
val url = originalHttpUrl.newBuilder()
.addQueryParameter("api_key", Constants.API_KEY)
.build()
// Build a new request with the modified URL
val requestBuilder = original.newBuilder().url(url)
val request = requestBuilder.build()
// Proceed with the new request and return the response
return chain.proceed(request)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/remote/network/AuthInterceptor.kt
|
22985743
|
package ge.edu.btu.imdb.data.remote.network
import ge.edu.btu.imdb.data.model.remote.dto.MoviesGenresDTO
import ge.edu.btu.imdb.dashboardimpl.remote.model.dto.MoviesDTOModel
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface MoviesApiService {
@GET("{category}")
suspend fun getMoviesByCategory(
@Path("category") category: String,
@Query("page") page: Int
): Response<MoviesDTOModel>
@GET("genre/movie/list")
suspend fun getGenres(): Response<MoviesGenresDTO>
@GET("search/movie")
suspend fun searchMovies(
@Query("query") query: String,
@Query("page") page: Int
): Response<MoviesDTOModel>
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/data/remote/network/MoviesApiService.kt
|
895054715
|
package ge.edu.btu.imdb.domain.repository.local
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import kotlinx.coroutines.flow.Flow
interface FavoritesRepository {
suspend fun addFavoriteMovie(movie: MoviesDomainModel.ResultDomain)
fun getAllFavoriteMovies(): Flow<List<MoviesDomainModel.ResultDomain>>
suspend fun deleteFavoriteMovieById(movieId: Int)
suspend fun isMovieFavorite(id: Int): Boolean
fun getAllFavoriteMovieIds(): Flow<List<Int>>
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/repository/local/FavoritesRepository.kt
|
1613811492
|
package ge.edu.btu.imdb.domain.repository.remote
import androidx.paging.PagingData
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import kotlinx.coroutines.flow.Flow
interface MoviesRepository {
fun getMoviesByCategory(category: String): Flow<PagingData<MoviesDomainModel.ResultDomain>>
fun searchMovies(query: String): Flow<PagingData<MoviesDomainModel.ResultDomain>>
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/repository/remote/MoviesRepository.kt
|
1851723861
|
package ge.edu.btu.imdb.domain.mapper
import ge.edu.btu.imdb.common.mapper.ModelMapper
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.data.model.local.FavoriteMoviesEntity
class EntityToDomainMapper : ModelMapper<FavoriteMoviesEntity, MoviesDomainModel.ResultDomain> {
override operator fun invoke(model: FavoriteMoviesEntity): MoviesDomainModel.ResultDomain {
with(model){
return MoviesDomainModel.ResultDomain(
id = id,
title = title,
overview = overview,
posterPath = posterPath,
adult = adult,
backdropPath = backdropPath,
genreIds = genreIds,
originalLanguage = originalLanguage,
originalTitle = originalTitle,
popularity = popularity,
releaseDate = releaseDate,
video = video,
voteAverage = voteAverage,
voteCount = voteCount,
)
}}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/mapper/EntityToDomainMapper.kt
|
55344869
|
package ge.edu.btu.imdb.domain.mapper
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.dashboardimpl.remote.model.dto.MoviesDTOModel
class MoviesDTOToDomainMapper {
fun mapToDomainModel(model: MoviesDTOModel.ResultDTO, genreMap: Map<Int, String>): MoviesDomainModel.ResultDomain {
with(model) {
return MoviesDomainModel.ResultDomain(
adult = adult,
backdropPath = backdropPath,
genreIds = genreIds?.mapNotNull { genreId -> genreMap[genreId] },
id = id,
originalLanguage = originalLanguage,
originalTitle = originalTitle,
overview = overview,
popularity = popularity,
posterPath = posterPath,
releaseDate = releaseDate,
title = title,
video = video,
voteAverage = voteAverage,
voteCount = voteCount
)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/mapper/MoviesDTOToDomainMapper.kt
|
1610769449
|
package ge.edu.btu.imdb.domain.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class MoviesDomainModel(
val page: Int,
val results: List<ResultDomain>,
val totalPages: Int,
val totalResults: Int
) : Parcelable {
@Parcelize
data class ResultDomain(
val adult: Boolean?,
val backdropPath: String?,
val genreIds: List<String>?,
val id: Int,
val originalLanguage: String?,
val originalTitle: String?,
val overview: String?,
val popularity: Double?,
val posterPath: String?,
val releaseDate: String?,
val title: String?,
val video: Boolean?,
val voteAverage: Double?,
val voteCount: Int?,
) : Parcelable {
var isFavorite: Boolean = false
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/model/MoviesDomainModel.kt
|
1878575933
|
package ge.edu.btu.imdb.domain.usecase.local
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
class CheckIfMovieIsFavoritesUseCase(private val favoritesRepository: FavoritesRepository) {
suspend operator fun invoke(movieId: Int): Boolean {
return favoritesRepository.isMovieFavorite(movieId)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/local/CheckIfMovieIsFavoritesUseCase.kt
|
3371835887
|
package ge.edu.btu.imdb.domain.usecase.local
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
class AddFavoriteMovieUseCase(private val favoritesRepository: FavoritesRepository) {
suspend operator fun invoke(movie: MoviesDomainModel.ResultDomain) {
favoritesRepository.addFavoriteMovie(movie)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/local/AddFavoriteMovieUseCase.kt
|
1988794989
|
package ge.edu.btu.imdb.domain.usecase.local
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
import kotlinx.coroutines.flow.Flow
class GetFavoriteMoviesUseCase(private val favoritesRepository: FavoritesRepository) {
operator fun invoke(): Flow<List<MoviesDomainModel.ResultDomain>> {
return favoritesRepository.getAllFavoriteMovies()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/local/GetFavoriteMoviesUseCase.kt
|
1167093205
|
package ge.edu.btu.imdb.domain.usecase.local
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
class DeleteFavoriteMovieUseCase(private val favoritesRepository: FavoritesRepository) {
suspend operator fun invoke(movieId: Int) {
favoritesRepository.deleteFavoriteMovieById(movieId)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/local/DeleteFavoriteMovieUseCase.kt
|
4136467850
|
package ge.edu.btu.imdb.domain.usecase.local
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
import kotlinx.coroutines.flow.Flow
class GetAllFavoriteMovieIdsUseCase(private val favoritesRepository: FavoritesRepository) {
fun invoke(): Flow<List<Int>> {
return favoritesRepository.getAllFavoriteMovieIds()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/local/GetAllFavoriteMovieIdsUseCase.kt
|
188983995
|
package ge.edu.btu.imdb.domain.usecase.base
abstract class BaseUseCase<in Params, out T> {
abstract suspend operator fun invoke(params: Params? = null): T
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/base/BaseUseCase.kt
|
1319376321
|
package ge.edu.btu.imdb.dashboardimpl.container.domain.usecase.remote
import androidx.paging.PagingData
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.domain.repository.remote.MoviesRepository
import kotlinx.coroutines.flow.Flow
class SearchMovieUseCase(private val repository: MoviesRepository) {
fun searchMovies(query: String): Flow<PagingData<MoviesDomainModel.ResultDomain>> {
return repository.searchMovies(query)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/remote/SearchMovieUseCase.kt
|
3173216680
|
package ge.edu.btu.imdb.domain.usecase.remote
import androidx.paging.PagingData
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.domain.repository.remote.MoviesRepository
import kotlinx.coroutines.flow.Flow
class GetMovieUseCase(private val moviesRepository: MoviesRepository) {
operator fun invoke(params: String?): Flow<PagingData<MoviesDomainModel.ResultDomain>> {
return moviesRepository.getMoviesByCategory(params!!)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/domain/usecase/remote/GetMovieUseCase.kt
|
3977589267
|
package ge.edu.btu.imdb.presentation.home.ui
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import ge.edu.btu.imdb.common.extension.lifecycleScope
import ge.edu.btu.imdb.presentation.dialog.ErrorDialogFragment
import ge.edu.btu.imdb.presentation.dialog.LoadingDialogFragment
import ge.edu.btu.imdb.common.extension.viewBinding
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.presentation.enums.MovieCategory
import ge.edu.btu.imdb.presentation.custom_view.SearchCustomView
import ge.edu.btu.imdb.databinding.FragmentHomeBinding
import ge.edu.btu.imdb.presentation.home.vm.HomeViewModel
import ge.edu.btu.imdb.presentation.home.adapter.HomeAdapter
import ge.edu.btu.imdb.presentation.base.CoreBaseFragment
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlin.reflect.KClass
class HomeFragment : CoreBaseFragment<HomeViewModel>(), SearchCustomView.OnTextChangeListener {
private lateinit var loadingDialogFragment: LoadingDialogFragment
private lateinit var errorDialogFragment: ErrorDialogFragment
private val binding by viewBinding(FragmentHomeBinding::bind)
override val viewModelClass: KClass<HomeViewModel>
get() = HomeViewModel::class
private val homeAdapter by lazy {
HomeAdapter()
}
override val layout: Int
get() = R.layout.fragment_home
override fun onBind() {
loadingDialogFragment = LoadingDialogFragment()
errorDialogFragment = ErrorDialogFragment()
binding.searchCustomView.addTextChangeListener(this)
initObserver()
setOnCLickListeners()
setUpRecycler()
setAdapterClickListeners()
setCategoryListener()
}
private fun setUpRecycler() {
binding.homeRecyclerView.adapter = homeAdapter
}
private fun setCategoryListener() {
with(binding) {
searchCustomView.setOnPopularClickListener {
viewModel.getMovies(MovieCategory.POPULAR.category)
}
searchCustomView.setOnTopRatedClickListener {
viewModel.getMovies(MovieCategory.TOP_RATED.category)
}
}
}
private fun initObserver() {
viewModel.favoriteMovieIds
.onEach { favoriteIds ->
homeAdapter.setFavoriteIds(favoriteIds)
}
.launchIn(lifecycleScope)
lifecycleScope {
viewModel.movies
.collectLatest { pagingData ->
loadingDialogFragment.dismissDialog()
homeAdapter.submitData(pagingData)
}
}
lifecycleScope {
homeAdapter.loadStateFlow.collectLatest { loadStates ->
val isLoading = loadStates.refresh is LoadState.Loading
if (isLoading) {
loadingDialogFragment.show(childFragmentManager, "LoadingDialogFragment")
} else {
loadingDialogFragment.dismissDialog()
}
val isError = loadStates.refresh is LoadState.Error
if (isError) {
showErrorDialog()
}
}
}
}
private fun setOnCLickListeners() {
with(binding) {
searchCustomView.setOnFilterClickListener {
searchCustomView.setFilterView()
}
searchCustomView.setOnSearchClickListener {
searchCustomView.setTyping()
}
searchCustomView.setOnCancelClickListener {
searchCustomView.cancelClicked()
}
}
}
private fun showErrorDialog() {
errorDialogFragment.show(childFragmentManager, "ErrorDialogFragment")
errorDialogFragment.setOnRefreshClickListener {
errorDialogFragment.dismiss()
}
}
private fun setAdapterClickListeners() {
homeAdapter.setOnItemClickListener { item ->
viewModel.navigateToDetail(item)
}
homeAdapter.setOnFavoriteClickListener { movie ->
viewLifecycleOwner.lifecycleScope.launch {
viewModel.manageFavoriteMovie(movie)
}
}
}
override fun onTextChange(query: String) {
viewModel.searchMovies(query)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/home/ui/HomeFragment.kt
|
1022598504
|
package ge.edu.btu.imdb.presentation.home.adapter
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.RecyclerView
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.extension.setImage
import ge.edu.btu.imdb.common.extension.viewBinding
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.MovieItemLayoutBinding
import ge.edu.btu.imdb.common.constants.Constants.IMG_BASE_URL
class HomeAdapter :
PagingDataAdapter<MoviesDomainModel.ResultDomain, HomeAdapter.MovieViewHolder>(DiffCallback()) {
private var onFavoriteClicked: ((MoviesDomainModel.ResultDomain) -> Unit)? = null
private var onItemClickListener: ((MoviesDomainModel.ResultDomain) -> Unit)? = null
private var favoriteIds: List<Int> = emptyList()
fun setOnFavoriteClickListener(listener: (MoviesDomainModel.ResultDomain) -> Unit) {
onFavoriteClicked = listener
}
fun setOnItemClickListener(listener: (MoviesDomainModel.ResultDomain) -> Unit) {
onItemClickListener = listener
}
fun setFavoriteIds(ids: List<Int>) {
favoriteIds = ids
notifyDataSetChanged()
}
class MovieViewHolder(
private val binding: MovieItemLayoutBinding,
private val onFavoriteClicked: ((MoviesDomainModel.ResultDomain) -> Unit)?,
private val onItemClickListener: ((MoviesDomainModel.ResultDomain) -> Unit)?,
) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: MoviesDomainModel.ResultDomain, isFavorite: Boolean) {
with(binding) {
dashboardHeadLineTextView.text = item.title
dashboardDateTextView.text = item.releaseDate?.dropLast(6)
dashboardMovieImageView.setImage(IMG_BASE_URL + item.posterPath)
dashboardCategoryTextView.text = item.genreIds?.first()
updateFavoriteIcon(isFavorite)
dashboardFavoritesImageView.setOnClickListener {
onFavoriteClicked?.invoke(item)
}
root.setOnClickListener {
onItemClickListener?.invoke(item)
}
}
}
private fun updateFavoriteIcon(isFavorite: Boolean) {
val drawableRes =
if (isFavorite) R.drawable.ic_favorites_true else R.drawable.ic_favorites_false
binding.dashboardFavoritesImageView.setImageResource(drawableRes)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
return MovieViewHolder(
parent.viewBinding(MovieItemLayoutBinding::inflate),
onFavoriteClicked,
onItemClickListener
)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val item = getItem(position)
item?.let { movie ->
val isFavorite = movie.id in favoriteIds
holder.bind(movie, isFavorite)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/home/adapter/HomeAdapter.kt
|
2054871991
|
package ge.edu.btu.imdb.presentation.home.adapter
import android.annotation.SuppressLint
import androidx.recyclerview.widget.DiffUtil
/**
* DiffUtil.ItemCallback implementation for comparing items in a RecyclerView adapter.
*
* @param T The type of items being compared.
*/
class DiffCallback<T : Any> : DiffUtil.ItemCallback<T>() {
/**
* Checks if the items have the same identity.
*
* @param oldItem The old item to compare.
* @param newItem The new item to compare.
* @return True if the items have the same identity, false otherwise.
*/
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
return oldItem === newItem
}
/**
* Checks if the contents of the items are the same.
*
* @param oldItem The old item to compare.
* @param newItem The new item to compare.
* @return True if the contents of the items are the same, false otherwise.
*/
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
return oldItem == newItem
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/home/adapter/DiffCallBack.kt
|
3780478362
|
package ge.edu.btu.imdb.presentation.home.vm
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.map
import ge.edu.btu.imdb.common.extension.viewModelScope
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.constants.MovieItemKeyConstant
import ge.edu.btu.imdb.domain.usecase.remote.GetMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.AddFavoriteMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.CheckIfMovieIsFavoritesUseCase
import ge.edu.btu.imdb.domain.usecase.local.DeleteFavoriteMovieUseCase
import ge.edu.btu.imdb.dashboardimpl.container.domain.usecase.remote.SearchMovieUseCase
import ge.edu.btu.imdb.presentation.enums.MovieCategory
import ge.edu.btu.imdb.domain.usecase.local.GetAllFavoriteMovieIdsUseCase
import ge.edu.btu.imdb.navigation.detail.DetailNavigationApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class HomeViewModel(
private val navigationApi: DetailNavigationApi,
private val getMovieUseCase: GetMovieUseCase,
private val searchMovieUseCase: SearchMovieUseCase,
private val addFavoriteMovieUseCase: AddFavoriteMovieUseCase,
private val checkIfMovieIsFavoritesUseCase: CheckIfMovieIsFavoritesUseCase,
private val deleteFavoriteMovieUseCase: DeleteFavoriteMovieUseCase,
private val getAllFavoriteMovieIdsUseCase: GetAllFavoriteMovieIdsUseCase
) : ViewModel() {
private val _movies =
MutableStateFlow<PagingData<MoviesDomainModel.ResultDomain>>(PagingData.empty())
val movies: StateFlow<PagingData<MoviesDomainModel.ResultDomain>> = _movies
private val _favoriteMovieIds: MutableStateFlow<List<Int>> = MutableStateFlow(emptyList())
val favoriteMovieIds: StateFlow<List<Int>> = _favoriteMovieIds
init {
getMovies(MovieCategory.POPULAR.category)
viewModelScope.launch {
getAllFavoriteMovieIdsUseCase.invoke()
.collect { ids ->
_favoriteMovieIds.value = ids
}
}
}
fun getMovies(category: String) {
viewModelScope.launch {
getMovieUseCase.invoke(category)
.map { pagingData ->
pagingData.map { movie ->
val isFavorite = movie.id in (favoriteMovieIds.firstOrNull() ?: emptyList())
movie.isFavorite = isFavorite
movie
}
}
.cachedIn(viewModelScope)
.collectLatest { moviesData ->
_movies.value = moviesData
}
}
}
fun searchMovies(query: String) {
viewModelScope.launch {
searchMovieUseCase.searchMovies(query)
.map { result ->
result.map { movie ->
val isFavorite = movie.id in (favoriteMovieIds.firstOrNull() ?: emptyList())
movie.isFavorite = isFavorite
movie
}
}
.cachedIn(viewModelScope)
.collectLatest { searchData ->
_movies.value = searchData
}
}
}
private fun deleteFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
viewModelScope {
deleteFavoriteMovieUseCase.invoke(movie.id)
}
}
private suspend fun isMovieInFavorites(movieId: Int): Boolean {
return checkIfMovieIsFavoritesUseCase.invoke(movieId)
}
private fun addToFavorites(movie: MoviesDomainModel.ResultDomain) {
viewModelScope {
addFavoriteMovieUseCase.invoke(movie)
}
}
suspend fun manageFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
val isFavorite = isMovieInFavorites(movie.id)
if (isFavorite) {
deleteFavoriteMovie(movie)
} else {
addToFavorites(movie)
}
}
fun navigateToDetail(item: MoviesDomainModel.ResultDomain) {
val bundle = Bundle().apply {
putParcelable(MovieItemKeyConstant.MOVIE_ITEM_KEY, item)
}
navigationApi.navigateToDetail(bundle)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/home/vm/HomeViewModel.kt
|
1215134925
|
package ge.edu.btu.imdb.presentation.splash.ui
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.presentation.base.CoreBaseFragment
import ge.edu.btu.imdb.presentation.splash.vm.SplashViewModel
import kotlin.reflect.KClass
class SplashFragment : CoreBaseFragment<SplashViewModel>() {
override val viewModelClass: KClass<SplashViewModel>
get() = SplashViewModel::class
override val layout: Int
get() = R.layout.fragment_splash
override fun onBind() {
viewModel.navigateToDashboard()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/splash/ui/SplashFragment.kt
|
1851569839
|
package ge.edu.btu.imdb.presentation.splash.vm
import androidx.lifecycle.ViewModel
import ge.edu.btu.imdb.common.extension.viewModelScope
import ge.edu.btu.imdb.navigation.dashboard.DashboardNavigationApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
class SplashViewModel(private val navigationApi: DashboardNavigationApi) : ViewModel() {
fun navigateToDashboard() {
viewModelScope(Dispatchers.Main) {
delay(DELAY_DURATION)
navigationApi.navigateToDashboard()
}
}
companion object {
const val DELAY_DURATION = 2000L
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/splash/vm/SplashViewModel.kt
|
3686524952
|
package ge.edu.btu.imdb.presentation.favorites.ui
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import ge.edu.btu.imdb.common.extension.lifecycleScope
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.extension.hide
import ge.edu.btu.imdb.common.extension.show
import ge.edu.btu.imdb.common.extension.viewBinding
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.presentation.favorites.adapter.FavoritesAdapter
import ge.edu.btu.imdb.databinding.FragmentFavoritesBinding
import ge.edu.btu.imdb.presentation.base.CoreBaseFragment
import ge.edu.btu.imdb.presentation.favorites.vm.FavoritesViewModel
import ge.edu.btu.imdb.presentation.favorites.worker.DownloadWorker
import kotlinx.coroutines.flow.collectLatest
import kotlin.reflect.KClass
class FavoritesFragment : CoreBaseFragment<FavoritesViewModel>() {
private val binding by viewBinding(FragmentFavoritesBinding::bind)
override val viewModelClass: KClass<FavoritesViewModel>
get() = FavoritesViewModel::class
override val layout: Int
get() = R.layout.fragment_favorites
private val favoritesAdapter by lazy {
FavoritesAdapter()
}
override fun onBind() {
observeFavoriteMovies()
setUpRecycler()
setOnCLickListeners()
}
private fun setUpRecycler() {
binding.favoritesRecyclerView.adapter = favoritesAdapter
}
private fun observeFavoriteMovies() {
lifecycleScope {
viewModel.favoriteMovies
.collectLatest { favoriteMovies ->
handleFavoriteMoviesList(favoriteMovies)
}
}
}
private fun setOnCLickListeners() {
favoritesAdapter.setOnFavoriteClickListener { data ->
viewModel.deleteFavoriteMovie(data)
}
favoritesAdapter.setOnItemClickListener { item ->
viewModel.navigateToDetails(item)
}
binding.downloadImageView.setOnClickListener {
if (checkPermissions()) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val csvWorkRequest = OneTimeWorkRequest.Builder(DownloadWorker::class.java)
.setConstraints(constraints)
.build()
context?.let { WorkManager.getInstance(it).enqueue(csvWorkRequest) }
}
}
}
private fun checkPermissions(): Boolean{
val sdkAfter29 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
if (sdkAfter29){
return true
}
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
== PackageManager.PERMISSION_GRANTED
) {
return true
}else {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
1
)
return false
}
}
private fun handleFavoriteMoviesList(favoriteMovies: List<MoviesDomainModel.ResultDomain>) {
if (favoriteMovies.isEmpty()) {
showEmptyState()
} else {
showNonEmptyState()
favoritesAdapter.submitList(favoriteMovies)
}
}
private fun showEmptyState() {
with(binding) {
favoritesRecyclerView.hide()
emptyFavoritesTextView.show()
emptyFavoritesImageView.show()
}
}
private fun showNonEmptyState() {
with(binding) {
favoritesRecyclerView.show()
emptyFavoritesTextView.hide()
emptyFavoritesImageView.hide()
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/favorites/ui/FavoritesFragment.kt
|
653067320
|
package ge.edu.btu.imdb.presentation.favorites.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.extension.setImage
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.MovieItemLayoutBinding
import ge.edu.btu.imdb.common.constants.Constants
import ge.edu.btu.imdb.presentation.home.adapter.DiffCallback
class FavoritesAdapter :
ListAdapter<MoviesDomainModel.ResultDomain, FavoritesAdapter.MovieViewHolder>(DiffCallback()) {
private var onFavoriteClicked: ((MoviesDomainModel.ResultDomain) -> Unit)? = null
private var onItemClickListener: ((MoviesDomainModel.ResultDomain) -> Unit)? = null
fun setOnFavoriteClickListener(listener: (MoviesDomainModel.ResultDomain) -> Unit) {
onFavoriteClicked = listener
}
fun setOnItemClickListener(listener: (MoviesDomainModel.ResultDomain) -> Unit) {
onItemClickListener = listener
}
class MovieViewHolder(private val binding: MovieItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(
item: MoviesDomainModel.ResultDomain,
onItemClickListener: ((MoviesDomainModel.ResultDomain) -> Unit)?,
onFavoriteClicked: ((MoviesDomainModel.ResultDomain) -> Unit)?
) {
with(binding) {
dashboardHeadLineTextView.text = item.title
dashboardDateTextView.text = item.releaseDate?.dropLast(6)
dashboardMovieImageView.setImage(Constants.IMG_BASE_URL + item.posterPath)
dashboardCategoryTextView.text = item.genreIds?.first()
dashboardFavoritesImageView.setImageResource(R.drawable.ic_favorites_true)
dashboardFavoritesImageView.setOnClickListener {
onFavoriteClicked?.invoke(item)
}
root.setOnClickListener {
onItemClickListener?.invoke(item)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val binding =
MovieItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MovieViewHolder(binding)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item, onItemClickListener, onFavoriteClicked)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/favorites/adapter/FavoritesAdapter.kt
|
1902895302
|
package ge.edu.btu.imdb.presentation.favorites.vm
import android.os.Bundle
import androidx.lifecycle.ViewModel
import ge.edu.btu.imdb.common.extension.viewModelScope
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.constants.MovieItemKeyConstant
import ge.edu.btu.imdb.domain.usecase.local.DeleteFavoriteMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.GetFavoriteMoviesUseCase
import ge.edu.btu.imdb.navigation.detail.DetailNavigationApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
class FavoritesViewModel(
private val navigationApi: DetailNavigationApi,
private val getFavoriteMoviesUseCase: GetFavoriteMoviesUseCase,
private val deleteFavoriteMovieUseCase: DeleteFavoriteMovieUseCase
) : ViewModel() {
private val _favoriteMovies =
MutableStateFlow<List<MoviesDomainModel.ResultDomain>>(emptyList())
val favoriteMovies: StateFlow<List<MoviesDomainModel.ResultDomain>> get() = _favoriteMovies
init {
fetchFavoriteMovies()
}
private fun fetchFavoriteMovies() {
viewModelScope {
getFavoriteMoviesUseCase.invoke().collectLatest {
_favoriteMovies.value = it
}
}
}
fun deleteFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
viewModelScope {
deleteFavoriteMovieUseCase.invoke(movie.id)
}
}
fun navigateToDetails(item: MoviesDomainModel.ResultDomain) {
val bundle = Bundle().apply {
putParcelable(MovieItemKeyConstant.MOVIE_ITEM_KEY, item)
}
navigationApi.navigateToDetail(bundle)
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/favorites/vm/FavoritesViewModel.kt
|
3700643013
|
package ge.edu.btu.imdb.presentation.favorites.receiver
import android.content.Context
import android.content.BroadcastReceiver
import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
class DownloadCompleteReceiver(private val listener: DownloadCompleteListener) : BroadcastReceiver() {
interface DownloadCompleteListener {
fun onDownloadComplete()
}
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == ACTION_FILE_WRITE_COMPLETE) {
listener.onDownloadComplete()
}
}
companion object {
const val ACTION_FILE_WRITE_COMPLETE = "ge.edu.btu.imdb.download.FILE_WRITE_COMPLETE"
fun sendDownloadCompleteBroadcast(context: Context) {
val intent = Intent(ACTION_FILE_WRITE_COMPLETE)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/favorites/receiver/DownloadCompleteReceiver.kt
|
1453470364
|
package ge.edu.btu.imdb.presentation.favorites.worker
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.domain.repository.local.FavoritesRepository
import ge.edu.btu.imdb.presentation.favorites.receiver.DownloadCompleteReceiver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class DownloadWorker(val context: Context, workerParams: WorkerParameters) : Worker(context,
workerParams
), KoinComponent
{
private val favoritesRepository: FavoritesRepository by inject()
override fun doWork(): Result {
val workerScope = CoroutineScope(Dispatchers.Default)
var result = Result.success()
workerScope.launch {
val moviesList = favoritesRepository.getAllFavoriteMovies().firstOrNull()
if (moviesList == null){
Log.e("DownloadWorker", "Error: Favorite Movies Empty.")
result = Result.failure()
}else{
val csvData = convertToCSV(moviesList)
saveCSVToFile(csvData)
}
}
return result
}
private fun convertToCSV(mList: List<MoviesDomainModel.ResultDomain>): String {
val header = "Id,Title,Rating,Release Date\n"
val csvData = StringBuilder(header)
for (movie in mList) {
val line = "${movie.id},${movie.title},${movie.voteAverage},${movie.releaseDate}\n"
csvData.append(line)
}
return csvData.toString()
}
private fun saveCSVToFile(csvData: String){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, FILE_NAME)
put(MediaStore.MediaColumns.MIME_TYPE, FILE_TYPE)
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + DIRECTORY_NAME)
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), contentValues)
uri?.let { documentUri ->
try {
resolver.openOutputStream(documentUri)?.use { outputStream ->
outputStream.write(csvData.toByteArray())
}
DownloadCompleteReceiver.sendDownloadCompleteBroadcast(context)
} catch (e: IOException) {
e.printStackTrace()
Log.e("DownloadWorker", "Error saving CSV file: ${e.message}")
}
}
} else {
val externalDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
if (externalDir != null ) {
val file = File(externalDir, FILE_NAME)
val outputStream = FileOutputStream(file)
outputStream.write(csvData.toByteArray())
outputStream.close()
DownloadCompleteReceiver.sendDownloadCompleteBroadcast(context)
} else {
Log.e("DownloadWorker", "Error: External directory not available.")
}
}
}
companion object {
const val FILE_NAME = "favorites.csv"
const val FILE_TYPE = "text/csv"
const val DIRECTORY_NAME = "/IMDB"
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/favorites/worker/DownloadWorker.kt
|
1530169945
|
package ge.edu.btu.imdb.presentation.enums
enum class MovieCategory(val category: String) {
POPULAR("movie/popular"),
TOP_RATED("movie/top_rated"),
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/enums/MovieCategory.kt
|
2389990168
|
package ge.edu.btu.imdb.presentation.details.ui
import ge.edu.btu.imdb.common.extension.lifecycleScope
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.common.constants.MovieItemKeyConstant.MOVIE_ITEM_KEY
import ge.edu.btu.imdb.common.extension.setImage
import ge.edu.btu.imdb.common.extension.viewBinding
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.FragmentDetailBinding
import ge.edu.btu.imdb.presentation.details.vm.DetailViewModel
import ge.edu.btu.imdb.common.constants.Constants.IMG_BASE_URL
import ge.edu.btu.imdb.presentation.base.CoreBaseFragment
import kotlin.reflect.KClass
class DetailFragment : CoreBaseFragment<DetailViewModel>() {
private val binding by viewBinding(FragmentDetailBinding::bind)
override val viewModelClass: KClass<DetailViewModel>
get() = DetailViewModel::class
override val layout: Int
get() = R.layout.fragment_detail
override fun onBind() {
val movieItem =
requireArguments().getParcelable<MoviesDomainModel.ResultDomain>(MOVIE_ITEM_KEY)!!
setupViews(movieItem)
setupHeartImageView(movieItem)
setListener()
}
private fun setupViews(movieItem: MoviesDomainModel.ResultDomain) {
with(binding) {
titleTextView.text = movieItem.title
posterImageView.setImage(IMG_BASE_URL + movieItem.posterPath)
genreTextView.text = movieItem.genreIds?.first()
dateTextView.text = movieItem.releaseDate?.dropLast(6)
descriptionTextView.text = movieItem.overview
ratingTextView.text = movieItem.voteAverage.toString()
}
}
private fun setupHeartImageView(movieItem: MoviesDomainModel.ResultDomain) {
val heartImageView = binding.heartImageView
fun updateFavoriteStatus(isFavorite: Boolean) {
val drawableRes =
if (isFavorite) R.drawable.ic_favorites_true else R.drawable.ic_favorites_false
heartImageView.setBackgroundResource(drawableRes)
}
lifecycleScope {
val isFavorite = viewModel.isMovieInFavorites(movieItem.id)
updateFavoriteStatus(isFavorite)
heartImageView.setOnClickListener {
lifecycleScope {
viewModel.manageFavoriteMovie(movieItem)
updateFavoriteStatus(!isFavorite)
}
}
}
}
private fun setListener() {
binding.backImageButton.setOnClickListener {
viewModel.navigateToDashboard()
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/details/ui/DetailFragment.kt
|
436096337
|
package ge.edu.btu.imdb.presentation.details.vm
import androidx.lifecycle.ViewModel
import ge.edu.btu.imdb.common.extension.viewModelScope
import ge.edu.btu.imdb.domain.model.MoviesDomainModel
import ge.edu.btu.imdb.navigation.dashboard.DashboardNavigationApi
import ge.edu.btu.imdb.domain.usecase.local.AddFavoriteMovieUseCase
import ge.edu.btu.imdb.domain.usecase.local.CheckIfMovieIsFavoritesUseCase
import ge.edu.btu.imdb.domain.usecase.local.DeleteFavoriteMovieUseCase
class DetailViewModel(
private val addFavoriteMovieUseCase: AddFavoriteMovieUseCase,
private val checkIfMovieIsFavoritesUseCase: CheckIfMovieIsFavoritesUseCase,
private val deleteFavoriteMovieUseCase: DeleteFavoriteMovieUseCase,
private val navigationApi: DashboardNavigationApi
) : ViewModel() {
private fun deleteFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
viewModelScope {
deleteFavoriteMovieUseCase.invoke(movie.id)
}
}
suspend fun isMovieInFavorites(movieId: Int): Boolean {
return checkIfMovieIsFavoritesUseCase.invoke(movieId)
}
private fun addToFavorites(movie: MoviesDomainModel.ResultDomain) {
viewModelScope {
addFavoriteMovieUseCase.invoke(movie)
}
}
suspend fun manageFavoriteMovie(movie: MoviesDomainModel.ResultDomain) {
val isFavorite = isMovieInFavorites(movie.id)
if (isFavorite) {
deleteFavoriteMovie(movie)
} else {
addToFavorites(movie)
}
}
fun navigateToDashboard() {
navigationApi.navigateToDashboard()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/details/vm/DetailViewModel.kt
|
2736847178
|
package ge.edu.btu.imdb.presentation.dialog
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.FragmentErrorDialogBinding
import ge.edu.btu.imdb.common.extension.viewBinding
class ErrorDialogFragment : BaseDialogFragment() {
private val binding by viewBinding(FragmentErrorDialogBinding::bind)
private var onRefreshClickListener: (() -> Unit)? = null
override fun getLayoutResourceId(): Int {
return R.layout.fragment_error_dialog
}
override fun onStart() {
super.onStart()
binding.refreshImageView.setOnClickListener {
onRefreshClickListener?.invoke()
}
}
fun setOnRefreshClickListener(onRefreshClickListener: (() -> Unit)) {
this.onRefreshClickListener = onRefreshClickListener
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/dialog/ErrorDialogFragment.kt
|
1104064902
|
package ge.edu.btu.imdb.presentation.dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
abstract class BaseDialogFragment : DialogFragment() {
abstract fun getLayoutResourceId(): Int
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(getLayoutResourceId(), container, false)
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.BLACK))
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/dialog/BaseDialogFragment.kt
|
1685304812
|
package ge.edu.btu.imdb.presentation.dialog
import ge.edu.btu.imdb.R
class LoadingDialogFragment : BaseDialogFragment() {
override fun getLayoutResourceId(): Int {
return R.layout.fragment_loading_dialog
}
fun dismissDialog() {
if (isVisible) {
dismiss()
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/dialog/LoadingDialogFragment.kt
|
2392947347
|
package ge.edu.btu.imdb.presentation
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.navigation.NavController
import androidx.navigation.findNavController
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.navigation.NavControllerManager
import ge.edu.btu.imdb.presentation.favorites.receiver.DownloadCompleteReceiver
import org.koin.android.ext.android.inject
class MovieActivity : AppCompatActivity(), DownloadCompleteReceiver.DownloadCompleteListener {
private val navControllerManager by inject<NavControllerManager>()
private val navController: NavController by lazy {
findNavController(R.id.mainFragmentContainerView)
}
private val downloadCompleteReceiver = DownloadCompleteReceiver(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navControllerManager.setNavController(navController)
LocalBroadcastManager.getInstance(this).registerReceiver(
downloadCompleteReceiver,
IntentFilter(DownloadCompleteReceiver.ACTION_FILE_WRITE_COMPLETE)
)
}
override fun onDestroy() {
super.onDestroy()
LocalBroadcastManager.getInstance(this).unregisterReceiver(downloadCompleteReceiver)
}
override fun onDownloadComplete() {
Toast.makeText(this, "Download Successfully Completed", Toast.LENGTH_SHORT).show()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/MovieActivity.kt
|
1336227129
|
package ge.edu.btu.imdb.presentation.container.ui
import androidx.viewpager2.widget.ViewPager2
import ge.edu.btu.imdb.common.extension.viewBinding
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.presentation.container.adapter.ContainerPagerAdapter
import ge.edu.btu.imdb.presentation.container.vm.ContainerViewModel
import ge.edu.btu.imdb.databinding.FragmentContainerBinding
import ge.edu.btu.imdb.presentation.base.CoreBaseFragment
import kotlin.reflect.KClass
class ContainerFragment : CoreBaseFragment<ContainerViewModel>() {
private val binding by viewBinding(FragmentContainerBinding::bind)
override val viewModelClass: KClass<ContainerViewModel>
get() = ContainerViewModel::class
override val layout: Int
get() = R.layout.fragment_container
override fun onBind() {
viewPagerSetUp()
}
private fun viewPagerSetUp() {
with(binding) {
val viewPager: ViewPager2 = viewPager
viewPager.adapter = ContainerPagerAdapter(requireActivity())
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
when (position) {
0 -> bottomCustomView.setHomeBackgrounds()
1 -> bottomCustomView.setFavoritesBackgrounds()
}
}
})
bottomCustomView.setOnHomeClickListener {
viewPager.setCurrentItem(0, true)
}
bottomCustomView.setOnFavoritesClickListener {
viewPager.setCurrentItem(1, true)
}
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/container/ui/ContainerFragment.kt
|
568905382
|
package ge.edu.btu.imdb.presentation.container.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import ge.edu.btu.imdb.presentation.favorites.ui.FavoritesFragment
import ge.edu.btu.imdb.presentation.home.ui.HomeFragment
class ContainerPagerAdapter(fragmentActivity: FragmentActivity) :
FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> HomeFragment()
1 -> FavoritesFragment()
else -> throw IllegalArgumentException()
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/container/adapter/ContainerPagerAdapter.kt
|
2890547187
|
package ge.edu.btu.imdb.presentation.container.vm
import androidx.lifecycle.ViewModel
class ContainerViewModel:ViewModel(){
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/container/vm/ContainerViewModel.kt
|
2605708586
|
package ge.edu.btu.imdb.presentation.custom_view
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import ge.edu.btu.imdb.common.extension.hide
import ge.edu.btu.imdb.common.extension.show
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.SearchLayoutBinding
class SearchCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
interface OnTextChangeListener {
fun onTextChange(query: String)
}
private val binding by lazy {
SearchLayoutBinding.inflate(
LayoutInflater.from(context),
this,
true
)
}
private fun invisibleCategories() {
with(binding) {
topRatedChip.hide()
popularChip.hide()
filterImageView.setImageResource(R.drawable.ic_filter_false)
}
}
private fun visibleCategories() {
with(binding) {
topRatedChip.show()
popularChip.show()
popularChip.isChecked = true
filterImageView.setImageResource(R.drawable.ic_filter_true)
}
}
fun setTyping() {
with(binding) {
filterImageView.hide()
cancelTextView.show()
}
invisibleCategories()
}
fun cancelClicked() {
with(binding) {
cancelTextView.hide()
filterImageView.show()
filterImageView.setImageResource(R.drawable.ic_filter_false)
searchEditText.setText("")
searchEditText.clearFocus()
}
}
private var filterButtonFalse = false
fun setFilterView() {
with(binding) {
filterImageView.setOnClickListener {
filterButtonFalse = !filterButtonFalse
if (filterButtonFalse) {
visibleCategories()
} else {
invisibleCategories()
}
}
popularChip.isChecked = true
}
}
fun setOnFilterClickListener(listener: OnClickListener) {
binding.filterImageView.setOnClickListener(listener)
}
fun setOnCancelClickListener(listener: OnClickListener) {
binding.cancelTextView.setOnClickListener(listener)
}
fun setOnSearchClickListener(listener: OnClickListener) {
binding.searchEditText.setOnClickListener(listener)
}
fun setOnPopularClickListener(listener: OnClickListener) {
binding.popularChip.setOnClickListener(listener)
}
fun setOnTopRatedClickListener(listener: OnClickListener) {
binding.topRatedChip.setOnClickListener(listener)
}
fun addTextChangeListener(textChangeListener: OnTextChangeListener) {
val handler = Handler(Looper.getMainLooper())
val delayMills = 1000L
binding.searchEditText.addTextChangedListener {
var searchQuery = ""
handler.removeCallbacksAndMessages(null)
val query = it?.toString() ?: ""
searchQuery = query
if (query.length >= 2) {
handler.postDelayed({
if (searchQuery == query) {
textChangeListener.onTextChange(query)
}
}, delayMills)
}
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/custom_view/SearchCustomView.kt
|
113938624
|
package ge.edu.btu.imdb.presentation.custom_view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import ge.edu.btu.imdb.R
import ge.edu.btu.imdb.databinding.BottomCustomViewBinding
class BottomNavigationCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding by lazy {
BottomCustomViewBinding.inflate(
LayoutInflater.from(context),
this,
true
)
}
fun setOnHomeClickListener(listener: OnClickListener) {
binding.homeImageView.setOnClickListener(listener)
}
fun setOnFavoritesClickListener(listener: OnClickListener) {
binding.favoritesImageView.setOnClickListener(listener)
}
fun setHomeBackgrounds() {
with(binding) {
homeImageView.setImageResource(R.drawable.ic_home_active)
favoritesImageView.setImageResource(R.drawable.ic_favorites_inactive)
}
}
fun setFavoritesBackgrounds() {
with(binding) {
homeImageView.setImageResource(R.drawable.ic_home_inactive)
favoritesImageView.setImageResource(R.drawable.ic_favorites_active)
}
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/custom_view/BottomNavigationCustomView.kt
|
154448717
|
package ge.edu.btu.imdb.presentation.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import org.koin.androidx.viewmodel.ext.android.viewModelForClass
import kotlin.reflect.KClass
abstract class CoreBaseFragment<VM : ViewModel> : Fragment() {
protected val viewModel: VM by viewModelForClass(clazz = viewModelClass)
abstract val viewModelClass: KClass<VM>
protected abstract val layout: Int
abstract fun onBind()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(layout, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onBind()
}
}
|
finalProj/app/src/main/java/ge/edu/btu/imdb/presentation/base/CoreBaseFragment.kt
|
302146282
|
package com.scandog
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.scandog", appContext.packageName)
}
}
|
scan-dog/app/src/androidTest/java/com/scandog/ExampleInstrumentedTest.kt
|
2801289360
|
package com.scandog
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)
}
}
|
scan-dog/app/src/test/java/com/scandog/ExampleUnitTest.kt
|
657464225
|
package com.scandog.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)
|
scan-dog/app/src/main/java/com/scandog/ui/theme/Color.kt
|
2955277999
|
package com.scandog.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 ScandogTheme(
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
)
}
|
scan-dog/app/src/main/java/com/scandog/ui/theme/Theme.kt
|
3809263913
|
package com.scandog.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
)
*/
)
|
scan-dog/app/src/main/java/com/scandog/ui/theme/Type.kt
|
1021481142
|
package com.scandog
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.scandog.ui.theme.ScandogTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ScandogTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ScandogTheme {
Greeting("Android")
}
}
|
scan-dog/app/src/main/java/com/scandog/MainActivity.kt
|
1998433831
|
package com.example.artspaceapp
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.artspaceapp", appContext.packageName)
}
}
|
Kt11-SpaceArtApp/app/src/androidTest/java/com/example/artspaceapp/ExampleInstrumentedTest.kt
|
3847144682
|
package com.example.artspaceapp
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)
}
}
|
Kt11-SpaceArtApp/app/src/test/java/com/example/artspaceapp/ExampleUnitTest.kt
|
4002457320
|
package com.example.artspaceapp.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)
|
Kt11-SpaceArtApp/app/src/main/java/com/example/artspaceapp/ui/theme/Color.kt
|
1521077131
|
package com.example.artspaceapp.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 ArtSpaceAppTheme(
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
)
}
|
Kt11-SpaceArtApp/app/src/main/java/com/example/artspaceapp/ui/theme/Theme.kt
|
3237002527
|
package com.example.artspaceapp.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
)
*/
)
|
Kt11-SpaceArtApp/app/src/main/java/com/example/artspaceapp/ui/theme/Type.kt
|
720135603
|
package com.example.artspaceapp
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.Menu
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.palette.graphics.Palette
import com.example.artspaceapp.ui.theme.ArtSpaceAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ArtSpaceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ArtApp()
}
}
}
}
}
@Composable
fun ArtApp() {
Column(modifier = Modifier
.fillMaxSize().background(Brush.linearGradient(listOf( Color(0xFF854AD9),Color(0xFFF2D43D))))
.padding(20.dp), verticalArrangement = Arrangement.Center) {
var currentArtIndex by remember { mutableStateOf(8) }
/*
EiffelExplanation()
HagisophiaExplanation()
SagradeExplanation()
BigBenExplanation()
SydneyOperaExplanation()
BurjKhalifaExplanation()
EmpireStateExplanation()
GizaExplanation()
CollosseumExplanation()
NotreDameExplanation()
ParthenonExplanation()
PetronasExplanation()
TajMahalExplanation()
*/
when(currentArtIndex){
1 -> EiffelExplanation()
2 -> HagisophiaExplanation()
3 -> SagradeExplanation()
4 -> BigBenExplanation()
5 -> SydneyOperaExplanation()
6 -> BurjKhalifaExplanation()
7 -> EmpireStateExplanation()
8 -> GizaExplanation()
9 -> CollosseumExplanation()
10 -> NotreDameExplanation()
11 -> ParthenonExplanation()
12 -> PetronasExplanation()
else -> TajMahalExplanation()
}
Spacer(modifier = Modifier.height(15.dp))
OutlinedCard {
Row (modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center){
ElevatedButton(onClick = {
if (currentArtIndex>1){
currentArtIndex--
} }) {
Text(text = "Previos")
}
Spacer(modifier = Modifier
.width(35.dp)
.height(20.dp))
ElevatedButton(onClick = {
if (currentArtIndex<13){
currentArtIndex++
}
}) {
Text(text = " Next ")
}
}
}
}
}
@Composable
fun TajMahalExplanation(){
val image = painterResource(id = R.drawable.tacmahal)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(style = SpanStyle(color = Color.Black, fontWeight = FontWeight.Light, fontSize = 32.sp)) {
append("Taj Mahal\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.DarkGray, fontSize =20.sp
)
) {
append("Agra/India (1631)\n")
}
}
withStyle(style= ParagraphStyle(lineHeight = 14.sp)){
withStyle(style =SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.Normal)){
append("The Taj Mahal, located in Agra, India, is a breathtaking white marble mausoleum built by Mughal emperor Shah Jahan in memory of his third wife Mumtaz Mahal.\nCompleted in 1643, this architectural masterpiece exemplifies Mughal style, blending elements of Persian, Islamic, and Indian architectural traditions.\nConsidered a symbol of eternal love and intricate craftsmanship, the Taj Mahal attracts millions of visitors each year, standing as a testament to Shah Jahan's devotion and Mughal artistic brilliance.")
}
}
}
)
}
}
}
}
@Composable
fun SydneyOperaExplanation(){
val image = painterResource(id = R.drawable.sidneyopera)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Sydney Opera House\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Sydney/Australia (1959)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Sydney Opera House, nestled on the Sydney Harbour, is an architectural marvel recognized worldwide for its distinctive shell-like roof design.\nCompleted in 1973, this multi-venue performing arts center consists of several concrete \"shells\" clad in matte white ceramic tiles.\nDesigned by Danish architect Jørn Utzon, the building's unconventional shape sparked controversy during its construction but has since become an iconic symbol of Sydney and a UNESCO World Heritage Site.")
}
}
}
)
}
}
}
}
@Composable
fun PetronasExplanation(){
val image = painterResource(id = R.drawable.petronastowers)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(style = SpanStyle(color = Color.Black, fontWeight = FontWeight.Light, fontSize = 32.sp)) {
append("Petronas Twin Towers\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.DarkGray, fontSize =20.sp
)
) {
append("Kuala Lumpur/Malaysia (1993)\n")
}
}
withStyle(style= ParagraphStyle(lineHeight = 14.sp)){
withStyle(style =SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.Normal)){
append("Soaring above Kuala Lumpur, Malaysia, the Petronas Twin Towers held the title of the world's tallest twin towers from 1998 to 2004.\nReaching a height of 452 meters (1,483 feet) each, these postmodern skyscrapers boast a unique design inspired by Islamic geometric patterns and traditional Malaysian motifs.\nThe towers are not just visually striking but also house office space, a concert hall, and an art gallery, serving as a prominent landmark and a symbol of Malaysia's economic and technological advancement.")
}
}
}
)
}
}
}
}
@Composable
fun ParthenonExplanation(){
val image = painterResource(id = R.drawable.parthenon)
OutlinedCard(
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Parthenon\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Athens/Greece (BC. 447)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Perched atop the Acropolis in Athens, Greece, the Parthenon stands as a magnificent testament to ancient Greek architecture and art.\nCompleted in 438 BC, this Doric temple was dedicated to the Greek goddess Athena and housed a colossal gold and ivory statue of the deity.\nThe Parthenon's iconic features, including its sculpted friezes and marble columns, celebrate Greek mythology and artistic achievements, making it a timeless symbol of their civilization and cultural legacy.")
}
}
}
)
}
}
}
}
@Composable
fun NotreDameExplanation(){
val image = painterResource(id = R.drawable.notredame)
OutlinedCard(
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Notre-Dame\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Paris/France (1163)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Notre Dame Cathedral, located in the heart of Paris, France, is a stunning example of French Gothic architecture.\nOriginally constructed between the 12th and 14th centuries, its iconic features include flying buttresses, stained glass windows, and gargoyles.\nBeyond its architectural beauty, Notre Dame holds immense cultural and religious significance, serving as a place of worship and a symbol of Parisian history and identity.\nUnfortunately, a major fire in 2019 caused significant damage to the cathedral, and restoration efforts are currently underway.")
}
}
}
)
}
}
}
}
@Composable
fun CollosseumExplanation(){
val image = painterResource(id = R.drawable.kolezyum)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(style = SpanStyle(color = Color.Black, fontWeight = FontWeight.Light, fontSize = 32.sp)) {
append("Collosseum\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.DarkGray, fontSize =20.sp
)
) {
append("Roma/Italy (AD. 72)\n")
}
}
withStyle(style= ParagraphStyle(lineHeight = 14.sp)){
withStyle(style =SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.Normal)){
append("The Colosseum, also known as the Flavius Amphitheatre, stands as an awe-inspiring remnant of ancient Rome.\nConstructed between 70 and 80 AD, it was the largest amphitheater ever built in the Roman Empire, capable of holding an estimated 50,000 spectators.\nIts purpose was to host gladiatorial combats, public executions, animal hunts, and other spectacles, serving as a center of entertainment and public gathering for centuries.\nToday, the Colosseum remains a popular tourist destination and a powerful symbol of Roman engineering and historical significance.")
}
}
}
)
}
}
}
}
@Composable
fun GizaExplanation(){
val image = painterResource(id = R.drawable.gize)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(style = SpanStyle(color = Color.Black, fontWeight = FontWeight.Light, fontSize = 32.sp)) {
append("Pyramids of Giza\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.DarkGray, fontSize =20.sp
)
) {
append("Giza Plateau/Egypt (BC. 2560)\n")
}
}
withStyle(style= ParagraphStyle(lineHeight = 14.sp)){
withStyle(style =SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.Normal)){
append("Giza, located on the Giza Plateau in Egypt, is most famous for its three iconic pyramids: the Great Pyramid of Giza, the Pyramid of Khafre, and the Pyramid of Menkaure.\nThese monumental structures, built as tombs for pharaohs during the Old Kingdom (2686–2181 BC), are considered some of the most ancient and impressive wonders of the world.\nGiza also encompasses other significant structures like the Great Sphinx, a monumental limestone statue with a human head and a lion's body, further enriching the site's historical and cultural significance.")
}
}
}
)
}
}
}
}
@Composable
fun EmpireStateExplanation(){
val image = painterResource(id = R.drawable.empirestate)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Empire State\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Manhattan/USA (1930)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("The Empire State Building, a towering Art Deco skyscraper in New York City, stands at 1,250 feet tall, making it one of the most iconic landmarks in the world.\nOpened in 1931, it briefly held the title of the world's tallest building until the construction of the World Trade Center towers in the 1970s.\nDespite this, the Empire State Building remains a beloved symbol of New York City's skyline and resilience, offering breathtaking panoramic views and serving as a popular tourist destination.")
}
}
}
)
}
}
}
}
@Composable
fun BurjKhalifaExplanation(){
val image = painterResource(id = R.drawable.burjkhalifa)
OutlinedCard(
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Burj Khalifa\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Dubai/UAE (2004)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Soaring high above Dubai, the Burj Khalifa holds the title of the world's tallest building at a staggering 828 meters (2,717 feet).\nThis architectural marvel, inaugurated in 2010, boasts a sleek and modern design inspired by the Hymenocallis flower, a regional desert bloom.\nOffering breathtaking panoramic views from observation decks throughout the tower, the Burj Khalifa serves as a prominent landmark and a symbol of Dubai's innovation and ambition.")
}
}
}
)
}
}
}
}
@Composable
fun BigBenExplanation(){
val image = painterResource(id = R.drawable.bigben)
OutlinedCard(
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Big Ben\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("London/England (1859)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Big Ben, officially known as the Elizabeth Tower, is the iconic clock tower located at the Palace of Westminster in London, England.\nCompleted in 1859, it stands at an impressive 316 feet tall and houses the Great Bell, whose deep chime has become synonymous with London and the UK.\n Big Ben is not only a functioning clock but also a beloved landmark, a symbol of British history and tradition.")
}
}
}
)
}
}
}
}
@Composable
fun SagradeExplanation(){
val image = painterResource(id = R.drawable.sagrefamilia)
OutlinedCard(
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 32.sp
)
) {
append("Sagrada Família\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Barcelona/Spain (1882)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("The Sagrada Família, meaning \"Holy Family,\" is a majestic Roman Catholic church under construction in Barcelona, Spain.\nDesigned by the renowned architect Antoni Gaudí, its unique and intricate facade showcases his distinctive style inspired by nature.\nThough not yet finished, construction began in 1882 and continues to this day, making it a fascinating testament to architectural ambition and Gaudí's enduring legacy.")
}
}
}
)
}
}
}
}
@Composable
fun HagisophiaExplanation(){
val image = painterResource(id = R.drawable.ayasofya)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)
) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column(modifier = Modifier.padding(5.dp)) {
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(
style = SpanStyle(
color = Color.Black,
fontWeight = FontWeight.Light,
fontSize = 25.sp
)
) {
append("Hagia Sophia Grand Mosque\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
fontSize = 20.sp
)
) {
append("Istanbul/Turkiye (AD. 537)\n")
}
}
withStyle(style = ParagraphStyle(lineHeight = 14.sp)) {
withStyle(
style = SpanStyle(
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
) {
append("Hagia Sophia Grand Mosque, originally the Hagia Sophia (\"Holy Wisdom\") church, stands as a landmark in Istanbul's historic center.\nBuilt in the 6th century as a Byzantine basilica, it became a mosque after the Ottoman conquest in 1453.\nNotably, it served as both a church and a mosque for centuries, reflecting the city's rich cultural and religious history.")
}
}
}
)
}
}
}
}
@Composable
fun EiffelExplanation(){
val image = painterResource(id = R.drawable.paris)
OutlinedCard(
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
){
Box(modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
.shadow(20.dp, shape = RectangleShape)) {
Image(
painter = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
}
Column (modifier = Modifier.padding(5.dp)){
Text(
buildAnnotatedString {
withStyle(style = ParagraphStyle(lineHeight = 17.sp,)) {
withStyle(style = SpanStyle(color = Color.Black, fontWeight = FontWeight.Light, fontSize = 32.sp)) {
append("Eiffel Tower\n")
}
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold, color = Color.DarkGray, fontSize =20.sp
)
) {
append("Paris/France (1899)\n")
}
}
withStyle(style= ParagraphStyle(lineHeight = 14.sp)){
withStyle(style =SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.Normal)){
append("The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France.\nIt is named after the engineer Gustave Eiffel, whose company designed and built the tower from 1887 to 1889.\nThe tower is the tallest structure in Paris and the most-visited paid monument in the world; 6.91 million people ascended it in 2015.\nThe tower received its 250 millionth visitor in 2010. ")
}
}
}
)
}
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun GreetingPreview() {
ArtSpaceAppTheme {
ArtApp()
}
}
|
Kt11-SpaceArtApp/app/src/main/java/com/example/artspaceapp/MainActivity.kt
|
4001371286
|
package com.aunt.opeace
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.aunt.opeace", appContext.packageName)
}
}
|
DDD-10-Aunt-Android/app/src/androidTest/java/com/aunt/opeace/ExampleInstrumentedTest.kt
|
912193013
|
package com.aunt.opeace
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)
}
}
|
DDD-10-Aunt-Android/app/src/test/java/com/aunt/opeace/ExampleUnitTest.kt
|
1049645699
|
package com.aunt.opeace.write
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.aunt.opeace.ui.theme.OPeaceTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class WriteActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OPeaceTheme {
WriteScreen()
}
}
}
}
|
DDD-10-Aunt-Android/app/src/main/java/com/aunt/opeace/write/WriteActivity.kt
|
2402135224
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.