content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package pt.isel.ls.data.mem
import pt.isel.ls.data.DataContext
import java.sql.Connection
object MemDataContext : DataContext {
override fun handleData(block: (Connection?) -> Unit) {
block(null)
}
}
| isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemDataContext.kt | 751610320 |
package pt.isel.ls.data.mem
import pt.isel.ls.TaskAppException
import pt.isel.ls.data.BoardsData
import pt.isel.ls.data.entities.Board
import pt.isel.ls.data.entities.User
import pt.isel.ls.data.entities.UserBoard
import pt.isel.ls.tasksServices.dtos.EditBoardDto
import pt.isel.ls.tasksServices.dtos.InputBoardDto
import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto
import pt.isel.ls.utils.ErrorCodes
import java.sql.Connection
object MemBoardsData : BoardsData {
private val CASCADE_DELETE = false
override fun getByName(name: String, connection: Connection?): Board =
MemDataSource.boards.firstOrNull { it.name == name }
?: throw TaskAppException(ErrorCodes.BOARD_READ_FAIL)
override fun getUserBoards(user: User, limit: Int, skip: Int, connection: Connection?): List<Board> {
val boards = MemDataSource.usersBoards.filter { it.userId == user.id }
if (skip > boards.lastIndex) return emptyList()
val boardIds = boards.subList(
skip,
if (skip + limit <= boards.lastIndex) skip + limit else boards.lastIndex + 1
).map { it.boardId }
return MemDataSource.boards.filter { it.id in boardIds }
}
override fun edit(editBoard: EditBoardDto, connection: Connection?) {
val oldBoard = MemDataSource.boards.firstOrNull { it.id == editBoard.id }
?: throw TaskAppException(ErrorCodes.BOARD_UPDATE_FAIL)
val newBoard = Board(oldBoard.id, oldBoard.name, editBoard.description)
MemDataSource.boards.remove(oldBoard)
MemDataSource.boards.add(newBoard)
}
override fun add(newBoard: InputBoardDto, connection: Connection?): Board {
if (MemDataSource.boards.any { it.name == newBoard.name }) {
throw TaskAppException(ErrorCodes.BOARD_NAME_IN_USE)
}
val newId = if (MemDataSource.boards.isEmpty()) 1 else MemDataSource.boards.maxOf { it.id } + 1
val board = Board(newId, newBoard.name, newBoard.description)
MemDataSource.boards.add(board)
return board
}
override fun getUsers(boardId: Int, user: User, limit: Int, skip: Int, connection: Connection?): List<SecureOutputUserDto> {
val users = MemDataSource.usersBoards.filter { it.boardId == boardId }
if (skip > users.lastIndex) return emptyList()
val usersIds = users.subList(
skip,
if (skip + limit <= users.lastIndex) skip + limit else users.lastIndex + 1
).map { it.userId }
return MemDataSource.users.filter { it.id in usersIds }.map { SecureOutputUserDto(it.id, it.name, it.email) }
}
override fun filterByName(user: User, searchField: String, con: Connection?): List<Board> {
val boards = MemDataSource.usersBoards.filter { it.userId == user.id }
val boardIds = boards.map { it.boardId }
return MemDataSource.boards.filter { it.id in boardIds && it.name.contains(searchField.lowercase()) }
}
override fun addUserToBoard(userId: Int, boardId: Int, connection: Connection?) {
val pair = UserBoard(userId, boardId)
if (MemDataSource.boards.any { it.id == boardId } && MemDataSource.users.any { it.id == userId }) {
if (!MemDataSource.usersBoards.any { it == pair }) {
MemDataSource.usersBoards.add(pair)
}
} else {
throw TaskAppException(ErrorCodes.ADD_USER_FAIL)
}
}
override fun deleteUserFromBoard(userId: Int, boardId: Int, connection: Connection?) {
val pair = UserBoard(userId, boardId)
MemDataSource.usersBoards.remove(pair)
}
override fun getById(id: Int, connection: Connection?): Board =
MemDataSource.boards.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.BOARD_READ_FAIL)
override fun delete(id: Int, connection: Connection?) {
val board = MemDataSource.boards.firstOrNull { it.id == id } ?: TaskAppException(ErrorCodes.BOARD_DELETE_FAIL)
if (MemDataSource.lists.any { it.boardId == id }) {
if (CASCADE_DELETE) {
MemDataSource.lists.removeAll { it.boardId == id }
} else {
// Should never happen due to cascade being used in live, thus doesn't have a specific code
throw TaskAppException(message = "Cannot delete a board that has lists.")
}
}
if (MemDataSource.cards.any { it.boardId == id }) {
if (CASCADE_DELETE) {
MemDataSource.cards.removeAll { it.listId == id }
} else {
// Should never happen due to cascade being used in live, thus doesn't have a specific code
throw TaskAppException(message = "Cannot delete a board that has cards.")
}
}
MemDataSource.usersBoards.removeAll { it.boardId == id }
MemDataSource.boards.remove(board)
}
override fun exists(id: Int, connection: Connection?): Boolean =
MemDataSource.boards.any { it.id == id }
}
| isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemBoardsData.kt | 444833129 |
package pt.isel.ls.data.mem
import pt.isel.ls.TaskAppException
import pt.isel.ls.data.UsersData
import pt.isel.ls.data.entities.User
import pt.isel.ls.data.entities.UserToken
import pt.isel.ls.tasksServices.dtos.CreateUserDto
import pt.isel.ls.tasksServices.dtos.EditUserDto
import pt.isel.ls.utils.ErrorCodes
import java.sql.Connection
import java.sql.Timestamp
import java.util.UUID
object MemUsersData : UsersData {
override fun createToken(user: User, connection: Connection?): String {
if (!MemDataSource.users.any { it == user }) throw TaskAppException(ErrorCodes.USER_READ_FAIL)
val token = UUID.randomUUID()
val ts = Timestamp(System.currentTimeMillis())
MemDataSource.usersTokens.add(UserToken(token, user.id, ts))
return token.toString()
}
override fun getByToken(token: String, connection: Connection?): User {
val id = MemDataSource.usersTokens.firstOrNull { it.token.toString() == token }?.userId
?: throw TaskAppException(ErrorCodes.NO_TOKEN_MATCH)
return MemDataSource.users.first { it.id == id }
}
override fun getByEmail(email: String, connection: Connection?): User =
MemDataSource.users.firstOrNull { it.email == email }
?: throw TaskAppException(ErrorCodes.NO_EMAIL_MATCH)
override fun add(newUser: CreateUserDto, connection: Connection?): User {
if (MemDataSource.users.any { it.email == newUser.email }) throw TaskAppException(ErrorCodes.EMAIL_ALREADY_IN_USE)
val newId = if (MemDataSource.users.isEmpty()) 1 else MemDataSource.users.maxOf { it.id } + 1
val user = User(newId, newUser.name, newUser.email, newUser.passwordHash, newUser.salt)
MemDataSource.users.add(user)
return user
}
override fun edit(editUser: EditUserDto, connection: Connection?) {
val oldUser = MemDataSource.users.firstOrNull { it.id == editUser.id } ?: throw TaskAppException(ErrorCodes.USER_READ_FAIL)
val newUser = User(oldUser.id, editUser.name, oldUser.email, oldUser.passwordHash, oldUser.salt)
MemDataSource.users.remove(oldUser)
MemDataSource.users.add(newUser)
}
override fun getById(id: Int, connection: Connection?): User =
MemDataSource.users.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.USER_READ_FAIL)
override fun delete(id: Int, connection: Connection?) {
val user = MemDataSource.users.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.USER_READ_FAIL)
val userBoards = MemDataSource.usersBoards.filter { it.userId == id }
if (userBoards.isNotEmpty()) {
// For now unlink, find a better way to deal with orphan boards later
MemDataSource.usersBoards.removeAll { it.userId == id }
}
MemDataSource.usersTokens.removeAll { it.userId == id }
MemDataSource.users.remove(user)
}
override fun exists(id: Int, connection: Connection?): Boolean =
MemDataSource.users.any { it.id == id }
}
| isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemUsersData.kt | 3922451273 |
package pt.isel.ls.data.mem
import pt.isel.ls.data.entities.Board
import pt.isel.ls.data.entities.BoardList
import pt.isel.ls.data.entities.Card
import pt.isel.ls.data.entities.User
import pt.isel.ls.data.entities.UserBoard
import pt.isel.ls.data.entities.UserToken
import pt.isel.ls.utils.PasswordUtils
import java.sql.Timestamp
import java.util.*
object MemDataSource {
val users = mutableListOf<User>()
val usersTokens = mutableListOf<UserToken>()
val boards = mutableListOf<Board>()
val usersBoards = mutableListOf<UserBoard>()
val lists = mutableListOf<BoardList>()
val cards = mutableListOf<Card>()
private fun initStorage() {
users.addAll(
listOf(
User(1, "Beatriz", "beatriz@example.org", PasswordUtils.hashPassword("HelloWorld", "aaaaaaaaaaaa"), "aaaaaaaaaaaa"),
User(2, "Fatima", "fatima@example.org", PasswordUtils.hashPassword("OlaMundo", "bbbbbbbbbbbb"), "bbbbbbbbbbbb"),
User(3, "Miguel", "miguel@example.org", PasswordUtils.hashPassword("HejVerden", "cccccccccccc"), "cccccccccccc")
)
)
usersTokens.addAll(
listOf(
UserToken(UUID.fromString("f52129ca-ccf1-42cc-a363-fdc89f71901b"), 1, Timestamp.valueOf("2023-02-23 18:30:00")),
UserToken(UUID.fromString("6d061c83-707f-4143-9c66-5128a6c5ea63"), 2, Timestamp.valueOf("2023-02-23 18:31:00")),
UserToken(UUID.fromString("95b36fe5-a100-462c-9123-dc310f92defc"), 3, Timestamp.valueOf("2023-02-23 18:31:30"))
)
)
boards.add(Board(1, "Viagem na Europa", "Reunir as ideias da viagem"))
usersBoards.addAll(
listOf(
UserBoard(1, 1),
UserBoard(2, 1),
UserBoard(3, 1)
)
)
lists.addAll(
listOf(
BoardList(1, "Reservas", 1, 3),
BoardList(2, "Sitos para comer", 1, 0),
BoardList(3, "Sitos para visitar", 1, 0)
)
)
cards.addAll(
listOf(
Card(1, "Viena", "Austria", null, null, 1, 0),
Card(2, "Roma", "Italia", null, null, 1, 1),
Card(3, "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch", "Pais de Gales", null, null, 1, 2),
Card(4, "Avião", "Comprar os bilhetes para todos", Timestamp.valueOf("2023-04-15 12:30:00"), 1, 1, 0),
Card(5, "Hotel", "Reservar os quartos (para quantos?)", Timestamp.valueOf("2023-05-01 12:00:00"), 1, 1, 1),
Card(6, "Transportes", "De e para o aeroporto", Timestamp.valueOf("2023-06-09 23:59:59"), 1, 1, 2)
)
)
}
fun resetStorage() {
clearStorage()
initStorage()
}
fun clearStorage() {
users.clear()
usersTokens.clear()
boards.clear()
usersBoards.clear()
lists.clear()
cards.clear()
}
}
| isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemDataSource.kt | 4083987842 |
package pt.isel.ls
import pt.isel.ls.utils.ErrorCodes
open class TaskAppException(
val errorCode: ErrorCodes = ErrorCodes.UNDEFINED,
val issue: String? = null,
override val message: String? = errorCode.message
) : Exception(message)
| isel-ls/src/main/kotlin/pt/isel/ls/TaskAppException.kt | 3103606079 |
package pt.isel.ls
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.RequestContexts
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.filter.ServerFilters
import org.http4k.routing.ResourceLoader
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.routing.singlePageApp
import org.http4k.server.Jetty
import org.http4k.server.asServer
import org.slf4j.LoggerFactory
import pt.isel.ls.data.mem.MemBoardsData
import pt.isel.ls.data.mem.MemCardsData
import pt.isel.ls.data.mem.MemDataContext
import pt.isel.ls.data.mem.MemDataSource
import pt.isel.ls.data.mem.MemListsData
import pt.isel.ls.data.mem.MemUsersData
import pt.isel.ls.data.pgsql.PgDataContext
import pt.isel.ls.data.pgsql.PgSqlBoardsData
import pt.isel.ls.data.pgsql.PgSqlCardsData
import pt.isel.ls.data.pgsql.PgSqlListsData
import pt.isel.ls.data.pgsql.PgSqlUsersData
import pt.isel.ls.tasksServices.TasksServices
import pt.isel.ls.webApi.BoardsApi
import pt.isel.ls.webApi.CardsApi
import pt.isel.ls.webApi.Filters
import pt.isel.ls.webApi.ListsApi
import pt.isel.ls.webApi.UsersApi
import java.io.File
fun main() {
val logger = LoggerFactory.getLogger("pt.isel.ls.http.HTTPServer")
// Make sure an env key for ``USE_POSTGRESQL`` exists with the value ``true`` to use the Postgresql for data
val usePostgresql = System.getenv("USE_POSTGRESQL")?.lowercase() == "true"
if (!usePostgresql) {
logger.info("Using Memory for data.")
MemDataSource.resetStorage()
} else {
logger.info("Using Postgres for data.")
}
val serverPort = System.getenv("PORT")?.toInt() ?: 9000
val boardsRepo = if (usePostgresql) PgSqlBoardsData else MemBoardsData
val usersRepo = if (usePostgresql) PgSqlUsersData else MemUsersData
val listsRepo = if (usePostgresql) PgSqlListsData else MemListsData
val cardsRepo = if (usePostgresql) PgSqlCardsData else MemCardsData
val dataContext = if (usePostgresql) PgDataContext else MemDataContext
val services = TasksServices(dataContext, boardsRepo, usersRepo, listsRepo, cardsRepo)
val boardsApi = BoardsApi(services)
val cardsApi = CardsApi(services)
val listsApi = ListsApi(services)
val usersApi = UsersApi(services)
val filters = Filters(services)
val usersRoutes = routes(
"users/{id}" bind Method.GET to usersApi::getUser,
"users" bind Method.POST to usersApi::createUser
)
val contexts = RequestContexts()
val injectUserRoutes = ServerFilters.InitialiseRequestContext(contexts).then(filters.filterUser(contexts)).then(
routes(
"boards/{id}/user-list" bind Method.GET to boardsApi.getBoardUsers(contexts),
"boards/" bind Method.GET to boardsApi.getBoards(contexts),
"boards/" bind Method.POST to boardsApi.createBoard(contexts),
"boards/{id}" bind Method.GET to boardsApi.getBoard(contexts)
)
)
val boardRoutes = filters.authFilter.then(
routes(
"boards/{id}/user-list/{uid}" bind Method.PUT to boardsApi::addUsersOnBoard,
"boards/{id}/user-list/{uid}" bind Method.DELETE to boardsApi::deleteUserFromBoard,
"boards/{id}/lists" bind Method.GET to listsApi::getLists,
"boards/{id}/lists" bind Method.POST to listsApi::createList,
"boards/{id}/lists/{lid}" bind Method.PUT to listsApi::editList,
"boards/{id}/lists/{lid}" bind Method.GET to listsApi::getList,
"boards/{id}/lists/{lid}/cards" bind Method.GET to cardsApi::getCardsFromList,
"boards/{id}/lists/{lid}/cards" bind Method.POST to cardsApi::createCard,
"boards/{id}/cards/{cid}" bind Method.GET to cardsApi::getCard,
"boards/{id}/cards/{cid}" bind Method.PUT to cardsApi::editCard,
"boards/{id}/cards/{cid}/move" bind Method.PUT to cardsApi::alterCardListPosition,
"boards/{id}/cards/{cid}" bind Method.DELETE to cardsApi::deleteCard,
"boards/{id}/lists/{lid}" bind Method.DELETE to listsApi::deleteList
)
)
val app = filters.logRequest(
routes(
"session" bind Method.POST to usersApi::loginUser,
usersRoutes,
boardRoutes,
injectUserRoutes,
"/open-api" bind Method.GET to { _: Request ->
val fileContents = File("./open-api.json").readText()
Response(OK).body(fileContents)
},
singlePageApp(ResourceLoader.Directory("static-content"))
)
)
val jettyServer = app.asServer(Jetty(serverPort)).start()
logger.info("server started listening")
readln()
jettyServer.stop()
logger.info("leaving Main")
}
| isel-ls/src/main/kotlin/pt/isel/ls/TaskServer.kt | 2201042439 |
package com.eugeneprojects.habittracker
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
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.eugeneprojects.habittracker", appContext.packageName)
}
} | habit-tracker/app/src/androidTest/java/com/eugeneprojects/habittracker/ExampleInstrumentedTest.kt | 1042858260 |
package com.eugeneprojects.habittracker
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* 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)
}
} | habit-tracker/app/src/test/java/com/eugeneprojects/habittracker/ExampleUnitTest.kt | 2192325138 |
package com.eugeneprojects.habittracker
import android.app.Application
import androidx.room.Room
import com.eugeneprojects.habittracker.data.room.HabitDatabase
class App : Application() {
val habitDatabase: HabitDatabase by lazy {
Room.databaseBuilder(
applicationContext,
HabitDatabase::class.java,
"habits_db.db"
).build()
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/App.kt | 1661347992 |
package com.eugeneprojects.habittracker.utils
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.eugeneprojects.habittracker.App
import com.eugeneprojects.habittracker.data.repository.HabitRepositoryIMPL
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitViewModel
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitsListViewModel
class ViewModelFactory(
private val app: App
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val viewModel = when (modelClass) {
HabitsListViewModel::class.java -> {
HabitsListViewModel(HabitRepositoryIMPL(app.habitDatabase.getHabitDao()))
}
HabitViewModel::class.java -> {
HabitViewModel(HabitRepositoryIMPL(app.habitDatabase.getHabitDao()))
}
else -> {
throw IllegalStateException("Unknown view model class")
}
}
return viewModel as T
}
}
fun Fragment.factory() = ViewModelFactory(requireContext().applicationContext as App) | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/utils/ViewModelFactory.kt | 1047130438 |
package com.eugeneprojects.habittracker.models
import androidx.annotation.StringRes
import com.eugeneprojects.habittracker.R
enum class HabitType(@StringRes val stringId: Int) {
GOOD(R.string.radio_good),
BAD(R.string.radio_bad)
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/models/HabitType.kt | 3071456363 |
package com.eugeneprojects.habittracker.models
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.time.OffsetDateTime
@Parcelize
@Entity(tableName = "table_habits")
data class Habit(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
var habitName: String?,
var habitDescription: String?,
var habitPriority: HabitPriority,
var habitType: HabitType,
var habitCount: String?,
var habitRhythm: String?,
var habitCreationDate: OffsetDateTime?
) : Parcelable {
companion object {
@JvmStatic
val DEFAULT: Habit
get() = Habit(
id = this.DEFAULT_ID,
habitName = "",
habitDescription = "",
habitPriority = HabitPriority.NEUTRAL,
habitType = HabitType.GOOD,
habitCount = "",
habitRhythm = "",
habitCreationDate = null
)
const val DEFAULT_ID: Int = -1
}
}
| habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/models/Habit.kt | 2496092791 |
package com.eugeneprojects.habittracker.models
import androidx.annotation.StringRes
import com.eugeneprojects.habittracker.R
enum class HabitPriority(@StringRes val stringId: Int) {
NEUTRAL(R.string.habit_type_neutral),
IMPORTANT(R.string.habit_type_important),
UNIMPORTANT(R.string.habit_type_unimportant);
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/models/HabitPriority.kt | 3650475466 |
package com.eugeneprojects.habittracker.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.eugeneprojects.habittracker.databinding.ItemHabitLayoutBinding
import com.eugeneprojects.habittracker.models.Habit
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
class HabitsAdapter(private val actionListener: (Habit) -> Unit) :
RecyclerView.Adapter<HabitsAdapter.HabitsViewHolder>(), View.OnClickListener {
var habits: List<Habit> = emptyList()
set(newValue) {
field = newValue
notifyDataSetChanged()
}
class HabitsViewHolder(val binding: ItemHabitLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HabitsViewHolder {
val inflater = LayoutInflater.from((parent.context))
val binding = ItemHabitLayoutBinding.inflate(inflater, parent, false)
binding.root.setOnClickListener(this)
return HabitsViewHolder(binding)
}
override fun getItemCount(): Int = habits.size
override fun onBindViewHolder(holder: HabitsViewHolder, position: Int) {
val habit = habits[position]
val context = holder.itemView.context
with(holder.binding) {
holder.itemView.tag = habit
tvHabitName.text = habit.habitName
tvHabitDescription.text = habit.habitDescription
tvHabitPriority.text = context.getText(habit.habitPriority.stringId)
tvHabitType.text = context.getText(habit.habitType.stringId)
tvHabitCount.text = habit.habitCount
tvHabitRhythm.text = habit.habitRhythm
tvHabitDate.text =
habit.habitCreationDate?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG))
}
}
override fun onClick(v: View) {
val habit = v.tag as Habit
actionListener(habit)
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/adapters/HabitsAdapter.kt | 654202566 |
package com.eugeneprojects.habittracker.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.eugeneprojects.habittracker.presentation.fragments.BadHabitsListFragment
import com.eugeneprojects.habittracker.presentation.fragments.GoodHabitsListFragment
class ViewPagerAdapter(
fm: FragmentManager,
lifecycle: Lifecycle
) : FragmentStateAdapter(fm, lifecycle) {
private val fragmentList = arrayListOf(
GoodHabitsListFragment(),
BadHabitsListFragment()
)
override fun getItemCount(): Int {
return fragmentList.size
}
override fun createFragment(position: Int): Fragment {
return fragmentList[position]
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/adapters/ViewPagerAdapter.kt | 891939938 |
package com.eugeneprojects.habittracker.data.repository
import androidx.lifecycle.LiveData
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitType
interface HabitRepository {
suspend fun insertHabit(habit: Habit)
suspend fun updateHabit(habit: Habit)
suspend fun getHabits(type: HabitType): LiveData<List<Habit>>
suspend fun getHabitsByTypeAsc(type: HabitType): LiveData<List<Habit>>
suspend fun getHabitsByTypeDesc(type: HabitType): LiveData<List<Habit>>
suspend fun searchHabitAsc(query: String, type: HabitType): LiveData<List<Habit>>
suspend fun searchHabitDesc(query: String, type: HabitType): LiveData<List<Habit>>
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/data/repository/HabitRepository.kt | 290956359 |
package com.eugeneprojects.habittracker.data.repository
import androidx.lifecycle.LiveData
import com.eugeneprojects.habittracker.data.room.HabitDao
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class HabitRepositoryIMPL(private val dao: HabitDao) : HabitRepository {
override suspend fun insertHabit(habit: Habit): Unit =
withContext(Dispatchers.IO) { dao.insert(habit) }
override suspend fun updateHabit(habit: Habit): Unit =
withContext(Dispatchers.IO) { dao.update(habit) }
override suspend fun getHabits(type: HabitType): LiveData<List<Habit>> =
withContext(Dispatchers.IO) { dao.getHabitsByType(type) }
override suspend fun getHabitsByTypeAsc(type: HabitType): LiveData<List<Habit>> =
withContext(Dispatchers.IO) { dao.getHabitsByTypeAsc(type) }
override suspend fun getHabitsByTypeDesc(type: HabitType): LiveData<List<Habit>> =
withContext(Dispatchers.IO) { dao.getHabitsByTypeDesc(type) }
override suspend fun searchHabitAsc(query: String, type: HabitType): LiveData<List<Habit>> =
withContext(Dispatchers.IO) { dao.searchHabitAsc(query, type) }
override suspend fun searchHabitDesc(query: String, type: HabitType): LiveData<List<Habit>> =
withContext(Dispatchers.IO) { dao.searchHabitDesc(query, type) }
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/data/repository/HabitRepositoryIMPL.kt | 3151241434 |
package com.eugeneprojects.habittracker.data.room
import androidx.room.TypeConverter
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
class Converters {
@TypeConverter
fun fromData(data: OffsetDateTime): String = data.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
@TypeConverter
fun toData(data: String): OffsetDateTime =
OffsetDateTime.parse(data, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/data/room/Converters.kt | 3079051106 |
package com.eugeneprojects.habittracker.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.eugeneprojects.habittracker.models.Habit
@Database(entities = [Habit::class], version = 1)
@TypeConverters(Converters::class)
abstract class HabitDatabase : RoomDatabase() {
abstract fun getHabitDao(): HabitDao
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/data/room/HabitDatabase.kt | 1373339425 |
package com.eugeneprojects.habittracker.data.room
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query
import androidx.room.Update
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitType
@Dao
interface HabitDao {
@Insert(onConflict = REPLACE)
suspend fun insert(habit: Habit)
@Update
suspend fun update(habit: Habit): Int
@Query("SELECT * FROM table_habits WHERE habitType = :type ORDER BY habitCreationDate ASC")
fun getHabitsByTypeAsc(type: HabitType): LiveData<List<Habit>>
@Query("SELECT * FROM table_habits WHERE habitType = :type ORDER BY habitCreationDate DESC")
fun getHabitsByTypeDesc(type: HabitType): LiveData<List<Habit>>
@Query("SELECT * FROM table_habits WHERE habitType = :type")
fun getHabitsByType(type: HabitType): LiveData<List<Habit>>
@Query("SELECT * FROM table_habits WHERE habitType = :type AND habitName LIKE '%'||:query||'%' ORDER BY habitCreationDate ASC")
fun searchHabitAsc(query: String, type: HabitType): LiveData<List<Habit>>
@Query("SELECT * FROM table_habits WHERE habitType = :type AND habitName LIKE '%'||:query||'%' ORDER BY habitCreationDate DESC")
fun searchHabitDesc(query: String, type: HabitType): LiveData<List<Habit>>
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/data/room/HabitDao.kt | 2202445576 |
package com.eugeneprojects.habittracker.presentation.viewmodels
import androidx.lifecycle.ViewModel
import com.eugeneprojects.habittracker.data.repository.HabitRepository
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitPriority
import com.eugeneprojects.habittracker.models.HabitType
import java.time.OffsetDateTime
class HabitViewModel(
private val habitRepository: HabitRepository
) : ViewModel() {
suspend fun updateHabit(
id: Int,
habitName: String?,
habitDescription: String?,
habitPriority: HabitPriority,
habitType: HabitType,
habitCount: String?,
habitRhythm: String?
) {
habitRepository.updateHabit(
Habit(
id = id,
habitName = habitName,
habitDescription = habitDescription,
habitPriority = habitPriority,
habitType = habitType,
habitCount = habitCount,
habitRhythm = habitRhythm,
habitCreationDate = OffsetDateTime.now()
)
)
}
suspend fun saveHabit(
habitName: String?,
habitDescription: String?,
habitPriority: HabitPriority,
habitType: HabitType,
habitCount: String?,
habitRhythm: String?
) {
habitRepository.insertHabit(
Habit(
habitName = habitName,
habitDescription = habitDescription,
habitPriority = habitPriority,
habitType = habitType,
habitCount = habitCount,
habitRhythm = habitRhythm,
habitCreationDate = OffsetDateTime.now()
)
)
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/viewmodels/HabitViewModel.kt | 1083431276 |
package com.eugeneprojects.habittracker.presentation.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.eugeneprojects.habittracker.data.repository.HabitRepository
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitType
import kotlinx.coroutines.Dispatchers
class HabitsListViewModel(
private val habitRepository: HabitRepository
) : ViewModel() {
private val _state: MutableLiveData<State> = MutableLiveData(State(null, false))
val goodHabits: LiveData<List<Habit>> = _state.switchMap {
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emitSource(getHabits(it, HabitType.GOOD))
}
}
val badHabits: LiveData<List<Habit>> = _state.switchMap {
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emitSource(getHabits(it, HabitType.BAD))
}
}
var query: String?
set(value) {
_state.value = _state.value?.copy(query = value)
}
get() = _state.value?.query
var sortDirection: Boolean
set(value) {
_state.value = _state.value?.copy(direction = value)
}
get() = _state.value!!.direction
data class State(val query: String?, val direction: Boolean)
private suspend fun getHabits(state: State, habitType: HabitType): LiveData<List<Habit>> {
return if (state.query != null) {
if (state.direction) {
habitRepository.searchHabitAsc(state.query, habitType)
} else {
habitRepository.searchHabitDesc(state.query, habitType)
}
} else {
if (state.direction) {
habitRepository.getHabitsByTypeAsc(habitType)
} else {
habitRepository.getHabitsByTypeDesc(habitType)
}
}
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/viewmodels/HabitsListViewModel.kt | 3639236741 |
package com.eugeneprojects.habittracker.presentation
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.eugeneprojects.habittracker.R
import com.eugeneprojects.habittracker.databinding.ActivityHabitListBinding
class HabitListActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityHabitListBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHabitListBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.habits_host_fragment_container) as NavHostFragment
navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(navController.graph, binding.drawerLayout)
binding.navView.setupWithNavController(navController)
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/HabitListActivity.kt | 817329989 |
package com.eugeneprojects.habittracker.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.eugeneprojects.habittracker.R
import com.eugeneprojects.habittracker.adapters.HabitsAdapter
import com.eugeneprojects.habittracker.databinding.FragmentGoodHabitsListBinding
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitsListViewModel
import com.eugeneprojects.habittracker.utils.factory
class GoodHabitsListFragment : Fragment() {
private lateinit var habitsAdapter: HabitsAdapter
private var _binding: FragmentGoodHabitsListBinding? = null
private val binding: FragmentGoodHabitsListBinding
get() = _binding!!
private val viewModel: HabitsListViewModel by activityViewModels { factory() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentGoodHabitsListBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpRecyclerView()
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun setUpRecyclerView() {
habitsAdapter = HabitsAdapter {
findNavController().navigate(
R.id.action_habitsListFragment_to_habitFragment,
bundleOf(HabitFragment.ARGS_HABIT to it)
)
}
binding.rvGoodHabitsList.apply {
adapter = habitsAdapter
}
viewModel.goodHabits.observe(viewLifecycleOwner) {
habitsAdapter.habits = it
}
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/fragments/GoodHabitsListFragment.kt | 1139488791 |
package com.eugeneprojects.habittracker.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.eugeneprojects.habittracker.R
import com.eugeneprojects.habittracker.adapters.ViewPagerAdapter
import com.eugeneprojects.habittracker.databinding.FragmentHabitsHomeBinding
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitsListViewModel
import com.eugeneprojects.habittracker.utils.factory
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.tabs.TabLayoutMediator
class HabitsHomeFragment : Fragment() {
private lateinit var habitsListsViewPagerAdapter: ViewPagerAdapter
private var _binding: FragmentHabitsHomeBinding? = null
private val binding: FragmentHabitsHomeBinding
get() = _binding!!
private val viewModel: HabitsListViewModel by activityViewModels { factory() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHabitsHomeBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.fabAddHabit.setOnClickListener { onAddHabitFABPressed() }
setUpViewPager()
setUpBottomSheet()
setSearchChangeListener()
setSortByDate()
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun setUpViewPager() {
val tabsNamesList = arrayListOf(
requireContext().getText(R.string.tab_good_text),
requireContext().getText(R.string.tab_bad_text)
)
habitsListsViewPagerAdapter = ViewPagerAdapter(
childFragmentManager,
lifecycle
)
with(binding) {
vpHabitsLists.adapter = habitsListsViewPagerAdapter
let {
TabLayoutMediator(it.tlHabitsLists, it.vpHabitsLists) { tab, position ->
tab.text = tabsNamesList[position]
}.attach()
}
}
}
private fun setUpBottomSheet() {
binding.bottomSheet.let {
BottomSheetBehavior.from(it).apply {
this.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
}
private fun onAddHabitFABPressed() {
findNavController().navigate(R.id.action_habitsListFragment_to_habitFragment)
}
private fun setSearchChangeListener() {
binding.habitSearchName.doOnTextChanged { searchQuery, _, _, _ ->
viewModel.query = searchQuery.toString()
}
}
private fun setSortByDate() {
binding.upArrow.setOnClickListener {
viewModel.sortDirection = true
}
binding.downArrow.setOnClickListener {
viewModel.sortDirection = false
}
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/fragments/HabitsHomeFragment.kt | 2349433087 |
package com.eugeneprojects.habittracker.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.RadioButton
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.eugeneprojects.habittracker.R
import com.eugeneprojects.habittracker.databinding.FragmentHabitBinding
import com.eugeneprojects.habittracker.models.Habit
import com.eugeneprojects.habittracker.models.HabitPriority
import com.eugeneprojects.habittracker.models.HabitType
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitViewModel
import com.eugeneprojects.habittracker.utils.factory
import kotlinx.coroutines.launch
class HabitFragment : Fragment() {
private lateinit var habit: Habit
private lateinit var spinnerArrayAdapter: ArrayAdapter<HabitPriorityHolder>
private var _binding: FragmentHabitBinding? = null
private val binding: FragmentHabitBinding
get() = _binding!!
private val viewModel: HabitViewModel by viewModels { factory() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHabitBinding.inflate(inflater)
habit = arguments?.getParcelable(ARGS_HABIT) ?: Habit.DEFAULT
return binding.root
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
if (savedInstanceState == null) {
setUpHabitPriority()
if (habit.id != Habit.DEFAULT_ID) {
setUpUIParams()
setUpUpdateHabitButton()
} else {
with(binding) {
btnHabitSave.isEnabled = false
tiHabitName.error =
requireContext().getText(R.string.empty_habit_name_error)
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setCheckSiteNameListener()
setUpUI()
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun setUpHabitPriority() {
val priorityItems = HabitPriority.entries.map {
HabitPriorityHolder(it, requireContext().getText(it.stringId).toString())
}.toTypedArray()
with(binding) {
spinnerArrayAdapter = ArrayAdapter(
requireContext(),
android.R.layout.simple_spinner_item,
priorityItems
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinHabitPriority.adapter = adapter
}
spinHabitPriority.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
}
//TODO: обрабатывать от состояния один листенер, внутри листенера решать
private fun setUpUI() {
setUpHabitPriority()
if (habit.id == Habit.DEFAULT_ID) {
setUpSavedHabitButton()
} else {
setUpUIParams()
setUpUpdateHabitButton()
}
}
private fun setUpUIParams() {
with(binding) {
edHabitName.setText(habit.habitName)
edHabitDescription.setText(habit.habitDescription)
when (habit.habitType) {
HabitType.GOOD -> radioGood.isChecked = true
HabitType.BAD -> radioBad.isChecked = true
}
spinHabitPriority.setSelection(spinnerArrayAdapter.getPosition(HabitPriorityHolder(habit.habitPriority)))
edHabitCount.setText(habit.habitCount)
edHabitRhythm.setText(habit.habitRhythm)
}
}
private fun setUpSavedHabitButton() {
binding.btnHabitSave.setOnClickListener { onSaveHabitPressed() }
}
private fun setUpUpdateHabitButton() {
binding.btnHabitSave.setOnClickListener { onUpdateHabitPressed() }
}
private fun onSaveHabitPressed() {
saveHabit()
findNavController().popBackStack()
}
private fun onUpdateHabitPressed() {
updateHabit()
findNavController().popBackStack()
}
private fun updateHabit() {
val id = habit.id
with(binding) {
lifecycleScope.launch {
viewModel.updateHabit(
id = id,
habitName = edHabitName.text.toString(),
habitDescription = edHabitDescription.text.toString(),
habitPriority = spinnerArrayAdapter.getItem(spinHabitPriority.selectedItemId.toInt())!!.priority,
habitType = when (binding.rgHabitType.findViewById<RadioButton>(rgHabitType.checkedRadioButtonId)) {
radioGood -> HabitType.GOOD
radioBad -> HabitType.BAD
else -> throw Exception()
},
habitCount = edHabitCount.text.toString(),
habitRhythm = edHabitRhythm.text.toString()
)
}
}
}
private fun saveHabit() {
with(binding) {
lifecycleScope.launch {
viewModel.saveHabit(
habitName = edHabitName.text.toString(),
habitDescription = edHabitDescription.text.toString(),
habitPriority = spinnerArrayAdapter.getItem(spinHabitPriority.selectedItemId.toInt())!!.priority,
habitType = when (rgHabitType.findViewById<RadioButton>(rgHabitType.checkedRadioButtonId)) {
radioGood -> HabitType.GOOD
radioBad -> HabitType.BAD
else -> throw Exception()
},
habitCount = edHabitCount.text.toString(),
habitRhythm = edHabitRhythm.text.toString()
)
}
}
}
private fun setCheckSiteNameListener() {
with(binding) {
edHabitName.addTextChangedListener { text ->
if (text?.isBlank() == false) {
btnHabitSave.isEnabled = true
tiHabitName.error = null
} else {
btnHabitSave.isEnabled = false
tiHabitName.error =
requireContext().getText(R.string.empty_habit_name_error)
}
}
}
}
private class HabitPriorityHolder(val priority: HabitPriority, val name: String = "") {
override fun toString() = name
override fun equals(other: Any?): Boolean {
if (other is HabitPriorityHolder) {
return priority == other.priority
}
return super.equals(other)
}
override fun hashCode(): Int {
return priority.hashCode()
}
}
companion object {
const val ARGS_HABIT = "habit"
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/fragments/HabitFragment.kt | 2593839530 |
package com.eugeneprojects.habittracker.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.eugeneprojects.habittracker.R
class AppInfoFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_app_info, container, false)
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/fragments/AppInfoFragment.kt | 4003841053 |
package com.eugeneprojects.habittracker.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.eugeneprojects.habittracker.R
import com.eugeneprojects.habittracker.adapters.HabitsAdapter
import com.eugeneprojects.habittracker.databinding.FragmentBadHabitsListBinding
import com.eugeneprojects.habittracker.presentation.viewmodels.HabitsListViewModel
import com.eugeneprojects.habittracker.utils.factory
class BadHabitsListFragment : Fragment() {
private lateinit var habitsAdapter: HabitsAdapter
private var _binding: FragmentBadHabitsListBinding? = null
private val binding: FragmentBadHabitsListBinding
get() = _binding!!
private val viewModel: HabitsListViewModel by activityViewModels { factory() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentBadHabitsListBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpRecyclerView()
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun setUpRecyclerView() {
habitsAdapter = HabitsAdapter {
findNavController().navigate(
R.id.action_habitsListFragment_to_habitFragment,
bundleOf(HabitFragment.ARGS_HABIT to it)
)
}
binding.rvBadHabitsList.apply {
adapter = habitsAdapter
}
viewModel.badHabits.observe(viewLifecycleOwner) {
habitsAdapter.habits = it
}
}
} | habit-tracker/app/src/main/java/com/eugeneprojects/habittracker/presentation/fragments/BadHabitsListFragment.kt | 826503352 |
package com.cupp.msu.criminalintentchapter9a
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.cupp.msu.criminalintentchapter9a", appContext.packageName)
}
} | Homework_6_1A/app/src/androidTest/java/com/cupp/msu/criminalintentchapter9a/ExampleInstrumentedTest.kt | 3868554181 |
package com.cupp.msu.criminalintentchapter9a
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)
}
} | Homework_6_1A/app/src/test/java/com/cupp/msu/criminalintentchapter9a/ExampleUnitTest.kt | 112849297 |
package com.cupp.msu.criminalintentchapter9a
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Homework_6_1A/app/src/main/java/com/cupp/msu/criminalintentchapter9a/MainActivity.kt | 340641451 |
package com.cupp.msu.criminalintentchapter9a
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import com.cupp.msu.criminalintentchapter9a.databinding.FragmentCrimeDetailBinding
import java.util.Date
import java.util.UUID
import java.util.*
class CrimeDetailFragment :Fragment(){
private lateinit var crime:Crime
// private lateinit var binding :FragmentCrimeDetailBinding
private var _binding : FragmentCrimeDetailBinding? = null
private val binding
get() = checkNotNull(_binding){
"Cannot access binding because it is null. Is the view visible"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
crime = Crime(
UUID.randomUUID(),
title = "",
date = Date(),
isSolved = false
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// binding = FragmentCrimeDetailBinding.inflate(layoutInflater, container, false)
_binding = FragmentCrimeDetailBinding.inflate(layoutInflater, container, false)
return binding.root
}
//wiring up views in a fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
// listener for edit text
crimeTitle.doOnTextChanged{text,_,_,_ ->
crime = crime.copy(title = text.toString())
}
// Listener for button text
crimeDate.apply {
text = crime.date.toString()
isEnabled = false
}
//listner for textbox changes
crimeSolved.setOnCheckedChangeListener{_, isChecked ->
crime = crime.copy(isSolved = isChecked)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
// binding = null
_binding = null
}
}
| Homework_6_1A/app/src/main/java/com/cupp/msu/criminalintentchapter9a/CrimeDetailFragment.kt | 3901671383 |
package com.cupp.msu.criminalintentchapter9a
import java.util.Date
import java.util.UUID
data class Crime (
val id: UUID,
val title: String,
val date: Date,
val isSolved: Boolean
) | Homework_6_1A/app/src/main/java/com/cupp/msu/criminalintentchapter9a/Crime.kt | 950189448 |
package com.example.daggerhiltdemo
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.daggerhiltdemo", appContext.packageName)
}
} | DaggerHiltDemo/app/src/androidTest/java/com/example/daggerhiltdemo/ExampleInstrumentedTest.kt | 1799750263 |
package com.example.daggerhiltdemo
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)
}
} | DaggerHiltDemo/app/src/test/java/com/example/daggerhiltdemo/ExampleUnitTest.kt | 3271840186 |
package com.plcoding.daggerhiltcourse.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/ui/theme/Shape.kt | 2134901707 |
package com.plcoding.daggerhiltcourse.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/ui/theme/Color.kt | 2408265663 |
package com.plcoding.daggerhiltcourse.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun DaggerHiltCourseTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/ui/theme/Theme.kt | 2059663878 |
package com.plcoding.daggerhiltcourse.ui.theme
import androidx.compose.material.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(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/ui/theme/Type.kt | 1612425992 |
package com.example.daggerhiltdemo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.hilt.navigation.compose.hiltViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val viewModel = hiltViewModel<MyViewModel>()
viewModel.temp()
}
}
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/MainActivity.kt | 1610843128 |
package com.example.daggerhiltdemo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MyApp: Application() | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/MyApp.kt | 3759493898 |
package com.example.daggerhiltdemo.di
import android.app.Application
import android.util.Log
import com.example.daggerhiltdemo.data.remote.MyApi
import com.example.daggerhiltdemo.data.repository.MyRepositoryImpl
import com.example.daggerhiltdemo.domain.repository.MyRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import javax.inject.Named
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideMyApi(): MyApi {
return Retrofit.Builder()
.baseUrl("https://test.com")
.build()
.create(MyApi::class.java)
}
@Provides
@Singleton
fun provideMyRepo(api: MyApi, application: Application): MyRepository{
Log.e("inside","here")
return MyRepositoryImpl(api, application)
}
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/di/AppModule.kt | 2902340852 |
package com.example.daggerhiltdemo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daggerhiltdemo.domain.repository.MyRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class MyViewModel @Inject constructor(
private val repository: MyRepository
) : ViewModel() {
init {
}
fun temp() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
repository.doNetworkCall()
}
}
}
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/MyViewModel.kt | 323832840 |
package com.example.daggerhiltdemo.data.repository
import android.app.Application
import com.example.daggerhiltdemo.R
import com.example.daggerhiltdemo.data.remote.MyApi
import com.example.daggerhiltdemo.domain.repository.MyRepository
import javax.inject.Inject
class MyRepositoryImpl @Inject constructor(
private val api: MyApi,
private val appContext: Application
): MyRepository {
init {
val appName = appContext.getString(R.string.app_name)
println("Hello from the repository. The app name is $appName")
}
override suspend fun doNetworkCall() {
println("doNetworkCall")
api.doNetworkCall()
}
override suspend fun doNetworkCall1() {
println("doNetworkCall1")
api.doNetworkCall()
}
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/data/repository/MyRepositoryImpl.kt | 2678293826 |
package com.example.daggerhiltdemo.data.remote
import retrofit2.http.GET
interface MyApi {
@GET("test")
suspend fun doNetworkCall()
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/data/remote/MyApi.kt | 4037524806 |
package com.example.daggerhiltdemo.domain.repository
interface MyRepository {
suspend fun doNetworkCall()
suspend fun doNetworkCall1()
} | DaggerHiltDemo/app/src/main/java/com/example/daggerhiltdemo/domain/repository/MyRepository.kt | 4097335121 |
package com.example.mobile
data class Pengguna (
val id: String,
val email: String,
val name: String,
val nohp: String,
val pass: String
) {
constructor() : this("","","","","")
} | HumanInitiative/app/Pengguna.kt | 2270916528 |
package com.example.mobile
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.mobile", appContext.packageName)
}
} | HumanInitiative/app/src/androidTest/java/com/example/mobile/ExampleInstrumentedTest.kt | 2245130245 |
package com.example.mobile
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)
}
} | HumanInitiative/app/src/test/java/com/example/mobile/ExampleUnitTest.kt | 1895185502 |
package com.example.mobile
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.example.mobile.databinding.FragmentTambahBinding
class TambahFragment : Fragment(), View.OnClickListener {
private lateinit var binding: FragmentTambahBinding
private lateinit var ref: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentTambahBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ref = FirebaseDatabase.getInstance().getReference("bencana")
binding.btnSimpan.setOnClickListener(this)
}
override fun onClick(v: View?) {
simpanData()
val bncn = BerandaFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.container, TambahFragment())
transaction.commit()
}
private fun simpanData() {
val judul = binding.edtJudul.text.toString().trim()
val bencana = binding.edtBencana.text.toString().trim()
val kategori = binding.edtKategori.text.toString().trim()
val target = binding.edtTarget.text.toString().trim()
val tingkat = binding.edtTingkat.text.toString().trim()
val nama = binding.edtNama.text.toString().trim()
val norek = binding.edtNorek.text.toString().trim()
if (judul.isEmpty() or bencana.isEmpty() or kategori.isEmpty() or target.isEmpty() or
tingkat.isEmpty() or nama.isEmpty() or norek.isEmpty()) {
Toast.makeText(
requireContext(),
"Isi data secara lengkap tidak boleh kosong",
Toast.LENGTH_SHORT
).show()
return
}
val bncnId = ref.push().key
val bncna = Bencana(bncnId!!, judul, bencana, kategori, target, tingkat, nama, norek)
bncnId?.let {
ref.child(it).setValue(bncna).addOnCompleteListener { task ->
if(isAdded) {
if (task.isSuccessful) {
Toast.makeText(
requireContext(),
"Data berhasil ditambahkan",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
requireContext(),
"Gagal menambahkan data",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
} | HumanInitiative/app/src/main/java/com/example/mobile/TambahFragment.kt | 1419643299 |
package com.example.mobile
import android.app.AlertDialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.google.firebase.database.FirebaseDatabase
class BencanaAdapter(
val bencanaContext: Context,
val layoutResId: Int,
val bencanaList: List<Bencana>
) : ArrayAdapter<Bencana>(bencanaContext, layoutResId, bencanaList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val layoutInflater: LayoutInflater = LayoutInflater.from(bencanaContext)
val view: View = layoutInflater.inflate(layoutResId, null)
val o_judul: TextView = view.findViewById(R.id.ou_judul)
val o_bencana: TextView = view.findViewById(R.id.ou_bencana)
val o_kategori: TextView = view.findViewById(R.id.ou_kategori)
val o_target: TextView = view.findViewById(R.id.ou_target)
val o_tingkat: TextView = view.findViewById(R.id.ou_tingkat)
val o_nama: TextView = view.findViewById(R.id.ou_nama)
val o_norek: TextView = view.findViewById(R.id.ou_norek)
val imgEdit: ImageView = view.findViewById(R.id.icn_edit)
val anggota = bencanaList[position]
imgEdit.setOnClickListener {
updateDialog(anggota)
}
o_judul.text = "Judul : " + anggota.judul
o_bencana.text = "Bencana Alam : " + anggota.bencana
o_kategori.text = "Jenis Kategori Bencana : " + anggota.kategori
o_target.text = "Target Donasi : IDR" + anggota.target
o_tingkat.text = "Tingkat Kerusakan :" + anggota.tingkat+"%"
o_nama.text = "Nama Rekening Penerima : " + anggota.nama
o_norek.text = "No Rekening Penerima : " + anggota.norek
return view
}
private fun updateDialog(anggota: Bencana) {
val builder = AlertDialog.Builder(bencanaContext)
builder.setTitle("Update Data")
val inflater = LayoutInflater.from(bencanaContext)
val view = inflater.inflate(R.layout.update, null)
val edtJudul = view.findViewById<EditText>(R.id.upJudul)
val edtBencana = view.findViewById<EditText>(R.id.upBencana)
val edtKategori = view.findViewById<EditText>(R.id.upKategori)
val edtTarget = view.findViewById<EditText>(R.id.upTarget)
val edtTingkat = view.findViewById<EditText>(R.id.upTingkat)
val edtNama = view.findViewById<EditText>(R.id.upNama)
val edtNorek = view.findViewById<EditText>(R.id.upNoRek)
edtJudul.setText(anggota.judul)
edtBencana.setText(anggota.bencana)
edtKategori.setText(anggota.kategori)
edtTarget.setText(anggota.target)
edtTingkat.setText(anggota.tingkat)
edtNama.setText(anggota.nama)
edtNorek.setText(anggota.norek)
builder.setView(view)
builder.setPositiveButton("Ubah") { pe, p1 ->
val dbAnggota = FirebaseDatabase.getInstance().getReference("bencana")
val judul = edtJudul.text.toString().trim()
val bencana = edtBencana.text.toString().trim()
val kategori = edtKategori.text.toString().trim()
val target = edtTarget.text.toString().trim()
val tingkat = edtTingkat.text.toString().trim()
val nama = edtNama.text.toString().trim()
val norek = edtNorek.text.toString().trim()
if (judul.isEmpty() or bencana.isEmpty() or kategori.isEmpty() or target.isEmpty() or
tingkat.isEmpty() or nama.isEmpty() or norek.isEmpty()) {
Toast.makeText(
bencanaContext, "Isi data secara lengkap tidak boleh kosong",
Toast.LENGTH_SHORT
)
.show()
return@setPositiveButton
}
val anggota = Bencana(anggota.id, judul, bencana, kategori, target, tingkat, nama, norek)
dbAnggota.child(anggota.id).setValue(anggota)
Toast.makeText(bencanaContext, "Data berhasil di update", Toast.LENGTH_SHORT)
.show()
}
builder.setNeutralButton("Batal") { po, p1 -> }
builder.setNegativeButton("Hapus") { po, p1 ->
val dbAnggota = FirebaseDatabase.getInstance().getReference("bencana")
.child(anggota.id)
dbAnggota.removeValue()
Toast.makeText(bencanaContext, "Data berhasil di hapus", Toast.LENGTH_SHORT)
.show()
}
val alert = builder.create()
alert.show()
}
} | HumanInitiative/app/src/main/java/com/example/mobile/BencanaAdapter.kt | 609561905 |
package com.example.mobile
data class Pengguna (
val id: String,
val uemail: String,
val unama: String,
val unohp: String,
val upass: String,
) {
constructor() : this("","","","","")
} | HumanInitiative/app/src/main/java/com/example/mobile/Pengguna.kt | 93834077 |
package com.example.mobile
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.mobile.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
changeFragment(BerandaFragment())
binding.navbar.setOnItemSelectedListener {
when(it.itemId) {
R.id.beranda -> changeFragment(BerandaFragment())
R.id.profil -> changeFragment(ProfilFragment())
R.id.tambah -> changeFragment(TambahFragment())
else -> {}
}
true
}
}
private fun changeFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.container, fragment)
fragmentTransaction.commit()
}
} | HumanInitiative/app/src/main/java/com/example/mobile/MainActivity.kt | 3872331073 |
package com.example.mobile
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseAuthInvalidUserException
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.ktx.Firebase
class LoginFragment : Fragment(R.layout.fragment_login) {
private lateinit var auth: FirebaseAuth
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
auth = Firebase.auth
// Inisialisasi elemen-elemen UI
val uemail: EditText = view.findViewById(R.id.edt_email)
val usandi: EditText = view.findViewById(R.id.edt_pass)
val btnMasuk: Button = view.findViewById(R.id.button_login)
val txtDaftar: TextView = view.findViewById(R.id.txt_daftar)
// Set listener untuk tombol masuk
btnMasuk.setOnClickListener {
val gmail = uemail.text.toString().trim()
val password = usandi.text.toString().trim()
// Validasi input sebelum masuk
if (gmail.isEmpty() || password.isEmpty()) {
Toast.makeText(requireContext(), "Harap isi semua kolom", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// login process
auth.signInWithEmailAndPassword(gmail, password)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
val userId = user?.uid
val database = FirebaseDatabase.getInstance()
val reference = database.getReference("User")
userId?.let {
reference.child(it).get().addOnSuccessListener { snapshot ->
val intent = Intent(requireContext(), MainActivity::class.java)
startActivity(intent)
requireActivity().finish() // close current activity
}.addOnFailureListener { e ->
// login failed
Toast.makeText(requireContext(),
"Login gagal: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
} else {
// login failed
val exception = task.exception
if (exception is FirebaseAuthInvalidUserException
|| exception is FirebaseAuthInvalidCredentialsException) {
// wrong email or password
Toast.makeText(requireContext(),
"Email atau password salah", Toast.LENGTH_SHORT).show()
} else {
// other failure
Toast.makeText(requireContext(),
"Login gagal: ${exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
// Listener untuk tombol daftar (redirect ke halaman daftar)
txtDaftar.setOnClickListener {
val daftar = RegisFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.begin, daftar)
transaction.commit()
}
}
} | HumanInitiative/app/src/main/java/com/example/mobile/LoginFragment.kt | 4183728301 |
package com.example.mobile
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.ktx.Firebase
class RegisFragment : Fragment(R.layout.fragment_regis) {
private lateinit var auth: FirebaseAuth
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
auth = Firebase.auth
// Inisialisasi elemen-elemen UI
val uemail: EditText = view.findViewById(R.id.edt_email)
val uname: EditText = view.findViewById(R.id.edt_username)
val unohp: EditText = view.findViewById(R.id.edt_mobilenumber)
val usandi: EditText = view.findViewById(R.id.edt_pass)
val btnDaftar: Button = view.findViewById(R.id.button_daftar)
val txtLogin: TextView = view.findViewById(R.id.txt_masuk)
// Set listener untuk tombol daftar
btnDaftar.setOnClickListener {
val gmail = uemail.text.toString().trim()
val username = uname.text.toString().trim()
val nohandphone = unohp.text.toString().trim()
val password = usandi.text.toString().trim()
// Validasi input sebelum pendaftaran
if (gmail.isEmpty() || username.isEmpty() || nohandphone.isEmpty() || password.isEmpty()) {
Toast.makeText(requireContext(), "Harap isi semua kolom", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// Proses pendaftaran ke Firebase Authentication
auth.createUserWithEmailAndPassword(gmail, password)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
// Pendaftaran berhasil
val user = auth.currentUser
val userId = user?.uid // atau dapatkan ID pengguna dari hasil pendaftaran
// Menyimpan informasi pengguna ke Realtime Database
val database = FirebaseDatabase.getInstance()
val reference = database.getReference("User") // Ganti dengan lokasi yang benar di database Anda
val userData = HashMap<String, Any>()
userData["email"] = gmail
userData["username"] = username
userData["nohandphone"] = nohandphone
userData["password"] = password
userId?.let {
reference.child(it).setValue(userData)
.addOnSuccessListener {
// Data pengguna berhasil disimpan ke database
Toast.makeText(requireContext(), "Pendaftaran berhasil!", Toast.LENGTH_SHORT).show()
// Redirect ke halaman utama setelah pendaftaran berhasil
val loginFragment = LoginFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
if (!requireActivity().isFinishing && !requireActivity().isDestroyed) {
transaction.replace(R.id.begin, loginFragment)
transaction.commit()
}
}
.addOnFailureListener { e ->
// Gagal menyimpan data pengguna ke database
Toast.makeText(requireContext(), "Gagal menyimpan data pengguna: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
} else {
// Pendaftaran gagal, tampilkan pesan kesalahan
val exception = task.exception
Toast.makeText(requireContext(), "Pendaftaran gagal: ${exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
// Listener untuk tombol daftar (redirect ke halaman login)
txtLogin.setOnClickListener {
val login = LoginFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.begin, login)
transaction.commit()
}
}
} | HumanInitiative/app/src/main/java/com/example/mobile/RegisFragment.kt | 3646437132 |
package com.example.mobile
import android.app.Dialog
import android.app.admin.TargetUser
import android.os.Bundle
import android.os.UserHandle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.mobile.databinding.FragmentBerandaBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.StorageReference
class BerandaFragment : Fragment() {
lateinit var binding: FragmentBerandaBinding
private lateinit var bencanaList: MutableList<Bencana>
private lateinit var ref: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentBerandaBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ref = FirebaseDatabase.getInstance().getReference("bencana")
bencanaList = mutableListOf()
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (isAdded) { // Pastikan Fragment terpasang sebelum menggunakan requireActivity()
if (snapshot.exists()) {
bencanaList.clear()
for (a in snapshot.children) {
val bencanalam = a.getValue(Bencana::class.java)
bencanalam ?.let {
bencanaList.add(it)
}
}
val adapter = BencanaAdapter(
requireActivity(),
R.layout.detil_bencana,
bencanaList
)
binding.hasil.adapter = adapter
println("Output: " + bencanaList)
}
}
}
override fun onCancelled(error: DatabaseError) {
// Handle onCancelled
}
})
}
}
| HumanInitiative/app/src/main/java/com/example/mobile/BerandaFragment.kt | 2174008877 |
package com.example.mobile
import android.app.Activity
import android.app.Dialog
import android.app.admin.TargetUser
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.UserHandle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentTransaction
import com.bumptech.glide.Glide
import com.example.mobile.databinding.FragmentProfilBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserProfileChangeRequest
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
class ProfilFragment : Fragment() {
private lateinit var binding: FragmentProfilBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var storageRef: StorageReference
private lateinit var userRef: DatabaseReference
private val PICK_IMAGE_REQUEST = 1
private var isFragmentAttached = false // Variabel untuk menandai fragment terpasang
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentProfilBinding.inflate(inflater, container, false)
binding.editprofil.setOnClickListener{
val userFragment = UserFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.container,userFragment)
transaction.commit()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isFragmentAttached = true // Set variabel bahwa fragment terpasang
firebaseAuth = FirebaseAuth.getInstance()
storageRef = FirebaseStorage.getInstance().reference
userRef = FirebaseDatabase.getInstance().getReference("User")
binding.btnEditLogo.setOnClickListener {
changeProfileImage()
}
displayUserInfo()
binding.keluar.setOnClickListener {
logout()
}
}
private fun logout() {
firebaseAuth.signOut()
val i = Intent(requireContext(), BeginActivity::class.java)
startActivity(i)
requireActivity().finish()
}
override fun onDestroyView() {
super.onDestroyView()
isFragmentAttached = false // Set variabel bahwa fragment sudah tidak terpasang lagi
}
private fun displayUserInfo() {
val user = firebaseAuth.currentUser
val profileImageUri = user?.photoUrl
val userId = user?.uid
userId?.let {
userRef.child(it).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (isFragmentAttached) { // Pastikan fragment masih terpasang sebelum menggunakan konteks
if (snapshot.exists()) {
val username = snapshot.child("username").getValue(String::class.java)
val nohp = snapshot.child("nohandphone").getValue(String::class.java)
binding.namauser.setText(username)
binding.nouser.setText(nohp)
profileImageUri?.let {
Glide.with(requireContext())
.load(profileImageUri)
.placeholder(R.drawable.squid)
.error(R.drawable.squid)
.into(binding.foto)
}
}
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
private fun changeProfileImage() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, PICK_IMAGE_REQUEST)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
val imageUri: Uri = data.data!!
uploadImageToFirebaseStorage(imageUri)
}
}
private fun uploadImageToFirebaseStorage(imageUri: Uri) {
val user = firebaseAuth.currentUser
val userId = user?.uid
userId?.let {
val profileImageRef = storageRef.child("profile_images/$it.jpg")
profileImageRef.putFile(imageUri)
.addOnSuccessListener { _ ->
profileImageRef.downloadUrl.addOnSuccessListener { uri ->
val profileUpdates = UserProfileChangeRequest.Builder()
.setPhotoUri(uri)
.build()
user.updateProfile(profileUpdates)
.addOnCompleteListener { task ->
if (task.isSuccessful && isFragmentAttached) {
displayUserInfo()
}
}
}
}
.addOnFailureListener { e ->
// Handle failure
}
}
}
}
| HumanInitiative/app/src/main/java/com/example/mobile/ProfilFragment.kt | 3652526892 |
package com.example.mobile
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.example.mobile.databinding.FragmentBeginBinding
class BeginFragment : Fragment() {
lateinit var binding: FragmentBeginBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentBeginBinding.inflate(layoutInflater)
binding.btnRegisAwal.setOnClickListener{
val regisFragment = RegisFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.begin,regisFragment)
transaction.commit()
}
binding.btnLoginAwal.setOnClickListener{
val loginFragment = LoginFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.begin,loginFragment)
transaction.commit()
}
return binding.root
}
} | HumanInitiative/app/src/main/java/com/example/mobile/BeginFragment.kt | 3824244508 |
package com.example.mobile
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.mobile.databinding.ActivityBeginBinding
class BeginActivity : AppCompatActivity() {
lateinit var binding: ActivityBeginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBeginBinding.inflate(layoutInflater)
setContentView(binding.root)
changeFragment(BeginFragment())
}
private fun changeFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.begin, fragment)
fragmentTransaction.commit()
}
} | HumanInitiative/app/src/main/java/com/example/mobile/BeginActivity.kt | 2880281600 |
package com.example.mobile
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.example.mobile.databinding.FragmentUserBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class UserFragment : Fragment() {
private lateinit var binding: FragmentUserBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var userRef: DatabaseReference
private var isFragmentAttached = false // Variabel untuk menandai fragment terpasang
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentUserBinding.inflate(inflater, container, false)
binding.backBtn.setOnClickListener{
val profilFragment = ProfilFragment()
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.container,profilFragment)
transaction.commit()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isFragmentAttached = true // Set variabel bahwa fragment terpasang
firebaseAuth = FirebaseAuth.getInstance()
userRef = FirebaseDatabase.getInstance().getReference("User")
displayUserInfo()
}
private fun displayUserInfo() {
val user = firebaseAuth.currentUser
val userId = user?.uid
userId?.let {
userRef.child(it).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (isFragmentAttached) { // Pastikan fragment masih terpasang sebelum menggunakan konteks
if (snapshot.exists()) {
val username = snapshot.child("username").getValue(String::class.java)
val nohp = snapshot.child("nohandphone").getValue(String::class.java)
val password = snapshot.child("password").getValue(String::class.java)
val email = snapshot.child("email").getValue(String::class.java)
binding.oUName.setText(username)
binding.oUNoHp.setText(nohp)
binding.oUPass.setText(password)
binding.oUEmail.setText(email)
}
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
}
| HumanInitiative/app/src/main/java/com/example/mobile/UserFragment.kt | 2050260135 |
package com.example.mobile
data class Bencana (
val id: String,
val judul: String,
val bencana: String,
val kategori: String,
val target: String,
val tingkat: String,
val nama: String,
val norek: String
) {
constructor() : this("","","","","","","","")
} | HumanInitiative/app/src/main/java/com/example/mobile/Bencana.kt | 3286981262 |
package com.example.jokerapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.jokerapp", appContext.packageName)
}
} | JokerApp/app/src/androidTest/java/com/example/jokerapp/ExampleInstrumentedTest.kt | 3481645225 |
package com.example.jokerapp
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)
}
} | JokerApp/app/src/test/java/com/example/jokerapp/ExampleUnitTest.kt | 2288331390 |
package com.example.jokerapp.model
data class Category(
val name: String,
val bgColor: Long
)
| JokerApp/app/src/main/java/com/example/jokerapp/model/Category.kt | 2744897824 |
package com.example.jokerapp.model
import com.google.gson.annotations.SerializedName
data class Joke(
@SerializedName("value")val text: String,
@SerializedName("icon_url")val iconUrl: String
)
| JokerApp/app/src/main/java/com/example/jokerapp/model/Joke.kt | 203702693 |
package com.example.jokerapp.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.jokerapp.R
import com.example.jokerapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val toolbar = binding.appBarMain.toolbar
setSupportActionBar(toolbar)
val drawerLayout = binding.drawerLayout
val navView = binding.navView
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment_content_main) as NavHostFragment?
val navController = navHostFragment!!.navController
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_home,
R.id.nav_joke_day,
R.id.nav_about
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(this.appBarConfiguration) || super.onSupportNavigateUp()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/view/MainActivity.kt | 1540525154 |
package com.example.jokerapp.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.example.jokerapp.R
import com.example.jokerapp.model.Joke
import com.example.jokerapp.presentation.JokePresenter
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.squareup.picasso.Picasso
class JokeFragment : Fragment() {
companion object {
const val CATEGORY_KEY = "category"
}
private lateinit var progressBar: ProgressBar
private lateinit var textView: TextView
private lateinit var imageView: ImageView
private lateinit var presenter: JokePresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter = JokePresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_joke, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val categoryName = arguments?.getString(CATEGORY_KEY)!!
activity?.findViewById<Toolbar>(R.id.toolbar)?.title = categoryName
progressBar = view.findViewById(R.id.progress_bar)
textView = view.findViewById(R.id.txt_joke)
imageView = view.findViewById(R.id.img_joke)
view.findViewById<FloatingActionButton>(R.id.fab).setOnClickListener {
presenter.findBy(categoryName)
}
presenter.findBy(categoryName)
}
fun showJoke(joke: Joke) {
textView.text = joke.text
Picasso.get().load(joke.iconUrl).into(imageView)
}
fun showProgress() {
progressBar.visibility = View.VISIBLE
}
fun hideProgress() {
progressBar.visibility = View.GONE
}
fun showFailure(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/view/JokeFragment.kt | 3293874418 |
package com.example.jokerapp.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.example.jokerapp.R
import com.example.jokerapp.model.Joke
import com.example.jokerapp.presentation.JokeDayPresenter
import com.squareup.picasso.Picasso
class JokeDayFragment : Fragment() {
private lateinit var progressBar: ProgressBar
private lateinit var textView: TextView
private lateinit var imageView: ImageView
private lateinit var presenter: JokeDayPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter = JokeDayPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_joke_day, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.findViewById<Toolbar>(R.id.toolbar)?.title = getString(R.string.menu_joke_day)
progressBar = view.findViewById(R.id.progress_bar)
textView = view.findViewById(R.id.txt_joke)
imageView = view.findViewById(R.id.img_joke)
presenter.findRandom()
}
fun showJoke(joke: Joke) {
textView.text = joke.text
Picasso.get().load(joke.iconUrl).into(imageView)
}
fun showProgress() {
progressBar.visibility = View.VISIBLE
}
fun hideProgress() {
progressBar.visibility = View.GONE
}
fun showFailure(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/view/JokeDayFragment.kt | 817843144 |
package com.example.jokerapp.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.jokerapp.BuildConfig
import com.example.jokerapp.R
class AboutFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_about, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<TextView>(R.id.txt_version).text = getString(R.string.build_version, BuildConfig.VERSION_NAME)
}
} | JokerApp/app/src/main/java/com/example/jokerapp/view/AboutFragment.kt | 611714 |
package com.example.jokerapp.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.jokerapp.R
import com.example.jokerapp.model.Category
import com.example.jokerapp.presentation.HomePresenter
import com.xwray.groupie.GroupieAdapter
class HomeFragment : Fragment() {
private lateinit var progressBar: ProgressBar
private lateinit var presenter: HomePresenter
private val adapter = GroupieAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter = HomePresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBar = view.findViewById(R.id.progress_bar)
val recyclerView = view.findViewById<RecyclerView>(R.id.rv_main)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
if(adapter.itemCount == 0) {
presenter.findAllCategories()
}
recyclerView.adapter = adapter
adapter.setOnItemClickListener { item, view ->
val bundle = Bundle()
val categoryName = (item as CategoryItem).category.name
bundle.putString("category", categoryName)
findNavController().navigate(R.id.action_nav_home_to_nav_joke, bundle)
}
}
fun showCategories(response: List<Category>) {
val categories = response.map { CategoryItem(it) }
adapter.addAll(categories)
adapter.notifyDataSetChanged()
}
fun showFailure(message: String){
Toast.makeText(requireContext(),message,Toast.LENGTH_SHORT).show()
}
fun showProgress(){
progressBar.visibility = View.VISIBLE
}
fun hideProgress(){
progressBar.visibility = View.GONE
}
} | JokerApp/app/src/main/java/com/example/jokerapp/view/HomeFragment.kt | 415824975 |
package com.example.jokerapp.view
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.example.jokerapp.R
import com.example.jokerapp.model.Category
import com.xwray.groupie.GroupieViewHolder
import com.xwray.groupie.Item
class CategoryItem(val category: Category) : Item<CategoryItem.CategoryViewHolder>() {
class CategoryViewHolder(view: View) : GroupieViewHolder(view)
override fun createViewHolder(itemView: View) = CategoryViewHolder(itemView)
override fun bind(viewHolder: CategoryViewHolder, position: Int) {
viewHolder.itemView.findViewById<TextView>(R.id.txt_category).text = category.name
viewHolder.itemView.findViewById<LinearLayout>(R.id.container_category)
.setBackgroundColor(category.bgColor.toInt())
}
override fun getLayout() = R.layout.item_category
}
| JokerApp/app/src/main/java/com/example/jokerapp/view/CategoryItem.kt | 2087980380 |
package com.example.jokerapp.data
import com.example.jokerapp.model.Joke
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface ChuckNorrisAPI {
@GET("jokes/categories")
fun findAllCategories(@Query("apiKey")apiKey: String = HTTPClient.API_KEY): Call<List<String>>
@GET("jokes/random")
fun findRandom(@Query("category")categoryName: String? = null, @Query("apiKey") apiKey: String = HTTPClient.API_KEY) : Call <Joke>
} | JokerApp/app/src/main/java/com/example/jokerapp/data/ChuckNorrisAPI.kt | 1767519182 |
package com.example.jokerapp.data
import com.example.jokerapp.model.Joke
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class JokeRemoteDataSource {
fun findBy(categoryName: String, callback: JokeCallBack) {
HTTPClient.retrofit()
.create(ChuckNorrisAPI::class.java)
.findRandom(categoryName)
.enqueue(object : Callback<Joke>{
override fun onResponse(call: Call<Joke>, response: Response<Joke>) {
if (response.isSuccessful){
val joke = response.body()
callback.onSuccess(joke ?: throw RuntimeException("Piada não encontrada"))
} else {
val error = response.errorBody()?.string()
callback.onError(error?: "Erro desconhecido")
}
callback.onComplete()
}
override fun onFailure(call: Call<Joke>, t: Throwable) {
callback.onError(t.message ?: "Erro interno")
callback.onComplete()
}
})
}
} | JokerApp/app/src/main/java/com/example/jokerapp/data/JokeRemoteDataSource.kt | 425880249 |
package com.example.jokerapp.data
interface ListCategoryCallback {
fun onSuccess(response: List<String>)
fun onError(response: String)
fun onComplete()
} | JokerApp/app/src/main/java/com/example/jokerapp/data/ListCategoryCallback.kt | 205550170 |
package com.example.jokerapp.data
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object HTTPClient {
private const val BASE_URL = "https://api.tiagoaguiar.co/jokerapp/"
const val API_KEY = "3d9e4f0a-fd58-46ec-b3ac-1ee85853727f"
private fun httpClient() : OkHttpClient{
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder()
.addInterceptor(logging)
.build()
}
fun retrofit() = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient())
.build()
} | JokerApp/app/src/main/java/com/example/jokerapp/data/HTTPClient.kt | 3454753675 |
package com.example.jokerapp.data
import com.example.jokerapp.model.Joke
interface JokeCallBack {
fun onSuccess(response: Joke)
fun onError(response: String)
fun onComplete()
}
| JokerApp/app/src/main/java/com/example/jokerapp/data/JokeCallBack.kt | 1305742270 |
package com.example.jokerapp.data
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class CategoryRemoteDataSource {
fun findAllCategories(callback: ListCategoryCallback) {
HTTPClient.retrofit()// Instancia do Retrofit
.create(ChuckNorrisAPI::class.java)
.findAllCategories()
.enqueue(object : Callback<List<String>> {
override fun onResponse(call: Call<List<String>>, response: Response<List<String>>) {
if (response.isSuccessful){
val categories = response.body()
callback.onSuccess(categories ?: emptyList())
} else {
val error = response.errorBody()?.string()
callback.onError(error?: "Erro desconhecido")
}
callback.onComplete()
}
override fun onFailure(call: Call<List<String>>, t: Throwable) {
callback.onError(t.message ?: "Erro interno")
callback.onComplete()
}
})
}
} | JokerApp/app/src/main/java/com/example/jokerapp/data/CategoryRemoteDataSource.kt | 869892161 |
package com.example.jokerapp.data
import com.example.jokerapp.model.Joke
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class JokeDayRemoteDataSource {
fun findRandom(callback: JokeCallBack) {
HTTPClient.retrofit()
.create(ChuckNorrisAPI::class.java)
.findRandom()
.enqueue(object : Callback<Joke>{
override fun onResponse(call: Call<Joke>, response: Response<Joke>) {
if (response.isSuccessful){
val joke = response.body()
callback.onSuccess(joke ?: throw RuntimeException("Piada não encontrada"))
} else {
val error = response.errorBody()?.string()
callback.onError(error?: "Erro desconhecido")
}
callback.onComplete()
}
override fun onFailure(call: Call<Joke>, t: Throwable) {
callback.onError(t.message ?: "Erro interno")
callback.onComplete()
}
})
}
} | JokerApp/app/src/main/java/com/example/jokerapp/data/JokeDayRemoteDataSource.kt | 984735251 |
package com.example.jokerapp.presentation
import com.example.jokerapp.data.JokeCallBack
import com.example.jokerapp.data.JokeDayRemoteDataSource
import com.example.jokerapp.model.Joke
import com.example.jokerapp.view.JokeDayFragment
class JokeDayPresenter(
private val view: JokeDayFragment,
private val dataSource: JokeDayRemoteDataSource = JokeDayRemoteDataSource()
) : JokeCallBack {
fun findRandom(){
view.showProgress()
dataSource.findRandom(this)
}
override fun onSuccess(response: Joke) {
view.showJoke(response)
}
override fun onError(response: String) {
view.showFailure(response)
}
override fun onComplete() {
view.hideProgress()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/presentation/JokeDayPresenter.kt | 292056466 |
package com.example.jokerapp.presentation
import android.graphics.Color
import com.example.jokerapp.data.CategoryRemoteDataSource
import com.example.jokerapp.data.ListCategoryCallback
import com.example.jokerapp.model.Category
import com.example.jokerapp.view.HomeFragment
class HomePresenter(
private val view: HomeFragment,
private val dataSource: CategoryRemoteDataSource = CategoryRemoteDataSource()
) : ListCategoryCallback {
fun findAllCategories() {
view.showProgress()
dataSource.findAllCategories(this)
}
override fun onSuccess(response: List<String>) {
val start = 40
val end = 190
val diff = (end - start) / response.size
val categories = response.mapIndexed() { index, s ->
val hsv = floatArrayOf(
start + (diff * index).toFloat(),
100.0f,
100.0f
)
Category(s, Color.HSVToColor(hsv).toLong())
}
view.showCategories(categories)
}
override fun onError(response: String) {
view.showFailure(response)
view.hideProgress()
}
override fun onComplete() {
view.hideProgress()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/presentation/HomePresenter.kt | 421652067 |
package com.example.jokerapp.presentation
import com.example.jokerapp.data.JokeCallBack
import com.example.jokerapp.data.JokeRemoteDataSource
import com.example.jokerapp.model.Joke
import com.example.jokerapp.view.JokeFragment
class JokePresenter(
private val view: JokeFragment ,
private val dataSource: JokeRemoteDataSource = JokeRemoteDataSource()
) : JokeCallBack {
fun findBy(categoryName: String){
view.showProgress()
dataSource.findBy(categoryName, this)
}
override fun onSuccess(response: Joke) {
view.showJoke(response)
}
override fun onError(response: String) {
view.showFailure(response)
}
override fun onComplete() {
view.hideProgress()
}
} | JokerApp/app/src/main/java/com/example/jokerapp/presentation/JokePresenter.kt | 2128856023 |
package com.eygraber.vice.portal
import androidx.compose.runtime.Composable
import com.eygraber.portal.compose.ComposePortal
import com.eygraber.vice.ViceCompositor
import com.eygraber.vice.ViceContainer
import com.eygraber.vice.ViceEffects
import com.eygraber.vice.ViceView
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
public abstract class VicePortal<K, V, I, C, E, S> : ComposePortal<K>, ViceContainer<V, I, C, E, S>
where V : ViceView<I, S>, C : ViceCompositor<I, S>, E : ViceEffects {
override val intents: SharedFlow<I> = MutableSharedFlow(extraBufferCapacity = 64)
@Composable
public final override fun Render() {
Vice()
}
}
| vice/vice-portal/src/commonMain/kotlin/com/eygraber/vice/portal/VicePortal.kt | 4256290178 |
package com.eygraber.vice
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
public abstract class ViceEffects {
internal fun initialize(scope: CoroutineScope) {
scope.onInitialized()
}
protected abstract fun CoroutineScope.onInitialized()
}
@Composable
internal fun ViceEffects.Launch() {
LaunchedEffect(Unit) {
@Suppress("InjectDispatcher")
launch(Dispatchers.Default) {
initialize(this)
}
}
}
| vice/vice-core/src/commonMain/kotlin/com/eygraber/vice/ViceEffects.kt | 3436960006 |
package com.eygraber.vice
import androidx.compose.runtime.Composable
public interface ViceView<Intent, State> {
@Composable
public fun Render(state: State, onIntent: (Intent) -> Unit)
}
| vice/vice-core/src/commonMain/kotlin/com/eygraber/vice/ViceView.kt | 1999369510 |
package com.eygraber.vice
import androidx.compose.runtime.Composable
public abstract class ViceCompositor<Intent, State> {
@Composable
public abstract fun composite(): State
internal suspend fun internalOnIntent(intent: Intent) = onIntent(intent)
protected open suspend fun onIntent(intent: Intent) {}
@Composable
internal fun internalIsBackHandlerEnabled(): Boolean = isBackHandlerEnabled()
@Composable
protected open fun isBackHandlerEnabled(): Boolean = false
internal fun internalOnBackPressed(emitIntent: (Intent) -> Unit) = onBackPressed(emitIntent)
protected open fun onBackPressed(emitIntent: (Intent) -> Unit) {}
}
| vice/vice-core/src/commonMain/kotlin/com/eygraber/vice/ViceCompositor.kt | 861485155 |
package com.eygraber.vice
import androidx.compose.runtime.Composable
public interface ViceSource<T> {
@Composable
public fun currentState(): T
}
public fun <T> ViceSource(state: @Composable () -> T): ViceSource<T> = object : ViceSource<T> {
@Composable
override fun currentState() = state()
}
| vice/vice-core/src/commonMain/kotlin/com/eygraber/vice/ViceSource.kt | 1816282796 |
package com.eygraber.vice
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
public interface ViceContainer<V, I, C, E, S>
where V : ViceView<I, S>, C : ViceCompositor<I, S>, E : ViceEffects {
public val view: V
public val intents: SharedFlow<I>
public val compositor: C
public val effects: E
@Composable
public fun OnBackPressedHandler(enabled: Boolean, onBackPressed: () -> Unit)
@Composable
public fun Vice() {
RunVice(
view = view,
intents = intents as MutableSharedFlow<I>,
compositor = compositor,
effects = effects,
onBackPressedHandler = { enabled, onBackPressed ->
OnBackPressedHandler(enabled, onBackPressed)
},
)
}
}
@Composable
private fun <I, S> RunVice(
view: ViceView<I, S>,
intents: MutableSharedFlow<I>,
compositor: ViceCompositor<I, S>,
effects: ViceEffects,
onBackPressedHandler: @Composable (Boolean, () -> Unit) -> Unit,
) {
val scope = rememberCoroutineScope {
Dispatchers.Main.immediate
}
onBackPressedHandler(compositor.internalIsBackHandlerEnabled()) {
compositor.internalOnBackPressed { intent ->
// this is synchronous because the dispatcher is Main.immediate
scope.launch {
compositor.internalOnIntent(intent)
}
intents.tryEmit(intent)
}
}
ViceUdf(
view,
intents,
compositor,
effects,
scope,
)
}
@Suppress("NOTHING_TO_INLINE")
@Composable
private inline fun <I, S> ViceUdf(
view: ViceView<I, S>,
intents: SharedFlow<I>,
compositor: ViceCompositor<I, S>,
effects: ViceEffects,
scope: CoroutineScope,
) {
effects.Launch()
val state = compositor.composite()
val intentHandler: (I) -> Unit = remember(scope, compositor, intents) {
{ intent: I ->
// this is synchronous because the dispatcher is Main.immediate
scope.launch {
compositor.internalOnIntent(intent)
}
(intents as MutableSharedFlow<I>).tryEmit(intent)
}
}
view.Render(state, intentHandler)
}
| vice/vice-core/src/commonMain/kotlin/com/eygraber/vice/ViceContainer.kt | 3567203567 |
package com.eygraber.vice
import platform.Foundation.NSDate
import platform.Foundation.timeIntervalSince1970
internal actual fun epochMillis(): Long = (NSDate().timeIntervalSince1970 * 1_000).toLong()
| vice/vice-sources/src/iosMain/kotlin/com/eygraber/vice/EpochMillis.ios.kt | 531738167 |
package com.eygraber.vice.loadable
import androidx.compose.runtime.Immutable
@Immutable
public sealed interface ViceLoadable<T> {
public val value: T
@Immutable
public data class Loading<T>(override val value: T) : ViceLoadable<T>
@Immutable
public data class Loaded<T>(override val value: T) : ViceLoadable<T>
}
public inline val ViceLoadable<*>.isLoading: Boolean get() = this is ViceLoadable.Loading
public inline val ViceLoadable<*>.isNotLoading: Boolean get() = this !is ViceLoadable.Loading
public inline val ViceLoadable<*>.isLoaded: Boolean get() = this is ViceLoadable.Loaded
public inline val ViceLoadable<*>.isNotLoaded: Boolean get() = this !is ViceLoadable.Loaded
public inline val <T> ViceLoadable<T>.loadedValueOrNull: T? get() = when(this) {
is ViceLoadable.Loading -> null
is ViceLoadable.Loaded -> value
}
public inline fun <T, R> ViceLoadable<T>.map(
mapper: (T) -> ViceLoadable<R>,
): ViceLoadable<R> = mapper(value)
public inline fun <T, R> ViceLoadable<T>.mapValue(
mapper: (T) -> R,
): ViceLoadable<R> = when(this) {
is ViceLoadable.Loading -> ViceLoadable.Loading(mapper(value))
is ViceLoadable.Loaded -> ViceLoadable.Loaded(mapper(value))
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/loadable/ViceLoadable.kt | 1630102784 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.snapshotFlow
import com.eygraber.vice.ViceSource
import kotlinx.coroutines.flow.Flow
public abstract class DerivedStateSource<T> : ViceSource<T>, State<T> {
protected abstract fun deriveState(): T
private val state by lazy {
derivedStateOf(::deriveState)
}
public val updates: Flow<T> get() = snapshotFlow { state.value }
override val value: T get() = state.value
@Composable
@ReadOnlyComposable
final override fun currentState(): T = state.value
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/DerivedStateSource.kt | 3806682966 |
package com.eygraber.vice.sources
import com.eygraber.vice.epochMillis
import com.eygraber.vice.loadable.ViceLoadable
import com.eygraber.vice.loadable.isLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
public abstract class LoadableFlowSource<T> : StateFlowSource<ViceLoadable<T>>() {
private val mutableFlow by lazy {
MutableStateFlow<ViceLoadable<T>>(ViceLoadable.Loading(placeholder))
}
override val flow: StateFlow<ViceLoadable<T>> by lazy { mutableFlow }
protected abstract val dataFlow: Flow<T>
protected abstract val placeholder: T
protected open val initialLoadingThresholdMillis: Int = 200
protected open val minLoadingDurationMillis: Long = 1_000L
override suspend fun onAttached(scope: CoroutineScope) {
val initialLoadingThreshold = epochMillis() + initialLoadingThresholdMillis
val minLoadingThreshold = initialLoadingThreshold + minLoadingDurationMillis
dataFlow.collect { value ->
if(flow.value.isLoading) {
val now = epochMillis()
if(now in initialLoadingThreshold..<minLoadingThreshold) {
delay(minLoadingThreshold - now)
}
}
mutableFlow.value = ViceLoadable.Loaded(value)
}
}
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/LoadableFlowSource.kt | 2064038510 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import com.eygraber.vice.ViceSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
public abstract class StateFlowSource<T> : ViceSource<T>, State<T> {
protected abstract val flow: StateFlow<T>
protected abstract suspend fun onAttached(scope: CoroutineScope)
override val value: T get() = flow.value
@Composable
final override fun currentState(): T {
LaunchedEffect(Unit) {
onAttached(this)
}
return flow.collectAsStateWithLifecycle().value
}
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/StateFlowSource.kt | 992944515 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@Composable
internal expect fun <T> StateFlow<T>.collectAsStateWithLifecycle(): State<T>
@Composable
internal expect fun <T> Flow<T>.collectAsStateWithLifecycle(initial: T): State<T>
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/CollectAsState.kt | 2653051236 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import com.eygraber.vice.ViceSource
import kotlinx.coroutines.flow.Flow
public abstract class FlowSource<T> : ViceSource<T> {
protected abstract val flow: Flow<T>
protected abstract val initial: T
@Composable
final override fun currentState(): T = flow.collectAsStateWithLifecycle(initial).value
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/FlowSource.kt | 3397452671 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshotFlow
import com.eygraber.vice.ViceSource
import kotlinx.coroutines.flow.Flow
public abstract class MutableStateSource<T> : ViceSource<T>, State<T> {
private val state by lazy {
mutableStateOf(initial)
}
public val updates: Flow<T> get() = snapshotFlow { state.value }
override val value: T get() = state.value
protected abstract val initial: T
protected fun update(value: T) {
state.value = value
}
@Composable
@ReadOnlyComposable
final override fun currentState(): T = state.value
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/MutableStateSource.kt | 377285178 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshotFlow
import com.eygraber.vice.ViceSource
import kotlinx.coroutines.flow.Flow
public abstract class MoleculeStateSource<T> : ViceSource<T>, State<T> {
private val state by lazy {
mutableStateOf(initial)
}
public val updates: Flow<T> get() = snapshotFlow { state.value }
override val value: T get() = state.value
protected abstract val initial: T
@Composable
@ReadOnlyComposable
protected abstract fun calculate(): T
@Composable
@ReadOnlyComposable
final override fun currentState(): T {
state.value = calculate()
return state.value
}
}
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/MoleculeStateSource.kt | 2378914135 |
package com.eygraber.vice
internal expect fun epochMillis(): Long
| vice/vice-sources/src/commonMain/kotlin/com/eygraber/vice/EpochMillis.kt | 892731555 |
package com.eygraber.vice.sources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@Composable
internal actual fun <T> StateFlow<T>.collectAsStateWithLifecycle(): State<T> = collectAsState()
@Composable
internal actual fun <T> Flow<T>.collectAsStateWithLifecycle(initial: T): State<T> = collectAsState(initial)
| vice/vice-sources/src/notAndroidMain/kotlin/com/eygraber/vice/sources/CollectAsState.notandroid.kt | 561509239 |
package com.eygraber.vice
internal actual fun epochMillis(): Long = System.currentTimeMillis()
| vice/vice-sources/src/jvmMain/kotlin/com/eygraber/vice/EpochMillis.jvm.kt | 2668680902 |
package com.eygraber.vice
@JsFun("() => { return Date.now(); }")
private external fun now(): Double
internal actual fun epochMillis(): Long = now().toLong()
| vice/vice-sources/src/wasmJsMain/kotlin/com/eygraber/vice/EpochMillis.wasmJs.kt | 4033136798 |