path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/api/MathApiResult.kt | 3853243106 | package io.github.aloussase.calculator.api
data class MathApiResult(
val result: String? = null,
val error: String? = null
)
|
android-clean-architecture-calculator/app/src/main/java/io/github/aloussase/calculator/data/HistoryItem.kt | 1987882048 | package io.github.aloussase.calculator.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(
tableName = "history_items"
)
data class HistoryItem(
val content: String,
@PrimaryKey val id: Long? = null,
)
|
Orgs2.0/app/src/androidTest/java/br/com/alura/orgs/ExampleInstrumentedTest.kt | 596631617 | package br.com.alura.orgs
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("br.com.alura.orgs", appContext.packageName)
}
} |
Orgs2.0/app/src/test/java/br/com/alura/orgs/ExampleUnitTest.kt | 1470607537 | package br.com.alura.orgs
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)
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/DetalhesProdutoActivity.kt | 73715922 | package br.com.alura.orgs.ui.activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.lifecycleScope
import br.com.alura.orgs.R
import br.com.alura.orgs.database.AppDatabase
import br.com.alura.orgs.databinding.ActivityDetalhesProdutoBinding
import br.com.alura.orgs.extensions.formataParaMoedaBrasileira
import br.com.alura.orgs.extensions.tentaCarregarImagem
import br.com.alura.orgs.model.Produto
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class DetalhesProdutoActivity : AppCompatActivity() {
private var produtoId: Long = 0L
private var produto: Produto? = null
private val binding by lazy {
ActivityDetalhesProdutoBinding.inflate(layoutInflater)
}
private val produtoDao by lazy {
AppDatabase.instancia(this).produtoDao()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
tentaCarregarProduto()
}
override fun onResume() {
super.onResume()
buscaProduto()
}
private fun buscaProduto() {
lifecycleScope.launch {
produtoDao.buscaPorId(produtoId).collect { produtoEncontrado ->
produto = produtoEncontrado
produto?.let {
preencheCampos(it)
} ?: finish()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_detalhes_produto, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_detalhes_produto_remover -> {
produto?.let {
lifecycleScope.launch {
produtoDao.remove(it)
finish()
}
}
}
R.id.menu_detalhes_produto_editar -> {
Intent(this, FormularioProdutoActivity::class.java).apply {
putExtra(CHAVE_PRODUTO_ID, produtoId)
startActivity(this)
}
}
}
return super.onOptionsItemSelected(item)
}
private fun tentaCarregarProduto() {
produtoId = intent.getLongExtra(CHAVE_PRODUTO_ID, 0L)
}
private fun preencheCampos(produtoCarregado: Produto) {
with(binding) {
activityDetalhesProdutoImagem.tentaCarregarImagem(produtoCarregado.imagem)
activityDetalhesProdutoNome.text = produtoCarregado.nome
activityDetalhesProdutoDescricao.text = produtoCarregado.descricao
activityDetalhesProdutoValor.text =
produtoCarregado.valor.formataParaMoedaBrasileira()
}
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/ConstantesActivities.kt | 2932867855 | package br.com.alura.orgs.ui.activity
const val CHAVE_PRODUTO_ID: String = "PRODUTO_ID" |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/FormularioProdutoActivity.kt | 3186066231 | package br.com.alura.orgs.ui.activity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import br.com.alura.orgs.database.AppDatabase
import br.com.alura.orgs.database.dao.ProdutoDao
import br.com.alura.orgs.databinding.ActivityFormularioProdutoBinding
import br.com.alura.orgs.extensions.tentaCarregarImagem
import br.com.alura.orgs.model.Produto
import br.com.alura.orgs.ui.dialog.FormularioImagemDialog
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.math.BigDecimal
class FormularioProdutoActivity : UsuarioBaseActivity() {
private val binding by lazy {
ActivityFormularioProdutoBinding.inflate(layoutInflater)
}
private var url: String? = null
private var produtoId = 0L
private val produtoDao: ProdutoDao by lazy {
val db = AppDatabase.instancia(this)
db.produtoDao()
}
private val usuarioDao by lazy {
AppDatabase.instancia(this).usuarioDao()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
title = "Cadastrar produto"
configuraBotaoSalvar()
binding.activityFormularioProdutoImagem.setOnClickListener {
FormularioImagemDialog(this).mostra(url) { imagem ->
url = imagem
binding.activityFormularioProdutoImagem.tentaCarregarImagem(url)
}
}
tentaCarregarProduto()
}
private fun tentaCarregarProduto() {
produtoId = intent.getLongExtra(CHAVE_PRODUTO_ID, 0L)
}
override fun onResume() {
super.onResume()
tentaBuscarProduto()
}
private fun tentaBuscarProduto() {
lifecycleScope.launch {
produtoDao.buscaPorId(produtoId).collect {
it?.let { produtoEncontrado ->
title = "Alterar produto"
preencheCampos(produtoEncontrado)
}
}
}
}
private fun preencheCampos(produto: Produto) {
url = produto.imagem
binding.activityFormularioProdutoImagem.tentaCarregarImagem(produto.imagem)
binding.activityFormularioProdutoNome.setText(produto.nome)
binding.activityFormularioProdutoDescricao.setText(produto.descricao)
binding.activityFormularioProdutoValor.setText(produto.valor.toPlainString())
}
private fun configuraBotaoSalvar() {
val botaoSalvar = binding.activityFormularioProdutoBotaoSalvar
botaoSalvar.setOnClickListener {
lifecycleScope.launch {
usuario.value?.let { usuario ->
val produtoNovo = criaProduto(usuario.id)
produtoDao.salva(produtoNovo)
finish()
}
}
}
}
private fun criaProduto(usuarioId: String): Produto {
val campoNome = binding.activityFormularioProdutoNome
val nome = campoNome.text.toString()
val campoDescricao = binding.activityFormularioProdutoDescricao
val descricao = campoDescricao.text.toString()
val campoValor = binding.activityFormularioProdutoValor
val valorEmTexto = campoValor.text.toString()
val valor = if (valorEmTexto.isBlank()) {
BigDecimal.ZERO
} else {
BigDecimal(valorEmTexto)
}
return Produto(
id = produtoId,
nome = nome,
descricao = descricao,
valor = valor,
imagem = url,
usuarioId = usuarioId
)
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/activity/ListaProdutosActivity.kt | 703765688 | package br.com.alura.orgs.ui.activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.preferences.core.edit
import androidx.lifecycle.lifecycleScope
import br.com.alura.orgs.R
import br.com.alura.orgs.database.AppDatabase
import br.com.alura.orgs.databinding.ActivityListaProdutosActivityBinding
import br.com.alura.orgs.extensions.vaiPara
import br.com.alura.orgs.preferences.dataStore
import br.com.alura.orgs.preferences.usuarioLogadoPreferences
import br.com.alura.orgs.ui.recyclerview.adapter.ListaProdutosAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
class ListaProdutosActivity : UsuarioBaseActivity() {
private val adapter = ListaProdutosAdapter(context = this)
private val binding by lazy {
ActivityListaProdutosActivityBinding.inflate(layoutInflater)
}
private val produtoDao by lazy {
val db = AppDatabase.instancia(this)
db.produtoDao()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
configuraRecyclerView()
configuraFab()
lifecycleScope.launch {
launch {
usuario
.filterNotNull()
.collect {usuario ->
buscaProdutosUsuario(usuario.id)
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_lista_produtos, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_lista_produtos_sair_do_app -> {
lifecycleScope.launch {
deslogaUsuario()
}
}
}
return super.onOptionsItemSelected(item)
}
private suspend fun buscaProdutosUsuario(usuarioId: String) {
produtoDao.buscaTodosDoUsuario(usuarioId).collect { produtos ->
adapter.atualiza(produtos)
}
}
private fun configuraFab() {
val fab = binding.activityListaProdutosFab
fab.setOnClickListener {
vaiParaFormularioProduto()
}
}
private fun vaiParaFormularioProduto() {
val intent = Intent(this, FormularioProdutoActivity::class.java)
startActivity(intent)
}
private fun configuraRecyclerView() {
val recyclerView = binding.activityListaProdutosRecyclerView
recyclerView.adapter = adapter
adapter.quandoClicaNoItem = {
val intent = Intent(
this,
DetalhesProdutoActivity::class.java
).apply {
putExtra(CHAVE_PRODUTO_ID, it.id)
}
startActivity(intent)
}
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/dialog/FormularioImagemDialog.kt | 946382730 | package br.com.alura.orgs.ui.dialog
import android.content.Context
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import br.com.alura.orgs.databinding.FormularioImagemBinding
import br.com.alura.orgs.extensions.tentaCarregarImagem
class FormularioImagemDialog(private val context: Context) {
fun mostra(
urlPadrao: String? = null,
quandoImagemCarragada: (imagem: String) -> Unit
) {
FormularioImagemBinding
.inflate(LayoutInflater.from(context)).apply {
urlPadrao?.let {
formularioImagemImageview.tentaCarregarImagem(it)
formularioImagemUrl.setText(it)
}
formularioImagemBotaoCarregar.setOnClickListener {
val url = formularioImagemUrl.text.toString()
formularioImagemImageview.tentaCarregarImagem(url)
}
AlertDialog.Builder(context)
.setView(root)
.setPositiveButton("Confirmar") { _, _ ->
val url = formularioImagemUrl.text.toString()
quandoImagemCarragada(url)
}
.setNegativeButton("Cancelar") { _, _ ->
}
.show()
}
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/ui/recyclerview/adapter/ListaProdutosAdapter.kt | 3653105942 | package br.com.alura.orgs.ui.recyclerview.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import br.com.alura.orgs.databinding.ProdutoItemBinding
import br.com.alura.orgs.extensions.formataParaMoedaBrasileira
import br.com.alura.orgs.extensions.tentaCarregarImagem
import br.com.alura.orgs.model.Produto
class ListaProdutosAdapter(
private val context: Context,
produtos: List<Produto> = emptyList(),
var quandoClicaNoItem: (produto: Produto) -> Unit = {}
) : RecyclerView.Adapter<ListaProdutosAdapter.ViewHolder>() {
private val produtos = produtos.toMutableList()
inner class ViewHolder(private val binding: ProdutoItemBinding) :
RecyclerView.ViewHolder(binding.root) {
private lateinit var produto: Produto
init {
itemView.setOnClickListener {
if (::produto.isInitialized) {
quandoClicaNoItem(produto)
}
}
}
fun vincula(produto: Produto) {
this.produto = produto
val nome = binding.produtoItemNome
nome.text = produto.nome
val descricao = binding.produtoItemDescricao
descricao.text = produto.descricao
val valor = binding.produtoItemValor
val valorEmMoeda: String = produto.valor
.formataParaMoedaBrasileira()
valor.text = valorEmMoeda
val visibilidade = if (produto.imagem != null) {
View.VISIBLE
} else {
View.GONE
}
binding.imageView.visibility = visibilidade
binding.imageView.tentaCarregarImagem(produto.imagem)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(context)
val binding = ProdutoItemBinding.inflate(inflater, parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val produto = produtos[position]
holder.vincula(produto)
}
override fun getItemCount(): Int = produtos.size
fun atualiza(produtos: List<Produto>) {
this.produtos.clear()
this.produtos.addAll(produtos)
notifyDataSetChanged()
}
}
|
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/Migrations.kt | 2908890328 | package br.com.alura.orgs.database
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("""
CREATE TABLE IF NOT EXISTS `Usuario` (
`id` TEXT NOT NULL,
`nome` TEXT NOT NULL,
`senha` TEXT NOT NULL, PRIMARY KEY(`id`))
""")
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE Produto ADD COLUMN 'usuarioId' TEXT")
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/converter/Converters.kt | 3420313798 | package br.com.alura.orgs.database.converter
import androidx.room.TypeConverter
import java.math.BigDecimal
class Converters {
@TypeConverter
fun deDouble(valor: Double?) : BigDecimal {
return valor?.let { BigDecimal(valor.toString()) } ?: BigDecimal.ZERO
}
@TypeConverter
fun bigDecimalParaDouble(valor: BigDecimal?) : Double? {
return valor?.let { valor.toDouble() }
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/dao/ProdutoDao.kt | 999944923 | package br.com.alura.orgs.database.dao
import androidx.room.*
import br.com.alura.orgs.model.Produto
import kotlinx.coroutines.flow.Flow
@Dao
interface ProdutoDao {
@Query("SELECT * FROM Produto")
fun buscaTodos(): Flow<List<Produto>>
@Query("SELECT * FROM Produto WHERE usuarioId = :usuarioId")
fun buscaTodosDoUsuario(usuarioId: String) : Flow<List<Produto>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun salva(vararg produto: Produto)
@Delete
suspend fun remove(produto: Produto)
@Query("SELECT * FROM Produto WHERE id = :id")
fun buscaPorId(id: Long): Flow<Produto?>
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/dao/UsuarioDao.kt | 3008690867 | package br.com.alura.orgs.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import br.com.alura.orgs.model.Usuario
import kotlinx.coroutines.flow.Flow
@Dao
interface UsuarioDao {
@Insert
suspend fun salva(usuario: Usuario)
@Query("""
SELECT * FROM Usuario
WHERE id = :usuarioId
AND senha = :senha""")
suspend fun autentica(
usuarioId: String,
senha: String
): Usuario?
@Query("SELECT * FROM Usuario WHERE id = :usuarioId")
fun buscaPorId(usuarioId: String): Flow<Usuario>
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/database/AppDatabase.kt | 1903781028 | package br.com.alura.orgs.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import br.com.alura.orgs.database.converter.Converters
import br.com.alura.orgs.database.dao.ProdutoDao
import br.com.alura.orgs.database.dao.UsuarioDao
import br.com.alura.orgs.model.Produto
import br.com.alura.orgs.model.Usuario
@Database(
entities = [
Produto::class,
Usuario::class
],
version = 3,
exportSchema = true
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun produtoDao(): ProdutoDao
abstract fun usuarioDao(): UsuarioDao
companion object {
@Volatile
private var db: AppDatabase? = null
fun instancia(context: Context): AppDatabase {
return db ?: Room.databaseBuilder(
context,
AppDatabase::class.java,
"orgs.db"
).addMigrations(
MIGRATION_1_2,
MIGRATION_2_3
)
.build().also {
db = it
}
}
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/preferences/UsuarioPreferences.kt | 3272267987 | package br.com.alura.orgs.preferences
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "sessao_usuario")
val usuarioLogadoPreferences = stringPreferencesKey("usuarioLogado") |
Orgs2.0/app/src/main/java/br/com/alura/orgs/extensions/BigDecimalExtensions.kt | 3030808231 | package br.com.alura.orgs.extensions
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.*
fun BigDecimal.formataParaMoedaBrasileira(): String {
val formatador: NumberFormat = NumberFormat
.getCurrencyInstance(Locale("pt", "br"))
return formatador.format(this)
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/extensions/ImageViewExtensions.kt | 2167883758 | package br.com.alura.orgs.extensions
import android.widget.ImageView
import br.com.alura.orgs.R
import coil.load
fun ImageView.tentaCarregarImagem(
url: String? = null,
fallback: Int = R.drawable.imagem_padrao
){
load(url) {
fallback(fallback)
error(R.drawable.erro)
placeholder(R.drawable.placeholder)
}
} |
Orgs2.0/app/src/main/java/br/com/alura/orgs/model/Produto.kt | 1760884583 | package br.com.alura.orgs.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.math.BigDecimal
@Entity
@Parcelize
data class Produto(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
val nome: String,
val descricao: String,
val valor: BigDecimal,
val imagem: String? = null,
val usuarioId: String? = null
) : Parcelable
|
inherita/src/main/kotlin/Main.kt | 2584249790 | fun main() {
oddNumbers()
serveDrinks(6)
product(50)
product(101)
println(myNAme(arrayOf("Maureen","Ivy", "Rehema", "Gatweri")))
}
fun oddNumbers() {
for (num1 in 1 ..100) {
if (num1 % 2 != 0) {
println(num1)
}
}
}
fun serveDrinks(age:Int){
if (age<=6){
println("Serve Milk")
}
else if (age <= 15 && age>6){
println(" Serve Fanta Orange")
}
else
println("Serve Cocacola")
}
fun product(num:Int){
for (num in 1..100){
when{
(num%3==0 && num%5 ==0)->
println("FizzBuzz")
(num %3 ==0)->
println("Fizz")
(num % 5==0)->
println("Buzz")
else->
( println(num))
}
}
}
fun myNAme (name: Array <String>):Int{
return name.count {it.length>5}
} |
QuickMuseum/app/src/androidTest/java/com/dtks/quickmuseum/ExampleInstrumentedTest.kt | 1531015177 | package com.dtks.quickmuseum
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* 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.dtks.quickmuseum", appContext.packageName)
}
} |
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/MainCoroutineRule.kt | 3199733987 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtks.quickmuseum.ui
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* Sets the main coroutines dispatcher to a [TestDispatcher] for unit testing.
*
* Declare it as a JUnit Rule:
*
* ```
* @get:Rule
* val mainCoroutineRule = MainCoroutineRule()
* ```
*
* Then, use `runTest` to execute your tests.
*/
@ExperimentalCoroutinesApi
class MainCoroutineRule(
val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
}
}
|
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/details/ArtDetailViewModelTest.kt | 3882703506 | package com.dtks.quickmuseum.ui.details
import androidx.lifecycle.SavedStateHandle
import com.dtks.quickmuseum.data.model.ArtDetailsRequest
import com.dtks.quickmuseum.data.repository.ArtDetailsRepository
import com.dtks.quickmuseum.data.repository.defaultArtDetails
import com.dtks.quickmuseum.ui.MainCoroutineRule
import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import junit.framework.TestCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class ArtDetailViewModelTest {
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
private lateinit var artDetailViewModel: ArtDetailViewModel
val repository: ArtDetailsRepository = mockk()
@Before
fun setup() {
every { repository.getArtDetailsFlow(any()) } returns flow {
emit(defaultArtDetails)
}
artDetailViewModel = ArtDetailViewModel(
repository,
SavedStateHandle(mapOf(QuickMuseumDestinationsArgs.ART_ID_ARG to "artId2"))
)
}
@Test
fun testInitialStateIsLoaded() = runTest {
Dispatchers.setMain(StandardTestDispatcher())
val uiState = artDetailViewModel.uiState
TestCase.assertTrue(uiState.first().isLoading)
advanceUntilIdle()
TestCase.assertFalse(uiState.first().isLoading)
TestCase.assertEquals(uiState.first().artDetails, defaultArtDetails)
coVerify {
repository.getArtDetailsFlow(
ArtDetailsRequest(
artObjectNumber = "artId2"
)
)
}
}
} |
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/ui/overview/OverviewViewModelTest.kt | 1858313880 | package com.dtks.quickmuseum.ui.overview
import com.dtks.quickmuseum.data.model.CollectionRequest
import com.dtks.quickmuseum.data.repository.OverviewRepository
import com.dtks.quickmuseum.data.repository.defaultArtObjectListItems
import com.dtks.quickmuseum.data.repository.secondaryArtObjectListItems
import com.dtks.quickmuseum.ui.MainCoroutineRule
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class OverviewViewModelTest {
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
private lateinit var overviewViewModel: OverviewViewModel
val repository: OverviewRepository = mockk()
@Before
fun setup() {
every { repository.getCollectionFlow(any()) } returns flow {
emit(defaultArtObjectListItems)
} andThen flow {
emit(secondaryArtObjectListItems)
}
overviewViewModel = OverviewViewModel(
repository
)
}
@Test
fun testInitialStateIsLoaded() = runTest {
Dispatchers.setMain(StandardTestDispatcher())
val uiState = overviewViewModel.combinedUiState
assertTrue(uiState.first().isLoading)
advanceUntilIdle()
assertFalse(uiState.first().isLoading)
assertEquals(uiState.first().items, defaultArtObjectListItems)
}
@Test
fun testLoadNextPage() = runTest {
Dispatchers.setMain(StandardTestDispatcher())
val uiState = overviewViewModel.combinedUiState
advanceUntilIdle()
overviewViewModel.loadNextPage()
assertTrue(uiState.first().isLoading)
advanceUntilIdle()
assertFalse(uiState.first().isLoading)
assertEquals(uiState.first().items, defaultArtObjectListItems+secondaryArtObjectListItems)
coVerify {
repository.getCollectionFlow(
CollectionRequest(
page = 2
)
)
}
}
} |
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/DefaultTestData.kt | 1887867612 | package com.dtks.quickmuseum.data.repository
import com.dtks.quickmuseum.data.model.ArtCreator
import com.dtks.quickmuseum.data.model.ArtDetailsDao
import com.dtks.quickmuseum.data.model.ArtDetailsResponse
import com.dtks.quickmuseum.data.model.ArtObjectDao
import com.dtks.quickmuseum.data.model.CollectionResponse
import com.dtks.quickmuseum.data.model.Dating
import com.dtks.quickmuseum.data.model.WebImage
import com.dtks.quickmuseum.ui.details.ArtDetails
import com.dtks.quickmuseum.ui.details.ArtDetailsImage
import com.dtks.quickmuseum.ui.overview.ArtObjectListItem
val defaultArtId = "art1"
val defaultObjectNumber = "artObject1"
val defaultTitle = "Eternal sunshine of the spotless mind"
val defaultMaterials = listOf("aluminium", "copper")
val defaultTechniques = listOf("acting")
val defaultDatingString = "2004"
val defaultImageUrl = "imageUrl.com/cool"
val defaultCreator = "Charlie Kaufman"
val defaultArtDetailsDao = ArtDetailsDao(
id = defaultArtId,
objectNumber = defaultObjectNumber,
title = defaultTitle,
principalMakers = listOf(
ArtCreator(
defaultCreator,
"USA",
occupation = null,
roles = listOf("writer")
)
),
materials = defaultMaterials,
techniques = defaultTechniques,
dating = Dating(defaultDatingString),
webImage = WebImage(guid = "id23", width = 100, height = 200, url = defaultImageUrl)
)
val defaultArtDetailsResponse = ArtDetailsResponse(
artObject = defaultArtDetailsDao
)
val defaultArtDetails = ArtDetails(
id = defaultArtId,
objectNumber = defaultObjectNumber,
title = defaultTitle,
creators = listOf(defaultCreator),
materials = defaultMaterials,
techniques = defaultTechniques,
dating = defaultDatingString,
image = ArtDetailsImage(
url = defaultImageUrl,
width = 100,
height = 200
)
)
val defaultArtObjectListItems = listOf(
ArtObjectListItem(
id = defaultArtId,
objectNumber = defaultObjectNumber,
title = defaultTitle,
creator = defaultCreator,
imageUrl = defaultImageUrl,
)
)
val secondaryArtObjectListItems = listOf(
ArtObjectListItem(
id = "id2",
objectNumber = "obj2",
title = "Drawing of the office",
creator = "Pam Beesly",
imageUrl = "http://theoffice.co.uk/pam_drawing.png",
)
)
val defaultCollectionResponse = CollectionResponse(
count = 1,
artObjects = listOf(
ArtObjectDao(
id = defaultArtId,
objectNumber = defaultObjectNumber,
title = defaultTitle,
hasImage = true,
principalOrFirstMaker = defaultCreator,
webImage = WebImage(
guid = "image2",
url = defaultImageUrl,
width = 100,
height = 100,
)
)
)
) |
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/OverviewRepositoryTest.kt | 407444457 | package com.dtks.quickmuseum.data.repository
import com.dtks.quickmuseum.data.RemoteDataSource
import com.dtks.quickmuseum.data.model.CollectionRequest
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class OverviewRepositoryTest{
val remoteDataSourceMock = mockk<RemoteDataSource>()
private lateinit var repository: OverviewRepository
private var testDispatcher = UnconfinedTestDispatcher()
private var testScope = TestScope(testDispatcher)
@Before
fun setup() {
repository = OverviewRepository(
remoteDataSource = remoteDataSourceMock,
dispatcher = testDispatcher
)
}
@Test
fun getOverviewArtObjectsMapsResponseCorrectly()= testScope.runTest{
val expectedArtObjectListItems = defaultArtObjectListItems
coEvery { remoteDataSourceMock.getCollection(any())} returns defaultCollectionResponse
val artObjects = repository.getOverviewArtObjects(
CollectionRequest()
)
Assert.assertEquals(expectedArtObjectListItems, artObjects)
}
} |
QuickMuseum/app/src/test/java/com/dtks/quickmuseum/data/repository/ArtDetailsRepositoryTest.kt | 2174042491 | package com.dtks.quickmuseum.data.repository
import com.dtks.quickmuseum.data.RemoteDataSource
import com.dtks.quickmuseum.data.model.ArtDetailsRequest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class ArtDetailsRepositoryTest{
val remoteDataSourceMock = mockk<RemoteDataSource>()
private lateinit var repository: ArtDetailsRepository
private var testDispatcher = UnconfinedTestDispatcher()
private var testScope = TestScope(testDispatcher)
@Before
fun setup() {
repository = ArtDetailsRepository(
remoteDataSource = remoteDataSourceMock,
dispatcher = testDispatcher
)
}
@Test
fun getArtDetailsMapsResponseCorrectly()= testScope.runTest{
val expectedArtDetails = defaultArtDetails
coEvery { remoteDataSourceMock.getArtDetails(any())} returns defaultArtDetailsResponse
val request = ArtDetailsRequest(artObjectNumber = "a")
val artDetails = repository.getArtDetails(
request
)
coVerify { remoteDataSourceMock.getArtDetails(request) }
Assert.assertEquals(expectedArtDetails, artDetails)
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/EmptyContent.kt | 3891257195 | package com.dtks.quickmuseum.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import com.dtks.quickmuseum.R
@Composable
fun EmptyContent(@StringRes emptyResultStringResource: Int) {
Box(modifier = Modifier.fillMaxSize()) {
Text(
text = stringResource(id = emptyResultStringResource),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.padding(
dimensionResource(id = R.dimen.horizontal_margin)
)
.fillMaxSize()
.align(Alignment.Center)
)
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/loading/ImageLoading.kt | 3540192662 | package com.dtks.quickmuseum.ui.loading
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import com.dtks.quickmuseum.R
@Composable
fun ImageLoading(modifier: Modifier) {
val transition = rememberInfiniteTransition(
label = stringResource(id = R.string.image_background_transition)
)
val borderColor by transition.animateColor(
initialValue = MaterialTheme.colorScheme.primaryContainer,
targetValue = MaterialTheme.colorScheme.inversePrimary,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
),
label = stringResource(id = R.string.image_background_label)
)
Box(
modifier = modifier.background(color = borderColor)
) {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.Center)
.width(dimensionResource(id = R.dimen.progress_indicator_size)),
color = MaterialTheme.colorScheme.secondary,
)
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/loading/LoadingContent.kt | 1928452846 | package com.dtks.quickmuseum.ui.loading
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import com.dtks.quickmuseum.R
@Composable
fun LoadingContent(
loading: Boolean,
empty: Boolean,
emptyContent: @Composable () -> Unit,
content: @Composable () -> Unit
) {
if (empty && loading) {
Box(
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.Center)
.width(dimensionResource(id = R.dimen.progress_indicator_size)),
color = MaterialTheme.colorScheme.secondary,
)
}
} else if (empty) {
emptyContent()
} else {
content()
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/navigation/QuickMuseumNavigation.kt | 2963255247 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtks.quickmuseum.ui.navigation
import androidx.navigation.NavHostController
import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.ART_ID_ARG
import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.USER_MESSAGE_ARG
import com.dtks.quickmuseum.ui.navigation.QuickMuseumScreens.ARTS_SCREEN
import com.dtks.quickmuseum.ui.navigation.QuickMuseumScreens.ART_DETAILS_SCREEN
private object QuickMuseumScreens {
const val ARTS_SCREEN = "arts"
const val ART_DETAILS_SCREEN = "art"
}
object QuickMuseumDestinationsArgs {
const val USER_MESSAGE_ARG = "userMessage"
const val ART_ID_ARG = "artId"
}
object QuickMuseumDestinations {
const val ARTS_ROUTE = "$ARTS_SCREEN?$USER_MESSAGE_ARG={$USER_MESSAGE_ARG}"
const val ART_DETAILS_ROUTE = "$ART_DETAILS_SCREEN/{$ART_ID_ARG}"
}
/**
* Models the navigation actions in the app.
*/
class QuickMuseumNavigationActions(private val navController: NavHostController) {
fun navigateToArtDetail(artObjectNumber: String) {
navController.navigate("$ART_DETAILS_SCREEN/$artObjectNumber")
}
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/navigation/QuickMuseumNavGraph.kt | 1283480676 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtks.quickmuseum.ui.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.dtks.quickmuseum.ui.details.ArtDetailScreen
import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs.USER_MESSAGE_ARG
import com.dtks.quickmuseum.ui.overview.OverviewScreen
import com.dtks.quickmuseum.ui.overview.OverviewViewModel
@Composable
fun QuickMuseumNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController = rememberNavController(),
startDestination: String = QuickMuseumDestinations.ARTS_ROUTE,
navActions: QuickMuseumNavigationActions = remember(navController) {
QuickMuseumNavigationActions(navController)
},
viewModel: OverviewViewModel = hiltViewModel(),
) {
val currentNavBackStackEntry by navController.currentBackStackEntryAsState()
NavHost(
navController = navController,
startDestination = startDestination,
modifier = modifier
) {
composable(
QuickMuseumDestinations.ARTS_ROUTE,
arguments = listOf(
navArgument(USER_MESSAGE_ARG) { type = NavType.IntType; defaultValue = 0 }
)
) {
OverviewScreen(
onArtItemClick = { art -> navActions.navigateToArtDetail(art.objectNumber) },
viewModel = viewModel
)
}
composable(QuickMuseumDestinations.ART_DETAILS_ROUTE) {
ArtDetailScreen(
onBack = { navController.popBackStack() },
)
}
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsTopBar.kt | 410280207 | package com.dtks.quickmuseum.ui.details
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.dtks.quickmuseum.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArtDetailsTopBar(title: String, onBack: () -> Unit) {
TopAppBar(
title = {
Text(text = title, maxLines = 1, overflow = TextOverflow.Ellipsis)
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.Filled.ArrowBack, stringResource(id = R.string.menu_back))
}
},
modifier = Modifier.fillMaxWidth()
)
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsImage.kt | 188553149 | package com.dtks.quickmuseum.ui.details
data class ArtDetailsImage(
val url : String?,
val width: Int,
val height: Int,
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailViewModel.kt | 1603520987 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtks.quickmuseum.ui.details
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dtks.quickmuseum.R
import com.dtks.quickmuseum.data.model.ArtDetailsRequest
import com.dtks.quickmuseum.data.repository.ArtDetailsRepository
import com.dtks.quickmuseum.ui.navigation.QuickMuseumDestinationsArgs
import com.dtks.quickmuseum.utils.AsyncResource
import com.dtks.quickmuseum.utils.WhileUiSubscribed
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class ArtDetailViewModel @Inject constructor(
artDetailsRepository: ArtDetailsRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val artObjectNumber: String = savedStateHandle[QuickMuseumDestinationsArgs.ART_ID_ARG]!!
private val _userMessage: MutableStateFlow<Int?> = MutableStateFlow(null)
private val _isLoading = MutableStateFlow(false)
private val _taskAsync = artDetailsRepository.getArtDetailsFlow(
ArtDetailsRequest(
artObjectNumber = artObjectNumber
)
)
.map { handleArtDetails(it) }
.catch { emit(AsyncResource.Error(R.string.loading_art_error)) }
val uiState: StateFlow<ArtDetailsUiState> = combine(
_userMessage, _isLoading, _taskAsync
) { userMessage, isLoading, taskAsync ->
when (taskAsync) {
AsyncResource.Loading -> {
ArtDetailsUiState(isLoading = true)
}
is AsyncResource.Error -> {
ArtDetailsUiState(
userMessage = taskAsync.errorMessage,
)
}
is AsyncResource.Success -> {
ArtDetailsUiState(
artDetails = taskAsync.data,
isLoading = isLoading,
userMessage = userMessage,
)
}
}
}
.stateIn(
scope = viewModelScope,
started = WhileUiSubscribed,
initialValue = ArtDetailsUiState(isLoading = true)
)
fun snackbarMessageShown() {
_userMessage.value = null
}
private fun handleArtDetails(artDetails: ArtDetails?): AsyncResource<ArtDetails?> {
if (artDetails == null) {
return AsyncResource.Error(R.string.art_details_not_found)
}
return AsyncResource.Success(artDetails)
}
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailsUiState.kt | 29837262 | package com.dtks.quickmuseum.ui.details
data class ArtDetailsUiState(
val artDetails: ArtDetails? = null,
val isLoading: Boolean = false,
val userMessage: Int? = null,
val isTaskDeleted: Boolean = false
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetails.kt | 3149133229 | package com.dtks.quickmuseum.ui.details
data class ArtDetails(
val id: String,
val objectNumber: String,
val title: String,
val creators: List<String>,
val materials: List<String>?,
val techniques: List<String>?,
val dating: String?,
val image: ArtDetailsImage?
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/details/ArtDetailScreen.kt | 2218110807 | package com.dtks.quickmuseum.ui.details
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
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.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
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.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntSize
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.SubcomposeAsyncImage
import com.dtks.quickmuseum.R
import com.dtks.quickmuseum.ui.EmptyContent
import com.dtks.quickmuseum.ui.loading.ImageLoading
import com.dtks.quickmuseum.ui.loading.LoadingContent
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArtDetailScreen(
onBack: () -> Unit,
modifier: Modifier = Modifier,
viewModel: ArtDetailViewModel = hiltViewModel(),
) {
val snackbarHostState = remember { SnackbarHostState() }
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val artDetails = uiState.artDetails
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
modifier = modifier.fillMaxSize(),
topBar = {
ArtDetailsTopBar(
title = artDetails?.title ?: "",
onBack = onBack,
)
},
floatingActionButton = {}
) { paddingValues ->
val scrollState = rememberScrollState()
var size by remember { mutableStateOf(IntSize.Zero) }
Column(
modifier = Modifier
.padding(paddingValues)
.fillMaxHeight()
.verticalScroll(state = scrollState)
.onSizeChanged { size = it }
) {
LoadingContent(
empty = artDetails == null,
loading = uiState.isLoading,
emptyContent = {
EmptyContent(R.string.art_details_not_found)
}
) {
ArtDetailsComposable(artDetails, size)
}
}
uiState.userMessage?.let { userMessage ->
val snackbarText = stringResource(userMessage)
LaunchedEffect(viewModel, userMessage, snackbarText) {
snackbarHostState.showSnackbar(snackbarText)
viewModel.snackbarMessageShown()
}
}
}
}
@Composable
private fun ArtDetailsComposable(artDetails: ArtDetails?, size: IntSize) {
artDetails?.let {
Row {
val heightToWidthRatio = artDetails.image?.let {
if (it.height != 0 && it.width != 0) {
it.height.toFloat() / it.width.toFloat()
} else {
null
}
}
var imageModifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
heightToWidthRatio?.let {
with(LocalDensity.current) {
val height = heightToWidthRatio.times(size.width).toDp()
imageModifier = imageModifier.height(
height
)
}
}
SubcomposeAsyncImage(
modifier = imageModifier,
model = artDetails.image?.url,
loading = {
ImageLoading(
Modifier
.width(dimensionResource(id = R.dimen.list_item_image_width))
.height(dimensionResource(id = R.dimen.list_item_height)),
)
},
contentDescription = artDetails.title,
contentScale = ContentScale.FillWidth
)
}
artDetails.dating?.let {
Row {
Text(
text = it,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(
start = dimensionResource(id = R.dimen.horizontal_margin)
)
)
}
}
Row {
Text(
text = artDetails.title,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(
start = dimensionResource(id = R.dimen.horizontal_margin)
)
)
}
artDetails.creators.let {
Row {
Text(
text = it.joinToString(),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(
start = dimensionResource(id = R.dimen.horizontal_margin)
)
)
}
}
artDetails.materials?.let {
Row {
Text(
text = it.joinToString(),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(
start = dimensionResource(id = R.dimen.horizontal_margin)
)
)
}
}
} ?: EmptyContent(R.string.art_details_not_found)
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtCollectionList.kt | 2318899735 | package com.dtks.quickmuseum.ui.overview
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import com.dtks.quickmuseum.R
@Composable
@OptIn(ExperimentalFoundationApi::class)
fun ArtCollectionList(
uiState: OverviewUiState,
onArtItemClick: (ArtObjectListItem) -> Unit,
viewModel: OverviewViewModel
) {
val listState = rememberLazyListState()
val items = uiState.items
LazyColumn(
state = listState,
modifier = Modifier
.background(color = MaterialTheme.colorScheme.background)
) {
val groupedItems = items.groupBy { it.creator }
groupedItems.forEach { (artist, items) ->
stickyHeader {
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.background(color = MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = artist,
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(
dimensionResource(id = R.dimen.horizontal_margin)
)
)
}
}
items(items, key = { it.id }) { artObject ->
ArtItem(
modifier = Modifier.animateItemPlacement(),
artObject = artObject,
onClick = onArtItemClick,
)
}
}
if (!uiState.isEmpty) {
item {
LoadMoreContent(uiState, viewModel)
}
}
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewScreen.kt | 3427053533 | package com.dtks.quickmuseum.ui.overview
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.dtks.quickmuseum.R
import com.dtks.quickmuseum.ui.EmptyContent
import com.dtks.quickmuseum.ui.loading.LoadingContent
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OverviewScreen(
onArtItemClick: (ArtObjectListItem) -> Unit,
modifier: Modifier = Modifier,
viewModel: OverviewViewModel = hiltViewModel(),
) {
val snackbarHostState = remember { SnackbarHostState() }
val uiState by viewModel.combinedUiState.collectAsStateWithLifecycle()
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
modifier = modifier.fillMaxSize(),
topBar = {
OverviewTopBar(
title = stringResource(id = R.string.app_name),
)
},
floatingActionButton = {}
) { paddingValues ->
Column(
modifier = modifier
.fillMaxSize()
.padding(paddingValues)
) {
LoadingContent(
empty = uiState.isEmpty,
loading = uiState.isLoading,
emptyContent = {
EmptyContent(R.string.no_art_found)
}
) {
ArtCollectionList(uiState, onArtItemClick, viewModel)
}
uiState.userMessage?.let { userMessage ->
val snackbarText = stringResource(userMessage)
LaunchedEffect(viewModel, userMessage, snackbarText) {
snackbarHostState.showSnackbar(snackbarText)
viewModel.snackbarMessageShown()
}
}
}
}
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/LoadMoreContent.kt | 1607440765 | package com.dtks.quickmuseum.ui.overview
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import com.dtks.quickmuseum.R
@Composable
fun LoadMoreContent(
uiState: OverviewUiState,
viewModel: OverviewViewModel
) {
Column(modifier = Modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.generic_padding))) {
if (!uiState.isLoading) {
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = {
viewModel.loadNextPage()
}) {
Text(
text = stringResource(
id =
if (uiState.isLoading)
R.string.loading
else R.string.load_more
)
)
}
} else {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.width(dimensionResource(id = R.dimen.progress_indicator_size)),
color = MaterialTheme.colorScheme.secondary,
)
}
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtObjectListItem.kt | 2286780233 | package com.dtks.quickmuseum.ui.overview
data class ArtObjectListItem(
val id: String,
val objectNumber: String,
val title: String,
val creator: String,
val imageUrl: String?= null,
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/ArtCard.kt | 1381765311 | package com.dtks.quickmuseum.ui.overview
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
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.layout.widthIn
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.SubcomposeAsyncImage
import com.dtks.quickmuseum.R
import com.dtks.quickmuseum.ui.loading.ImageLoading
@Composable
fun ArtItem(
modifier: Modifier,
artObject: ArtObjectListItem,
onClick: (ArtObjectListItem) -> Unit,
) {
Card(modifier = modifier
.fillMaxWidth()
.padding(
horizontal = dimensionResource(id = R.dimen.list_item_padding),
vertical = dimensionResource(id = R.dimen.list_item_padding),
)
.shadow(elevation = 10.dp, shape = RoundedCornerShape(12.dp))
.background(color = MaterialTheme.colorScheme.surface)
.clickable { onClick(artObject) }) {
Row {
Text(
text = artObject.title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.surfaceTint,
modifier = Modifier
.widthIn(max = dimensionResource(id = R.dimen.list_item_text_width))
.padding(
dimensionResource(id = R.dimen.horizontal_margin)
)
)
Box(
modifier = Modifier
.fillMaxWidth()
.widthIn(max = dimensionResource(id = R.dimen.list_item_image_width))
.height(dimensionResource(id = R.dimen.list_item_height))
) {
SubcomposeAsyncImage(
modifier = Modifier
.wrapContentWidth()
.align(Alignment.CenterEnd)
.height(
dimensionResource(id = R.dimen.list_item_height)
),
model = artObject.imageUrl,
loading = {
ImageLoading(
Modifier
.width(dimensionResource(id = R.dimen.list_item_image_width))
.height(dimensionResource(id = R.dimen.list_item_height)),
)
},
contentDescription = artObject.title,
contentScale = ContentScale.FillHeight
)
}
}
}
}
@Preview
@Composable
fun PreviewArtCard() {
ArtItem(modifier = Modifier, artObject = ArtObjectListItem(
id = "Jim",
objectNumber = "af",
title = "Regional manager",
creator = "Ricky Gervais",
imageUrl = null
), onClick = {})
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewViewModel.kt | 3531356572 | package com.dtks.quickmuseum.ui.overview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dtks.quickmuseum.R
import com.dtks.quickmuseum.data.model.CollectionRequest
import com.dtks.quickmuseum.data.repository.OverviewRepository
import com.dtks.quickmuseum.utils.AsyncResource
import com.dtks.quickmuseum.utils.WhileUiSubscribed
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class OverviewViewModel @Inject constructor(
private val overviewRepository: OverviewRepository
) : ViewModel() {
private val currentPage = MutableStateFlow(1)
private val initialState = overviewRepository.getCollectionFlow(CollectionRequest())
.map {
AsyncResource.Success(it)
}
.catch<AsyncResource<List<ArtObjectListItem>>> {
emit(AsyncResource.Error(R.string.loading_collection_error))
}
private val _isLoading = MutableStateFlow(false)
private val _userMessage: MutableStateFlow<Int?> = MutableStateFlow(null)
private val _updateState = MutableStateFlow(listOf<ArtObjectListItem>())
val combinedUiState =
combine(
initialState,
_updateState,
_isLoading,
_userMessage
) { initialState, updateState, isLoading, message ->
when (initialState) {
is AsyncResource.Loading -> {
OverviewUiState(isLoading = true, isEmpty = true)
}
is AsyncResource.Error -> {
OverviewUiState(userMessage = initialState.errorMessage, isEmpty = true)
}
is AsyncResource.Success -> {
val items = initialState.data + updateState
OverviewUiState(
items = items,
isLoading = isLoading,
isEmpty = items.isEmpty(),
userMessage = message
)
}
}
}.stateIn(
scope = viewModelScope,
started = WhileUiSubscribed,
initialValue = OverviewUiState(isLoading = true, isEmpty = true)
)
fun snackbarMessageShown() {
_userMessage.value = null
}
fun loadNextPage() {
_isLoading.value = true
viewModelScope.launch {
overviewRepository.getCollectionFlow(
CollectionRequest(
page = currentPage.value + 1
)
).catch {
_userMessage.value = R.string.loading_collection_error
_isLoading.value = false
}
.onEach { newState ->
currentPage.value += 1
val uniqueStates = (_updateState.value + newState).toSet().toList()
_updateState.value = uniqueStates
_isLoading.value = false
}.collect()
}
}
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewTopBar.kt | 1669009789 | package com.dtks.quickmuseum.ui.overview
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OverviewTopBar(title: String) {
TopAppBar(
title = {
Text(text = title)
},
modifier = Modifier.fillMaxWidth()
)
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewUiState.kt | 3505635252 | package com.dtks.quickmuseum.ui.overview
data class OverviewUiState(
val userMessage: Int? = null,
val isEmpty: Boolean = false,
val isLoading: Boolean = false,
val items: List<ArtObjectListItem> = emptyList(),
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/di/CoroutinesModule.kt | 761507023 | package com.dtks.quickmuseum.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Qualifier
import javax.inject.Singleton
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ApplicationScope
@Module
@InstallIn(SingletonComponent::class)
object CoroutinesModule {
@Provides
@IoDispatcher
fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO
@Provides
@DefaultDispatcher
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
@Provides
@Singleton
@ApplicationScope
fun providesCoroutineScope(
@DefaultDispatcher dispatcher: CoroutineDispatcher
): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher)
}
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/di/NetworkModule.kt | 1216945480 | package com.dtks.quickmuseum.di
import com.dtks.quickmuseum.data.api.RijksMuseumApi
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 {
private const val BASE_URL = "https://www.rijksmuseum.nl/api/"
@Singleton
@Provides
fun provideHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
return OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(15, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.build()
}
@Singleton
@Provides
fun provideConverterFactory(): GsonConverterFactory {
return GsonConverterFactory.create()
}
@Singleton
@Provides
fun provideRetrofitInstance(
okHttpClient: OkHttpClient,
gsonConverterFactory: GsonConverterFactory
): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(gsonConverterFactory)
.build()
}
@Provides
@Singleton
fun provideRijksMuseumApi(retrofit: Retrofit): RijksMuseumApi =
retrofit.create(RijksMuseumApi::class.java)
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/QuickMuseumActivity.kt | 1403567693 | package com.dtks.quickmuseum
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import com.dtks.quickmuseum.ui.navigation.QuickMuseumNavGraph
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class QuickMuseumActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
QuickMuseumNavGraph()
}
}
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/utils/AsyncResource.kt | 38044972 | package com.dtks.quickmuseum.utils
sealed class AsyncResource<out T> {
object Loading : AsyncResource<Nothing>()
data class Error(val errorMessage: Int) : AsyncResource<Nothing>()
data class Success<out T>(val data: T) : AsyncResource<T>()
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/utils/CoroutinesUtils.kt | 752373781 | package com.dtks.quickmuseum.utils
import kotlinx.coroutines.flow.SharingStarted
private const val StopTimeoutMillis: Long = 5000
val WhileUiSubscribed: SharingStarted = SharingStarted.WhileSubscribed(StopTimeoutMillis)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/QuickMuseumApplication.kt | 2033835346 | package com.dtks.quickmuseum
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class QuickMuseumApplication : Application() |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/repository/ArtDetailsRepository.kt | 187020808 | package com.dtks.quickmuseum.data.repository
import com.dtks.quickmuseum.data.RemoteDataSource
import com.dtks.quickmuseum.data.model.ArtDetailsRequest
import com.dtks.quickmuseum.di.DefaultDispatcher
import com.dtks.quickmuseum.ui.details.ArtDetails
import com.dtks.quickmuseum.ui.details.ArtDetailsImage
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
@ViewModelScoped
class ArtDetailsRepository @Inject constructor(
private val remoteDataSource: RemoteDataSource,
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
) {
suspend fun getArtDetails(artDetailsRequest: ArtDetailsRequest): ArtDetails {
return withContext(dispatcher) {
val artDetailsResponse = remoteDataSource.getArtDetails(artDetailsRequest)
val artDetails = artDetailsResponse.artObject
ArtDetails(
id = artDetails.id,
objectNumber = artDetails.objectNumber,
title = artDetails.title,
creators = artDetails.principalMakers.map {
it.name
},
materials = artDetails.materials,
techniques = artDetails.techniques,
dating = artDetails.dating?.presentingDate,
image = artDetails.webImage?.let {
ArtDetailsImage(
url = it.url,
width = it.width,
height = it.height
)
}
)
}
}
fun getArtDetailsFlow(artDetailsRequest: ArtDetailsRequest): Flow<ArtDetails> =
flow {
emit(getArtDetails(artDetailsRequest))
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/repository/OverviewRepository.kt | 1472904778 | package com.dtks.quickmuseum.data.repository
import com.dtks.quickmuseum.data.RemoteDataSource
import com.dtks.quickmuseum.data.model.CollectionRequest
import com.dtks.quickmuseum.di.DefaultDispatcher
import com.dtks.quickmuseum.ui.overview.ArtObjectListItem
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
@ViewModelScoped
class OverviewRepository @Inject constructor(
private val remoteDataSource: RemoteDataSource,
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
){
suspend fun getOverviewArtObjects(collectionRequest: CollectionRequest): List<ArtObjectListItem> {
return withContext(dispatcher) {
remoteDataSource.getCollection(collectionRequest).artObjects.filter { it.hasImage }.map {
ArtObjectListItem(
id = it.id,
title = it.title,
creator = it.principalOrFirstMaker,
imageUrl = it.webImage?.url,
objectNumber = it.objectNumber
)
}
}
}
fun getCollectionFlow(collectionRequest: CollectionRequest): Flow<List<ArtObjectListItem>> = flow {
emit(getOverviewArtObjects(collectionRequest))
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/RemoteDataSource.kt | 3940395843 | package com.dtks.quickmuseum.data
import com.dtks.quickmuseum.data.api.RijksMuseumApi
import com.dtks.quickmuseum.data.model.ArtDetailsRequest
import com.dtks.quickmuseum.data.model.ArtDetailsResponse
import com.dtks.quickmuseum.data.model.CollectionRequest
import com.dtks.quickmuseum.data.model.CollectionResponse
import javax.inject.Inject
class RemoteDataSource @Inject constructor(
private val rijksMuseumApi: RijksMuseumApi
) {
suspend fun getCollection(collectionRequest: CollectionRequest): CollectionResponse {
return rijksMuseumApi.getCollection(
searchType = collectionRequest.searchType,
page = collectionRequest.page,
pageSize = collectionRequest.pageSize,
language = collectionRequest.language
)
}
suspend fun getArtDetails(artDetailsRequest: ArtDetailsRequest): ArtDetailsResponse {
return rijksMuseumApi.getArtDetails(
artObjectNumber = artDetailsRequest.artObjectNumber,
language = artDetailsRequest.language
)
}
} |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsRequest.kt | 428892768 | package com.dtks.quickmuseum.data.model
data class ArtDetailsRequest(
val artObjectNumber: String,
val language: String = "en",
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtObjectDao.kt | 2536135750 | package com.dtks.quickmuseum.data.model
data class ArtObjectDao(
val id: String,
val objectNumber: String,
val title: String,
val hasImage: Boolean,
val principalOrFirstMaker: String,
val webImage: WebImage?
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/CollectionResponse.kt | 2467439500 | package com.dtks.quickmuseum.data.model
data class CollectionResponse(
val count: Long,
val artObjects: List<ArtObjectDao>,
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsResponse.kt | 4257592535 | package com.dtks.quickmuseum.data.model
data class ArtDetailsResponse(
val artObject: ArtDetailsDao
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsDao.kt | 2963975366 | package com.dtks.quickmuseum.data.model
data class ArtDetailsDao(
val id: String,
val objectNumber: String,
val title: String,
val principalMakers: List<ArtCreator>,
val materials: List<String>?,
val techniques: List<String>?,
val dating: Dating?,
val webImage: WebImage?
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/WebImage.kt | 59438240 | package com.dtks.quickmuseum.data.model
data class WebImage(
val guid: String,
val width: Int,
val height: Int,
val url: String? = null
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtCreator.kt | 709518188 | package com.dtks.quickmuseum.data.model
data class ArtCreator(
val name: String,
val nationality: String?,
val occupation: List<String>?,
val roles: List<String>?,
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/Dating.kt | 3450308172 | package com.dtks.quickmuseum.data.model
data class Dating(
val presentingDate: String
)
|
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/CollectionRequest.kt | 3653824033 | package com.dtks.quickmuseum.data.model
data class CollectionRequest(
val searchType: String = "relevance",
val page: Int = 1,
val pageSize: Int = 50,
val language: String = "en",
) |
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/api/RijksMuseumApi.kt | 4219232049 | package com.dtks.quickmuseum.data.api
import com.dtks.quickmuseum.data.model.ArtDetailsResponse
import com.dtks.quickmuseum.data.model.CollectionResponse
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface RijksMuseumApi {
@GET("{culture}/collection")
suspend fun getCollection(
@Path("culture")
language: String = "en",
@Query("s")
searchType: String = "relevance",
@Query("p")
page: Int = 0,
@Query("ps")
pageSize: Int = 10,
@Query("key")
apiKey: String = API_KEY
): CollectionResponse
@GET("{culture}/collection/{artObjectNumber}")
suspend fun getArtDetails(
@Path("culture")
language: String = "en",
@Path("artObjectNumber")
artObjectNumber: String,
@Query("key")
apiKey: String = API_KEY
): ArtDetailsResponse
companion object {
private const val API_KEY = "0fiuZFh4"
}
} |
NestedScrollExample/app/src/androidTest/java/br/com/devcapu/nestedscrollexample/ExampleInstrumentedTest.kt | 1462851345 | package br.com.devcapu.nestedscrollexample
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("br.com.devcapu.nestedscrollexample", appContext.packageName)
}
} |
NestedScrollExample/app/src/test/java/br/com/devcapu/nestedscrollexample/ExampleUnitTest.kt | 3750543286 | package br.com.devcapu.nestedscrollexample
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)
}
} |
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Color.kt | 3811189157 | package br.com.devcapu.nestedscrollexample.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) |
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Theme.kt | 2319342368 | package br.com.devcapu.nestedscrollexample.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 NestedScrollExampleTheme(
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
)
} |
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Type.kt | 3084803422 | package br.com.devcapu.nestedscrollexample.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
)
*/
) |
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/MainActivity.kt | 2325333046 | package br.com.devcapu.nestedscrollexample
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 br.com.devcapu.nestedscrollexample.ui.theme.NestedScrollExampleTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NestedScrollExampleTheme {
// 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() {
NestedScrollExampleTheme {
Greeting("Android")
}
} |
mobile-planivacances/app/src/androidTest/java/be/helmo/planivacances/ExampleInstrumentedTest.kt | 1802419454 | package be.helmo.planivacances
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("be.helmo.planivancances", appContext.packageName)
}
} |
mobile-planivacances/app/src/test/java/be/helmo/planivacances/ExampleUnitTest.kt | 3697766357 | package be.helmo.planivacances
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)
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/util/DTOMapper.kt | 3214316675 | package be.helmo.planivacances.util
import be.helmo.planivacances.domain.Group
import be.helmo.planivacances.domain.Place
import be.helmo.planivacances.presenter.viewmodel.*
import be.helmo.planivacances.service.dto.ActivityDTO
import be.helmo.planivacances.service.dto.GroupDTO
import be.helmo.planivacances.service.dto.GroupInviteDTO
import be.helmo.planivacances.service.dto.PlaceDTO
import com.google.android.gms.maps.model.LatLng
object DTOMapper {
fun groupToGroupDTO(group: Group) : GroupDTO {
return GroupDTO(
"null",
group.groupName,
group.description,
group.startDate,
group.endDate,
placeToPlaceDTO(group.place)
)
}
fun groupDtoToGroup(groupDTO: GroupDTO) : Group {
return Group(
groupDTO.groupName,
groupDTO.description,
groupDTO.startDate,
groupDTO.endDate,
placeDtoToPlace(groupDTO.place),
groupDTO.owner!!
)
}
fun groupToGroupListItem(gid: String, group: Group) : GroupListItemVM {
return GroupListItemVM(
gid,
group.groupName,
group.description,
group.startDate,
group.endDate
)
}
fun groupToGroupVM(group: Group) : GroupVM {
val placeVM : PlaceVM = placeToPlaceVM(group.place)
return GroupVM(group.groupName,group.description,group.startDate,group.endDate,placeVM)
}
fun groupVMToGroupDTO(groupVM: GroupVM,owner: String,gid:String) : GroupDTO {
val placeDTO = placeVMToPlaceDTO(groupVM.place)
return GroupDTO(gid,groupVM.name,groupVM.description,groupVM.startDate,groupVM.endDate,placeDTO,owner)
}
fun placeToPlaceDTO(place: Place) : PlaceDTO {
return PlaceDTO(
place.country,
place.city,
place.street,
place.number,
place.postalCode,
place.latLng.latitude,
place.latLng.longitude
)
}
fun placeDtoToPlace(placeDTO: PlaceDTO) : Place {
return Place(
placeDTO.country,
placeDTO.city,
if (placeDTO.street != null) placeDTO.street else "",
if (placeDTO.number != null) placeDTO.number else "",
placeDTO.postalCode,
LatLng(placeDTO.lat, placeDTO.lon)
)
}
fun placeToPlaceVM(place: Place) : PlaceVM {
return PlaceVM(place.street,place.number,place.postalCode,place.city,place.country,
LatLng(place.latLng.latitude,place.latLng.longitude)
)
}
fun placeVMToPlaceDTO(placeVM: PlaceVM) : PlaceDTO {
return PlaceDTO(placeVM.country,placeVM.city,placeVM.street,placeVM.number,placeVM.postalCode,placeVM.latLng.latitude,placeVM.latLng.longitude)
}
fun placeDTOToPlaceVM(placeDTO: PlaceDTO) : PlaceVM {
return PlaceVM(placeDTO.street,placeDTO.number,placeDTO.postalCode,placeDTO.city,placeDTO.country,
LatLng(placeDTO.lat,placeDTO.lon)
)
}
fun activityVMToActivityDTO(activityVM: ActivityVM) : ActivityDTO {
val placeDTO : PlaceDTO = placeVMToPlaceDTO(activityVM.place)
return ActivityDTO(activityVM.title,activityVM.description,activityVM.startDate,activityVM.duration,placeDTO)
}
fun activityDTOToActivityVM(activityDTO: ActivityDTO) : ActivityVM {
val placeVM : PlaceVM = placeDTOToPlaceVM(activityDTO.place)
return ActivityVM(activityDTO.title,activityDTO.description,activityDTO.startDate,activityDTO.duration,placeVM)
}
fun groupInviteDTOToGroupInvitationVM(groupInviteDTO: GroupInviteDTO) : GroupInvitationVM {
return GroupInvitationVM(groupInviteDTO.gid,groupInviteDTO.groupName,"Rejoindre le groupe")
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/util/DateFormatter.kt | 53178976 | package be.helmo.planivacances.util
import java.text.SimpleDateFormat
import java.util.*
object DateFormatter {
fun formatTimestampForDisplay(timestamp: Long): String {
val date = Date(timestamp)
val format = SimpleDateFormat("dd/MM/yyyy - HH'h'mm", Locale.getDefault())
return format.format(date)
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupDetailVM.kt | 428815704 | package be.helmo.planivacances.presenter.viewmodel
data class GroupDetailVM(val groupName: String,
val description: String,
val period : String,
val address: String)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupListItemVM.kt | 3543483726 | package be.helmo.planivacances.presenter.viewmodel
import java.util.*
data class GroupListItemVM(
var gid: String? = null,
val groupName: String,
val description: String,
val startDate: Date,
val endDate: Date)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/WeatherForecastVM.kt | 4788105 | package be.helmo.planivacances.presenter.viewmodel
data class WeatherForecastVM(val imageUrl: String, val temperature: String, val date: String, val infos: String) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/PlaceVM.kt | 4270062884 | package be.helmo.planivacances.presenter.viewmodel
import com.google.android.gms.maps.model.LatLng
data class PlaceVM(val street : String,
val number : String,
val postalCode : String,
val city : String,
val country: String,
val latLng: LatLng
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityDetailVM.kt | 1391650138 | package be.helmo.planivacances.presenter.viewmodel
data class ActivityDetailVM(
val activityTitle:String,
val activityPeriod: String,
val activityPlace: String,
val activityDescription: String
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupVM.kt | 2320907291 | package be.helmo.planivacances.presenter.viewmodel
import java.util.*
data class GroupVM(
val name:String,
val description: String,
val startDate: Date,
val endDate: Date,
val place: PlaceVM
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityListItemVM.kt | 107657653 | package be.helmo.planivacances.presenter.viewmodel
data class ActivityListItemVM(
val aid: String,
val title: String,
val startHour: String,
val duration: String
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityVM.kt | 1129489815 | package be.helmo.planivacances.presenter.viewmodel
import java.util.*
data class ActivityVM(
val title: String,
val description: String,
val startDate: Date,
val duration: Int,
val place: PlaceVM
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupInvitationVM.kt | 2136865911 | package be.helmo.planivacances.presenter.viewmodel
data class GroupInvitationVM(
val gid:String,
val groupName: String,
val content: String
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/TchatPresenter.kt | 2424026119 | package be.helmo.planivacances.presenter
import android.util.Log
import be.helmo.planivacances.presenter.interfaces.ITchatView
import be.helmo.planivacances.service.ApiClient
import be.helmo.planivacances.service.dto.MessageDTO
import be.helmo.planivacances.view.interfaces.IAuthPresenter
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import be.helmo.planivacances.view.interfaces.ITchatPresenter
import com.pusher.client.Pusher
import com.pusher.client.channel.PrivateChannel
import com.pusher.client.channel.PrivateChannelEventListener
import com.pusher.client.channel.PusherEvent
import com.pusher.client.connection.ConnectionState
import com.pusher.client.connection.ConnectionStateChange
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception
class TchatPresenter(val groupPresenter: IGroupPresenter,
val authPresenter: IAuthPresenter) : ITchatPresenter {
lateinit var tchatView : ITchatView
lateinit var tchatService : Pusher
lateinit var channel: PrivateChannel
var previousMessageLoaded : Boolean = false
override fun setITchatView(tchatView: ITchatView) {
this.tchatView = tchatView
}
override suspend fun connectToTchat() {
tchatService = ApiClient.getTchatInstance()
tchatService.connect(object:com.pusher.client.connection.ConnectionEventListener {
override fun onConnectionStateChange(change: ConnectionStateChange?) {
if (change != null) {
Log.d("Tchat Presenter : ",
"Etat de la connexion : ${change.currentState}")
if(change.currentState == ConnectionState.CONNECTED) {
subscribeToGroupChannel()
}
}
}
override fun onError(message: String?, code: String?, e: Exception?) {
Log.d("Tchat presenter : ",
"Erreur durant la connexion au tchat : $message")
}
})
}
fun subscribeToGroupChannel() {
channel = tchatService.subscribePrivate(
"private-${groupPresenter.getCurrentGroupId()}",
object:PrivateChannelEventListener {
override fun onEvent(event: PusherEvent?) {}
override fun onSubscriptionSucceeded(channelName: String?) {
Log.d("Tchat presenter : ","Suscription ok => $channelName")
bindToEvents()
CoroutineScope(Dispatchers.Main).launch {
loadPreviousMessages()
}
}
override fun onAuthenticationFailure(message: String?, e: Exception?) {
Log.d("Tchat presenter","Suscription failed : $message")
}
})
}
fun bindToEvents() {
channel.bind("new_messages",object:PrivateChannelEventListener {
override fun onEvent(event: PusherEvent?) {
if(previousMessageLoaded) {
Log.d("Tchat presenter : ", "${event?.eventName} => ${event?.data}")
if (event?.data != null) {
val messageDTO : MessageDTO? = ApiClient.formatMessageToDisplay(event.data)
if(messageDTO != null) {
sendMessageToView(messageDTO)
}
}
}
}
override fun onSubscriptionSucceeded(channelName: String?) {
}
override fun onAuthenticationFailure(message: String?, e: Exception?) {
}
})
}
suspend fun loadPreviousMessages() {
val response = ApiClient
.tchatService
.getPreviousMessages(groupPresenter.getCurrentGroupId())
if(response.isSuccessful && response.body() != null) {
val messages : List<MessageDTO> = response.body()!!
for(message in messages) {
sendMessageToView(message)
}
previousMessageLoaded = true
}
tchatView.stopLoading()
}
fun sendMessageToView(message: MessageDTO) {
if(message.sender == authPresenter.getUid()) {
message.sender = "me"
} else {
message.sender = "other"
}
tchatView.addMessageToView(message)
}
override fun sendMessage(message: String) {
if(message.isNotEmpty()) {
val messageDTO = MessageDTO(
authPresenter.getUid(),
authPresenter.getDisplayName(),
groupPresenter.getCurrentGroupId(),
message,
System.currentTimeMillis()
)
CoroutineScope(Dispatchers.Default).launch {
ApiClient.tchatService.sendMessage(messageDTO)
}
}
}
override fun disconnectToTchat() {
channel.unbind("new_messages",object:PrivateChannelEventListener {
override fun onEvent(event: PusherEvent?) {}
override fun onSubscriptionSucceeded(channelName: String?) {}
override fun onAuthenticationFailure(message: String?, e: Exception?) {}
})
tchatService.unsubscribe("private-${groupPresenter.getCurrentGroupId()}")
tchatService.disconnect()
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/GroupPresenter.kt | 3556818092 | package be.helmo.planivacances.presenter
import android.util.Log
import be.helmo.planivacances.domain.Group
import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM
import be.helmo.planivacances.domain.Place
import be.helmo.planivacances.presenter.interfaces.ICreateGroupView
import be.helmo.planivacances.presenter.interfaces.IGroupView
import be.helmo.planivacances.presenter.interfaces.IHomeView
import be.helmo.planivacances.presenter.interfaces.IUpdateGroupView
import be.helmo.planivacances.presenter.viewmodel.GroupDetailVM
import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM
import be.helmo.planivacances.presenter.viewmodel.GroupVM
import be.helmo.planivacances.service.ApiClient
import be.helmo.planivacances.service.dto.GroupDTO
import be.helmo.planivacances.util.DTOMapper
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import com.google.firebase.auth.FirebaseAuth
import java.text.SimpleDateFormat
class GroupPresenter : IGroupPresenter {
lateinit var groupView: IGroupView
lateinit var createGroupView: ICreateGroupView
lateinit var updateGroupView: IUpdateGroupView
lateinit var homeView: IHomeView
var groups : HashMap<String, Group> = HashMap()
lateinit var currentGid : String
/**
* Crée un groupe
* @param groupVM (GroupVM)
*/
override suspend fun createGroup(groupVM: GroupVM) {
val groupDto = DTOMapper.groupVMToGroupDTO(groupVM, "null", "null")
val group = DTOMapper.groupDtoToGroup(groupDto)
try {
val response = ApiClient.groupService.create(groupDto)
if (response.isSuccessful && response.body() != null) {
val gid = response.body()!!
currentGid = gid
group.owner = FirebaseAuth.getInstance().uid!!
groups[gid] = group
Log.d("CreateGroupFragment", "Group created : $gid")
createGroupView.onGroupCreated()
} else {
Log.d("CreateGroupFragment",
"${response.message()}, ${response.isSuccessful}")
createGroupView.showToast(
"Erreur lors de la création du groupe ${response.message()}",
1
)
}
} catch (e: Exception) {
createGroupView.showToast("Erreur durant la création du groupe", 1)
}
}
/**
* Charge les groupes de l'utilisateur
*/
override suspend fun loadUserGroups() {
try {
groups.clear()
currentGid = ""
val response = ApiClient.groupService.getList()
if (response.isSuccessful && response.body() != null) {
val groupsDto = response.body()!!
Log.d("ag", response.body().toString())
for(groupDto in groupsDto) {
Log.d("gg", groupDto.place.city)
groups[groupDto.gid!!] = DTOMapper.groupDtoToGroup(groupDto)
}
Log.d("GroupFragment", "Groups retrieved : ${groups.size}")
homeView.setGroupList(getGroupListItems())
} else {
Log.d("GroupFragment", "${response.message()}, ${response.isSuccessful}")
homeView.showToast(
"Erreur lors de la récupération des groupes ${response.message()}",
1
)
}
} catch (e: Exception) {
Log.d("GroupFragment",
"Erreur durant la récupération des groupes : ${e.message}")
homeView.showToast("Erreur durant la récupération des groupes", 1)
}
}
/**
* Charge les données nécessaires à l'affichage de l'itinéraire
*/
override fun loadItinerary() {
val place = groups[currentGid]?.place
val latitude = place?.latLng?.latitude.toString()
val longitude = place?.latLng?.longitude.toString()
groupView.buildItinerary(latitude,longitude)
}
override fun showGroupInfos() {
val group = getCurrentGroup()!!
val formatter = SimpleDateFormat("dd/MM/yyyy")
val startDate = formatter.format(group.startDate)
val endDate = formatter.format(group.endDate)
val groupDetailVM = GroupDetailVM(group.groupName,
group.description,
"Du $startDate au $endDate",
getCurrentGroupPlace().address)
groupView.setGroupInfos(groupDetailVM)
}
/**
* Récupère la liste des groupes
* @return (List<GroupDTO>)
*/
fun getGroupListItems(): List<GroupListItemVM> {
return groups.entries.map { (gid, group) ->
DTOMapper.groupToGroupListItem(gid, group)
}
}
/**
* Récupère le groupe courant
* @return (GroupDTO)
*/
override fun getCurrentGroup(): Group? {
return groups[currentGid]
}
/**
* Récupère le lieu du groupe courant
* @return (Place)
*/
override fun getCurrentGroupPlace(): Place {
return groups[currentGid]?.place!!
}
/**
* Récupère l'id du groupe courant
* @return (String)
*/
override fun getCurrentGroupId(): String {
return currentGid
}
/**
* Assigne l'id du groupe séléctionné
* @param gid (String)
*/
override fun setCurrentGroupId(gid: String) {
currentGid = gid
}
/**
* Assigne la GroupView Interface
*/
override fun setIGroupView(groupView: IGroupView) {
this.groupView = groupView
}
/**
* Assigne la CreateGroupView Interface
*/
override fun setICreateGroupView(createGroupView: ICreateGroupView) {
this.createGroupView = createGroupView
}
override fun setIUpdateGroupView(updateGroupView: IUpdateGroupView) {
this.updateGroupView = updateGroupView
}
/**
* Assigne la HomeView Interface
*/
override fun setIHomeView(homeView: IHomeView) {
this.homeView = homeView
}
override fun loadCurrentGroup() {
val currentGroupVM : GroupVM = DTOMapper.groupToGroupVM(getCurrentGroup()!!)
updateGroupView.setCurrentGroup(currentGroupVM)
}
override suspend fun updateCurrentGroup(groupVM: GroupVM) {
val group = getCurrentGroup()
val groupDTO : GroupDTO = DTOMapper.groupVMToGroupDTO(groupVM,group?.owner!!,currentGid)
val response = ApiClient.groupService.update(currentGid,groupDTO)
if(response.isSuccessful) {
updateGroupView.onGroupUpdated()
} else {
updateGroupView.showToast("Erreur lors de la mise à jour du groupe",1)
}
}
override suspend fun deleteCurrentGroup() {
val response = ApiClient.groupService.delete(currentGid)
if(response.isSuccessful) {
groupView.onGroupDeleted()
} else {
groupView.showToast("Erreur durant la suppression du groupe",1)
}
}
override suspend fun loadUserGroupInvites() {
val response = ApiClient.groupService.getUserGroupInvites()
if(response.isSuccessful && response.body() != null) {
val groupInvitationsList : ArrayList<GroupInvitationVM> = ArrayList()
for(invitation in response.body()!!) {
groupInvitationsList.add(DTOMapper.groupInviteDTOToGroupInvitationVM(invitation))
}
homeView.onGroupInvitationsLoaded(groupInvitationsList)
} else {
homeView.showToast("Erreur durant le chargement des invitations",1)
}
}
override suspend fun sendGroupInvite(email:String) {
val currentUserMail = FirebaseAuth.getInstance().currentUser?.email
if(currentUserMail != null && currentUserMail != email) {
val response = ApiClient.groupService.inviteUser(currentGid!!,email)
if(response.isSuccessful && response.body() == true) {
groupView.showToast("Invitation envoyée avec succès",1)
} else {
groupView.showToast("Erreur lors de l'envoi de l'invitation",1)
}
} else {
groupView.showToast("Impossible de s'inviter soi-même à rejoindre un groupe",1)
}
}
override suspend fun acceptGroupInvite(gid: String) {
val response = ApiClient.groupService.acceptGroupInvite(gid)
if(response.isSuccessful && response.body() == true) {
homeView.onGroupInvitationAccepted()
} else {
homeView.showToast("Erreur durant l'acceptation de l'invitation",1)
}
}
override suspend fun declineGroupInvite(gid: String) {
val response = ApiClient.groupService.declineGroupInvite(gid)
if(response.isSuccessful && response.body() != null) {
homeView.onGroupInvitationDeclined()
} else {
homeView.showToast("Erreur durant le refus de l'invitation",1)
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/AuthPresenter.kt | 2344298179 | package be.helmo.planivacances.presenter
import android.content.SharedPreferences
import android.util.Log
import be.helmo.planivacances.presenter.interfaces.IAuthView
import be.helmo.planivacances.service.ApiClient
import be.helmo.planivacances.service.TokenAuthenticator
import be.helmo.planivacances.service.dto.LoginUserDTO
import be.helmo.planivacances.service.dto.RegisterUserDTO
import be.helmo.planivacances.view.interfaces.IAuthPresenter
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import kotlinx.coroutines.tasks.await
/**
* Authentification Presenter
*/
class AuthPresenter : IAuthPresenter {
val mAuth: FirebaseAuth = FirebaseAuth.getInstance()
lateinit var sharedPreferences : SharedPreferences
lateinit var authView: IAuthView
val tokenAuthenticator: TokenAuthenticator = TokenAuthenticator.instance!!
/**
* Enregistrement asycnhrone d'un profil utilisateur
* @param username (String) nom
* @param mail (String) email
* @param password (String) mot de passe
* mail et mot de passe utilisateur
*/
override suspend fun register(username: String, mail: String, password: String) {
try {
val response = ApiClient.authService.register(RegisterUserDTO(username, mail, password))
if (!response.isSuccessful || response.body() == null) {
authView.showToast(
"Erreur lors de l'enregistrement : ${response.message()}",
1
)
return
}
val customToken = response.body()
Log.d("AuthFragment", "Register Response: $customToken")
auth(customToken!!, false)
} catch (e: Exception) {
Log.w("Erreur lors de l'enregistrement", "${e.message}")
authView.showToast(
"Une erreur est survenue lors de l'enregistrement",
1
)
}
}
/**
* Connexion asycnhrone à un profil utilisateur
* @param mail (String) email
* @param password (String) mot de passe
* @param keepConnected (Boolean) stocker le token en local ?
*/
override suspend fun login(mail: String, password: String, keepConnected: Boolean) {
try {
val response = ApiClient.authService.login(LoginUserDTO(mail, password))
if (!response.isSuccessful || response.body() == null) {
authView.showToast("Erreur lors de la connexion\n&${response.message()}", 1)
return
}
val customToken = response.body()
Log.d("AuthFragment", "Login Response : $customToken")
auth(customToken!!, keepConnected)
} catch (e: Exception) {
Log.w("Erreur lors de la connexion", "${e.message}")
authView.showToast("Une erreur est survenue lors de la connexion", 1)
}
}
/**
* Connexion asynchrone automatique sur base du potentiel token d'identification sauvegardé
*/
override suspend fun autoAuth() {
val customToken = sharedPreferences.getString("CustomToken", null)
if(customToken == null) {
authView.stopLoading()
return
}
auth(customToken, true)
}
/**
* Sauvegarde le resfresh token si demandé et précise le token au TokenAuthenticator
* @param customToken (String) customToken
* @param keepConnected (Boolean) stocker le token en local ?
*/
suspend fun auth(customToken: String, keepConnected: Boolean) {
if(keepConnected) {
val editor = sharedPreferences.edit()
editor.putString("CustomToken", customToken)
editor.apply()
}
try {
val authResult = mAuth.signInWithCustomToken(customToken).await()
if (authResult != null) {
initAuthenticator()
authView.goToHome()
return
}
} catch (_: FirebaseAuthInvalidCredentialsException) {}
authView.showToast("Erreur lors de l'authentification", 1)
}
/**
* load a new idToken in the TokenAuthenticator
* @return (Boolean)
*/
override suspend fun loadIdToken(): Boolean {
val tokenTask = mAuth.currentUser?.getIdToken(false)?.await()
return if (tokenTask != null) {
val token = "Bearer ${tokenTask.token}"
tokenAuthenticator.idToken = token
Log.i("AuthFragment.TAG", "Successfully retrieved new account token: $token")
true
} else {
val errorMessage = "Erreur lors de récupération d'un nouveau jeton d'identification"
Log.w("AuthFragment.TAG", errorMessage)
false
}
}
/**
* initialize the authenticator
* @return (Boolean)
*/
override suspend fun initAuthenticator(): Boolean {
tokenAuthenticator.authPresenter = this //todo setters ou pas en kotlin ?
return loadIdToken()
}
/**
* Get user id
* @return (String)
*/
override fun getUid(): String {
return mAuth.uid!!
}
/**
* get the name of the user
* @return (String)
*/
override fun getDisplayName(): String {
return mAuth.currentUser!!.displayName!!
}
/**
* assigne le sharedPreferences à la variable locale du presenter
* @param sharedPreferences (SharedPreferences)
*/
override fun setSharedPreference(sharedPreferences: SharedPreferences) {
this.sharedPreferences = sharedPreferences
}
/**
* Assigne la AuthView Interface
*/
override fun setIAuthView(authView : IAuthView) {
this.authView = authView
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/ActivityPresenter.kt | 11759843 | package be.helmo.planivacances.presenter
import be.helmo.planivacances.domain.Place
import be.helmo.planivacances.presenter.interfaces.IActivityView
import be.helmo.planivacances.presenter.interfaces.ICalendarView
import be.helmo.planivacances.presenter.interfaces.ICreateActivityView
import be.helmo.planivacances.presenter.interfaces.IUpdateActivityView
import be.helmo.planivacances.presenter.viewmodel.ActivityDetailVM
import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM
import be.helmo.planivacances.presenter.viewmodel.ActivityVM
import be.helmo.planivacances.presenter.viewmodel.PlaceVM
import be.helmo.planivacances.service.ApiClient
import be.helmo.planivacances.service.dto.ActivitiesDTO
import be.helmo.planivacances.service.dto.ActivityDTO
import be.helmo.planivacances.service.dto.PlaceDTO
import be.helmo.planivacances.util.DTOMapper
import be.helmo.planivacances.view.interfaces.IActivityPresenter
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class ActivityPresenter(private val groupPresenter: IGroupPresenter) : IActivityPresenter {
lateinit var calendarView : ICalendarView
lateinit var activityView: IActivityView
lateinit var createActivityView: ICreateActivityView
lateinit var updateActivityView: IUpdateActivityView
var activitiesDTO: ActivitiesDTO = ActivitiesDTO(HashMap())
lateinit var currentActivityDTO : Pair<String,ActivityDTO>
override fun setICalendarView(calendarView: ICalendarView) {
this.calendarView = calendarView
}
override fun setIActivityView(activityView: IActivityView) {
this.activityView = activityView
}
override fun setICreateActivityView(createIActivityView: ICreateActivityView) {
this.createActivityView = createIActivityView
}
override fun setIUpdateActivityView(updateActivityView: IUpdateActivityView) {
this.updateActivityView = updateActivityView
}
override fun setCurrentActivity(activityId: String) {
if(activitiesDTO.activitiesMap.contains(activityId)) {
currentActivityDTO = Pair(activityId,activitiesDTO.activitiesMap[activityId]!!)
}
}
override suspend fun getCalendarFile() {
try {
val response = ApiClient.calendarService.getICS(groupPresenter.getCurrentGroupId())
if(response.isSuccessful && response.body() != null) {
val currentGroup = groupPresenter.getCurrentGroup()!!
calendarView.downloadCalendar(response.body()!!,"Calendrier-${currentGroup.groupName}.ics")
}
} catch(e:Exception) {
e.printStackTrace()
calendarView.showToast("Erreur lors du téléchargement du calendrier",1)
}
}
override suspend fun loadActivities() {
val response = ApiClient.activityService.loadActivities(groupPresenter.getCurrentGroupId())
if(response.isSuccessful && response.body() != null) {
activitiesDTO.activitiesMap.clear()
response.body()!!.forEach { entry ->
run {
activitiesDTO.activitiesMap[entry.key] = entry.value
}
}
onActivitiesLoaded()
}
}
override suspend fun deleteCurrentActivity() {
val response = ApiClient.activityService.deleteActivity(groupPresenter.getCurrentGroupId(),currentActivityDTO.first)
if(response.isSuccessful) {
activityView.onActivityDeleted()
} else {
activityView.showToast("Erreur durant la suppression de l'activité",1)
}
}
override fun getCurrentActivity() {
val currentActivityVM : ActivityVM = DTOMapper.activityDTOToActivityVM(currentActivityDTO.second)
updateActivityView.setCurrentActivity(currentActivityVM)
}
override fun loadCurrentActivity() {
val currentActivity = currentActivityDTO.second
activityView.loadActivity(ActivityDetailVM(currentActivity.title,formatPeriod(currentActivity.startDate,currentActivity.duration),formatPlace(currentActivity.place),currentActivity.description))
}
override fun loadItinerary() {
val currentActivity = currentActivityDTO.second
activityView.buildItinerary(currentActivity.place.lat.toString(),currentActivity.place.lon.toString())
}
override suspend fun createActivity(activityVM: ActivityVM) {
val activityDTO : ActivityDTO = DTOMapper.activityVMToActivityDTO(activityVM)
val response = ApiClient.activityService.createActivity(groupPresenter.getCurrentGroupId(),activityDTO)
if(response.isSuccessful) {
createActivityView.onActivityCreated()
} else {
createActivityView.showToast("Erreur durant la création de l'activité",1)
}
}
override suspend fun updateCurrentActivity(activityVM: ActivityVM) {
val activityDTO : ActivityDTO = DTOMapper.activityVMToActivityDTO(activityVM)
val response = ApiClient.activityService.updateActivity(groupPresenter.getCurrentGroupId(),currentActivityDTO.first,activityDTO)
if(response.isSuccessful) {
updateActivityView.onActivityUpdated()
} else {
updateActivityView.showToast("Erreur lors de la mise à jour de l'activité",1)
}
}
fun onActivitiesLoaded() {
val activityDates : ArrayList<Date> = ArrayList()
activitiesDTO.activitiesMap.forEach {
entry ->
activityDates.add(entry.value.startDate)
}
calendarView.onActivitiesLoaded(activityDates)
}
override fun onActivityDateChanged(dayOfMonth: Int, month: Int, year: Int) {
val date = Calendar.getInstance()
date.set(year, month, dayOfMonth)
val activities : ArrayList<ActivityListItemVM> = ArrayList()
val dateFormat = SimpleDateFormat("dd/MM/YYYY")
val formattedDate = dateFormat.format(date.timeInMillis)
activitiesDTO.activitiesMap.forEach {
entry ->
val currentActivity = entry.value
if(formattedDate == dateFormat.format(currentActivity.startDate)) {
activities.add(ActivityListItemVM(entry.key,currentActivity.title,formatStartDate(currentActivity.startDate),formatDuration(currentActivity.duration)))
}
}
calendarView.setDisplayedActivities(activities)
}
fun formatStartDate(startDate:Date) : String {
val startDateFormat : SimpleDateFormat = SimpleDateFormat("HH'h'mm")
return startDateFormat.format(startDate)
}
fun formatPeriod(startDate: Date,duration: Int) : String {
val startDateFormat : SimpleDateFormat = SimpleDateFormat("dd/MM/yyyy")
return "Le ${startDateFormat.format(startDate)} à ${formatStartDate(startDate)} - Durée : ${formatDuration(duration)}"
}
fun formatPlace(placeDTO: PlaceDTO) : String {
return "${placeDTO.street},${placeDTO.number},${placeDTO.city} ${placeDTO.postalCode},${placeDTO.country}"
}
fun formatDuration(duration: Int) : String {
val hours = duration / 3600
val minutes = (duration % 3600) / 60
return String.format("%dh%02d",hours,minutes)
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/WeatherPresenter.kt | 225867197 | package be.helmo.planivacances.presenter
import android.util.Log
import be.helmo.planivacances.presenter.viewmodel.WeatherForecastVM
import be.helmo.planivacances.presenter.interfaces.IWeatherView
import be.helmo.planivacances.service.ApiClient
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import be.helmo.planivacances.view.interfaces.IWeatherPresenter
class WeatherPresenter(val groupPresenter: IGroupPresenter) : IWeatherPresenter {
lateinit var weatherView: IWeatherView
/**
* get the weather forecast for the current group place
*/
override suspend fun getForecast() {
try {
val latLng = groupPresenter.getCurrentGroupPlace()?.latLngString
if(latLng == null) {
weatherView.showToast(
"Erreur lors de la récupération du lieu de météo",
1
)
return
}
val response = ApiClient.weatherService.getForecast(latLng)
if (!response.isSuccessful || response.body() == null) {
Log.e("WeatherFragment","${response.message()}, ${response.isSuccessful}")
weatherView.showToast("Erreur lors de la récupération " +
"des données météo ${response.message()}", 1)
}
val weatherData = response.body()
val forecastList = weatherData?.forecast?.forecastday?.map { it ->
WeatherForecastVM(
"https:${it.day.condition.icon}",
"${it.day.avgtemp_c}° C",
it.date,
"Humidité : ${it.day.avghumidity}%, " +
"Pluie : ${it.day.daily_chance_of_rain}%, " +
"Vent : ${it.day.maxwind_kph}km/h"
)
} ?: emptyList()
Log.d("WeatherFragment", "Weather retrieved")
weatherView.onForecastLoaded(forecastList)
} catch (e: Exception) {
Log.e("WeatherFragment",
"Error while retrieving weather : ${e.message}")
weatherView.showToast(
"Erreur durant la récupération des données météo",
1
)
}
}
/**
* Assigne la WeatherView Interface
*/
override fun setIWeatherView(weatherView: IWeatherView) {
this.weatherView = weatherView
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IGroupView.kt | 981022186 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.GroupDetailVM
interface IGroupView : IShowToast {
fun buildItinerary(latitude:String,longitude:String)
fun setGroupInfos(group: GroupDetailVM)
fun onGroupDeleted()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IActivityView.kt | 868751211 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.ActivityDetailVM
interface IActivityView : IShowToast {
fun loadActivity(activity:ActivityDetailVM)
fun buildItinerary(latitude: String, longitude: String)
fun onActivityDeleted()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IUpdateActivityView.kt | 3978029636 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.ActivityVM
interface IUpdateActivityView : IShowToast {
fun setCurrentActivity(activityVM: ActivityVM)
fun onActivityUpdated()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IShowToast.kt | 4292816971 | package be.helmo.planivacances.presenter.interfaces
interface IShowToast {
fun showToast(message : String, length: Int)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ITchatView.kt | 116630499 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.service.dto.MessageDTO
interface ITchatView {
fun addMessageToView(message: MessageDTO)
fun stopLoading()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICreateGroupView.kt | 618525246 | package be.helmo.planivacances.presenter.interfaces
interface ICreateGroupView : IShowToast {
fun onGroupCreated()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICreateActivityView.kt | 2123830959 | package be.helmo.planivacances.presenter.interfaces
interface ICreateActivityView : IShowToast {
fun onActivityCreated()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IUpdateGroupView.kt | 2576536124 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.GroupVM
interface IUpdateGroupView : IShowToast {
fun onGroupUpdated()
fun setCurrentGroup(groupVM: GroupVM)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IHomeView.kt | 763258560 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM
import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM
interface IHomeView : IShowToast {
fun setGroupList(groups: List<GroupListItemVM>)
fun onGroupInvitationsLoaded(invitations: List<GroupInvitationVM>)
fun onGroupInvitationAccepted()
fun onGroupInvitationDeclined()
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICalendarView.kt | 3401566593 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM
import java.util.*
interface ICalendarView : IShowToast {
fun downloadCalendar(calendarContent:String,fileName:String)
fun onActivitiesLoaded(activityDates: List<Date>)
fun setDisplayedActivities(activities: List<ActivityListItemVM>)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IAuthView.kt | 2595702684 | package be.helmo.planivacances.presenter.interfaces
interface IAuthView : IShowToast {
fun goToHome()
fun stopLoading()
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.