content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2024 Mikhail Titov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.d1s.salesanalyzer.data
import dev.d1s.salesanalyzer.entity.Simulation
import kweb.components.Component
import kweb.state.render
fun Component.renderWithCurrentSimulation(block: Component.(Result<Simulation>) -> Unit) {
val simulation = SimulationRepository.getBySession(browser.sessionId)
render(simulation) {
block(it)
}
} | sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/data/Render.kt | 3444358120 |
/*
* Copyright 2024 Mikhail Titov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.d1s.salesanalyzer.data
import dev.d1s.salesanalyzer.entity.Simulation
import dev.d1s.salesanalyzer.entity.SimulationState
import java.util.concurrent.ConcurrentHashMap
object SimulationRepository {
private const val NO_SIMULATION_MESSAGE = "Вы еще не создали ни одной симуляции."
private val simulations = ConcurrentHashMap<String, SimulationState>()
fun getBySession(sessionId: String): SimulationState =
simulations.getOrPut(sessionId) {
val result = Result.failure<Simulation>(IllegalStateException(NO_SIMULATION_MESSAGE))
SimulationState(result)
}
fun saveBySession(sessionId: String, simulation: Result<Simulation>): SimulationState =
simulations[sessionId]?.let {
it.value = simulation
it
} ?: run {
val state = SimulationState(simulation)
simulations[sessionId] = state
state
}
} | sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/data/SimulationRepository.kt | 412847009 |
package com.doit
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "DoIt"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
| DoIt-Note-App/android/app/src/main/java/com/doit/MainActivity.kt | 4146016492 |
package com.doit
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return PackageList(this).packages
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
| DoIt-Note-App/android/app/src/main/java/com/doit/MainApplication.kt | 3912094175 |
package com.example.bangkitfinalprojectandroid
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.bangkitfinalprojectandroid", appContext.packageName)
}
} | BlogMakananAndroid/app/src/androidTest/java/com/example/bangkitfinalprojectandroid/ExampleInstrumentedTest.kt | 1851633795 |
package com.example.bangkitfinalprojectandroid
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)
}
} | BlogMakananAndroid/app/src/test/java/com/example/bangkitfinalprojectandroid/ExampleUnitTest.kt | 1256935010 |
package com.example.bangkitfinalprojectandroid
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.bangkitfinalprojectandroid.databinding.ActivityDetailActivityBinding
import com.example.bangkitfinalprojectandroid.databinding.ActivityMainBinding
class DetailActivity : AppCompatActivity() {
companion object {
const val EXTRA_BLOG = "key_blog"
}
private lateinit var binding: ActivityDetailActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
val actionbar = supportActionBar
val dataBlog = if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra<Blog>(EXTRA_BLOG, Blog::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra<Blog>(EXTRA_BLOG)
}
if (dataBlog != null) {
binding.tvSetName.text = dataBlog.name.toString()
actionbar!!.title = dataBlog.name.toString()
actionbar.setDisplayHomeAsUpEnabled(true)
binding.tvSetDetail.text = dataBlog.description
binding.imgItemPhoto.setImageResource(dataBlog.photo)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressedDispatcher.onBackPressed()
return true
}
} | BlogMakananAndroid/app/src/main/java/com/example/bangkitfinalprojectandroid/DetailActivity.kt | 1094849686 |
package com.example.bangkitfinalprojectandroid
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.bangkitfinalprojectandroid.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var rvBlog: RecyclerView
private val list = ArrayList<Blog>()
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
rvBlog = binding.rvBlog
rvBlog.setHasFixedSize(true)
list.addAll(getListBlog())
showRecyclerList()
}
private fun getListBlog(): ArrayList<Blog> {
val dataName = resources.getStringArray(R.array.data_name)
val dataDescription = resources.getStringArray(R.array.data_description)
val dataPhoto = resources.obtainTypedArray(R.array.data_photo)
val listBlog = ArrayList<Blog>()
for (i in dataName.indices) {
val hero = Blog(dataName[i], dataDescription[i], dataPhoto.getResourceId(i, -1))
listBlog.add(hero)
}
return listBlog
}
private fun showRecyclerList() {
rvBlog.layoutManager = LinearLayoutManager(this)
val listBlogAdapter = ListBlogAdapter(list)
rvBlog.adapter = listBlogAdapter
listBlogAdapter.setOnItemClickCallback(object : ListBlogAdapter.OnItemClickCallback {
override fun onItemClicked(data: Blog) {
showSelectedBlog(data)
}
})
}
private fun showSelectedBlog(blog: Blog) {
Toast.makeText(this, "Kamu memilih " + blog.name, Toast.LENGTH_SHORT).show()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.miCompose -> {
val about = Intent(this@MainActivity, About::class.java)
startActivity(about)
}
}
return super.onOptionsItemSelected(item)
}
} | BlogMakananAndroid/app/src/main/java/com/example/bangkitfinalprojectandroid/MainActivity.kt | 4020789612 |
package com.example.bangkitfinalprojectandroid
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Blog(
val name: String,
val description: String,
val photo: Int
) : Parcelable
| BlogMakananAndroid/app/src/main/java/com/example/bangkitfinalprojectandroid/Blog.kt | 2489085395 |
package com.example.bangkitfinalprojectandroid
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.bangkitfinalprojectandroid.databinding.ItemRowBlogBinding
class ListBlogAdapter(private val listBlog: ArrayList<Blog>) : RecyclerView.Adapter<ListBlogAdapter.ListViewHolder>() {
private lateinit var onItemClickCallback: OnItemClickCallback
class ListViewHolder(var binding: ItemRowBlogBinding) : RecyclerView.ViewHolder(binding.root)
fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) {
this.onItemClickCallback = onItemClickCallback
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ListViewHolder {
val binding = ItemRowBlogBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
return ListViewHolder(binding)
}
override fun getItemCount(): Int = listBlog.size
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val (name, description, photo) = listBlog[position]
holder.binding.imgItemPhoto.setImageResource(photo)
holder.binding.tvItemName.text = name
holder.binding.tvItemDescription.text = description
holder.itemView.setOnClickListener {
val intentDetail = Intent(holder.itemView.context, DetailActivity::class.java)
intentDetail.putExtra("key_blog", listBlog[holder.adapterPosition])
holder.itemView.context.startActivity(intentDetail)
// holder.itemView.context.startActivity(intentDetail)
// onItemClickCallback.onItemClicked(listBlog[holder.adapterPosition])
}
}
interface OnItemClickCallback {
fun onItemClicked(data: Blog)
}
} | BlogMakananAndroid/app/src/main/java/com/example/bangkitfinalprojectandroid/ListBlogAdapter.kt | 2696043016 |
package com.example.bangkitfinalprojectandroid
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class About : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
val actionbar = supportActionBar
actionbar!!.title = "Tentang Saya"
actionbar.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressedDispatcher.onBackPressed()
return true
}
} | BlogMakananAndroid/app/src/main/java/com/example/bangkitfinalprojectandroid/About.kt | 2580182291 |
package com.example.flutter_in_focus
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| flutter_in_focus/android/app/src/main/kotlin/com/example/flutter_in_focus/MainActivity.kt | 1202007700 |
package com.home.Improve_Loops
val fruits = listOf("Apple", "Banana", "Cherry", "Orange")
fun main() {
println("Normal for loop")
for(index in 0..fruits.size -1 ) {
val fruit = fruits[index]
println("$index : $fruit")
}
println("=============")
println("Using until")
for(index in 0 until fruits.size) {
val fruit = fruits[index]
println("$index : $fruit")
}
println("=============")
println("Using lastIndex")
for(index in 0..fruits.lastIndex) {
val fruit = fruits[index]
println("$index : $fruit")
}
println("=============")
println("Using Indices")
for(index in fruits.indices) {
val fruit = fruits[index]
println("$index : $fruit")
}
println("=============")
println("Loop using withIndex")
for((index, fruit) in fruits.withIndex()) {
println("$index : $fruit")
}
println("=============")
println("Using ForEachIndex")
fruits.forEachIndexed {
index , fruit -> println("$index : $fruit")
}
} | Algorithmic-Challenges/src/main/kotlin/com/home/Improve_Loops/Main.kt | 1715231562 |
package academy.learnprogramming.oochallenge.round2
fun main() {
val bike2 = Bicycle(5, 10)
bike2.printDescription()
val mountainBike2 = MountainBike(22, 6, 11)
mountainBike2.printDescription()
val roadBike2 = RoadBike(55, 4, 20)
roadBike2.printDescription()
val mountainBike3 = MountainBike(100, 100, 100, 100, "Red")
mountainBike3.printDescription()
MountainBike.availableColors.listIterator().forEach{ i -> println(i)}
}
open class Bicycle(var cadence: Int, var speed: Int, var gear: Int = 10) {
fun applyBrake(decrement: Int) {
speed -= decrement
}
fun speedUp(increment: Int) {
speed += increment
}
open fun printDescription(){
println("Bike is in gear $gear with a cadence of $cadence travelling at a speed of $speed.")
}
}
class MountainBike(var seatHeight: Int, cadence: Int, speed: Int, gear: Int = 10): Bicycle(cadence, speed, gear) {
constructor(seatHeight: Int, cadence: Int, speed: Int, gear: Int, color: String):
this(seatHeight, cadence, speed, gear) {
println("The color is $color")
}
companion object {
val availableColors = listOf("blue", "red", "white", "black", "green", "brown")
}
override fun printDescription() {
super.printDescription()
println("The mountain bike has a seat height of $seatHeight inches.")
}
}
class RoadBike(val tireWidth: Int, cadence: Int, speed: Int, gear: Int = 10): Bicycle(cadence, speed, gear) {
override fun printDescription() {
super.printDescription()
println("The road bike has a tire width of $tireWidth MM.")
}
} | kotlin-challenge-3/src/academy/learnprogramming/oochallenge/round2/OOChallenge.kt | 534393928 |
package academy.learnprogramming.oochallenge.round1
fun main() {
val bike = Bicycle(5, 10, 1)
bike.printDescription()
val mountainBike = MountainBike(22,6, 11, 2)
mountainBike.printDescription()
val roadBike = RoadBike(55, 4, 20, 3)
roadBike.printDescription()
}
open class Bicycle(var cadence: Int, var speed: Int, var gear: Int) {
fun applyBrake(decrement: Int) {
speed -= decrement
}
fun speedUp(increment: Int) {
speed += increment
}
open fun printDescription(){
println("Bike is in gear $gear with a cadence of $cadence travelling at a speed of $speed.")
}
}
class MountainBike(var seatHeight: Int, cadence: Int, speed: Int, gear: Int): Bicycle(cadence, speed, gear) {
override fun printDescription() {
super.printDescription()
println("The mountain bike has a seat height of $seatHeight inches.")
}
}
class RoadBike(val tireWidth: Int, cadence: Int, speed: Int, gear: Int): Bicycle(cadence, speed, gear) {
override fun printDescription() {
super.printDescription()
println("The road bike has a tire width of $tireWidth MM.")
}
} | kotlin-challenge-3/src/academy/learnprogramming/oochallenge/round1/OOChallenge.kt | 629495742 |
package com.example.homework15
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.homework15", appContext.packageName)
}
} | Android-home-work-15/app/src/androidTest/java/com/example/homework15/ExampleInstrumentedTest.kt | 2774531930 |
package com.example.homework15
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)
}
} | Android-home-work-15/app/src/test/java/com/example/homework15/ExampleUnitTest.kt | 384604006 |
package com.example.homework15
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework15.Data.DictionaryDao
import com.example.homework15.Data.Word
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
class MainViewModel(private val dictionaryDao: DictionaryDao) : ViewModel() {
val allWord = this.dictionaryDao.getAll()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
fun add(word: String) {
viewModelScope.launch {
for (i in allWord.value) {
if (word.equals(i.word)) {
val updateWord = i.copy(
counter = i.counter + 1
)
dictionaryDao.update(updateWord)
return@launch
}
}
dictionaryDao.insert(Word(word = word, counter = 1))
}
}
fun delete() {
viewModelScope.launch {
dictionaryDao.delete()
}
}
}
| Android-home-work-15/app/src/main/java/com/example/homework15/MainViewModel.kt | 2287101139 |
package com.example.homework15
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.homework15.Data.App
import com.example.homework15.Data.DictionaryDao
import com.example.homework15.databinding.ActivityMainBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/*
Что нужно сделать
1. Напишите мини-приложение для подсчёта слов. Интерфейс должен позволять добавлять в словарь новое слово,
просматривать список первых слов в словаре, искать количество совпадений, а также очищать данные приложения.
2. Создайте базу данных, используя Room.
3. В качестве модели необходимо объявить сущность, содержащую слово (оно же используется в качестве ключа) и количество его повторений.
7. Добавьте проверку на ввод слова. Необходимо блокировать добавление пустых строк и слов, содержащих пробелы,
цифры, точки и запятые (допустимы только буквы и дефисы). При попытке пользователя добавить такое сочетание выводите соответствующее сообщение на экран.
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel:MainViewModel by viewModels{
object : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val dictionaryDao: DictionaryDao = (application as App).db.dictionaryDao()
return MainViewModel(dictionaryDao) as T
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.addBtn.setOnClickListener {
val text = binding.textInput.text.toString()
if (text.isNotBlank()){
viewModel.add(text)
}else{
Toast.makeText(this, "Ошибка!", Toast.LENGTH_SHORT).show()
}
}
binding.clearBtn.setOnClickListener {
viewModel.delete()
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED){
viewModel.allWord.collect{word ->
binding.text.text = word.joinToString(
separator = "\r\n"
)
}
}
}
}
fun isValid(text: String): Boolean {
return text.matches(Regex("""[A-Za-z-]"""))
}
} | Android-home-work-15/app/src/main/java/com/example/homework15/MainActivity.kt | 621869139 |
package com.example.homework15.Data
import android.app.Application
import androidx.room.Room
class App: Application() {
lateinit var db: AppDB
override fun onCreate() {
super.onCreate()
db = Room.inMemoryDatabaseBuilder(
this,
AppDB::class.java,
)
.fallbackToDestructiveMigration()
.build()
}
} | Android-home-work-15/app/src/main/java/com/example/homework15/Data/App.kt | 1756470939 |
package com.example.homework15.Data
import androidx.room.ColumnInfo
import androidx.room.PrimaryKey
data class Word(
@PrimaryKey
@ColumnInfo(name = "id") val id: Int? = null,
@ColumnInfo(name = "word") val word: String,
@ColumnInfo(name = "counter") val counter: Int
)
| Android-home-work-15/app/src/main/java/com/example/homework15/Data/Word.kt | 1315642600 |
package com.example.homework15.Data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "dictionary")
data class Dictionary (
@PrimaryKey
@ColumnInfo(name = "id") val id: Int,
@ColumnInfo(name = "word") val word: String,
@ColumnInfo(name = "counter") var counter: Int
)
| Android-home-work-15/app/src/main/java/com/example/homework15/Data/Dictionary.kt | 3121950192 |
package com.example.homework15.Data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Dictionary::class], version = 1)
abstract class AppDB:RoomDatabase() {
abstract fun dictionaryDao(): DictionaryDao
} | Android-home-work-15/app/src/main/java/com/example/homework15/Data/AppDB.kt | 4154402345 |
package com.example.homework15.Data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface DictionaryDao {
@Query("SELECT * FROM Dictionary")
fun getAll(): Flow<List<Dictionary>>
@Insert (entity = Dictionary::class)
suspend fun insert(word: Word)
@Query("DELETE FROM Dictionary")
suspend fun delete()
@Update
suspend fun update(updateWord: Dictionary)
} | Android-home-work-15/app/src/main/java/com/example/homework15/Data/DictionaryDao.kt | 2604569073 |
package kr.ac.kopo.sshj08
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("kr.ac.kopo.sshj08", appContext.packageName)
}
} | HelloAndroid0307/app/src/androidTest/java/kr/ac/kopo/sshj08/ExampleInstrumentedTest.kt | 955073223 |
package kr.ac.kopo.sshj08
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)
}
} | HelloAndroid0307/app/src/test/java/kr/ac/kopo/sshj08/ExampleUnitTest.kt | 2314138584 |
package kr.ac.kopo.sshj08.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) | HelloAndroid0307/app/src/main/java/kr/ac/kopo/sshj08/ui/theme/Color.kt | 1883744034 |
package kr.ac.kopo.sshj08.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 HelloAndroidTheme(
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
)
} | HelloAndroid0307/app/src/main/java/kr/ac/kopo/sshj08/ui/theme/Theme.kt | 1490179992 |
package kr.ac.kopo.sshj08.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
)
*/
) | HelloAndroid0307/app/src/main/java/kr/ac/kopo/sshj08/ui/theme/Type.kt | 4225349097 |
package kr.ac.kopo.sshj08
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 kr.ac.kopo.sshj08.ui.theme.HelloAndroidTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HelloAndroidTheme {
// 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() {
HelloAndroidTheme {
Greeting("Android")
}
} | HelloAndroid0307/app/src/main/java/kr/ac/kopo/sshj08/MainActivity.kt | 3239076147 |
package kr.ac.kopo.sshj08
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | HelloAndroid0307/app/src/main/java/kr/ac/kopo/sshj08/MainActivity2.kt | 1293377445 |
package com.example.mapd721_a2_calistdsouza
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.mapd721_a2_calistdsouza", appContext.packageName)
}
} | MAPD721Assignment2_CalistDsouza/app/src/androidTest/java/com/example/mapd721_a2_calistdsouza/ExampleInstrumentedTest.kt | 1947145117 |
package com.example.mapd721_a2_calistdsouza
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)
}
} | MAPD721Assignment2_CalistDsouza/app/src/test/java/com/example/mapd721_a2_calistdsouza/ExampleUnitTest.kt | 1252871285 |
package com.example.mapd721_a2_calistdsouza.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) | MAPD721Assignment2_CalistDsouza/app/src/main/java/com/example/mapd721_a2_calistdsouza/ui/theme/Color.kt | 1467767723 |
package com.example.mapd721_a2_calistdsouza.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 MAPD721_A2_CalistDsouzaTheme(
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
)
} | MAPD721Assignment2_CalistDsouza/app/src/main/java/com/example/mapd721_a2_calistdsouza/ui/theme/Theme.kt | 1017331521 |
package com.example.mapd721_a2_calistdsouza.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
)
*/
) | MAPD721Assignment2_CalistDsouza/app/src/main/java/com/example/mapd721_a2_calistdsouza/ui/theme/Type.kt | 1037194388 |
package com.example.mapd721_a2_calistdsouza
import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.ContentValues
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.mapd721_a2_calistdsouza.ui.theme.MAPD721_A2_CalistDsouzaTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MAPD721_A2_CalistDsouzaTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(android.graphics.Color.parseColor("#E1BEE7"))
) {
MainScreen(context = this)
}
}
}
}
}
@Composable
fun MainScreen(context: ComponentActivity) {
var contactName by remember { mutableStateOf("") }
var contactNumber by remember { mutableStateOf("") }
var contacts by remember { mutableStateOf(emptyList<Contact>()) }
Column(modifier = Modifier.padding(16.dp)) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(text = "Assignment 2", style = MaterialTheme.typography.headlineMedium)
Spacer(modifier = Modifier.height(16.dp))
TextField(
value = contactName,
onValueChange = { contactName = it },
label = { Text("Contact Name") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
TextField(
value = contactNumber,
onValueChange = { contactNumber = it },
label = { Text("Phone Number") },
modifier = Modifier.fillMaxWidth()
)
}
Spacer(modifier = Modifier.height(16.dp))
Row(modifier = Modifier.fillMaxWidth()) {
Button(
onClick = { contacts = loadContacts(context) },
modifier = Modifier.weight(1f)
) {
Text("Load")
}
Spacer(modifier = Modifier.width(16.dp))
Button(onClick = {if (contactName.isNotBlank() && contactNumber.isNotBlank()) {
val newContact = Contact(contactName, contactNumber)
contacts += newContact
addContact(context, newContact)
} }, modifier = Modifier.weight(1f)) {
Text("Save")
}
}
Spacer(modifier = Modifier.height(16.dp))
ContactsList(contacts = contacts)
Spacer(modifier = Modifier.height(16.dp))
AboutSection()
}
}
@Composable
fun ContactsList(contacts: List<Contact>) {
if (contacts.isEmpty()) {
Text(text = "No contacts available")
} else {
LazyColumn {
items(contacts) { contact ->
ContactItem(contact)
}
}
}
}
fun addContact(context: ComponentActivity, contact: Contact) {
// Prepare the values for insertion
val rawContactUri: Uri =
context.contentResolver.insert(ContactsContract.RawContacts.CONTENT_URI, ContentValues())
?: return
val rawContactId = ContentUris.parseId(rawContactUri)
val values = ContentValues().apply {
put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
)
put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contact.displayName)
}
val numberValues = ContentValues().apply {
put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
)
put(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.phoneNumber)
}
context.contentResolver.insert(ContactsContract.Data.CONTENT_URI, values)
context.contentResolver.insert(ContactsContract.Data.CONTENT_URI, numberValues)
}
@Composable
fun ContactsList(context: ComponentActivity) {
// State to track if it's the first time loading
var firstTimeLoaded by remember { mutableStateOf(true) }
// State to hold the list of contacts
var contacts by remember { mutableStateOf(emptyList<Contact>()) }
// LaunchedEffect to perform data loading
LaunchedEffect(firstTimeLoaded) {
if (firstTimeLoaded) {
// Load contacts when it's the first time
contacts = loadContacts(context)
firstTimeLoaded = false
}
}
// Display the list of contacts or a message if the list is empty
if (contacts.isEmpty()) {
Text(text = "No contacts available")
} else {
LazyColumn {
// Display each contact in a row
items(contacts) { contact ->
ContactItem(contact)
}
}
}
}
@Composable
fun ContactItem(contact: Contact) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(imageVector = Icons.Default.Person, contentDescription = null)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(text = contact.displayName)
Text(text = contact.phoneNumber)
}
}
}
@Composable
fun AboutSection() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "About", style = MaterialTheme.typography.headlineSmall)
Text(text = "Name: Calist Dsouza")
Text(text = "Student number: 301359253")
}
}
// Data class to represent a contact
data class Contact(val displayName: String, val phoneNumber: String)
@SuppressLint("Range")
fun loadContacts(context: ComponentActivity): List<Contact> {
val contacts = mutableListOf<Contact>()
context.contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
arrayOf(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
),
null,
null,
null
)?.use { cursor ->
while (cursor.moveToNext()) {
val displayName =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
val phoneNumber =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
contacts.add(Contact(displayName, phoneNumber))
}
}
return contacts
}
@Preview(showBackground = true)
@Composable
fun ContactsListPreview() {
// Display a preview of the contact list
MAPD721_A2_CalistDsouzaTheme {
ContactsList(context = ComponentActivity())
}
}
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
MAPD721_A2_CalistDsouzaTheme {
MainScreen(context = ComponentActivity())
}
} | MAPD721Assignment2_CalistDsouza/app/src/main/java/com/example/mapd721_a2_calistdsouza/MainActivity.kt | 3521579292 |
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.treasureHunt
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
/*
* This class contains the state of the game. The two important pieces of state are the index
* of the geofence, which is the geofence that the game thinks is active, and the state of the
* hint being shown. If the hint matches the geofence, then the Activity won't update the geofence
* as it cycles through various activity states.
*
* These states are stored in SavedState, which matches the Android lifecycle. Destroying the
* associated Activity with the back action will delete all state and reset the game, while
* the Home action will cause the state to be saved, even if the game is terminated by Android in
* the background.
*/
class GeofenceViewModel(state: SavedStateHandle) : ViewModel() {
private val _geofenceIndex = state.getLiveData(GEOFENCE_INDEX_KEY, -1)
private val _hintIndex = state.getLiveData(HINT_INDEX_KEY, 0)
val geofenceIndex: LiveData<Int>
get() = _geofenceIndex
val geofenceHintResourceId = Transformations.map(geofenceIndex) {
val index = geofenceIndex?.value ?: -1
when {
index < 0 -> R.string.not_started_hint
index < GeofencingConstants.NUM_LANDMARKS -> GeofencingConstants.LANDMARK_DATA[geofenceIndex.value!!].hint
else -> R.string.geofence_over
}
}
val geofenceImageResourceId = Transformations.map(geofenceIndex) {
val index = geofenceIndex.value ?: -1
when {
index < GeofencingConstants.NUM_LANDMARKS -> R.drawable.android_map
else -> R.drawable.android_treasure
}
}
fun updateHint(currentIndex: Int) {
_hintIndex.value = currentIndex+1
}
fun geofenceActivated() {
_geofenceIndex.value = _hintIndex.value
}
fun geofenceIsActive() =_geofenceIndex.value == _hintIndex.value
fun nextGeofenceIndex() = _hintIndex.value ?: 0
}
private const val HINT_INDEX_KEY = "hintIndex"
private const val GEOFENCE_INDEX_KEY = "geofenceIndex"
| androidSec6/app/src/main/java/com/example/android/treasureHunt/GeofenceViewModel.kt | 307387749 |
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.treasureHunt
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.Manifest
import android.annotation.TargetApi
import android.content.IntentSender
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModelProviders
import com.example.android.treasureHunt.databinding.ActivityHuntMainBinding
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingClient
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.material.snackbar.Snackbar
/**
* The Treasure Hunt app is a single-player game based on geofences.
*
* This app demonstrates how to create and remove geofences using the GeofencingApi. Uses an
* BroadcastReceiver to monitor geofence transitions and creates notification and finishes the game
* when the user enters the final geofence (destination).
*
* This app requires a device's Location settings to be turned on. It also requires
* the ACCESS_FINE_LOCATION permission and user consent. For geofences to work
* in Android Q, app also needs the ACCESS_BACKGROUND_LOCATION permission and user consent.
*/
class HuntMainActivity : AppCompatActivity() {
private lateinit var binding: ActivityHuntMainBinding
private lateinit var geofencingClient: GeofencingClient
private lateinit var viewModel: GeofenceViewModel
private val runningQOrLater =
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q
// A PendingIntent for the Broadcast Receiver that handles geofence transitions.
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceBroadcastReceiver::class.java)
intent.action = ACTION_GEOFENCE_EVENT
// Use FLAG_UPDATE_CURRENT so that you get the same pending intent back when calling
// addGeofences() and removeGeofences().
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_hunt_main)
viewModel = ViewModelProviders.of(this, SavedStateViewModelFactory(this.application,
this)).get(GeofenceViewModel::class.java)
binding.viewmodel = viewModel
binding.lifecycleOwner = this
geofencingClient = LocationServices.getGeofencingClient(this)
// Create channel for notifications
createChannel(this )
}
override fun onStart() {
super.onStart()
checkPermissionsAndStartGeofencing()
}
/*
* When we get the result from asking the user to turn on device location, we call
* checkDeviceLocationSettingsAndStartGeofence again to make sure it's actually on, but
* we don't resolve the check to keep the user from seeing an endless loop.
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_TURN_DEVICE_LOCATION_ON) {
// We don't rely on the result code, but just check the location setting again
checkDeviceLocationSettingsAndStartGeofence(false)
}
}
/*
* When the user clicks on the notification, this method will be called, letting us know that
* the geofence has been triggered, and it's time to move to the next one in the treasure
* hunt.
*/
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val extras = intent?.extras
if(extras != null){
if(extras.containsKey(GeofencingConstants.EXTRA_GEOFENCE_INDEX)){
viewModel.updateHint(extras.getInt(GeofencingConstants.EXTRA_GEOFENCE_INDEX))
checkPermissionsAndStartGeofencing()
}
}
}
/*
* In all cases, we need to have the location permission. On Android 10+ (Q) we need to have
* the background permission as well.
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Log.d(TAG, "onRequestPermissionResult")
if (
grantResults.isEmpty() ||
grantResults[LOCATION_PERMISSION_INDEX] == PackageManager.PERMISSION_DENIED ||
(requestCode == REQUEST_FOREGROUND_AND_BACKGROUND_PERMISSION_RESULT_CODE &&
grantResults[BACKGROUND_LOCATION_PERMISSION_INDEX] ==
PackageManager.PERMISSION_DENIED))
{
// Permission denied.
Snackbar.make(
binding.activityMapsMain,
R.string.permission_denied_explanation, Snackbar.LENGTH_INDEFINITE
)
.setAction(R.string.settings) {
// Displays App settings screen.
startActivity(Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
})
}.show()
} else {
checkDeviceLocationSettingsAndStartGeofence()
}
}
/**
* This will also destroy any saved state in the associated ViewModel, so we remove the
* geofences here.
*/
override fun onDestroy() {
super.onDestroy()
removeGeofences()
}
/**
* Starts the permission check and Geofence process only if the Geofence associated with the
* current hint isn't yet active.
*/
private fun checkPermissionsAndStartGeofencing() {
if (viewModel.geofenceIsActive()) return
if (foregroundAndBackgroundLocationPermissionApproved()) {
checkDeviceLocationSettingsAndStartGeofence()
} else {
requestForegroundAndBackgroundLocationPermissions()
}
}
/*
* Uses the Location Client to check the current state of location settings, and gives the user
* the opportunity to turn on location services within our app.
*/
private fun checkDeviceLocationSettingsAndStartGeofence(resolve:Boolean = true) {
val locationRequest = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_LOW_POWER
}
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val settingsClient = LocationServices.getSettingsClient(this)
val locationSettingsResponseTask =
settingsClient.checkLocationSettings(builder.build())
locationSettingsResponseTask.addOnFailureListener { exception ->
if (exception is ResolvableApiException && resolve){
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
exception.startResolutionForResult(this@HuntMainActivity,
REQUEST_TURN_DEVICE_LOCATION_ON)
} catch (sendEx: IntentSender.SendIntentException) {
Log.d(TAG, "Error geting location settings resolution: " + sendEx.message)
}
} else {
Snackbar.make(
binding.activityMapsMain,
R.string.location_required_error, Snackbar.LENGTH_INDEFINITE
).setAction(android.R.string.ok) {
checkDeviceLocationSettingsAndStartGeofence()
}.show()
}
}
locationSettingsResponseTask.addOnCompleteListener {
if ( it.isSuccessful ) {
addGeofenceForClue()
}
}
}
/*
* Determines whether the app has the appropriate permissions across Android 10+ and all other
* Android versions.
*/
@TargetApi(29)
private fun foregroundAndBackgroundLocationPermissionApproved(): Boolean {
val foregroundLocationApproved = (
PackageManager.PERMISSION_GRANTED ==
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION))
val backgroundPermissionApproved =
if (runningQOrLater) {
PackageManager.PERMISSION_GRANTED ==
ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_BACKGROUND_LOCATION
)
} else {
true
}
return foregroundLocationApproved && backgroundPermissionApproved
}
/*
* Requests ACCESS_FINE_LOCATION and (on Android 10+ (Q) ACCESS_BACKGROUND_LOCATION.
*/
@TargetApi(29 )
private fun requestForegroundAndBackgroundLocationPermissions() {
if (foregroundAndBackgroundLocationPermissionApproved())
return
// Else request the permission
// this provides the result[LOCATION_PERMISSION_INDEX]
var permissionsArray = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
val resultCode = when {
runningQOrLater -> {
// this provides the result[BACKGROUND_LOCATION_PERMISSION_INDEX]
permissionsArray += Manifest.permission.ACCESS_BACKGROUND_LOCATION
REQUEST_FOREGROUND_AND_BACKGROUND_PERMISSION_RESULT_CODE
}
else -> REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
}
Log.d(TAG, "Request foreground only location permission")
ActivityCompat.requestPermissions(
this@HuntMainActivity,
permissionsArray,
resultCode
)
}
/*
* Adds a Geofence for the current clue if needed, and removes any existing Geofence. This
* method should be called after the user has granted the location permission. If there are
* no more geofences, we remove the geofence and let the viewmodel know that the ending hint
* is now "active."
*/
private fun addGeofenceForClue() {
if (viewModel.geofenceIsActive()) return
val currentGeofenceIndex = viewModel.nextGeofenceIndex()
if(currentGeofenceIndex >= GeofencingConstants.NUM_LANDMARKS) {
removeGeofences()
viewModel.geofenceActivated()
return
}
val currentGeofenceData = GeofencingConstants.LANDMARK_DATA[currentGeofenceIndex]
// Build the Geofence Object
val geofence = Geofence.Builder()
// Set the request ID, string to identify the geofence.
.setRequestId(currentGeofenceData.id)
// Set the circular region of this geofence.
.setCircularRegion(currentGeofenceData.latLong.latitude,
currentGeofenceData.latLong.longitude,
GeofencingConstants.GEOFENCE_RADIUS_IN_METERS
)
// Set the expiration duration of the geofence. This geofence gets
// automatically removed after this period of time.
.setExpirationDuration(GeofencingConstants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build()
// Build the geofence request
val geofencingRequest = GeofencingRequest.Builder()
// The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
// GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
// is already inside that geofence.
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
// Add the geofences to be monitored by geofencing service.
.addGeofence(geofence)
.build()
// First, remove any existing geofences that use our pending intent
geofencingClient.removeGeofences(geofencePendingIntent)?.run {
// Regardless of success/failure of the removal, add the new geofence
addOnCompleteListener {
// Add the new geofence request with the new geofence
geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent)?.run {
addOnSuccessListener {
// Geofences added.
Toast.makeText(this@HuntMainActivity, R.string.geofences_added,
Toast.LENGTH_SHORT)
.show()
Log.e("Add Geofence", geofence.requestId)
// Tell the viewmodel that we've reached the end of the game and
// activated the last "geofence" --- by removing the Geofence.
viewModel.geofenceActivated()
}
addOnFailureListener {
// Failed to add geofences.
Toast.makeText(this@HuntMainActivity, R.string.geofences_not_added,
Toast.LENGTH_SHORT).show()
if ((it.message != null)) {
Log.w(TAG, it.message)
}
}
}
}
}
}
/**
* Removes geofences. This method should be called after the user has granted the location
* permission.
*/
private fun removeGeofences() {
if (!foregroundAndBackgroundLocationPermissionApproved()) {
return
}
geofencingClient.removeGeofences(geofencePendingIntent)?.run {
addOnSuccessListener {
// Geofences removed
Log.d(TAG, getString(R.string.geofences_removed))
Toast.makeText(applicationContext, R.string.geofences_removed, Toast.LENGTH_SHORT)
.show()
}
addOnFailureListener {
// Failed to remove geofences
Log.d(TAG, getString(R.string.geofences_not_removed))
}
}
}
companion object {
internal const val ACTION_GEOFENCE_EVENT =
"HuntMainActivity.treasureHunt.action.ACTION_GEOFENCE_EVENT"
}
}
private const val REQUEST_FOREGROUND_AND_BACKGROUND_PERMISSION_RESULT_CODE = 33
private const val REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE = 34
private const val REQUEST_TURN_DEVICE_LOCATION_ON = 29
private const val TAG = "HuntMainActivity"
private const val LOCATION_PERMISSION_INDEX = 0
private const val BACKGROUND_LOCATION_PERMISSION_INDEX = 1 | androidSec6/app/src/main/java/com/example/android/treasureHunt/HuntMainActivity.kt | 2055992798 |
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.treasureHunt
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import androidx.core.app.NotificationCompat
/*
* We need to create a NotificationChannel associated with our CHANNEL_ID before sending a
* notification.
*/
fun createChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
CHANNEL_ID,
context.getString(R.string.channel_name),
NotificationManager.IMPORTANCE_HIGH
)
.apply {
setShowBadge(false)
}
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.description = context.getString(R.string.notification_channel_description)
val notificationManager = context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
}
}
/*
* A Kotlin extension function for AndroidX's NotificationCompat that sends our Geofence
* entered notification. It sends a custom notification based on the name string associated
* with the LANDMARK_DATA from GeofencingConstatns in the GeofenceUtils file.
*/
fun NotificationManager.sendGeofenceEnteredNotification(context: Context, foundIndex: Int) {
val contentIntent = Intent(context, HuntMainActivity::class.java)
contentIntent.putExtra(GeofencingConstants.EXTRA_GEOFENCE_INDEX, foundIndex)
val contentPendingIntent = PendingIntent.getActivity(
context,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mapImage = BitmapFactory.decodeResource(
context.resources,
R.drawable.map_small
)
val bigPicStyle = NotificationCompat.BigPictureStyle()
.bigPicture(mapImage)
.bigLargeIcon(null)
// We use the name resource ID from the LANDMARK_DATA along with content_text to create
// a custom message when a Geofence triggers.
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.content_text,
context.getString(GeofencingConstants.LANDMARK_DATA[foundIndex].name)))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.map_small)
.setStyle(bigPicStyle)
.setLargeIcon(mapImage)
notify(NOTIFICATION_ID, builder.build())
}
private const val NOTIFICATION_ID = 33
private const val CHANNEL_ID = "GeofenceChannel"
| androidSec6/app/src/main/java/com/example/android/treasureHunt/NotificationUtils.kt | 856943922 |
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.treasureHunt
import android.content.Context
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.maps.model.LatLng
import java.util.concurrent.TimeUnit
/**
* Returns the error string for a geofencing error code.
*/
fun errorMessage(context: Context, errorCode: Int): String {
val resources = context.resources
return when (errorCode) {
GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE -> resources.getString(
R.string.geofence_not_available
)
GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES -> resources.getString(
R.string.geofence_too_many_geofences
)
GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS -> resources.getString(
R.string.geofence_too_many_pending_intents
)
else -> resources.getString(R.string.unknown_geofence_error)
}
}
/**
* Stores latitude and longitude information along with a hint to help user find the location.
*/
data class LandmarkDataObject(val id: String, val hint: Int, val name: Int, val latLong: LatLng)
internal object GeofencingConstants {
/**
* Used to set an expiration time for a geofence. After this amount of time, Location services
* stops tracking the geofence. For this sample, geofences expire after one hour.
*/
val GEOFENCE_EXPIRATION_IN_MILLISECONDS: Long = TimeUnit.HOURS.toMillis(1)
val LANDMARK_DATA = arrayOf(
LandmarkDataObject(
"enter",
R.string.enter_hint,
R.string.enter_location,
LatLng(47.216916060575144, 39.628686010837555)),
LandmarkDataObject(
"corner",
R.string.corner_hint,
R.string.corner_location,
LatLng(47.21680561247273, 39.62795443832874)),
LandmarkDataObject(
"parking",
R.string.parking_hint,
R.string.parking_location,
LatLng(47.216391600837156, 39.629066549241536)),
LandmarkDataObject(
"bicycle",
R.string.bicycle_hint,
R.string.bicycle_location,
LatLng(47.21670222373123, 39.62923653423786)),
LandmarkDataObject(
"smoking",
R.string.smoking_hint,
R.string.smoking_location,
LatLng(47.216940199717435, 39.628869742155075))
)
val NUM_LANDMARKS = LANDMARK_DATA.size
const val GEOFENCE_RADIUS_IN_METERS = 20f
const val EXTRA_GEOFENCE_INDEX = "GEOFENCE_INDEX"
}
| androidSec6/app/src/main/java/com/example/android/treasureHunt/GeofenceUtils.kt | 265792045 |
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.treasureHunt
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat
import com.example.android.treasureHunt.HuntMainActivity.Companion.ACTION_GEOFENCE_EVENT
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingEvent
/*
* Triggered by the Geofence. Since we only have one active Geofence at once, we pull the request
* ID from the first Geofence, and locate it within the registered landmark data in our
* GeofencingConstants within GeofenceUtils, which is a linear string search. If we had very large
* numbers of Geofence possibilities, it might make sense to use a different data structure. We
* then pass the Geofence index into the notification, which allows us to have a custom "found"
* message associated with each Geofence.
*/
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_GEOFENCE_EVENT) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = errorMessage(context, geofencingEvent.errorCode)
Log.e(TAG, errorMessage)
return
}
if (geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Log.v(TAG, context.getString(R.string.geofence_entered))
val fenceId = when {
geofencingEvent.triggeringGeofences.isNotEmpty() ->
geofencingEvent.triggeringGeofences[0].requestId
else -> {
Log.e(TAG, "No Geofence Trigger Found! Abort mission!")
return
}
}
// Check geofence against the constants listed in GeofenceUtil.kt to see if the
// user has entered any of the locations we track for geofences.
val foundIndex = GeofencingConstants.LANDMARK_DATA.indexOfFirst {
it.id == fenceId
}
// Unknown Geofences aren't helpful to us
if ( -1 == foundIndex ) {
Log.e(TAG, "Unknown Geofence: Abort Mission")
return
}
val notificationManager = ContextCompat.getSystemService(
context,
NotificationManager::class.java
) as NotificationManager
notificationManager.sendGeofenceEnteredNotification(
context, foundIndex
)
}
}
}
}
private const val TAG = "GeofenceReceiver"
| androidSec6/app/src/main/java/com/example/android/treasureHunt/GeofenceBroadcastReceiver.kt | 1007537582 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | temp-project/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | temp-project/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
class MainFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val mylayout = LinearLayout(container!!.context)
val lp = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// val mybutton = Button(container.context)
// mybutton.text = "hhhhhh"
// mybutton.setLayoutParams(lp)
// mylayout.addView(mybutton)
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.duckduckgo.com"))
startActivity(browserIntent)
return mylayout
}
companion object {
fun newInstance(param1: String?, param2: String?): MainFragment {
return MainFragment()
}
}
}
| temp-project/app/src/main/java/com/example/myapplication/MainFragment.kt | 1255398588 |
package com.b2_backoffice.b2_backoffice
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class B2BackofficeApplicationTests {
@Test
fun contextLoads() {
}
}
| B2_BackOffice/src/test/kotlin/com/b2_backoffice/b2_backoffice/B2BackofficeApplicationTests.kt | 1251169048 |
package com.b2_backoffice.b2_backoffice
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class B2BackofficeApplication
fun main(args: Array<String>) {
runApplication<B2BackofficeApplication>(*args)
}
| B2_BackOffice/src/main/kotlin/com/b2_backoffice/b2_backoffice/B2BackofficeApplication.kt | 1429689850 |
package com.hayatibahar.simpleandyummy
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.hayatibahar.simpleandyummy", appContext.packageName)
}
} | Simple-And-Yummy/app/src/androidTest/java/com/hayatibahar/simpleandyummy/ExampleInstrumentedTest.kt | 1011979660 |
package com.hayatibahar.simpleandyummy
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Simple-And-Yummy/app/src/test/java/com/hayatibahar/simpleandyummy/ExampleUnitTest.kt | 3603244762 |
package com.hayatibahar.simpleandyummy.ui.settings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.hayatibahar.simpleandyummy.databinding.FragmentSettingsBinding
import com.hayatibahar.simpleandyummy.ui.home.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SettingsFragment : Fragment() {
private var _binding: FragmentSettingsBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<HomeViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentSettingsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initListeners()
getDarkMode()
}
private fun getDarkMode() {
viewModel.isDarkMode.observe(viewLifecycleOwner) {
binding.themeSwitch.isChecked = it
}
}
private fun initListeners() {
binding.themeSwitch.setOnCheckedChangeListener { _, isChecked ->
viewModel.saveDarkModeState(isChecked)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/settings/SettingsFragment.kt | 23110888 |
package com.hayatibahar.simpleandyummy.ui.home
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hayatibahar.simpleandyummy.core.common.ResponseState
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetAllRecipesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetDarkModeStateUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetRecipesWithSearchUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.SaveDarkModeStateUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val getAllRecipesUseCase: GetAllRecipesUseCase,
private val getRecipesWithSearchUseCase: GetRecipesWithSearchUseCase,
private val getDarkModeStateUseCase: GetDarkModeStateUseCase,
private val saveDarkModeStateUseCase: SaveDarkModeStateUseCase,
) :
ViewModel() {
private val _homeUiState = MutableLiveData<HomeUiState>()
val homeUiState: LiveData<HomeUiState> get() = _homeUiState
private val _isDarkMode = MutableLiveData(false)
val isDarkMode: LiveData<Boolean> get() = _isDarkMode
init {
getAllRecipes()
isAppDarkMode()
}
fun getAllRecipes() {
viewModelScope.launch {
getAllRecipesUseCase().collect { responseState ->
when (responseState) {
is ResponseState.Loading -> {
_homeUiState.postValue(
HomeUiState.Loading
)
}
is ResponseState.Success -> {
_homeUiState.postValue(
HomeUiState.Success(
HomeData(
recipes = responseState.data.shuffled(),
shouldScrollUp = false,
noMatch = responseState.data.isEmpty()
)
)
)
}
is ResponseState.Error -> {
_homeUiState.postValue(
HomeUiState.Error(
errorMessage = responseState.message
)
)
}
}
}
}
}
fun getRecipesWithSearch(
query: String? = null,
cuisine: String? = null,
type: String? = null,
diet: String? = null,
) {
viewModelScope.launch {
getRecipesWithSearchUseCase(
query.orEmpty(),
cuisine.orEmpty(),
type.orEmpty(),
diet.orEmpty()
).collect { responseState ->
when (responseState) {
is ResponseState.Loading -> {
_homeUiState.postValue(
HomeUiState.Loading
)
}
is ResponseState.Success -> {
_homeUiState.postValue(
HomeUiState.Success(
HomeData(
recipes = responseState.data.shuffled(),
shouldScrollUp = true,
noMatch = responseState.data.isEmpty()
)
)
)
}
is ResponseState.Error -> {
_homeUiState.postValue(
HomeUiState.Error(
errorMessage = responseState.message
)
)
}
}
}
}
}
private fun isAppDarkMode() {
viewModelScope.launch {
getDarkModeStateUseCase().collect {
_isDarkMode.postValue(it)
if (it) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
}
}
fun saveDarkModeState(isDarkMode : Boolean){
viewModelScope.launch {
saveDarkModeStateUseCase(isDarkMode)
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/home/HomeViewModel.kt | 1432773587 |
package com.hayatibahar.simpleandyummy.ui.home
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.showToast
import com.hayatibahar.simpleandyummy.core.domain.model.Recipe
sealed class HomeUiState {
data object Loading : HomeUiState()
data class Error(val errorMessage: String) : HomeUiState()
data class Success(val data: HomeData) : HomeUiState()
}
data class HomeData(
val recipes: List<Recipe> = emptyList(),
private var shouldScrollUp: Boolean = false,
private var noMatch: Boolean = false,
) {
fun scrollIfNeeded(recyclerView: RecyclerView) {
if (shouldScrollUp) {
recyclerView.scrollToPosition(0)
shouldScrollUp = false
}
}
fun showToastIfNeeded(context: Context) {
if (noMatch) {
showToast(context, "No matching result found")
noMatch = false
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/home/HomeUiState.kt | 1924751728 |
package com.hayatibahar.simpleandyummy.ui.home.adapter
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.inflateAdapterItem
import com.hayatibahar.simpleandyummy.core.domain.model.Recipe
import com.hayatibahar.simpleandyummy.databinding.RecipeItemBinding
class RecipesAdapter : RecyclerView.Adapter<RecipeViewHolder>() {
private val items = mutableListOf<Recipe>()
private var onRecipeItemClickListener: ((String) -> Unit)? = null
fun setOnRecipeItemClickListener(onRecipeItemClickListener: ((String) -> Unit)?) {
this.onRecipeItemClickListener = onRecipeItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
return RecipeViewHolder(
parent.inflateAdapterItem(RecipeItemBinding::inflate),
onRecipeItemClickListener
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: RecipeViewHolder, position: Int) {
holder.bind(items[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateRecipes(newItems: List<Recipe>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
fun getItemIdAtPosition(position: Int): Int {
return items[position].id
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/home/adapter/RecipesAdapter.kt | 3206857083 |
package com.hayatibahar.simpleandyummy.ui.home.adapter
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.loadFromUrlByGlide
import com.hayatibahar.simpleandyummy.core.domain.model.Recipe
import com.hayatibahar.simpleandyummy.databinding.RecipeItemBinding
class RecipeViewHolder(
private val binding: RecipeItemBinding,
private val onRecipeItemClickListener: ((String) -> Unit)?,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(recipe: Recipe) {
with(binding) {
recipeNameTv.text = recipe.title
"Ready in ${recipe.readyInMinutes} min".also { readyInMinutesTv.text = it }
recipeIv.loadFromUrlByGlide(recipe.image)
}
binding.root.setOnClickListener {
onRecipeItemClickListener?.invoke(recipe.id.toString())
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/home/adapter/RecipeViewHolder.kt | 1899984437 |
package com.hayatibahar.simpleandyummy.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.hayatibahar.simpleandyummy.core.common.hideKeyboard
import com.hayatibahar.simpleandyummy.core.common.makeGone
import com.hayatibahar.simpleandyummy.core.common.makeVisible
import com.hayatibahar.simpleandyummy.core.common.showToast
import com.hayatibahar.simpleandyummy.databinding.FragmentHomeBinding
import com.hayatibahar.simpleandyummy.ui.home.adapter.RecipesAdapter
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<HomeViewModel>()
private val adapter = RecipesAdapter().apply {
setOnRecipeItemClickListener {
val action = HomeFragmentDirections.actionHomeFragmentToDetailFragment(it)
findNavController().navigate(action)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initAdapter()
observeData()
handleSearch()
swipeRefreshListener()
handleFilter()
}
private fun swipeRefreshListener() {
binding.swipeRefresh.setOnRefreshListener {
binding.searchBox.text?.clear()
viewModel.getAllRecipes()
binding.swipeRefresh.isRefreshing = false
}
}
private fun handleFilter() {
binding.filterBtn.setOnClickListener {
val action = HomeFragmentDirections.actionHomeFragmentToFilterFragment()
findNavController().navigate(action)
}
}
private fun handleSearch() {
binding.searchBox.setOnEditorActionListener { textView, i, _ ->
if (i == EditorInfo.IME_ACTION_SEARCH) {
viewModel.getRecipesWithSearch(textView.text.toString())
clearSearchAndHideKeyboard()
}
true
}
binding.searchContainer.setEndIconOnClickListener {
binding.searchBox.text?.clear()
clearSearchAndHideKeyboard()
}
}
private fun clearSearchAndHideKeyboard() {
binding.searchBox.hideKeyboard(requireContext())
binding.searchBox.clearFocus()
}
private fun observeData() {
viewModel.homeUiState.observe(viewLifecycleOwner) {
when (it) {
is HomeUiState.Error -> {
handleError(it.errorMessage)
}
is HomeUiState.Loading -> {
handleLoading()
}
is HomeUiState.Success -> {
handleSuccess(it.data)
}
}
}
}
private fun handleError(errorMessage: String) {
binding.progressBar.makeGone()
showToast(requireContext(), errorMessage)
}
private fun handleLoading() {
binding.progressBar.makeVisible()
}
private fun handleSuccess(homeData: HomeData) {
homeData.scrollIfNeeded(binding.recipeRv)
homeData.showToastIfNeeded(requireContext())
adapter.updateRecipes(homeData.recipes)
binding.progressBar.makeGone()
}
private fun initAdapter() {
binding.recipeRv.adapter = adapter
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/home/HomeFragment.kt | 3945834018 |
package com.hayatibahar.simpleandyummy.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.hayatibahar.simpleandyummy.R
import com.hayatibahar.simpleandyummy.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
navController = findNavController(R.id.navHostFragment)
binding.bottomNavMenu.setupWithNavController(navController)
navController.addOnDestinationChangedListener { _, destination, _ ->
binding.bottomNavMenu.visibility = when (destination.id) {
R.id.detailFragment -> View.GONE
R.id.filterFragment -> View.GONE
else -> View.VISIBLE
}
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/MainActivity.kt | 2342945143 |
package com.hayatibahar.simpleandyummy.ui.favorites
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.hayatibahar.simpleandyummy.databinding.FragmentFavoritesBinding
import com.hayatibahar.simpleandyummy.ui.home.adapter.RecipesAdapter
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class FavoritesFragment : Fragment() {
private var _binding: FragmentFavoritesBinding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<FavoritesViewModel>()
private val adapter = RecipesAdapter().apply {
setOnRecipeItemClickListener {
val action = FavoritesFragmentDirections.actionFavoritesFragmentToDetailFragment(it)
findNavController().navigate(action)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentFavoritesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getFavoriteRecipes()
initAdapter()
observeData()
}
private fun getFavoriteRecipes() {
viewModel.getFavoriteRecipes()
}
private fun observeData() {
viewModel.favoriteRecipes.observe(viewLifecycleOwner) {
adapter.updateRecipes(it)
}
}
private fun initAdapter() {
binding.favoriteRv.adapter = adapter
val itemTouchHelperCallback = createItemTouchHelperCallback()
val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
itemTouchHelper.attachToRecyclerView(binding.favoriteRv)
}
private fun createItemTouchHelperCallback(): ItemTouchHelper.SimpleCallback {
return object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder,
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
handleSwipe(viewHolder)
}
}
}
private fun handleSwipe(viewHolder: RecyclerView.ViewHolder) {
val id = adapter.getItemIdAtPosition(viewHolder.adapterPosition)
viewModel.updateFavoriteRecipe(id, false)
Snackbar.make(binding.favoriteRv, "Recipe deleted", Snackbar.LENGTH_LONG)
.setAction("Undo") {
viewModel.updateFavoriteRecipe(id, true)
}
.show()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/favorites/FavoritesFragment.kt | 904262028 |
package com.hayatibahar.simpleandyummy.ui.favorites
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hayatibahar.simpleandyummy.core.domain.model.Recipe
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetAllFavoriteRecipes
import com.hayatibahar.simpleandyummy.core.domain.usecase.UpdateFavoriteStatusUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class FavoritesViewModel @Inject constructor(
private val getAllFavoriteRecipes: GetAllFavoriteRecipes,
private val updateFavoriteStatusUseCase: UpdateFavoriteStatusUseCase,
) : ViewModel() {
private val _favoriteRecipes = MutableLiveData<List<Recipe>>()
val favoriteRecipes: LiveData<List<Recipe>> get() = _favoriteRecipes
fun getFavoriteRecipes() {
viewModelScope.launch {
getAllFavoriteRecipes.invoke().collect {
_favoriteRecipes.postValue(it)
}
}
}
fun updateFavoriteRecipe(recipeId: Int, isFavorite: Boolean) {
viewModelScope.launch {
updateFavoriteStatusUseCase.invoke(recipeId, isFavorite)
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/favorites/FavoritesViewModel.kt | 910083511 |
package com.hayatibahar.simpleandyummy.ui.grocery.adapter
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.databinding.GroceriesItemBinding
class GroceriesViewHolder(
private val binding: GroceriesItemBinding,
private val onGroceryCheckBoxListener: ((Int, Boolean) -> Unit)?,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(groceryEntity: GroceryEntity) {
with(binding) {
itemNameTv.text = groceryEntity.nameClean
"${groceryEntity.amount} ${groceryEntity.unit}".also { itemAmountTv.text = it }
itemCb.isChecked = groceryEntity.isChecked
}
binding.itemCb.setOnClickListener {
onGroceryCheckBoxListener?.invoke(groceryEntity.id, binding.itemCb.isChecked)
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/grocery/adapter/GroceriesViewHolder.kt | 2785743134 |
package com.hayatibahar.simpleandyummy.ui.grocery.adapter
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.inflateAdapterItem
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.databinding.GroceriesItemBinding
class GroceriesAdapter : RecyclerView.Adapter<GroceriesViewHolder>() {
private val items = mutableListOf<GroceryEntity>()
private var onGroceryCheckBoxListener: ((Int, Boolean) -> Unit)? = null
fun onGroceryCheckBoxListener(onGroceryCheckBoxListener: ((Int, Boolean) -> Unit)?) {
this.onGroceryCheckBoxListener = onGroceryCheckBoxListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GroceriesViewHolder {
return GroceriesViewHolder(
parent.inflateAdapterItem(GroceriesItemBinding::inflate),
onGroceryCheckBoxListener
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: GroceriesViewHolder, position: Int) {
holder.bind(items[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateGroceries(newItems: List<GroceryEntity>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/grocery/adapter/GroceriesAdapter.kt | 2867613983 |
package com.hayatibahar.simpleandyummy.ui.grocery
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import com.hayatibahar.simpleandyummy.core.common.makeGone
import com.hayatibahar.simpleandyummy.core.common.makeVisible
import com.hayatibahar.simpleandyummy.databinding.FragmentGroceryBinding
import com.hayatibahar.simpleandyummy.ui.grocery.adapter.GroceriesAdapter
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class GroceryFragment : Fragment() {
private var _binding: FragmentGroceryBinding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<GroceryViewModel>()
private val groceryAdapter = GroceriesAdapter().apply {
onGroceryCheckBoxListener { id, isChecked ->
viewModel.updateGroceryCheckStatusUseCase(id, isChecked)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentGroceryBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getGroceries()
initAdapter()
initListeners()
observeData()
}
private fun initListeners() {
binding.deleteFab.setOnClickListener {
showAlertDialog()
}
}
private fun showAlertDialog() {
AlertDialog.Builder(requireContext())
.setTitle("Delete Groceries")
.setMessage("Which groceries would you like to delete?")
.setPositiveButton("Delete All") { _, _ ->
viewModel.deleteGroceries()
}
.setNegativeButton("Delete Checked") { _, _ ->
viewModel.deleteCheckedGroceries()
}
.setNeutralButton("Cancel", null)
.show()
}
private fun getGroceries() {
viewModel.getGroceries()
}
private fun observeData() {
viewModel.groceries.observe(viewLifecycleOwner) {
groceryAdapter.updateGroceries(it)
if (it.isNotEmpty()) makeInvisibleNoDataTv() else makeVisibleNoDataTv()
}
}
private fun initAdapter() {
binding.groceriesRv.adapter = groceryAdapter
}
private fun makeInvisibleNoDataTv() {
binding.nothingToBuyTv.makeGone()
binding.browseTv.makeGone()
}
private fun makeVisibleNoDataTv() {
binding.nothingToBuyTv.makeVisible()
binding.browseTv.makeVisible()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/grocery/GroceryFragment.kt | 1897549883 |
package com.hayatibahar.simpleandyummy.ui.grocery
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.core.domain.usecase.DeleteCheckedGroceriesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.DeleteGroceriesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetGroceriesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.UpdateGroceryCheckStatusUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class GroceryViewModel @Inject constructor(
private val getGroceriesUseCase: GetGroceriesUseCase,
private val updateGroceryCheckStatusUseCase: UpdateGroceryCheckStatusUseCase,
private val deleteCheckedGroceriesUseCase: DeleteCheckedGroceriesUseCase,
private val deleteGroceriesUseCase: DeleteGroceriesUseCase,
) : ViewModel() {
private val _groceries = MutableLiveData<List<GroceryEntity>>()
val groceries: LiveData<List<GroceryEntity>> get() = _groceries
fun getGroceries() {
viewModelScope.launch {
getGroceriesUseCase.invoke().collect {
_groceries.postValue(it)
}
}
}
fun updateGroceryCheckStatusUseCase(id: Int, isChecked: Boolean) {
viewModelScope.launch {
updateGroceryCheckStatusUseCase.invoke(id, isChecked)
}
}
fun deleteCheckedGroceries() {
viewModelScope.launch {
deleteCheckedGroceriesUseCase()
}
}
fun deleteGroceries() {
viewModelScope.launch {
deleteGroceriesUseCase()
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/grocery/GroceryViewModel.kt | 1618510781 |
package com.hayatibahar.simpleandyummy.ui.detail
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hayatibahar.simpleandyummy.core.common.ResponseState
import com.hayatibahar.simpleandyummy.core.common.mapTo
import com.hayatibahar.simpleandyummy.core.domain.model.Ingredient
import com.hayatibahar.simpleandyummy.core.domain.model.Recipe
import com.hayatibahar.simpleandyummy.core.domain.model.RecipeDetail
import com.hayatibahar.simpleandyummy.core.domain.usecase.DeleteGroceriesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.GetRecipeDetailUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.InsertGroceriesUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.InsertRecipeUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.IsRecipeFavoriteUseCase
import com.hayatibahar.simpleandyummy.core.domain.usecase.UpdateFavoriteStatusUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailViewModel @Inject constructor(
private val getRecipeDetailUseCase: GetRecipeDetailUseCase,
private val isRecipeFavoriteUseCase: IsRecipeFavoriteUseCase,
private val updateFavoriteStatusUseCase: UpdateFavoriteStatusUseCase,
private val insertGroceriesUseCase: InsertGroceriesUseCase,
private val deleteGroceriesUseCase: DeleteGroceriesUseCase,
private val insertRecipeUseCase: InsertRecipeUseCase,
) :
ViewModel() {
private val _detailUiState = MutableLiveData<DetailUiState>()
val detailUiState: LiveData<DetailUiState> get() = _detailUiState
fun getRecipeDetail(id: String) {
viewModelScope.launch {
combine(
getRecipeDetailUseCase(id),
isRecipeFavoriteUseCase(id.toInt())
) { responseState, isFavorite ->
when (responseState) {
is ResponseState.Loading -> {
_detailUiState.postValue(
DetailUiState.Loading
)
}
is ResponseState.Success -> {
_detailUiState.postValue(
DetailUiState.Success(
RecipeDetail(
id = responseState.data.id,
title = responseState.data.title,
summary = responseState.data.summary,
image = responseState.data.image,
readyInMinutes = responseState.data.readyInMinutes,
ingredients = responseState.data.ingredients,
vegan = responseState.data.vegan,
vegetarian = responseState.data.vegetarian,
dairyFree = responseState.data.dairyFree,
glutenFree = responseState.data.glutenFree,
cheap = responseState.data.cheap,
veryHealthy = responseState.data.veryHealthy,
instructions = responseState.data.instructions,
isFavorite = isFavorite,
onFavorite = {
updateFavorite(
recipe = responseState.data.mapTo {
Recipe(
it.id,
it.title,
it.image,
it.readyInMinutes
)
},
isFavorite
)
}
)
)
)
}
is ResponseState.Error -> {
_detailUiState.postValue(
DetailUiState.Error(
responseState.message
)
)
}
}
}.collect()
}
}
fun addToGroceries(ingredients: List<Ingredient>) {
viewModelScope.launch {
insertGroceriesUseCase.invoke(ingredients)
}
}
fun deleteGroceries() {
viewModelScope.launch {
deleteGroceriesUseCase()
}
}
private fun updateFavorite(recipe: Recipe, favorite: Boolean) {
viewModelScope.launch {
insertRecipeUseCase(recipe)
if (favorite) {
updateFavoriteStatusUseCase(recipe.id, false)
} else {
updateFavoriteStatusUseCase(recipe.id, true)
}
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/DetailViewModel.kt | 3155563563 |
package com.hayatibahar.simpleandyummy.ui.detail
import com.hayatibahar.simpleandyummy.core.domain.model.RecipeDetail
sealed class DetailUiState {
data object Loading : DetailUiState()
data class Error(val errorMessage: String) : DetailUiState()
data class Success(val data: RecipeDetail) : DetailUiState()
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/DetailUiState.kt | 3502334383 |
package com.hayatibahar.simpleandyummy.ui.detail.adapter
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.inflateAdapterItem
import com.hayatibahar.simpleandyummy.core.domain.model.Ingredient
import com.hayatibahar.simpleandyummy.databinding.IngredientsItemBinding
class IngredientsAdapter : RecyclerView.Adapter<IngredientsViewHolder>() {
private val items = mutableListOf<Ingredient>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IngredientsViewHolder {
return IngredientsViewHolder(
parent.inflateAdapterItem(IngredientsItemBinding::inflate),
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: IngredientsViewHolder, position: Int) {
holder.bind(items[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateIngredients(newItems: List<Ingredient>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/adapter/IngredientsAdapter.kt | 2611593111 |
package com.hayatibahar.simpleandyummy.ui.detail.adapter
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.BuildConfig
import com.hayatibahar.simpleandyummy.core.common.loadFromUrlByGlide
import com.hayatibahar.simpleandyummy.core.domain.model.Ingredient
import com.hayatibahar.simpleandyummy.databinding.IngredientsItemBinding
class IngredientsViewHolder(
private val binding: IngredientsItemBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(ingredient: Ingredient) {
with(binding) {
ingredientTv.text = ingredient.originalName
"${ingredient.amount} ${ingredient.unit}".also { amountTv.text = it }
ingredientIv.loadFromUrlByGlide(BuildConfig.BASE_IMAGE_URL + ingredient.image)
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/adapter/IngredientsViewHolder.kt | 2181057800 |
package com.hayatibahar.simpleandyummy.ui.detail.adapter
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.domain.model.Instruction
import com.hayatibahar.simpleandyummy.databinding.InstructionItemBinding
class InstructionViewHolder(
private val binding: InstructionItemBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(instruction: Instruction) {
with(binding) {
"Step ${instruction.number}".also { stepNumberTv.text = it }
stepDescriptionTv.text = instruction.step
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/adapter/InstructionViewHolder.kt | 2075935241 |
package com.hayatibahar.simpleandyummy.ui.detail.adapter
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.inflateAdapterItem
import com.hayatibahar.simpleandyummy.core.domain.model.Instruction
import com.hayatibahar.simpleandyummy.databinding.InstructionItemBinding
class InstructionAdapter : RecyclerView.Adapter<InstructionViewHolder>() {
private val items = mutableListOf<Instruction>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InstructionViewHolder {
return InstructionViewHolder(
parent.inflateAdapterItem(InstructionItemBinding::inflate),
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: InstructionViewHolder, position: Int) {
holder.bind(items[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateInstructions(newItems: List<Instruction>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/adapter/InstructionAdapter.kt | 3934423049 |
package com.hayatibahar.simpleandyummy.ui.detail
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.hayatibahar.simpleandyummy.R
import com.hayatibahar.simpleandyummy.core.common.loadFromUrlByGlide
import com.hayatibahar.simpleandyummy.core.common.makeInvisible
import com.hayatibahar.simpleandyummy.core.common.makeVisible
import com.hayatibahar.simpleandyummy.core.common.showToast
import com.hayatibahar.simpleandyummy.core.domain.model.Ingredient
import com.hayatibahar.simpleandyummy.core.domain.model.RecipeDetail
import com.hayatibahar.simpleandyummy.databinding.FragmentDetailBinding
import com.hayatibahar.simpleandyummy.ui.detail.adapter.IngredientsAdapter
import com.hayatibahar.simpleandyummy.ui.detail.adapter.InstructionAdapter
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class DetailFragment : Fragment() {
private var _binding: FragmentDetailBinding? = null
private val binding get() = _binding!!
private val args: DetailFragmentArgs by navArgs()
private val viewModel by viewModels<DetailViewModel>()
private val ingredientsAdapter = IngredientsAdapter()
private val instructionAdapter = InstructionAdapter()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
buttonListeners()
getRecipeDetail()
initAdapter()
observeData()
showIngredientsOrRecipe()
}
private fun getRecipeDetail() {
viewModel.getRecipeDetail(args.id)
}
private fun observeData() {
viewModel.detailUiState.observe(viewLifecycleOwner) {
when (it) {
is DetailUiState.Error -> {
handleError(it.errorMessage)
}
is DetailUiState.Loading -> {
handleLoading()
}
is DetailUiState.Success -> {
handleSuccess(it.data)
}
}
}
}
private fun handleError(errorMessage: String) {
binding.progressBar.makeInvisible()
findNavController().popBackStack()
showToast(requireContext(), errorMessage)
}
private fun handleLoading() {
binding.progressBar.makeVisible()
}
private fun handleSuccess(recipeDetail: RecipeDetail) {
with(binding) {
favoriteIv.setImageResource(if (recipeDetail.isFavorite) R.drawable.baseline_favorite_24 else R.drawable.baseline_favorite_border_24)
favoriteIv.setOnClickListener { recipeDetail.onFavorite.invoke() }
recipeNameTv.text = recipeDetail.title
"Ready in ${recipeDetail.readyInMinutes} min".also { timeTv.text = it }
recipeIv.loadFromUrlByGlide(recipeDetail.image)
summaryTv.text = recipeDetail.summary
ingredientsAdapter.updateIngredients(recipeDetail.ingredients)
instructionAdapter.updateInstructions(recipeDetail.instructions)
progressBar.makeInvisible()
addToGroceriesBtn.setOnClickListener {
showAlertDialog(recipeDetail.ingredients)
}
}
}
private fun showAlertDialog(ingredients : List<Ingredient>) {
AlertDialog.Builder(requireContext())
.setTitle("Grocery List")
.setMessage("Replace list or add to it?")
.setPositiveButton("Replace List") { _, _ ->
viewModel.deleteGroceries()
viewModel.addToGroceries(ingredients)
}
.setNegativeButton("Add to List") { _, _ ->
viewModel.addToGroceries(ingredients)
}
.setNeutralButton("Cancel", null)
.show()
}
private fun initAdapter() {
binding.ingredientsRv.adapter = ingredientsAdapter
binding.instructionVp.adapter = instructionAdapter
}
private fun buttonListeners() {
binding.backIv.setOnClickListener {
findNavController().popBackStack()
}
}
private fun showIngredientsOrRecipe() {
with(binding) {
ingredientsTv.setOnClickListener {
instructionVp.makeInvisible()
addToGroceriesBtn.makeVisible()
ingredientsRv.makeVisible()
}
recipeTv.setOnClickListener {
ingredientsRv.makeInvisible()
addToGroceriesBtn.makeInvisible()
instructionVp.makeVisible()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/detail/DetailFragment.kt | 1783655924 |
package com.hayatibahar.simpleandyummy.ui.filter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.hayatibahar.simpleandyummy.core.common.ApiConstants.cuisines
import com.hayatibahar.simpleandyummy.core.common.ApiConstants.diet
import com.hayatibahar.simpleandyummy.core.common.ApiConstants.mealType
import com.hayatibahar.simpleandyummy.databinding.FragmentFilterBinding
import com.hayatibahar.simpleandyummy.ui.filter.adapter.FilterAdapter
import com.hayatibahar.simpleandyummy.ui.filter.adapter.FilterItem
import com.hayatibahar.simpleandyummy.ui.home.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class FilterFragment : Fragment() {
private var _binding: FragmentFilterBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<HomeViewModel>()
private val filterLists =
listOf(cuisines, diet, mealType).map { it -> it.map { FilterItem(it) } }
private val adapters = filterLists.map { list ->
FilterAdapter().apply {
setOnFilterItemClickListener {
updateFilters(changeSelectedItem(list, it))
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentFilterBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initAdapters()
initListeners()
}
private fun changeSelectedItem(
items: List<FilterItem>,
filterItem: FilterItem,
): List<FilterItem> {
return items.map {
if (it.name == filterItem.name) {
it.isSelected = !filterItem.isSelected
} else {
it.isSelected = false
}
it
}
}
private fun initListeners() {
binding.applyBtn.setOnClickListener {
viewModel.getRecipesWithSearch(
cuisine = filterLists[0].firstOrNull { it.isSelected }?.name,
diet = filterLists[1].firstOrNull { it.isSelected }?.name,
type = filterLists[2].firstOrNull { it.isSelected }?.name,
)
findNavController().popBackStack()
}
binding.backIv.setOnClickListener {
findNavController().popBackStack()
}
}
private fun initAdapters() {
listOf(
binding.cuisineRv,
binding.dietRv,
binding.mealRv
).forEachIndexed { index, recyclerView ->
val flexLayout = FlexboxLayoutManager(requireContext()).apply {
flexDirection = FlexDirection.ROW
justifyContent = JustifyContent.FLEX_START
}
recyclerView.adapter = adapters[index]
adapters[index].updateFilters(filterLists[index])
recyclerView.layoutManager = flexLayout
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/filter/FilterFragment.kt | 2567308997 |
package com.hayatibahar.simpleandyummy.ui.filter.adapter
data class FilterItem(
val name: String,
var isSelected: Boolean = false,
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/filter/adapter/FilterItem.kt | 468591933 |
package com.hayatibahar.simpleandyummy.ui.filter.adapter
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.core.common.inflateAdapterItem
import com.hayatibahar.simpleandyummy.databinding.FilterItemBinding
class FilterAdapter : RecyclerView.Adapter<FilterViewHolder>() {
private val items = mutableListOf<FilterItem>()
private var onFilterItemClickListener: ((FilterItem) -> Unit)? = null
fun setOnFilterItemClickListener(onFilterItemClickListener: ((FilterItem) -> Unit)?) {
this.onFilterItemClickListener = onFilterItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilterViewHolder {
return FilterViewHolder(
parent.inflateAdapterItem(FilterItemBinding::inflate),
onFilterItemClickListener
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: FilterViewHolder, position: Int) {
holder.bind(items[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateFilters(newItems: List<FilterItem>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/filter/adapter/FilterAdapter.kt | 3633493586 |
package com.hayatibahar.simpleandyummy.ui.filter.adapter
import androidx.recyclerview.widget.RecyclerView
import com.hayatibahar.simpleandyummy.R
import com.hayatibahar.simpleandyummy.databinding.FilterItemBinding
class FilterViewHolder(
private val binding: FilterItemBinding,
private val onFilterItemClickListener: ((FilterItem) -> Unit)?,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(filterItem: FilterItem) {
with(binding) {
nameTv.text = filterItem.name
if (filterItem.isSelected) {
frameLayout.setBackgroundResource(R.drawable.filter_selected_background)
} else {
frameLayout.setBackgroundResource(R.drawable.filter_unselected_background)
}
}
binding.root.setOnClickListener {
onFilterItemClickListener?.invoke(filterItem)
}
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/ui/filter/adapter/FilterViewHolder.kt | 3804439338 |
package com.hayatibahar.simpleandyummy.core.database.di
import com.hayatibahar.simpleandyummy.core.database.source.LocalDataSource
import com.hayatibahar.simpleandyummy.core.database.source.LocalDataSourceImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class SourceModule {
@Binds
@Singleton
abstract fun bindLocalDataSource(localDataSourceImpl: LocalDataSourceImpl): LocalDataSource
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/di/SourceModule.kt | 580311866 |
package com.hayatibahar.simpleandyummy.core.database.di
import android.content.Context
import androidx.room.Room
import com.hayatibahar.simpleandyummy.core.common.DbConstants.DATABASE_NAME
import com.hayatibahar.simpleandyummy.core.database.source.DataStoreManager
import com.hayatibahar.simpleandyummy.core.database.source.RecipeDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext context: Context,
): RecipeDatabase = Room.databaseBuilder(
context,
RecipeDatabase::class.java,
DATABASE_NAME
).build()
@Provides
@Singleton
fun provideRecipeDao(database: RecipeDatabase) = database.recipeDao()
@Provides
@Singleton
fun provideGroceryDao(database: RecipeDatabase) = database.groceryDao()
@Provides
@Singleton
fun provideDataStoreManager(@ApplicationContext context: Context): DataStoreManager {
return DataStoreManager(context)
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/di/DatabaseModule.kt | 1580423847 |
package com.hayatibahar.simpleandyummy.core.database.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.hayatibahar.simpleandyummy.core.common.DbConstants.RECIPES_TABLE
@Entity(tableName = RECIPES_TABLE)
data class RecipeEntity(
@PrimaryKey(autoGenerate = false)
val id: Int = 0,
val title: String,
val image: String,
val readyInMinutes: Int,
val isFavorite: Boolean
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/entity/RecipeEntity.kt | 1358437503 |
package com.hayatibahar.simpleandyummy.core.database.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.hayatibahar.simpleandyummy.core.common.DbConstants.GROCERY_TABLE
@Entity(tableName = GROCERY_TABLE)
data class GroceryEntity(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
val nameClean: String,
val amount: Double,
val unit: String,
val isChecked: Boolean,
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/entity/GroceryEntity.kt | 1710519733 |
package com.hayatibahar.simpleandyummy.core.database.source
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.hayatibahar.simpleandyummy.core.database.entity.RecipeEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface RecipeDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertRecipes(recipeEntities: List<RecipeEntity>)
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertRecipe(recipeEntity: RecipeEntity)
@Delete
suspend fun deleteRecipe(recipeEntity: RecipeEntity)
@Query("UPDATE RECIPES_TABLE SET isFavorite = :isFavorite WHERE id= :recipeId")
suspend fun updateFavoriteStatus(recipeId: Int, isFavorite: Boolean)
@Query("SELECT isFavorite FROM RECIPES_TABLE WHERE id = :recipeId")
fun isRecipeFavorite(recipeId: Int): Flow<Boolean>
@Query("SELECT * FROM RECIPES_TABLE")
fun getAllRecipes(): Flow<List<RecipeEntity>>
@Query("SELECT * FROM RECIPES_TABLE where isFavorite == 1")
fun getAllFavoriteRecipes(): Flow<List<RecipeEntity>>
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/RecipeDao.kt | 667883629 |
package com.hayatibahar.simpleandyummy.core.database.source
import androidx.room.Database
import androidx.room.RoomDatabase
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.core.database.entity.RecipeEntity
@Database(entities = [RecipeEntity::class, GroceryEntity::class], version = 2, exportSchema = false)
abstract class RecipeDatabase : RoomDatabase() {
abstract fun recipeDao(): RecipeDao
abstract fun groceryDao(): GroceryDao
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/RecipeDatabase.kt | 2331266092 |
package com.hayatibahar.simpleandyummy.core.database.source
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hayatibahar.simpleandyummy.core.common.DataStoreConstants.IS_DARK_MODE
import com.hayatibahar.simpleandyummy.core.common.DataStoreConstants.LAST_REQUEST_TIME
import com.hayatibahar.simpleandyummy.core.common.DataStoreConstants.RECIPE_DATA_STORE
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class DataStoreManager @Inject constructor(private val context: Context) {
private val Context.dataStore by preferencesDataStore(name = RECIPE_DATA_STORE)
companion object {
val lastRequestTime = longPreferencesKey(LAST_REQUEST_TIME)
val isDarkMode = booleanPreferencesKey(IS_DARK_MODE)
}
suspend fun saveLastRequestTime(time: Long) {
context.dataStore.edit {
it[lastRequestTime] = time
}
}
fun getLastRequestTime(): Flow<Long> = context.dataStore.data.map {
it[lastRequestTime] ?: 0
}
suspend fun saveDarkModeState(isEnabled: Boolean) {
context.dataStore.edit {
it[isDarkMode] = isEnabled
}
}
fun getDarkModeState(): Flow<Boolean> = context.dataStore.data.map {
it[isDarkMode] ?: false
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/DataStoreManager.kt | 637353863 |
package com.hayatibahar.simpleandyummy.core.database.source
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.core.database.entity.RecipeEntity
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class LocalDataSourceImpl @Inject constructor(
private val recipeDao: RecipeDao,
private val groceryDao: GroceryDao,
private val dataStoreManager: DataStoreManager,
) : LocalDataSource {
override suspend fun insertRecipes(recipeEntities: List<RecipeEntity>) {
recipeDao.insertRecipes(recipeEntities)
}
override suspend fun insertRecipe(recipeEntity: RecipeEntity) {
recipeDao.insertRecipe(recipeEntity)
}
override suspend fun deleteRecipe(recipeEntity: RecipeEntity) {
recipeDao.deleteRecipe(recipeEntity)
}
override suspend fun updateFavoriteStatus(recipeId: Int, isFavorite: Boolean) {
recipeDao.updateFavoriteStatus(recipeId, isFavorite)
}
override suspend fun isRecipeFavorite(recipeId: Int): Flow<Boolean> {
return recipeDao.isRecipeFavorite(recipeId)
}
override suspend fun getAllRecipes(): Flow<List<RecipeEntity>> {
return recipeDao.getAllRecipes()
}
override suspend fun getAllFavoriteRecipes(): Flow<List<RecipeEntity>> {
return recipeDao.getAllFavoriteRecipes()
}
override suspend fun insertGroceries(groceries: List<GroceryEntity>) {
groceryDao.insertGroceries(groceries)
}
override suspend fun insertGrocery(groceryEntity: GroceryEntity) {
groceryDao.insertGrocery(groceryEntity)
}
override suspend fun deleteGrocery(groceryEntity: GroceryEntity) {
groceryDao.deleteGrocery(groceryEntity)
}
override suspend fun deleteCheckedGroceries() {
groceryDao.deleteCheckedGroceries()
}
override suspend fun deleteGroceries() {
groceryDao.deleteGroceries()
}
override suspend fun updateGroceryCheckStatus(id: Int, isChecked: Boolean) {
groceryDao.updateGroceryCheckStatus(id, isChecked)
}
override suspend fun getGroceries(): Flow<List<GroceryEntity>> {
return groceryDao.getGroceries()
}
override suspend fun saveLastRequestTime(time: Long) {
dataStoreManager.saveLastRequestTime(time)
}
override fun getLastRequestTime(): Flow<Long> {
return dataStoreManager.getLastRequestTime()
}
override suspend fun saveDarkModeState(isEnabled: Boolean) {
dataStoreManager.saveDarkModeState(isEnabled)
}
override fun getDarkModeState(): Flow<Boolean> {
return dataStoreManager.getDarkModeState()
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/LocalDataSourceImpl.kt | 2330954790 |
package com.hayatibahar.simpleandyummy.core.database.source
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import com.hayatibahar.simpleandyummy.core.database.entity.RecipeEntity
import kotlinx.coroutines.flow.Flow
interface LocalDataSource {
suspend fun insertRecipes(recipeEntities: List<RecipeEntity>)
suspend fun insertRecipe(recipeEntity: RecipeEntity)
suspend fun deleteRecipe(recipeEntity: RecipeEntity)
suspend fun updateFavoriteStatus(recipeId: Int, isFavorite: Boolean)
suspend fun isRecipeFavorite(recipeId: Int): Flow<Boolean>
suspend fun getAllRecipes(): Flow<List<RecipeEntity>>
suspend fun getAllFavoriteRecipes(): Flow<List<RecipeEntity>>
suspend fun insertGroceries(groceries: List<GroceryEntity>)
suspend fun insertGrocery(groceryEntity: GroceryEntity)
suspend fun deleteGrocery(groceryEntity: GroceryEntity)
suspend fun deleteCheckedGroceries()
suspend fun deleteGroceries()
suspend fun updateGroceryCheckStatus(id: Int, isChecked: Boolean)
suspend fun getGroceries(): Flow<List<GroceryEntity>>
suspend fun saveLastRequestTime(time: Long)
fun getLastRequestTime(): Flow<Long>
suspend fun saveDarkModeState(isEnabled: Boolean)
fun getDarkModeState(): Flow<Boolean>
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/LocalDataSource.kt | 1738493748 |
package com.hayatibahar.simpleandyummy.core.database.source
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.hayatibahar.simpleandyummy.core.database.entity.GroceryEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface GroceryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertGroceries(groceries: List<GroceryEntity>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertGrocery(groceryEntity: GroceryEntity)
@Delete
suspend fun deleteGrocery(groceryEntity: GroceryEntity)
@Query("DELETE FROM GROCERY_TABLE WHERE isChecked = 1")
suspend fun deleteCheckedGroceries()
@Query("DELETE FROM GROCERY_TABLE")
suspend fun deleteGroceries()
@Query("UPDATE GROCERY_TABLE SET isChecked = :isChecked WHERE id = :id")
suspend fun updateGroceryCheckStatus(id: Int, isChecked: Boolean)
@Query("SELECT * FROM GROCERY_TABLE")
fun getGroceries(): Flow<List<GroceryEntity>>
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/database/source/GroceryDao.kt | 3806558311 |
package com.hayatibahar.simpleandyummy.core.network.dto
data class AnalyzedInstructions(
val name: String,
val steps: List<Step>,
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/AnalyzedInstructions.kt | 3088300567 |
package com.hayatibahar.simpleandyummy.core.network.dto
data class Step(
val ingredients: List<Ingredient>,
val number: Int,
val step: String
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/Step.kt | 1862830951 |
package com.hayatibahar.simpleandyummy.core.network.dto
import com.google.gson.annotations.SerializedName
data class Result(
@SerializedName("id")
val foodId: Int,
val title: String,
val author: String,
val summary: String,
val image: String,
val imageType: String,
val sourceName: String,
val sourceUrl: String,
val spoonacularSourceUrl: String,
val license: String,
val creditsText: String,
val aggregateLikes: Int,
val likes: Int,
val pricePerServing: Double,
val weightWatcherSmartPoints: Int,
val healthScore: Int,
val cookingMinutes: Int,
val preparationMinutes: Int,
val readyInMinutes: Int,
val servings: Int,
val usedIngredientCount: Int,
val missedIngredientCount: Int,
val cuisines: List<String>,
val diets: List<String>,
val dishTypes: List<String>,
val occasions: List<String>,
val extendedIngredients: List<ExtendedIngredient>,
val usedIngredients: List<Any>,
val unusedIngredients: List<Any>,
val analyzedInstructions: List<AnalyzedInstructions>,
val gaps: String,
val cheap: Boolean,
val dairyFree: Boolean,
val glutenFree: Boolean,
val lowFodmap: Boolean,
val sustainable: Boolean,
val vegan: Boolean,
val vegetarian: Boolean,
val veryHealthy: Boolean,
val veryPopular: Boolean,
)
| Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/Result.kt | 2900178561 |
package com.hayatibahar.simpleandyummy.core.network.dto
data class ExtendedIngredient(
val aisle: String,
val amount: Double,
val consistency: String,
val id: Int,
val image: String,
val meta: List<String>,
val name: String?,
val nameClean: String?,
val original: String,
val originalName: String,
val unit: String,
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/ExtraIngredient.kt | 72382484 |
package com.hayatibahar.simpleandyummy.core.network.dto
import com.google.gson.annotations.SerializedName
data class RecipesResponse(
@SerializedName("number")
val number: Int?,
@SerializedName("offset")
val offset: Int?,
@SerializedName("results")
val results: List<Result?>?,
@SerializedName("totalResults")
val totalResults: Int?
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/RecipesResponse.kt | 4077664409 |
package com.hayatibahar.simpleandyummy.core.network.dto
data class Ingredient(
val id: Int,
val image: String,
val localizedName: String,
val name: String
) | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/dto/Ingredient.kt | 167804807 |
package com.hayatibahar.simpleandyummy.core.network.di
import com.hayatibahar.simpleandyummy.BuildConfig
import com.hayatibahar.simpleandyummy.core.network.interceptor.ApiKeyInterceptor
import com.hayatibahar.simpleandyummy.core.network.interceptor.NetworkStatusInterceptor
import com.hayatibahar.simpleandyummy.core.network.source.RecipeApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideHttpLoggingInterceptor() = HttpLoggingInterceptor().apply {
setLevel(HttpLoggingInterceptor.Level.BODY)
}
@Provides
@Singleton
fun provideApiKeyInterceptor() = ApiKeyInterceptor()
@Provides
@Singleton
fun provideHttpClient(
httpLoggingInterceptor: HttpLoggingInterceptor,
apiKeyInterceptor: ApiKeyInterceptor,
networkStatusInterceptor: NetworkStatusInterceptor,
): OkHttpClient {
return OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(apiKeyInterceptor)
.addInterceptor(networkStatusInterceptor)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor)
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideRecipeApiService(retrofit: Retrofit): RecipeApi = retrofit.create(RecipeApi::class.java)
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/di/NetworkModule.kt | 1089318581 |
package com.hayatibahar.simpleandyummy.core.network.di
import com.hayatibahar.simpleandyummy.core.network.source.RemoteDataSource
import com.hayatibahar.simpleandyummy.core.network.source.RemoteDataSourceImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class SourceModule {
@Binds
@Singleton
abstract fun bindRemoteDataSource(remoteDataSourceImpl: RemoteDataSourceImpl): RemoteDataSource
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/di/SourceModule.kt | 615881904 |
package com.hayatibahar.simpleandyummy.core.network.source
import com.hayatibahar.simpleandyummy.core.network.dto.RecipesResponse
import com.hayatibahar.simpleandyummy.core.network.dto.Result
import retrofit2.Response
interface RemoteDataSource {
suspend fun getAllRecipes(): Response<RecipesResponse>
suspend fun getRecipesWithSearch(
query: String,
cuisine: String,
type: String,
diet: String,
): Response<RecipesResponse>
suspend fun getRecipeDetail(id: String): Response<Result>
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/source/RemoteDataSource.kt | 4245580958 |
package com.hayatibahar.simpleandyummy.core.network.source
import com.hayatibahar.simpleandyummy.core.network.dto.RecipesResponse
import com.hayatibahar.simpleandyummy.core.network.dto.Result
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface RecipeApi {
@GET("recipes/complexSearch")
suspend fun getAllRecipes(
@Query("number") number: String = "100",
@Query("cuisine") cuisine: String = "european",
@Query("addRecipeInformation") addRecipeInformation: String = "true",
): Response<RecipesResponse>
@GET("recipes/complexSearch")
suspend fun getRecipesWithSearch(
@Query("number") number: String = "10",
@Query("query") query: String = "",
@Query("cuisine") cuisine: String = "",
@Query("type") type: String = "",
@Query("diet") diet: String = "",
@Query("addRecipeInformation") addRecipeInformation: String = "true",
): Response<RecipesResponse>
@GET("recipes/{id}/information")
suspend fun getRecipeDetail(
@Path("id") id: String = "1646939",
): Response<Result>
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/source/RecipeApi.kt | 3348891444 |
package com.hayatibahar.simpleandyummy.core.network.source
import com.hayatibahar.simpleandyummy.core.network.dto.RecipesResponse
import com.hayatibahar.simpleandyummy.core.network.dto.Result
import retrofit2.Response
import javax.inject.Inject
class RemoteDataSourceImpl @Inject constructor(private val recipeApi: RecipeApi) :
RemoteDataSource {
override suspend fun getAllRecipes(): Response<RecipesResponse> {
return recipeApi.getAllRecipes()
}
override suspend fun getRecipesWithSearch(
query: String,
cuisine: String,
type: String,
diet: String,
): Response<RecipesResponse> {
return recipeApi.getRecipesWithSearch(
query = query,
cuisine = cuisine,
type = type,
diet = diet
)
}
override suspend fun getRecipeDetail(id: String): Response<Result> {
return recipeApi.getRecipeDetail(id)
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/source/RemoteDataSourceImpl.kt | 3893093745 |
package com.hayatibahar.simpleandyummy.core.network.interceptor
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import dagger.hilt.android.qualifiers.ApplicationContext
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
class NetworkStatusInterceptor @Inject constructor(
private val connectionManager: ConnectionManager,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return if (connectionManager.isConnected) {
chain.proceed(chain.request())
} else {
throw NetworkUnavailableException()
}
}
}
class NetworkUnavailableException(
message: String = "Connection is lost, network error!",
) : IOException(message)
class ConnectionManager @Inject constructor(@ApplicationContext private val context: Context) {
val isConnected: Boolean
get() = _isConnected.get()
private val _isConnected = AtomicBoolean(false)
init {
listenToNetworkChanges()
}
private fun listenToNetworkChanges() {
val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build()
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
_isConnected.set(true)
}
override fun onLost(network: Network) {
_isConnected.set(false)
}
}
val connectivityManager =
context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
connectivityManager.requestNetwork(networkRequest, networkCallback)
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/interceptor/NetworkStatusInterceptor.kt | 622155132 |
package com.hayatibahar.simpleandyummy.core.network.interceptor
import com.hayatibahar.simpleandyummy.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response
private const val API_KEY = "apiKey"
class ApiKeyInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url
.newBuilder()
.addQueryParameter(API_KEY, BuildConfig.API_KEY)
.build()
val requestBuilder = request.newBuilder()
.url(url)
return chain.proceed(requestBuilder.build())
}
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/network/interceptor/ApiKeyInterceptor.kt | 3391033199 |
package com.hayatibahar.simpleandyummy.core.common
object ApiConstants {
val diet = listOf(
"Gluten Free",
"Ketogenic",
"Vegetarian",
"Lacto-Vegetarian",
"OvoVegetarian",
"Vegan",
"Pescetarian",
"Paleo",
"Primal",
"LowFODMAP",
"Whole30"
)
val mealType = listOf(
"Main course",
"Side dish",
"Dessert",
"Appetizer",
"Salad",
"Bread",
"Breakfast",
"Soup",
"Beverage",
"Sauce",
"Marinade",
"Fingerfood",
"Snack",
"Drink"
)
val cuisines = listOf(
"African",
"Asian",
"American",
"British",
"Cajun",
"Caribbean",
"Chinese",
"European",
"French",
"German",
"Greek",
"Indian",
"Irish",
"Italian",
"Japanese",
"Jewish",
"Korean",
"LatinAmerican",
"Mediterranean",
"Mexican",
"MiddleEastern",
"Nordic",
"Southern",
"Spanish",
"Thai",
"Vietnamese"
)
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/common/ApiConstants.kt | 3798894501 |
package com.hayatibahar.simpleandyummy.core.common
object DataStoreConstants {
const val RECIPE_DATA_STORE = "recipe_data_store"
const val LAST_REQUEST_TIME = "last_request_time"
const val IS_DARK_MODE = "is_dark_mode"
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/common/DataStoreConstants.kt | 306890504 |
package com.hayatibahar.simpleandyummy.core.common
sealed class ResponseState<out T> {
data object Loading : ResponseState<Nothing>()
data class Error(val message: String) : ResponseState<Nothing>()
data class Success<T>(val data: T) : ResponseState<T>()
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/common/ResponseState.kt | 1469236396 |
package com.hayatibahar.simpleandyummy.core.common
inline fun <I,O> I.mapTo(crossinline mapper:(I)->O):O{
return mapper(this)
} | Simple-And-Yummy/app/src/main/java/com/hayatibahar/simpleandyummy/core/common/MapExtension.kt | 3613574763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.