content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.reddit.backend.redditbackend.user.internal.exception
class EmailExistsException(email: String): RuntimeException(MESSAGE.format(email)) {
companion object {
const val MESSAGE = "Email %s already exists."
}
} | reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/user/internal/exception/EmailExistsException.kt | 3945559563 |
package com.reddit.backend.redditbackend.user.internal.exception
class InvalidPasswordException: RuntimeException(MESSAGE) {
companion object {
const val MESSAGE = "Invalid Password."
}
} | reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/user/internal/exception/InvalidPasswordException.kt | 204467991 |
package com.reddit.backend.redditbackend.user.internal.exception
class UsernameExistsException(username: String): RuntimeException(MESSAGE.format(username)) {
companion object {
const val MESSAGE = "Username %s already exists."
}
} | reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/user/internal/exception/UsernameExistsException.kt | 1209771331 |
package com.reddit.backend.redditbackend.user.internal.exception
class PasswordMissMatchException: RuntimeException(MESSAGE) {
companion object {
const val MESSAGE = "Wrong password."
}
} | reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/user/internal/exception/PasswordMissMatchException.kt | 2662363704 |
package com.reddit.backend.redditbackend.user.internal.exception
class UserNotFoundException: RuntimeException(MESSAGE) {
companion object {
const val MESSAGE = "User not found."
}
} | reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/user/internal/exception/UserNotFoundException.kt | 3362961492 |
package com.reddit.backend.redditbackend
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
import org.springframework.context.annotation.ComponentScan
@SpringBootApplication
@ComponentScan(basePackages = [
"com.reddit.backend.redditbackend.user",
"com.reddit.backend.redditbackend.core"
])
class RedditBackendApplication
fun main(args: Array<String>) {
runApplication<RedditBackendApplication>(*args)
}
| reddit-poc/src/main/kotlin/com/reddit/backend/redditbackend/RedditBackendApplication.kt | 3493308606 |
package arrays
import org.junit.jupiter.api.Assertions.*
class PrimesTest {
@org.junit.jupiter.api.Test
fun primes() {
val expected = listOf(2, 3, 5, 7, 11, 13, 17, 19)
val actual = Primes.primes(20)
assertEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/PrimesTest.kt | 4095222003 |
package arrays
import org.junit.jupiter.api.Assertions.*
class ShortestDistanceTest {
@org.junit.jupiter.api.Test
fun shortestDistance() {
val words = arrayOf("a", "c", "b", "b", "a")
val word1 = "a"
val word2 = "b"
val expected = 1
val actual = ShortestDistance.shortestDistance(words, word1, word2)
assertEquals(expected, actual)
}
@org.junit.jupiter.api.Test
fun shortestDistance2() {
val words = arrayOf("a", "c", "b", "b")
val word1 = "a"
val word2 = "b"
val expected = 2
val actual = ShortestDistance.shortestDistance(words, word1, word2)
assertEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/ShortestDistanceTest.kt | 2415029144 |
package arrays
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class ValidSudokuTest {
@Test
fun validSudoku() {
val board = arrayOf(
intArrayOf(5, 3, 0, 0, 7, 0, 0, 0, 0),
intArrayOf(6, 0, 0, 1, 9, 5, 0, 0, 0),
intArrayOf(0, 9, 8, 0, 0, 0, 0, 6, 0),
intArrayOf(8, 0, 0, 0, 6, 0, 0, 0, 3),
intArrayOf(4, 0, 0, 8, 0, 3, 0, 0, 1),
intArrayOf(7, 0, 0, 0, 2, 0, 0, 0, 6),
intArrayOf(0, 6, 0, 0, 0, 0, 2, 8, 0),
intArrayOf(0, 0, 0, 4, 1, 9, 0, 0, 5),
intArrayOf(0, 0, 0, 0, 8, 0, 0, 7, 9)
)
val expected = true
val actual = ValidSudoku.validSudoku(board)
assertEquals(expected, actual)
}
@Test
fun validSudoku2() {
val board = arrayOf(
intArrayOf(8, 3, 0, 0, 7, 0, 0, 0, 0),
intArrayOf(6, 0, 0, 1, 9, 5, 0, 0, 0),
intArrayOf(0, 9, 8, 0, 0, 0, 0, 6, 0),
intArrayOf(8, 0, 0, 0, 6, 0, 0, 0, 3),
intArrayOf(4, 0, 0, 8, 0, 3, 0, 0, 1),
intArrayOf(7, 0, 0, 0, 2, 0, 0, 0, 6),
intArrayOf(0, 6, 0, 0, 0, 0, 2, 8, 0),
intArrayOf(0, 0, 0, 4, 1, 9, 0, 0, 5),
intArrayOf(0, 0, 0, 0, 8, 0, 0, 7, 9)
)
val expected = false
val actual = ValidSudoku.validSudoku(board)
assertEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/ValidSudokuTest.kt | 4248271349 |
package arrays
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class TwoDMatrixTest {
@Test
fun rotate2DMatrix() {
val matrix = arrayOf(
intArrayOf(1, 2, 3, 4),
intArrayOf(5, 6, 7, 8),
intArrayOf(9, 10, 11, 12),
intArrayOf(13, 14, 15, 16)
)
val expected = arrayOf(
intArrayOf(13, 9, 5, 1),
intArrayOf(14, 10, 6, 2),
intArrayOf(15, 11, 7, 3),
intArrayOf(16, 12, 8, 4)
)
val actual = TwoDMatrix.rotate2DMatrix(matrix)
actual.forEach { row -> row.forEach { print("$it ") }; println() }
assertArrayEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/TwoDMatrixTest.kt | 4003551507 |
package arrays
import org.junit.jupiter.api.Assertions.*
class SpiralTraversalMatrixTest {
@org.junit.jupiter.api.Test
fun spiralTraversal() {
val matrix = arrayOf(
arrayOf(1, 2, 3, 4, 5),
arrayOf(6, 7, 8, 9, 10),
arrayOf(11, 12, 13, 14, 15),
arrayOf(16, 17, 18, 19, 20)
)
val expected = listOf(1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12)
val actual = SpiralTraversalMatrix.spiralTraversal(matrix)
assertEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/SpiralTraversalMatrixTest.kt | 173761132 |
package arrays
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class ThreeSumTest {
@Test
fun threeSum() {
val nums = listOf(-1, 0, 1, 2, -1, -4)
val expected = listOf(
listOf(-1, -1, 2),
listOf(-1, 0, 1)
)
val actual = ThreeSum.threeSum(nums)
assertEquals(expected.size, actual.size)
assert(expected == actual)
}
@Test
fun threeSum2() {
val nums = listOf(0, 0, 0, 0)
val expected = listOf(
listOf(0, 0, 0)
)
val actual = ThreeSum.threeSum(nums)
assertEquals(expected.size, actual.size)
assert(expected == actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/arrays/ThreeSumTest.kt | 3034448106 |
package graphs
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import graphs.CloneGraph.Node
class CloneGraphTest {
private lateinit var node1: Node
private lateinit var node2: Node
private lateinit var node3: Node
private lateinit var node4: Node
@BeforeEach
fun setup() {
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.neighbors.add(node2)
node1.neighbors.add(node3)
node2.neighbors.add(node1)
node2.neighbors.add(node3)
node3.neighbors.add(node2)
node3.neighbors.add(node1)
node4.neighbors.add(node1)
node4.neighbors.add(node3)
}
@Test
fun cloneGraphDFS() {
val actual = CloneGraph.cloneGraphDFS(node1)
assertEquals(node1.`val`, actual?.`val`)
assertEquals(node1.neighbors.size, actual?.neighbors?.size)
node1.neighbors.forEach { expectedNeighbor ->
assertTrue(actual?.neighbors?.any { actualNeighbor ->
expectedNeighbor?.`val` == actualNeighbor?.`val`
} ?: false)
}
}
@Test
fun cloneGraphDFSRecursive() {
val actual = CloneGraph.cloneGraphDFSRecursive(node1)
assertEquals(node1.`val`, actual?.`val`)
assertEquals(node1.neighbors.size, actual?.neighbors?.size)
node1.neighbors.forEach { expectedNeighbor ->
assertTrue(actual?.neighbors?.any { actualNeighbor ->
expectedNeighbor?.`val` == actualNeighbor?.`val`
} ?: false)
}
}
@Test
fun cloneGraphBFS() {
val actual = CloneGraph.cloneGraphBFS(node1)
assertEquals(node1.`val`, actual?.`val`)
assertEquals(node1.neighbors.size, actual?.neighbors?.size)
node1.neighbors.forEach { expectedNeighbor ->
assertTrue(actual?.neighbors?.any { actualNeighbor ->
expectedNeighbor?.`val` == actualNeighbor?.`val`
} ?: false)
}
}
} | The-Kotlin-Dojo/src/test/kotlin/graphs/CloneGraphTest.kt | 3764977488 |
package graphs
import org.junit.jupiter.api.Assertions.*
class KeysAndRoomsTest {
@org.junit.jupiter.api.Test
fun canVisitAllRooms() {
val rooms = listOf(
listOf(1),
listOf(2),
listOf(3),
listOf()
)
val expected = true
val actual = KeysAndRooms.canVisitAllRoomsDFS(rooms)
assertEquals(expected, actual)
}
@org.junit.jupiter.api.Test
fun canVisitAllRooms2() {
val rooms = listOf(
listOf(1, 3),
listOf(3, 0, 1),
listOf(2),
listOf(0)
)
val expected = false
val actual = KeysAndRooms.canVisitAllRoomsDFS(rooms)
assertEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/graphs/KeysAndRoomsTest.kt | 2269645184 |
package graphs
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class FloodFillTest {
@Test
fun floodFillDFS() {
val image = arrayOf(
intArrayOf(1, 1, 1),
intArrayOf(1, 1, 0),
intArrayOf(1, 0, 1)
)
val sr = 1
val sc = 1
val newColor = 2
val expected = arrayOf(
intArrayOf(2, 2, 2),
intArrayOf(2, 2, 0),
intArrayOf(2, 0, 1)
)
val actual = FloodFill.floodFillDFS(image, sr, sc, newColor)
assertArrayEquals(expected, actual)
}
@Test
fun floodFillDFSRecursive() {
val image = arrayOf(
intArrayOf(1, 1, 1),
intArrayOf(1, 1, 0),
intArrayOf(1, 0, 1)
)
val sr = 1
val sc = 1
val newColor = 2
val expected = arrayOf(
intArrayOf(2, 2, 2),
intArrayOf(2, 2, 0),
intArrayOf(2, 0, 1)
)
val actual = FloodFill.floodFillDFSRecursive(image, sr, sc, newColor)
assertArrayEquals(expected, actual)
}
@Test
fun floodFillBFS() {
val image = arrayOf(
intArrayOf(1, 1, 1),
intArrayOf(1, 1, 0),
intArrayOf(1, 0, 1)
)
val sr = 1
val sc = 1
val newColor = 2
val expected = arrayOf(
intArrayOf(2, 2, 2),
intArrayOf(2, 2, 0),
intArrayOf(2, 0, 1)
)
val actual = FloodFill.floodFillBFS(image, sr, sc, newColor)
assertArrayEquals(expected, actual)
}
} | The-Kotlin-Dojo/src/test/kotlin/graphs/FloodFillTest.kt | 2588006924 |
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
} | The-Kotlin-Dojo/src/main/kotlin/Main.kt | 784151555 |
package arrays
import kotlin.math.abs
/**
* Given a list of words, and two words word1 and word2, return the shortest distance between these two words in the
* list.
*/
object ShortestDistance {
fun shortestDistance(words: Array<String>, word1: String, word2: String): Int {
var shortest = Int.MAX_VALUE
var index1 = -1
var index2 = -1
for (i in words.indices) {
if (words[i] == word1) {
index1 = i
if (index2 != -1) shortest = shortest.coerceAtMost(abs(index1 - index2))
} else if (words[i] == word2) {
index2 = i
if (index1 != -1) shortest = shortest.coerceAtMost(abs(index1 - index2))
}
}
return shortest
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/ShortestDistance.kt | 1153563596 |
package arrays
/**
* Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following
* rules:
*
* 1. Each row must contain the digits 1-9 without repetition.
* 2. Each column must contain the digits 1-9 without repetition.
* 3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
*
* Note:
*
* 1. A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* 2. Only the filled cells need to be validated according to the mentioned rules.
*/
object ValidSudoku {
fun validSudoku(board: Array<IntArray>): Boolean {
val filled = hashSetOf<String>()
for (x in 0 until board.size) {
for (y in 0 until board[0].size) {
val cell = board[x][y]
if (cell == 0) continue
val rowSig = "R${x}-$cell"
val colSig = "C${y}-$cell"
val gridSig = "GR${x/3}GC${y/3}-$cell"
when {
!filled.add(rowSig) ||
!filled.add(colSig) ||
!filled.add(gridSig) -> return false
}
}
}
return true
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/ValidSudoku.kt | 1359020651 |
package arrays
/**
* Given a matrix of m x n elements (m rows, n columns), return a spiral readout of its values going clockwise
* & moving inward layer by layer (starting from the top-left).
*/
object SpiralTraversalMatrix {
fun spiralTraversal(matrix: Array<Array<Int>>): List<Int> {
val result = mutableListOf<Int>()
val rows = matrix.size
val cols = matrix.first().size
if (rows < 2) return matrix.first().asList()
if (cols < 2) {
matrix.forEach { result.add(it.first()) }
return result
}
result.addAll(matrix[0])
for (i in 1 until rows) {
result.add(matrix[i][cols - 1])
}
for (i in cols-2 downTo 0) {
result.add(matrix[rows - 1][i])
}
for (i in rows-2 downTo 1) {
result.add(matrix[i][0])
}
val subMatrix = mutableListOf<Array<Int>>()
matrix.slice(1 until rows-1).forEach {
subMatrix.add(it.slice(1 until cols-1).toTypedArray())
}
if (subMatrix.isEmpty()) return result
result.addAll(spiralTraversal(subMatrix.toTypedArray()))
return result
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/SpiralTraversalMatrix.kt | 2797736212 |
package arrays
/**
* Given an integer n, return the number of prime numbers that are strictly less than n.
*/
object Primes {
fun primes(n: Int): List<Int> {
val result = mutableListOf<Int>()
for (i in 2..n) result.add(i)
var i = 0
while (i < result.size) {
result.removeIf { it != result[i] && it % result[i] == 0 }
i++
}
return result
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/Primes.kt | 3079959823 |
package arrays
/**
* Given an n x n two-dimensional matrix of numbers, rotate the matrix 90 degrees to the right (clockwise).
*/
object TwoDMatrix {
fun rotate2DMatrix(matrix: Array<IntArray>): Array<IntArray> {
val lastIndex: Int = matrix.size - 1
val rotations = lastIndex / 2
for (rotation in 0..rotations) {
for (i in rotation until lastIndex - rotation) {
val top = matrix[rotation][i]
val right = matrix[i][lastIndex - rotation]
val bottom = matrix[lastIndex - rotation][lastIndex - i]
val left = matrix[lastIndex - i][rotation]
matrix[i][lastIndex-rotation] = top
matrix[lastIndex-rotation][lastIndex-i] = right
matrix[lastIndex-i][rotation] = bottom
matrix[rotation][i] = left
}
}
return matrix
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/TwoDMatrix.kt | 4144277655 |
package arrays
/**
* Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique
* triplets in the array which gives the sum of zero.
*/
object ThreeSum {
private fun twoSum(target: Int, nums: List<Int>, s: Int): List<Pair<Int, Int>> {
var start = s
var end = nums.size - 1
val result = mutableListOf<Pair<Int, Int>>()
while (start < end) {
val sum = nums[start] + nums[end]
if (sum == target) result.add(Pair(nums[start], nums[end]))
if (sum > target) end-- else start++
}
return result
}
fun threeSum(list: List<Int>): List<List<Int>> {
val result = hashSetOf<List<Int>>()
val sorted = list.sorted()
sorted.forEachIndexed { i, n ->
twoSum(0-n, sorted, i+1).forEach {
result.add(listOf(n, it.first, it.second))
}
}
return result.toList()
}
} | The-Kotlin-Dojo/src/main/kotlin/arrays/ThreeSum.kt | 3188923330 |
package graphs
import graphs.CloneGraph.Node
/**
* Given a reference of a node in a connected undirected graph.
* Return a deep copy (clone) of the graph.
* Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
*/
object CloneGraph {
class Node(var `val`: Int, var neighbors: MutableList<Node?> = mutableListOf())
fun cloneGraphDFS(node: Node?): Node? {
if (node == null) return null
val clone = mutableMapOf<Node, Node>()
val stack = ArrayDeque<Node>()
stack.add(node)
while (stack.isNotEmpty()) {
val current = stack.removeLast()
if (!clone.contains(current)) clone[current] = Node(current.`val`)
current.neighbors.filterNotNull().forEach {
if (!clone.contains(it)) {
clone[it] = Node(it.`val`)
stack.add(it)
}
clone[current]?.neighbors?.add(clone[it])
}
}
return clone[node]
}
fun cloneGraphDFSRecursive(node: Node?): Node? {
val clone = mutableMapOf<Node, Node>()
return dfs(node, clone)
}
private fun dfs(node: Node?, clone: MutableMap<Node, Node>): Node? {
return when {
node == null -> null
clone.contains(node) -> clone[node]
else -> {
clone[node] = Node(node.`val`)
node.neighbors.forEach {
clone[node]?.neighbors?.add(dfs(it, clone))
}
clone[node]
}
}
}
fun cloneGraphBFS(node: Node?): Node? {
if (node == null) return null
val clone = mutableMapOf<Node, Node>()
val queue = ArrayDeque<Node>()
queue.addLast(node)
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (!clone.contains(current)) clone[current] = Node(current.`val`)
current.neighbors.filterNotNull().forEach {
if (!clone.contains(it)) {
clone[it] = Node(it.`val`)
queue.add(it)
}
clone[current]?.neighbors?.add(clone[it])
}
}
return clone[node]
}
/**
* This is a recursive solution to the BFS problem. It is not as efficient as the iterative solution.
* It is included here for completeness. It is not tested in the unit tests because it can cause
* stack overflow errors.
*/
fun cloneGraphBFSRecursive(node: Node?): Node? {
val clone = mutableMapOf<Node, Node>()
return bfs(node, clone)
}
private fun bfs(node: Node?, clone: MutableMap<Node, Node>, queue: ArrayDeque<Node> = ArrayDeque()): Node? {
if (node == null) return null
clone[node] = Node(node.`val`)
for (neighbor in node.neighbors) {
neighbor?.let {
queue.add(it)
}
}
if (queue.isNotEmpty()) bfs(queue.removeFirst(), clone, queue)
return clone[node]
}
} | The-Kotlin-Dojo/src/main/kotlin/graphs/CloneGraph.kt | 3605861623 |
package graphs
/**
* There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1,
* and each room may have some keys to access the next room. Formally, each room i has a list of
* keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.
* A key rooms[i][j] = v opens the room with number v. Initially, all the rooms start locked
* (except for room 0). You can walk back and forth between rooms freely. Write a function that returns
* true if and only if you can enter every room.
*/
object KeysAndRooms {
fun canVisitAllRoomsDFS(rooms: List<List<Int>>): Boolean {
val seen = mutableSetOf<Int>()
val stack = mutableListOf<Int>()
stack.add(0)
while (stack.isNotEmpty()) {
val room = stack.removeAt(0)
if (seen.contains(room)) continue
seen.add(room)
stack.addAll(rooms[room])
}
return seen.size == rooms.size
}
} | The-Kotlin-Dojo/src/main/kotlin/graphs/KeysAndRooms.kt | 710454283 |
package graphs
import java.awt.Point
import java.util.Stack
/**
* An image is represented by a 2-D array of integers, each integer representing the pixel value of the image
* (from 0 to 65535).
*
* Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel
* value newColor, "flood fill" the image.
*
* To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the
* starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those
* pixels (also with the same color as the starting pixel), and so on. Replace the color of all the
* aforementioned pixels with the newColor.
*
* At the end, return the modified image.
*/
object FloodFill {
fun floodFillDFS(image: Array<IntArray>, sr: Int, sc: Int, color: Int): Array<IntArray> {
val oldColor = image[sr][sc]
if (oldColor == color) return image
val stack = Stack<Point>()
stack.push(Point(sc, sr))
while (stack.isNotEmpty()) {
val pixel = stack.pop()
if (pixel.x in image.indices && pixel.y in image.indices && image[pixel.x][pixel.y] == oldColor) {
image[pixel.x][pixel.y] = color
listOf(
Point(pixel.x+1, pixel.y),
Point(pixel.x-1, pixel.y),
Point(pixel.x, pixel.y+1),
Point(pixel.x, pixel.y-1)
).forEach { stack.push(it) }
}
}
return image
}
fun floodFillDFSRecursive(image: Array<IntArray>, sr: Int, sc: Int, color: Int): Array<IntArray> {
val oldColor = image[sr][sc]
if (oldColor == color) return image
tailrec fun dfs(sr: Int, sc: Int) {
if (sr in image.indices && sc in image[0].indices && image[sr][sc] == oldColor) {
image[sr][sc] = color
dfs(sr+1, sc)
dfs(sr-1, sc)
dfs(sr, sc+1)
dfs(sr, sc-1)
}
}
dfs(sr, sc)
return image
}
fun floodFillBFS(image: Array<IntArray>, sr: Int, sc: Int, color: Int): Array<IntArray> {
val oldColor = image[sr][sc]
if (oldColor == color) return image
val queue = ArrayDeque<Point>()
queue.add(Point(sr, sc))
while (queue.isNotEmpty()) {
val pixel = queue.removeFirst()
if (pixel.x in image.indices && pixel.y in image.indices && image[pixel.x][pixel.y] == oldColor) {
image[pixel.x][pixel.y] = color
listOf(
Point(pixel.x + 1, pixel.y),
Point(pixel.x - 1, pixel.y),
Point(pixel.x, pixel.y + 1),
Point(pixel.x, pixel.y - 1)
).forEach { queue.add(it) }
}
}
return image
}
} | The-Kotlin-Dojo/src/main/kotlin/graphs/FloodFill.kt | 3384239162 |
package com.example.bitfitp1
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.bitfitp1", appContext.packageName)
}
} | BitFitp1/app/src/androidTest/java/com/example/bitfitp1/ExampleInstrumentedTest.kt | 406140112 |
package com.example.bitfitp1
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)
}
} | BitFitp1/app/src/test/java/com/example/bitfitp1/ExampleUnitTest.kt | 341657061 |
package com.example.bitfitp1
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: NutritionViewModel
private lateinit var adapter: NutritionEntryAdapter
private lateinit var mealTypeEditText: EditText
private lateinit var caloriesEditText: EditText
private lateinit var addButton: Button
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mealTypeEditText = findViewById(R.id.mealTypeEditText)
caloriesEditText = findViewById(R.id.caloriesEditText)
addButton = findViewById(R.id.addButton)
recyclerView = findViewById(R.id.recyclerView)
val dao = MyApp.database.nutritionEntryDao()
val repository = NutritionRepository(dao)
viewModel = ViewModelProvider(
this,
NutritionViewModelFactory(repository)
)[NutritionViewModel::class.java]
// Initialize RecyclerView
adapter = NutritionEntryAdapter()
recyclerView.adapter = adapter
addButton.setOnClickListener {
val mealType = mealTypeEditText.text.toString()
val calories = caloriesEditText.text.toString().toInt()
val entry = NutritionEntry(
date = System.currentTimeMillis(),
mealType = mealType,
caloriesConsumed = calories
)
viewModel.insertEntry(entry)
}
lifecycleScope.launch {
// Observe the LiveData within the activity's lifecycle
viewModel.getAllEntries().observe(this@MainActivity) { entries ->
// Update the UI with the new list of entries
adapter.submitList(entries)
}
}
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/MainActivity.kt | 3388580742 |
package com.example.bitfitp1
import android.app.Application
import androidx.room.Room
class MyApp : Application() {
companion object {
lateinit var database: AppDatabase
private set
}
override fun onCreate() {
super.onCreate()
// Initialize the database
database = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"nutrition_database"
).build()
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/MyApp.kt | 4277045892 |
package com.example.bitfitp1
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import java.sql.Date
import java.text.SimpleDateFormat
import java.util.Locale
class NutritionEntryAdapter : ListAdapter<NutritionEntry, NutritionEntryAdapter.NutritionEntryViewHolder>(NutritionEntryDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NutritionEntryViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_nutrition_entry, parent, false)
return NutritionEntryViewHolder(itemView)
}
override fun onBindViewHolder(holder: NutritionEntryViewHolder, position: Int) {
val entry = getItem(position)
holder.bind(entry)
}
inner class NutritionEntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val dateTextView: TextView = itemView.findViewById(R.id.dateTextView)
private val mealTypeTextView: TextView = itemView.findViewById(R.id.mealTypeTextView)
private val caloriesTextView: TextView = itemView.findViewById(R.id.caloriesTextView)
fun bind(entry: NutritionEntry) {
val dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.getDefault())
dateTextView.text = dateFormat.format(Date(entry.date))
mealTypeTextView.text = entry.mealType
caloriesTextView.text = entry.caloriesConsumed.toString()
}
}
}
class NutritionEntryDiffCallback : DiffUtil.ItemCallback<NutritionEntry>() {
override fun areItemsTheSame(oldItem: NutritionEntry, newItem: NutritionEntry): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: NutritionEntry, newItem: NutritionEntry): Boolean {
return oldItem == newItem
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionEntryAdapter.kt | 211703576 |
package com.example.bitfitp1
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class NutritionRepository(private val nutritionEntryDao: NutritionEntryDao) {
suspend fun getAllEntries(): LiveData<List<NutritionEntry>> {
val entriesLiveData = MutableLiveData<List<NutritionEntry>>()
val entries = nutritionEntryDao.getAllEntries()
entriesLiveData.value = entries
return entriesLiveData
}
suspend fun insertEntry(entry: NutritionEntry) {
withContext(Dispatchers.IO) {
nutritionEntryDao.insertEntry(entry)
}
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionRepository.kt | 2768007068 |
package com.example.bitfitp1
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [NutritionEntry::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun nutritionEntryDao(): NutritionEntryDao
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/AppDatabase.kt | 1436922665 |
package com.example.bitfitp1
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
class NutritionFragment : Fragment() {
private lateinit var viewModel: NutritionViewModel
private lateinit var adapter: NutritionEntryAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_nutrition, container, false)
// Initialize ViewModel
viewModel = ViewModelProvider(this)[NutritionViewModel::class.java]
// Initialize RecyclerView and Adapter
val recyclerView: RecyclerView = rootView.findViewById(R.id.recyclerView)
adapter = NutritionEntryAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
// Observe LiveData from ViewModel
// Launching a coroutine scope
lifecycleScope.launch {
viewModel.getAllEntries().observe(viewLifecycleOwner) { entries ->
// Update the UI with the new list of entries
adapter.submitList(entries)
}
}
return rootView
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionFragment.kt | 797755736 |
package com.example.bitfitp1
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "nutrition_entries")
data class NutritionEntry(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val date: Long, // timestamp
val mealType: String,
val caloriesConsumed: Int
)
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritonEntry.kt | 901245725 |
package com.example.bitfitp1
// NutritionViewModelFactory.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class NutritionViewModelFactory(private val repository: NutritionRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(NutritionViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return NutritionViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionViewModelFactory.kt | 770841979 |
package com.example.bitfitp1
import androidx.lifecycle.ViewModel
import androidx.lifecycle.LiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class NutritionViewModel(private val repository: NutritionRepository) : ViewModel() {
// Function to fetch all entries from the repository
suspend fun getAllEntries(): LiveData<List<NutritionEntry>> {
return repository.getAllEntries()
}
// Function to insert an entry using CoroutineScope
fun insertEntry(entry: NutritionEntry) {
CoroutineScope(Dispatchers.IO).launch {
repository.insertEntry(entry)
}
}
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionViewModel.kt | 3063333395 |
package com.example.bitfitp1
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface NutritionEntryDao {
@Query("SELECT * FROM nutrition_entries")
suspend fun getAllEntries(): List<NutritionEntry>
@Insert
suspend fun insertEntry(entry: NutritionEntry)
}
| BitFitp1/app/src/main/java/com/example/bitfitp1/NutritionEntryDao.kt | 3325134002 |
package com.getir.patika.shoppingapp
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.getir.patika.shoppingapp", appContext.packageName)
}
} | getir-android-bootcamp-final-project/app/src/androidTest/java/com/getir/patika/shoppingapp/ExampleInstrumentedTest.kt | 484082072 |
package com.getir.patika.shoppingapp
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)
}
} | getir-android-bootcamp-final-project/app/src/test/java/com/getir/patika/shoppingapp/ExampleUnitTest.kt | 4120350565 |
package com.getir.patika.shoppingapp.ui.productlisting
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.databinding.ItemSuggestedproductBinding
import com.getir.patika.shoppingapp.utils.Constants
import com.getir.patika.shoppingapp.utils.dpToPx
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
import com.getir.patika.shoppingapp.viewmodels.ProductViewModel
class HorizontalAdapter(private var dataList: List<Product>,
private val viewModel: ProductViewModel,
private val cartViewModel: CartViewModel) :
RecyclerView.Adapter<HorizontalAdapter.HorizontalViewHolder>() {
fun updateData(newDataList: List<Product>) {
dataList = newDataList
notifyDataSetChanged()
}
fun refreshData(){
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HorizontalViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemSuggestedproductBinding.inflate(inflater, parent, false)
return HorizontalViewHolder(binding)
}
override fun onBindViewHolder(holder: HorizontalViewHolder, position: Int) {
val item = dataList[position]
//Dynamic UI updates
holder.bind(item)
}
override fun getItemCount(): Int = dataList.size
inner class HorizontalViewHolder(private val binding: ItemSuggestedproductBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
//Set add to cart button
binding.btnPlus.setOnClickListener {
val product = dataList[bindingAdapterPosition]
cartViewModel.addToCart(product)
}
//Set remove from cart button
binding.btnDelete.setOnClickListener {
val product = dataList[bindingAdapterPosition]
if (cartViewModel.isProductInCart(product)) {
cartViewModel.removeFromCart(product)
}
}
//Set product detail button
itemView.setOnClickListener {
val product = dataList[bindingAdapterPosition]
viewModel.setSelectedProduct(product)
itemView.findNavController().navigate(R.id.action_productListingFragment_to_productDetailFragment2)
}
}
fun bind(product: Product) {
//Load image
val imgUrl = product.squareThumbnailURL ?: product.imageURL
Glide.with(itemView.context)
.load(imgUrl)
.placeholder(R.drawable.img_defproduct)
.into(binding.imgSuggestedproduct)
//Set texts
binding.txtName.text = product.name
binding.txtPrice.text = product.priceText
val attText = product.attribute ?: product.shortDescription
binding.txtAtt.text = attText
// Check if the product is in the cart
val count = cartViewModel.getProductCount(product)
if (count > 0) {
//Show item count and remove button
binding.txtCount.text = count.toString()
binding.txtCount.visibility = View.VISIBLE
binding.btnDelete.visibility = View.VISIBLE
//Change the image stroke color
val color = ContextCompat.getColor(itemView.context, R.color.purple)
binding.cardSuggestedproduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.suggesteditemstatecardview.layoutParams
layoutParam.height = Constants.PRODUCT_ITEM_CARD_MAX_HEIGHT.dpToPx(itemView.context)
binding.suggesteditemstatecardview.layoutParams = layoutParam
//Change the button image according to count of that item
if(count == 1){
binding.btnDelete.setImageResource(R.drawable.img_trash)
}else{
binding.btnDelete.setImageResource(R.drawable.img_minus)
}
// If the product is not in the cart
} else {
//Hide item count and remove button
binding.txtCount.visibility = View.GONE
binding.btnDelete.visibility = View.GONE
//Change the image stroke color to the default
val color = ContextCompat.getColor(itemView.context, R.color.stroke_grey)
binding.cardSuggestedproduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.suggesteditemstatecardview.layoutParams
layoutParam.height = Constants.PRODUCT_ITEM_CARD_MIN_HEIGHT.dpToPx(itemView.context)
binding.suggesteditemstatecardview.layoutParams = layoutParam
}
}
}
}
| getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/productlisting/HorizontalAdapter.kt | 4164694744 |
package com.getir.patika.shoppingapp.ui.productlisting
import VerticalAdapter
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.databinding.FragmentProductListingBinding
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
import com.getir.patika.shoppingapp.viewmodels.ProductViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ProductListingFragment : Fragment() {
private lateinit var binding: FragmentProductListingBinding
private val productViewModel: ProductViewModel by activityViewModels()
private val cartViewModel: CartViewModel by activityViewModels()
private lateinit var horizontalAdapter: HorizontalAdapter
private lateinit var verticalAdapter: VerticalAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentProductListingBinding.inflate(inflater,container,false)
setupToolbar()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupCartButton()
setupRecyclerViews()
observeViewModels()
}
private fun setupToolbar() {
binding.incToolbar.apply {
txtToolbar.text = getString(R.string.urunler)
btnCart.visibility = View.VISIBLE
btnClose.visibility = View.GONE
btnDeletecart.visibility = View.GONE
}
}
private fun setupCartButton() {
binding.incToolbar.btnCart.setOnClickListener {
//Check if totalPrice greater than 0 to navigate Cart Screen
if (cartViewModel.totalPrice.value!! > 0) {
findNavController().navigate(R.id.action_productListingFragment_to_shoppingCartFragment2)
} else {
showToast(getString(R.string.cart_empty))
}
}
}
private fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
private fun setupRecyclerViews() {
//Set the Vertical Recyclerview adapter and layout
binding.recVertical.layoutManager = GridLayoutManager(requireContext(), 3)
verticalAdapter = VerticalAdapter(emptyList(), productViewModel, cartViewModel)
binding.recVertical.adapter = verticalAdapter
//Set the Horizontal Recyclerview adapter and layout
horizontalAdapter = HorizontalAdapter(emptyList(), productViewModel, cartViewModel)
binding.recHorizontal.adapter = horizontalAdapter
}
private fun observeViewModels() {
//Listen to the horizontalProductList to update recyclerview Items
productViewModel.horizontalProductList.observe(viewLifecycleOwner) { horizontalList ->
horizontalAdapter.updateData(horizontalList)
}
//Listen to the verticalProductList to update recyclerview Items
productViewModel.verticalProductList.observe(viewLifecycleOwner) { verticalList ->
verticalAdapter.updateData(verticalList)
}
//Listen to the totalPrice to set text
cartViewModel.totalPrice.observe(viewLifecycleOwner) { totalPrice ->
val formattedPrice = if (totalPrice < 0) {
0.00
} else {
totalPrice
}
binding.incToolbar.btnText.text = getString(R.string.price_format, formattedPrice)
}
//Listen to the cartItems to refresh recyclerview Items
cartViewModel.cartItems.observe(viewLifecycleOwner) {
verticalAdapter.refreshData()
horizontalAdapter.refreshData()
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/productlisting/ProductListingFragment.kt | 659062575 |
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.databinding.ItemProductBinding
import com.getir.patika.shoppingapp.utils.Constants.PRODUCT_ITEM_CARD_MAX_HEIGHT
import com.getir.patika.shoppingapp.utils.Constants.PRODUCT_ITEM_CARD_MIN_HEIGHT
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
import com.getir.patika.shoppingapp.viewmodels.ProductViewModel
import com.getir.patika.shoppingapp.utils.dpToPx
class VerticalAdapter(private var dataList: List<Product>,
private val viewModel: ProductViewModel,
private val cartViewModel: CartViewModel) :
RecyclerView.Adapter<VerticalAdapter.VerticalViewHolder>() {
fun updateData(newDataList: List<Product>) {
dataList = newDataList
notifyDataSetChanged()
}
fun refreshData(){
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VerticalViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemProductBinding.inflate(inflater, parent, false)
return VerticalViewHolder(binding)
}
override fun onBindViewHolder(holder: VerticalViewHolder, position: Int) {
val item = dataList[position]
//Dynamic UI updates
holder.bind(item)
}
override fun getItemCount(): Int = dataList.size
inner class VerticalViewHolder(private val binding: ItemProductBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
//Set add to cart button
binding.btnPlus.setOnClickListener {
val product = dataList[bindingAdapterPosition]
cartViewModel.addToCart(product)
}
//Set remove from cart button
binding.btnDelete.setOnClickListener {
val product = dataList[bindingAdapterPosition]
if (cartViewModel.isProductInCart(product)) {
cartViewModel.removeFromCart(product)
}
}
//Set product detail button
itemView.setOnClickListener {
val product = dataList[bindingAdapterPosition]
viewModel.setSelectedProduct(product)
itemView.findNavController().navigate(R.id.action_productListingFragment_to_productDetailFragment2)
}
}
fun bind(product: Product) {
//Load image
val imgUrl = product.thumbnailURL ?:product.imageURL
Glide.with(itemView.context)
.load(imgUrl)
.placeholder(R.drawable.img_defproduct)
.into(binding.imgProduct)
//Set texts
binding.txtName.text = product.name
binding.txtPrice.text = product.priceText
val attText = product.attribute ?: product.shortDescription
binding.txtAtt.text = attText
// Check if the product is in the cart
val count = cartViewModel.getProductCount(product)
if (count > 0) {
//Show item count and remove button
binding.txtCount.text = count.toString()
binding.txtCount.visibility = View.VISIBLE
binding.btnDelete.visibility = View.VISIBLE
//Change the image stroke color
val color = ContextCompat.getColor(itemView.context, R.color.purple)
binding.cardProduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.itemstatecardview.layoutParams
layoutParam.height = PRODUCT_ITEM_CARD_MAX_HEIGHT.dpToPx(itemView.context)
binding.itemstatecardview.layoutParams = layoutParam
//Change the button image according to count of that item
if(count == 1){
binding.btnDelete.setImageResource(R.drawable.img_trash)
}else{
binding.btnDelete.setImageResource(R.drawable.img_minus)
}
// If the product is not in the cart
} else {
//Hide item count and remove button
binding.txtCount.visibility = View.GONE
binding.btnDelete.visibility = View.GONE
//Change the image stroke color to the default
val color = ContextCompat.getColor(itemView.context, R.color.stroke_grey)
binding.cardProduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.itemstatecardview.layoutParams
layoutParam.height = PRODUCT_ITEM_CARD_MIN_HEIGHT.dpToPx(itemView.context)
binding.itemstatecardview.layoutParams = layoutParam
}
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/productlisting/VerticalAdapter.kt | 1737960465 |
package com.getir.patika.shoppingapp.ui.details
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.databinding.FragmentProductDetailBinding
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
import com.getir.patika.shoppingapp.viewmodels.ProductViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ProductDetailFragment : Fragment() {
private lateinit var binding: FragmentProductDetailBinding
private val viewModel: ProductViewModel by activityViewModels()
private val cartViewModel: CartViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentProductDetailBinding.inflate(inflater, container, false)
setupToolbar()
// Hide cart operation layout by default
binding.cardCartOps.visibility = View.GONE
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupButtonClickListeners()
observeSelectedProduct()
observeCartItems()
observeTotalPrice()
}
private fun setupToolbar() {
binding.incToolbar.apply {
txtToolbar.text = getString(R.string.urun_detay)
btnCart.visibility = View.GONE
btnClose.visibility = View.VISIBLE
btnDeletecart.visibility = View.GONE
}
}
private fun setupButtonClickListeners() {
binding.incToolbar.apply {
//Navigate to the Cart screen
btnCart.setOnClickListener {
findNavController().navigate(R.id.action_productDetailFragment_to_shoppingCartFragment2)
}
//Navigate back
btnClose.setOnClickListener {
findNavController().navigateUp()
}
}
//Add item to the cart
binding.btnAddcart.setOnClickListener {
viewModel.selectedProduct.value?.let { product ->
cartViewModel.addToCart(product)
}
}
//Add item to the cart (increase)
binding.btnPlus.setOnClickListener {
viewModel.selectedProduct.value?.let { product ->
cartViewModel.addToCart(product)
}
}
//Remove item from the cart
binding.btnDelete.setOnClickListener {
viewModel.selectedProduct.value?.let { product ->
cartViewModel.removeFromCart(product)
// This control is not necessary at this time
/*val itemCount = cartViewModel.getProductCount(product)
if (itemCount > 1) {
cartViewModel.removeFromCart(product)*/
}
}
}
private fun observeSelectedProduct() {
viewModel.selectedProduct.observe(viewLifecycleOwner) { selectedProduct ->
//Change the UI according to selectedProduct
displayProductDetails(selectedProduct)
}
}
private fun observeCartItems() {
cartViewModel.cartItems.observe(viewLifecycleOwner) { cartItems ->
viewModel.selectedProduct.value?.let { product ->
//Change the UI according to Cart info
updateCartView(product)
}
}
}
private fun observeTotalPrice() {
cartViewModel.totalPrice.observe(viewLifecycleOwner) { totalPrice ->
//Change the totalPrice text according to totalPrice
if (totalPrice > 0) {
binding.incToolbar.btnCart.visibility = View.VISIBLE
binding.incToolbar.btnText.text = getString(R.string.price_format, totalPrice)
} else {
binding.incToolbar.btnCart.visibility = View.GONE
}
}
}
private fun displayProductDetails(product: Product) {
//Load image
val imgUrl = product.imageURL ?: product.squareThumbnailURL
Glide.with(requireContext())
.load(imgUrl)
.placeholder(R.drawable.img_defproduct)
.into(binding.imgProduct)
//Set texts
binding.txtName.text = product.name
binding.txtPrice.text = product.priceText
binding.txtAtt.text = product.attribute ?: product.shortDescription
}
private fun updateCartView(product: Product) {
// Check if the product is in the cart
val itemCount = cartViewModel.getProductCount(product)
if (itemCount > 0) {
//Show Cartops and hide AddCart
binding.txtCount.text = itemCount.toString()
binding.cardCartOps.visibility = View.VISIBLE
binding.btnAddcart.visibility = View.GONE
//Change the button image according to count of that item
if (itemCount == 1) {
binding.btnDelete.setImageResource(R.drawable.img_trash)
} else {
binding.btnDelete.setImageResource(R.drawable.img_minus)
}
// If the product is not in the cart
} else {
binding.cardCartOps.visibility = View.GONE
binding.btnAddcart.visibility = View.VISIBLE
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/details/ProductDetailFragment.kt | 1026024804 |
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.TypedValue
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.getir.patika.shoppingapp.R
class DividerItemDecoration(private val context: Context,private val dividerHeightDP: Int = 1,
private val dividerMarginDP: Int = 12) : RecyclerView.ItemDecoration() {
private val dividerPaint = Paint()
init {
//Set line color
dividerPaint.color = ContextCompat.getColor(context, R.color.stroke_grey)
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
// Add margin to the top and bottom of the divider
outRect.set(0, dividerMarginDP.dpToPx(), 0, dividerMarginDP.dpToPx())
}
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
// Convert height and margin from dp to pixels
val dividerHeightPx = dividerHeightDP.dpToPx()
val dividerMarginPx = dividerMarginDP.dpToPx()
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
//Draw loop
for (i in 0 until parent.childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin + dividerMarginPx
val bottom = top + dividerHeightPx
canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), dividerPaint)
}
}
private fun Int.dpToPx(): Int {
// Convert dp to pixels
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(),
context.resources.displayMetrics).toInt()
}
}
| getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/shoppingcart/DividerItemDecoration.kt | 2827188764 |
package com.getir.patika.shoppingapp.ui.shoppingcart
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.databinding.ItemAddedproductBinding
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
class CartAdapter(private var dataList: List<Product>,private val cartViewModel: CartViewModel) :
RecyclerView.Adapter<CartAdapter.CartViewHolder>() {
fun updateData(newDataList: List<Product>) {
//To avoid showing duplicate products
val uniqueDataList = newDataList.distinctBy { it.id }
dataList = uniqueDataList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemAddedproductBinding.inflate(inflater, parent, false)
return CartViewHolder(binding)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
val item = dataList[position]
holder.bind(item)
}
override fun getItemCount(): Int = dataList.size
inner class CartViewHolder(private val binding: ItemAddedproductBinding) : RecyclerView.ViewHolder(binding.root) {
init {
//Set add to cart button
binding.btnPlus.setOnClickListener {
val product = dataList[bindingAdapterPosition]
cartViewModel.addToCart(product)
}
//Set remove from cart button
binding.btnDelete.setOnClickListener {
val product = dataList[bindingAdapterPosition]
if (cartViewModel.isProductInCart(product)) {
cartViewModel.removeFromCart(product)
}
}
}
fun bind(product: Product) {
//Load image
val imgUrl = product.squareThumbnailURL ?: product.thumbnailURL ?: product.imageURL
Glide.with(itemView.context)
.load(imgUrl)
.placeholder(R.drawable.img_defproduct)
.into(binding.imgProduct)
//Set texts
binding.txtName.text = product.name
binding.txtPrice.text = product.priceText
val attText = product.attribute ?: product.shortDescription
binding.txtAtt.text = attText
// Get the product count
val count = cartViewModel.getProductCount(product)
binding.txtCount.text = count.toString()
//Change the button image according to count of that item
if(count > 1){
binding.btnDelete.setImageResource(R.drawable.img_minus)
}else{
binding.btnDelete.setImageResource(R.drawable.img_trash)
}
}
}
}
| getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/shoppingcart/CartAdapter.kt | 242588792 |
package com.getir.patika.shoppingapp.ui.shoppingcart
import DividerItemDecoration
import android.app.AlertDialog
import android.graphics.Paint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.databinding.FragmentShoppingCartBinding
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
import com.getir.patika.shoppingapp.viewmodels.ProductViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class CartFragment : Fragment() {
private lateinit var binding: FragmentShoppingCartBinding
private val cartViewModel: CartViewModel by activityViewModels()
private val productViewModel: ProductViewModel by activityViewModels()
private lateinit var cartAdapter: CartAdapter
private lateinit var cartSuggestedAdapter: CartSuggestedAdapter
private var formattedPrice: String = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentShoppingCartBinding.inflate(inflater, container, false)
setupToolbar()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupListeners()
setupAdapters()
setupItemDecoration()
observeViewModels()
}
private fun setupToolbar() {
binding.incToolbar.apply {
txtToolbar.text = getString(R.string.sepetim)
btnCart.visibility = View.GONE
btnClose.visibility = View.VISIBLE
btnDeletecart.visibility = View.VISIBLE
}
}
private fun setupListeners() {
// Remove all the cart, firstly show a dialog
binding.incToolbar.btnDeletecart.setOnClickListener {
showRemoveAllCartDialog()
}
// Navigate back
binding.incToolbar.btnClose.setOnClickListener {
findNavController().navigateUp()
}
// Buy products in the cart, show dialog
binding.btnCheckout.setOnClickListener {
showCheckoutDialog()
}
}
private fun setupAdapters() {
cartSuggestedAdapter = CartSuggestedAdapter(emptyList(), cartViewModel)
binding.recSuggested.adapter = cartSuggestedAdapter
cartAdapter = CartAdapter(emptyList(), cartViewModel)
binding.recCart.adapter = cartAdapter
}
private fun setupItemDecoration() {
// Item decorator between items
val itemDecorator = DividerItemDecoration(requireContext())
binding.recCart.addItemDecoration(itemDecorator)
}
private fun observeViewModels() {
cartViewModel.cartItems.observe(viewLifecycleOwner) { cartList ->
//Update cart adapter, refresh horizontal adapter according to CartItem List
cartAdapter.updateData(cartList)
cartSuggestedAdapter.refreshData()
//if (cartList.isEmpty()) binding.incToolbar.btnDeletecart.visibility = View.GONE
//else binding.incToolbar.btnDeletecart.visibility = View.VISIBLE
}
//Listen to the totalPrice to set text
cartViewModel.totalPrice.observe(viewLifecycleOwner, Observer { totalPrice ->
val formattedDouble = if (totalPrice < 0) {
0.00
} else {
totalPrice
}
//Change the totalPrice text according to totalPrice
formattedPrice = getString(R.string.price_format, formattedDouble)
binding.totalLastprice.text = formattedPrice
binding.totalPrice.text = formattedPrice
binding.totalPrice.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
})
//Listen to the horizontalProductList to update recyclerview Items
productViewModel.horizontalProductList.observe(viewLifecycleOwner) { horizontalList ->
cartSuggestedAdapter.updateData(horizontalList)
}
}
private fun showCheckoutDialog() {
//Set parameters of dialog after pressing the Checkout button
showCustomDialog(
title = "Siparişiniz başarıyla alındı",
message = "Toplam sepet tutarı: $formattedPrice",
positiveButtonText = "TAMAM",
positiveButtonAction = {
cartViewModel.clearCart()
findNavController().navigate(R.id.action_shoppingCartFragment_to_productListingFragment)
},
negativeButtonText = null,
negativeButtonAction = null
)
}
private fun showRemoveAllCartDialog() {
//Set parameters of dialog after pressing the Remove Cart button
showCustomDialog(
title = "Sepeti sil",
message = "Sepetteki tüm ürünleri silmek istiyor musunuz?",
positiveButtonText = "SİL",
positiveButtonAction = {
cartViewModel.clearCart()
findNavController().navigate(R.id.action_shoppingCartFragment_to_productListingFragment)
},
negativeButtonText = "İPTAL",
negativeButtonAction = null
)
}
//Setting dialog
private fun showCustomDialog(
title: String,
message: String,
positiveButtonText: String,
negativeButtonText: String?,
positiveButtonAction: (() -> Unit)?,
negativeButtonAction: (() -> Unit)?
) {
val dialogView = layoutInflater.inflate(R.layout.custom_dialog, null)
val builder = AlertDialog.Builder(requireContext())
builder.setView(dialogView)
//Create dialog
val dialog = builder.create()
dialog.show()
//Dialog views
val titleTextView = dialogView.findViewById<TextView>(R.id.txt_dialogtitle)
val messageTextView = dialogView.findViewById<TextView>(R.id.txt_dialogbody)
val positiveButton = dialogView.findViewById<Button>(R.id.btn_pos)
val negativeButton = dialogView.findViewById<Button>(R.id.btn_neg)
//Setting dialog parameters to view
titleTextView.text = title
messageTextView.text = message
//Setting button parameters
positiveButton.text = positiveButtonText
positiveButton.setOnClickListener {
positiveButtonAction?.invoke()
dialog.dismiss()
}
if (negativeButtonText == null) {
negativeButton.visibility = View.GONE
} else {
negativeButton.text = negativeButtonText
negativeButton.setOnClickListener {
negativeButtonAction?.invoke()
dialog.dismiss()
}
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/shoppingcart/CartFragment.kt | 558039066 |
package com.getir.patika.shoppingapp.ui.shoppingcart
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.getir.patika.shoppingapp.R
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.databinding.ItemSuggestedproductBinding
import com.getir.patika.shoppingapp.utils.Constants
import com.getir.patika.shoppingapp.utils.dpToPx
import com.getir.patika.shoppingapp.viewmodels.CartViewModel
class CartSuggestedAdapter(private var dataList: List<Product>, private val cartViewModel: CartViewModel) :
RecyclerView.Adapter<CartSuggestedAdapter.CartViewHolder>() {
fun updateData(newDataList: List<Product>) {
dataList = newDataList
notifyDataSetChanged()
}
fun refreshData(){
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemSuggestedproductBinding.inflate(inflater, parent, false)
return CartViewHolder(binding)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
val item = dataList[position]
holder.bind(item)
}
override fun getItemCount(): Int = dataList.size
inner class CartViewHolder(private val binding: ItemSuggestedproductBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
//Set add to cart button
binding.btnPlus.setOnClickListener {
val product = dataList[bindingAdapterPosition]
cartViewModel.addToCart(product)
}
//Set remove from cart button
binding.btnDelete.setOnClickListener {
val product = dataList[bindingAdapterPosition]
if (cartViewModel.isProductInCart(product)) {
cartViewModel.removeFromCart(product)
}
}
}
fun bind(product: Product) {
//Load image
val imgUrl = product.squareThumbnailURL ?: product.imageURL
Glide.with(itemView.context)
.load(imgUrl)
.placeholder(R.drawable.img_defproduct)
.into(binding.imgSuggestedproduct)
//Set texts
binding.txtName.text = product.name
binding.txtPrice.text = product.priceText
val attText = product.attribute ?: product.shortDescription
binding.txtAtt.text = attText
// Check if the product is in the cart
val count = cartViewModel.getProductCount(product)
if (count > 0) {
//Show item count and remove button
binding.txtCount.text = count.toString()
binding.txtCount.visibility = View.VISIBLE
binding.btnDelete.visibility = View.VISIBLE
//Change the image stroke color
val color = ContextCompat.getColor(itemView.context, R.color.purple)
binding.cardSuggestedproduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.suggesteditemstatecardview.layoutParams
layoutParam.height = Constants.PRODUCT_ITEM_CARD_MAX_HEIGHT.dpToPx(itemView.context)
binding.suggesteditemstatecardview.layoutParams = layoutParam
//Change the button image according to count of that item
if(count == 1){
binding.btnDelete.setImageResource(R.drawable.img_trash)
}else{
binding.btnDelete.setImageResource(R.drawable.img_minus)
}
// If the product is not in the cart
} else {
//Hide item count and remove button
binding.txtCount.visibility = View.GONE
binding.btnDelete.visibility = View.GONE
//Change the image stroke color to the default
val color = ContextCompat.getColor(itemView.context, R.color.stroke_grey)
binding.cardSuggestedproduct.strokeColor = color
// Change the button cart's maximum height
val layoutParam = binding.suggesteditemstatecardview.layoutParams
layoutParam.height = Constants.PRODUCT_ITEM_CARD_MIN_HEIGHT.dpToPx(itemView.context)
binding.suggesteditemstatecardview.layoutParams = layoutParam
}
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/ui/shoppingcart/CartSuggestedAdapter.kt | 2840166140 |
package com.getir.patika.shoppingapp.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.getir.patika.shoppingapp.data.models.Product
class CartViewModel : ViewModel() {
//List of products in cart
private val _cartItems = MutableLiveData<List<Product>>(emptyList())
val cartItems: LiveData<List<Product>> = _cartItems
//Value of total cart price
private val _totalPrice = MutableLiveData<Double>(0.0)
val totalPrice: LiveData<Double> = _totalPrice
fun addToCart(product: Product) {
//Add product to the cart list
val currentItems = _cartItems.value.orEmpty().toMutableList()
currentItems.add(product)
_cartItems.value = currentItems
updateTotalPrice(product.price)
}
fun removeFromCart(product: Product) {
//Remove product from the cart list
val currentItems = _cartItems.value.orEmpty().toMutableList()
currentItems.remove(product)
_cartItems.value = currentItems
updateTotalPrice(-product.price)
}
private fun updateTotalPrice(amount: Double) {
//Update total cart price
_totalPrice.value = (_totalPrice.value ?: 0.0) + amount
}
fun clearCart() {
//Clear all items in the cart
_cartItems.value = emptyList()
_totalPrice.value = 0.0
}
fun isProductInCart(product: Product): Boolean {
//Check if product already in the cart
return _cartItems.value?.any { it.id == product.id } ?: false
}
fun getProductCount(product: Product): Int {
//Check that product count
return _cartItems.value?.count { it.id == product.id } ?: 0
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/viewmodels/CartViewModel.kt | 2188912267 |
package com.getir.patika.shoppingapp.viewmodels
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.data.repository.ProductRepository
import com.getir.patika.shoppingapp.data.service.CallResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProductViewModel @Inject constructor(private val productRepository: ProductRepository) : ViewModel() {
//List for the suggested products
private val _horizontalProductList = MutableLiveData<List<Product>>()
val horizontalProductList: LiveData<List<Product>> = _horizontalProductList
//List for the products
private val _verticalProductList = MutableLiveData<List<Product>>()
val verticalProductList: LiveData<List<Product>> = _verticalProductList
//Item for the Detail Screen
private val _selectedProduct = MutableLiveData<Product>()
val selectedProduct: LiveData<Product> = _selectedProduct
init {
getProducts()
getSuggestedProducts()
}
private fun getProducts() {
//Get the datas from repository
viewModelScope.launch {
productRepository.getProducts().collect { result ->
when (result) {
//is CallResult.Loading -> //Loading could be displayed in UI
is CallResult.Success -> {
result.data.let { products ->
_verticalProductList.value = products
}
}
else -> Log.e("ProductViewModel", "Failed to fetch vertical products")
}
}
}
}
private fun getSuggestedProducts() {
//Get the datas from repository
viewModelScope.launch {
productRepository.getSuggestedProducts().collect { result ->
when (result) {
//is CallResult.Loading -> //Loading could be displayed in UI
is CallResult.Success -> {
result.data.let { products ->
_horizontalProductList.value = products
}
}
else -> Log.e("ProductViewModel", "Failed to fetch horizontal products")
}
}
}
}
fun setSelectedProduct(product: Product) {
//Change the selected item
_selectedProduct.value = product
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/viewmodels/ProductViewModel.kt | 1447166228 |
package com.getir.patika.shoppingapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/MainActivity.kt | 4281151207 |
package com.getir.patika.shoppingapp.di
import com.getir.patika.shoppingapp.data.repository.ProductRepository
import com.getir.patika.shoppingapp.data.service.ApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideProductRepository(apiService: ApiService): ProductRepository {
return ProductRepository(apiService)
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/di/AppModule.kt | 452078651 |
package com.getir.patika.shoppingapp.di
import com.getir.patika.shoppingapp.BuildConfig
import com.getir.patika.shoppingapp.data.service.ApiService
import com.getir.patika.shoppingapp.utils.Constants.BASE_URL
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor =
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE
}
@Provides
@Singleton
fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
OkHttpClient.Builder().apply {
callTimeout(40, TimeUnit.SECONDS)
connectTimeout(40, TimeUnit.SECONDS)
readTimeout(40, TimeUnit.SECONDS)
addInterceptor(httpLoggingInterceptor)
return build()
}
}
@Provides
@Singleton
fun provideGson(): Gson = GsonBuilder().setLenient().create()
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL) //
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/di/NetworkModule.kt | 1507845591 |
package com.getir.patika.shoppingapp.utils
import android.content.Context
fun Int.dpToPx(context: Context): Int = (this * context.resources.displayMetrics.density).toInt()
| getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/utils/Extensions.kt | 3010502716 |
package com.getir.patika.shoppingapp.utils
object Constants {
const val BASE_URL = "https://65c38b5339055e7482c12050.mockapi.io/api/"
const val PRODUCT_ITEM_CARD_MAX_HEIGHT = 96
const val PRODUCT_ITEM_CARD_MIN_HEIGHT = 32
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/utils/Constants.kt | 3720610277 |
package com.getir.patika.shoppingapp.data.repository
import com.getir.patika.shoppingapp.data.models.Product
import com.getir.patika.shoppingapp.data.service.ApiService
import com.getir.patika.shoppingapp.data.service.CallResult
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProductRepository @Inject constructor(private val apiService: ApiService) {
//API call for Products
suspend fun getProducts(): Flow<CallResult<List<Product>>> {
//Get List from response if the List is not null
return fetchProductsFromApi { apiService.getProducts().body()?.get(0)?.products ?: emptyList() }
}
//API call for SuggestedProducts
suspend fun getSuggestedProducts(): Flow<CallResult<List<Product>>> {
//Get List from response if the List is not null
return fetchProductsFromApi { apiService.getSuggestedProducts().body()?.get(0)?.products ?: emptyList() }
}
private suspend fun fetchProductsFromApi(apiCall: suspend () -> List<Product>):
Flow<CallResult<List<Product>>> = flow {
//Loading Animation could be displayed in UI according to state
emit(CallResult.Loading)
try {
//Make the API call and get the response
val response = apiCall.invoke()
//If data was received successfully, success status
emit(CallResult.Success(response))
} catch (e: Exception) {
emit(CallResult.Error(e.message ?: "An error occurred while retrieving data"))
}
}
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/repository/ProductRepository.kt | 668161694 |
package com.getir.patika.shoppingapp.data.models
data class Product(
val id: String, //common
val name: String, //common
val price: Double, //common
val priceText: String?, //common
val imageURL: String?,
val shortDescription: String?,
val squareThumbnailURL: String?,
val attribute: String?,
val thumbnailURL: String?,
val category: String?,
val status: Int?,
val unitPrice: Double?
) | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/models/Product.kt | 2700917952 |
package com.getir.patika.shoppingapp.data.models
data class SuggestedProductItem(
val id: String,
val name: String,
val products: List<Product>
) | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/models/SuggestedProductItem.kt | 262349967 |
package com.getir.patika.shoppingapp.data.models
data class ProductsItem(
val email: String,
val id: String,
val name: String,
val password: String,
val productCount: Int,
val products: List<Product>
) | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/models/ProductsItem.kt | 1549927211 |
package com.getir.patika.shoppingapp.data.service
import com.getir.patika.shoppingapp.data.models.ProductsItem
import com.getir.patika.shoppingapp.data.models.SuggestedProductItem
import retrofit2.Response
import retrofit2.http.GET
interface ApiService {
@GET("products")
suspend fun getProducts(): Response<List<ProductsItem>>
@GET("suggestedProducts")
suspend fun getSuggestedProducts(): Response<List<SuggestedProductItem>>
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/service/ApiService.kt | 4264235959 |
package com.getir.patika.shoppingapp.data.service
sealed class CallResult<out T> {
data object Loading : CallResult<Nothing>()
data class Success<out T>(val data: T) : CallResult<T>()
data class Error(val message: String) : CallResult<Nothing>()
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/data/service/CallResult.kt | 3160244485 |
package com.getir.patika.shoppingapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class HiltApp : Application() {
} | getir-android-bootcamp-final-project/app/src/main/java/com/getir/patika/shoppingapp/HiltApp.kt | 3599245792 |
package com.example.subidanota
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.subidanota", appContext.packageName)
}
} | SubidaNotaAndroid/app/src/androidTest/java/com/example/subidanota/ExampleInstrumentedTest.kt | 1024629728 |
package com.example.subidanota
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)
}
} | SubidaNotaAndroid/app/src/test/java/com/example/subidanota/ExampleUnitTest.kt | 2660189460 |
package com.example.subidanota
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.subidanota.adapter.AdaptadorRecycler
import com.example.subidanota.adapter.AdaptadorSpinnerMoneda
import com.example.subidanota.data.DataSet
import com.example.subidanota.databinding.ActivityMainBinding
import com.example.subidanota.model.Moneda
import com.example.subidanota.model.TransaccionMoneda
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var binding: ActivityMainBinding
private lateinit var adaptadorMonedas: AdaptadorSpinnerMoneda
private lateinit var adaptadorRecycler: AdaptadorRecycler
private lateinit var listaMonedas: ArrayList<Moneda>
private val listaTransacciones = ArrayList<TransaccionMoneda>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
listaMonedas = DataSet.obtenerListaCompleta()
adaptadorMonedas = AdaptadorSpinnerMoneda(listaMonedas, this)
binding.monedaOrigen.adapter = adaptadorMonedas
binding.monedaDestino.adapter = adaptadorMonedas
adaptadorRecycler = AdaptadorRecycler(listaTransacciones, this)
binding.recyclerTransacciones.adapter = adaptadorRecycler
binding.botonCambio.setOnClickListener(this)
binding.recyclerTransacciones.layoutManager = LinearLayoutManager(this)
adaptadorRecycler = AdaptadorRecycler(listaTransacciones, this)
binding.recyclerTransacciones.adapter = adaptadorRecycler
}
override fun onClick(view: View?) {
when (view?.id) {
R.id.botonCambio -> {
val moneda1: Moneda = binding.monedaOrigen.selectedItem as Moneda
val moneda2: Moneda = binding.monedaDestino.selectedItem as Moneda
val monedaOrigen = moneda1
val monedaDestino = moneda2
val nuevaTransaccion = TransaccionMoneda(monedaOrigen, monedaDestino)
adaptadorRecycler.lista.add(nuevaTransaccion)
adaptadorRecycler.notifyDataSetChanged()
if (moneda1.nombre.equals("Euro", ignoreCase = true)) {
try {
val valor: Double = binding.textoCambio.text.toString().toDouble()
when (moneda2.nombre) {
"Euro" -> {
binding.textoCambio.setText((valor * 1).toString())
}
"Dollar" -> {
binding.textoCambio.setText((valor * 1.09).toString())
}
"Libra" -> {
binding.textoCambio.setText((valor * 0.85).toString())
}
}
} catch (e: NumberFormatException) {
}
}
if (moneda1.nombre.equals("Dollar", ignoreCase = true)) {
try {
val valor: Double = binding.textoCambio.text.toString().toDouble()
when (moneda2.nombre) {
"Euro" -> {
binding.textoCambio.setText((valor * 0.91).toString())
}
"Dollar" -> {
binding.textoCambio.setText((valor * 1).toString())
}
"Libra" -> {
binding.textoCambio.setText((valor * 0.78).toString())
}
}
} catch (e: NumberFormatException) {
}
}
if (moneda1.nombre.equals("Libra", ignoreCase = true)) {
try {
val valor: Double = binding.textoCambio.text.toString().toDouble()
when (moneda2.nombre) {
"Euro" -> {
binding.textoCambio.setText((valor * 1.16).toString())
}
"Dollar" -> {
binding.textoCambio.setText((valor * 1.27).toString())
}
"Libra" -> {
binding.textoCambio.setText((valor * 1).toString())
}
}
} catch (e: NumberFormatException) {
}
}
}
}
}
}
| SubidaNotaAndroid/app/src/main/java/com/example/subidanota/MainActivity.kt | 2461635422 |
package com.example.subidanota.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.example.subidanota.R
import com.example.subidanota.model.Moneda
class AdaptadorSpinnerMoneda(var lista: ArrayList<Moneda>, var contexto: Context) : BaseAdapter() {
override fun getCount(): Int {
return lista.size;
}
override fun getItem(position: Int): Moneda {
return lista[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
fun addMoneda(moneda: Moneda) {
lista.add(moneda)
notifyDataSetChanged()
}
fun cambiarListaMonedas(listaNueva: ArrayList<Moneda>) {
lista.clear()
lista.addAll(listaNueva)
notifyDataSetChanged()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?):
View {
val vista = LayoutInflater.from(contexto)
.inflate(R.layout.item_moneda, parent, false)
val moneda = lista[position]
val textoMoneda = vista.findViewById<TextView>(R.id.texto_moneda)
val imagenMoneda = vista.findViewById<ImageView>(R.id.imagen_moneda)
textoMoneda.text = moneda.nombre
imagenMoneda.setImageResource(moneda.imagen)
return vista;
}
} | SubidaNotaAndroid/app/src/main/java/com/example/subidanota/adapter/AdaptadorSpinnerMoneda.kt | 2144778500 |
package com.example.subidanota.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.example.subidanota.R
import com.example.subidanota.model.TransaccionMoneda
import com.google.android.material.snackbar.Snackbar
class AdaptadorRecycler(
var lista: ArrayList<TransaccionMoneda>,
var contexto: Context
) : RecyclerView.Adapter<AdaptadorRecycler.MyHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
val vista: View = LayoutInflater.from(contexto).inflate(R.layout.item_recycler, parent, false)
return MyHolder(vista)
}
override fun onBindViewHolder(holder: MyHolder, position: Int) {
val transaccion = lista[position]
holder.imagenMonedaOrigen.setImageResource(transaccion.monedaOrigen.imagen)
holder.imagenMonedaDestino.setImageResource(transaccion.monedaDestino.imagen)
holder.boton.setOnClickListener {
}
holder.itemView.setOnClickListener {
val textoSnackBar = "${transaccion.monedaOrigen.nombre} son ${transaccion.monedaDestino.nombre}"
Snackbar.make(holder.itemView, textoSnackBar, Snackbar.LENGTH_LONG).show()
}
}
override fun getItemCount(): Int {
return lista.size
}
class MyHolder(item: View) : RecyclerView.ViewHolder(item) {
var imagenMonedaOrigen: ImageView = item.findViewById(R.id.imagen_moneda_origen)
var imagenMonedaDestino: ImageView = item.findViewById(R.id.imagen_moneda_destino)
var boton: Button = item.findViewById(R.id.boton_detalles)
}
}
| SubidaNotaAndroid/app/src/main/java/com/example/subidanota/adapter/AdaptadorRecycler.kt | 2630921701 |
package com.example.subidanota.model
class TransaccionMoneda(val monedaOrigen: Moneda, val monedaDestino: Moneda)
| SubidaNotaAndroid/app/src/main/java/com/example/subidanota/model/TransaccionMoneda.kt | 3945921606 |
package com.example.subidanota.model
import java.io.Serializable
class Moneda (var nombre: String, var imagen: Int): Serializable {
} | SubidaNotaAndroid/app/src/main/java/com/example/subidanota/model/Moneda.kt | 297247793 |
package com.example.subidanota.data
import android.graphics.ColorSpace.Model
import com.example.subidanota.R
import com.example.subidanota.model.Moneda
class DataSet {
companion object{
val listaMonedas = ArrayList<Moneda>()
fun obtenerListaCompleta(): ArrayList<Moneda> {
listaMonedas.add(Moneda("Dollar",R.drawable.dollar))
listaMonedas.add(Moneda("Euro",R.drawable.euro))
listaMonedas.add(Moneda("Libra",R.drawable.libra))
return listaMonedas
}
}
} | SubidaNotaAndroid/app/src/main/java/com/example/subidanota/data/Dataset.kt | 3060933009 |
// child classes should extend the behavior of the base class without changing its expected behavior.
// means child classes should not break the behavior of parent classes.
open class Vehicle {
open fun getInteriorWidth(): Int {
return 0
}
}
open class Car: Vehicle() {
override fun getInteriorWidth(): Int {
return this.getCabinWidth()
}
fun getCabinWidth(): Int {
return 40
}
}
class RacingCar: Vehicle() {
override fun getInteriorWidth(): Int {
return this.cockpitWidth()
}
fun cockpitWidth(): Int {
return 10
}
}
fun main() {
val list = mutableListOf(RacingCar(), Car())
// I need to check for each class one by one, that's not a good idea
list.forEach {
when(it) {
is RacingCar -> {
println(it.cockpitWidth())
}
is Car -> {
println(it.getCabinWidth())
}
}
}
// now I implemented Vehicle class(that follows Liskov principle)
list.forEach {
println(it.getInteriorWidth())
}
}
class LSP {
}
| SOLID-Principle-Implementation/src/main/kotlin/LSP.kt | 3355216009 |
// This principle has 2 requirements:
// "High-level modules should not depend on low-level modules. Both should depend on abstractions"
// "Abstractions should not depend upon details. Details should depend upon abstractions"
// This means that if you use a class insider another class, this class will be dependent of the class injected. This is what is called rigidity.
// high level module
class ProductCatalog {
fun listAllProducts() {
// val sql: IProductRepo = SQLProductRepo()
val sql: IProductRepo = MongoProductRepo()
sql.getAllProducts().forEach{
println(it)
}
}
}
// low level module
class SQLProductRepo: IProductRepo {
override fun getAllProducts(): MutableList<String> {
return mutableListOf("Apple", "Lemon", "Mango")
}
}
class MongoProductRepo: IProductRepo {
override fun getAllProducts(): MutableList<String> {
return mutableListOf("Onion", "Garlic", "Ginger")
}
}
// lower and high both should depend upon abstraction
interface IProductRepo {
fun getAllProducts(): MutableList<String>
}
fun main() {
val productCatalog = ProductCatalog()
productCatalog.listAllProducts()
}
class DIP {
}
| SOLID-Principle-Implementation/src/main/kotlin/DIP.kt | 2593146729 |
// The Single Responsibility Principle (SRP):
//This principle states that "A class should have only one reason to change"
//This means that one class should only have one responsibility.
// this class has 2 responsibility, so it's not following the SRP.
class Square1 {
// These methods are belong to square that's good
fun calculateArea(side: Int): Int {
return side * side
}
fun calculatePerimeter(side: Int): Int {
return 4 * side
}
// But these methods don't belong to square. these are belong to Ui
fun renderSquare() {
println("Render Square")
}
fun renderLargeSquare() {
println("Render Large Square")
}
}
// Below classes have single responsibility so these follow the SRP.
class Square {
fun calculateArea(side: Int): Int {
return side * side
}
fun calculatePerimeter(side: Int): Int {
return 4 * side
}
}
class SquareUi {
fun renderSquare() {
println("Render Square")
}
fun renderLargeSquare() {
println("Render Large Square")
}
}
fun main(args: Array<String>) {
} | SOLID-Principle-Implementation/src/main/kotlin/SRP.kt | 4000480106 |
// Don't implement too fatty interface
// This principle states that "The interface-segregation principle (ISP) states
// - that no client should be forced to depend on methods it does not use."
// This means that if an interface becomes too fat, then it should be split into smaller
// - interfaces so that the client implementing the interface does
// - not implement methods that are of no use to it.
// this interface is too fatty
interface IMultiFunctional{
fun print()
fun printSpoonDetails()
fun scan()
fun scanPhoto()
fun fax()
fun internetFax()
}
class CannonPrinter: IMultiFunctional {
override fun print() {
TODO("Not yet implemented")
}
override fun printSpoonDetails() {
TODO("Not yet implemented")
}
override fun scan() {
TODO("Not yet implemented")
}
override fun scanPhoto() {
TODO("Not yet implemented")
}
// cannon printer doesn't have this functionality, still we have to add this method
override fun fax() {
TODO("Not yet implemented")
}
// cannon printer doesn't have this functionality, still we have to add this method
override fun internetFax() {
TODO("Not yet implemented")
}
}
// now split the fatty interface to smaller on
interface IPrint {
fun print()
fun printSpoonDetails()
}
interface IScan {
fun scan()
fun scanPhoto()
}
interface IFax {
fun fax()
fun internetFax()
}
// printer can scan and print so use only necessary interface (Follows Interface Segregation Principle)
class CannonPrinter1: IPrint, IScan {
override fun print() {
TODO("Not yet implemented")
}
override fun printSpoonDetails() {
TODO("Not yet implemented")
}
override fun scan() {
TODO("Not yet implemented")
}
override fun scanPhoto() {
TODO("Not yet implemented")
}
}
class ISP {
}
| SOLID-Principle-Implementation/src/main/kotlin/ISP.kt | 4117349007 |
//The Open-Closed Principle (OCP):
//This principle states that "Software entities such as classes, functions,
// modules should be open for extension but not for modification."
//This means that if we are required to add a new feature to the project,
// it is good practice to not modify the existing code but rather write new code in a seperate module
// and that will be used by the existing code.
class VehicleInsuranceCustomer1 {
fun isLoyalCustomer(): Boolean {
return true
}
}
class HomeInsuranceCustomer1 {
fun isLoyalCustomer(): Boolean {
return true
}
}
class LifeInsuranceCustomer1 {
fun isLoyalCustomer(): Boolean {
return true
}
}
class InsuranceCompany1 {
fun discountRate(vehicleInsuranceCustomer: VehicleInsuranceCustomer1): Int {
return if(vehicleInsuranceCustomer.isLoyalCustomer()) 30
else 10
}
fun discountRate(homeInsuranceCustomer: HomeInsuranceCustomer1): Int {
return if(homeInsuranceCustomer.isLoyalCustomer()) 40
else 12
}
fun discountRate(lifeInsuranceCustomer: LifeInsuranceCustomer1): Int {
return if(lifeInsuranceCustomer.isLoyalCustomer()) 35
else 15
}
}
// in above class isLoyalCustomer() is written multiple times so duplicate codes
// let's convert to Open for extension and Closed for modification
interface Customer {
fun isLoyalCustomer(): Boolean
}
class VehicleInsuranceCustomer: Customer {
override fun isLoyalCustomer(): Boolean {
return true
}
}
class HomeInsuranceCustomer: Customer {
override fun isLoyalCustomer(): Boolean {
return true
}
}
class LifeInsuranceCustomer: Customer {
override fun isLoyalCustomer(): Boolean {
return true
}
}
class InsuranceCompany {
fun discountRate(customer: Customer): Int {
return if(customer.isLoyalCustomer()) 40 else 15
}
}
fun main() {
val lifeInsuranceCustomer = LifeInsuranceCustomer()
val homeInsuranceCustomer = HomeInsuranceCustomer()
val vehicleInsuranceCustomer = VehicleInsuranceCustomer()
val insuranceCompany = InsuranceCompany()
insuranceCompany.discountRate(lifeInsuranceCustomer)
insuranceCompany.discountRate(homeInsuranceCustomer)
insuranceCompany.discountRate(vehicleInsuranceCustomer)
}
| SOLID-Principle-Implementation/src/main/kotlin/OCP.kt | 1062741551 |
package com.example.tutorial
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.tutorial", appContext.packageName)
}
} | MC_Assign1/app/src/androidTest/java/com/example/tutorial/ExampleInstrumentedTest.kt | 1011765673 |
package com.example.tutorial
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)
}
} | MC_Assign1/app/src/test/java/com/example/tutorial/ExampleUnitTest.kt | 3354416951 |
package com.example.tutorial.ui.theme
import androidx.compose.foundation.shape.CutCornerShape
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),
medium= CutCornerShape(topEnd = 24.dp),
large = RoundedCornerShape(0.dp)
) | MC_Assign1/app/src/main/java/com/example/tutorial/ui/theme/Shape.kt | 2884899456 |
package com.example.tutorial.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | MC_Assign1/app/src/main/java/com/example/tutorial/ui/theme/Color.kt | 2384020790 |
package com.example.tutorial.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 = Teal200,
primaryVariant = Purple700,
secondary = Purple200
)
private val LightColorPalette = lightColors(
primary = Teal200,
primaryVariant = Purple700,
secondary = Purple200
/* 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 TutorialTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | MC_Assign1/app/src/main/java/com/example/tutorial/ui/theme/Theme.kt | 3384161117 |
package com.example.tutorial.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
)
*/
) | MC_Assign1/app/src/main/java/com/example/tutorial/ui/theme/Type.kt | 2358303776 |
package com.example.tutorial
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Home
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import coil.compose.AsyncImage
import com.codingtroops.profilecardlayout.UserProfile
import com.codingtroops.profilecardlayout.userProfileList
import com.example.tutorial.ui.theme.TutorialTheme
val nameList:ArrayList<String> = arrayListOf(
"John",
"Michael",
"Andrew",
"Diana",
"Georgia"
)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TutorialTheme {
HomePage()
}
}
}
}
@Composable
fun HomePage(userProfiles:List<UserProfile> = userProfileList){
val navController= rememberNavController()
NavHost(navController = navController , startDestination ="user_list" ){
composable("user_list"){
MainScreen4(userProfiles,navController)
}
composable(route="user_details/{userId}",
arguments = listOf(navArgument("userId"){
type= NavType.IntType
})
){navBackStackEntry->
UserProfileDetailsScreen(navBackStackEntry.arguments!!.getInt("userId"),navController)
}
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainScreen4(userProfiles:List<UserProfile>,navController:NavHostController? ){
Scaffold(topBar = { Appbar(title="Users List", icon = Icons.Default.Home,{}) }){
Surface(
modifier=Modifier.fillMaxSize(),
color=Color.LightGray
) {
LazyColumn{
items(userProfiles){userProfile->
ProfileCard(userProfile = userProfile){
navController?.navigate("user_details/${userProfile.id}")
}
}
// ProfileCard(userProfileList[1])
}
}
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun UserProfileDetailsScreen(userId:Int,navController:NavHostController? ){
val userProfile= userProfileList.first{userProfile -> userId==userProfile.id }
Scaffold(topBar = { Appbar(title = "User Profile Details",Icons.Default.ArrowBack,{
navController?.popBackStack()
}) }){
Surface(
modifier=Modifier.fillMaxSize(),
color=Color.LightGray
) {
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
){
ProfilePicture(userProfile.pictureUrl,userProfile.status,200.dp)
ProfileContent(userProfile.name,userProfile.status,Alignment.CenterHorizontally)
}
}
}
}
@Composable
fun Appbar(title:String, icon:ImageVector,backAction:()->Unit){
TopAppBar(
navigationIcon= {
Icon(imageVector = icon,"Content Description",
Modifier.padding(horizontal = 12.dp).clickable(onClick = {backAction.invoke()})
)
},
title = {Text(title)}
)
}
@Composable
fun ProfileCard(userProfile: UserProfile,clickAction:()->Unit){
Card(
modifier = Modifier
.padding(top = 8.dp, bottom = 4.dp, start = 16.dp, end = 16.dp)
.fillMaxWidth()
.wrapContentHeight(align = Alignment.Top)
.clickable(onClick = { clickAction.invoke() })
,
elevation = 8.dp
){
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
){
ProfilePicture(userProfile.pictureUrl,userProfile.status,75.dp)
ProfileContent(userProfile.name,userProfile.status,Alignment.Start)
}
}
}
@Composable
fun ProfilePicture(pictureUrl:String,onlineStatus:Boolean,imageSize:Dp){
Card(
shape= CircleShape,
border = BorderStroke(width=2.dp,color=if(onlineStatus)Color.Green else Color.Red),
modifier = Modifier.padding(16.dp),
elevation = 4.dp
){
AsyncImage(
model = pictureUrl,
// placeholder = painterResource(id = R.drawable.sudoimage),
// error = painterResource(id = R.drawable.sudoimage),
contentDescription = "The delasign logo",
modifier=Modifier.size(imageSize)
)
// AsyncImage(model = "",
// contentDescription = "Content desc",
// modifier = Modifier.size(72.dp),
// contentScale = ContentScale.Crop
// )
// Image(painter = painterResource(id = drawableId),
// contentDescription = "Dummy Description",
// modifier = Modifier.size(72.dp),
// contentScale = ContentScale.Crop
// )
}
}
@Composable
fun ProfileContent(userName:String,onlineStatus: Boolean,alignment:Alignment.Horizontal){
Column (
modifier = Modifier
.padding(8.dp),
horizontalAlignment = alignment,
// .fillMaxWidth()
){
CompositionLocalProvider(LocalContentAlpha provides if(onlineStatus) 1f else ContentAlpha.medium) {
Text(text = userName,style=MaterialTheme.typography.h5)
}
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(text = if(onlineStatus)"Active Now" else "Offline", style = MaterialTheme.typography.body2)
}
}
}
@Composable
fun MainScreen3(){
val greetingListState= remember {
mutableStateListOf<String>("John","Michael")
}
val newNameState= remember {
mutableStateOf("")
}
Column(
modifier=Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally,
) {
GreetingList(greetingListState,
{greetingListState.add(newNameState.value)},
newNameState.value,
{new->newNameState.value=new}
)
}
}
//@SuppressLint("UnrememberedMutableState")
@Composable
fun GreetingList(nameListState:List<String>,buttonClick:()->Unit,textFieldValue:String,textFieldValueChange:(new:String)->Unit){
for (name in nameListState){
// Greeting(name = name)
Text(text="Hello $name",style=MaterialTheme.typography.h5)
}
TextField(value = textFieldValue, onValueChange = textFieldValueChange)
Button(onClick = buttonClick) {
Text(text = "Add new Name")
}
}
@Composable
fun MainScreen(){
Surface(color= Color.DarkGray,
modifier = Modifier.fillMaxSize()){
Row(
modifier=Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
HorizontalColorBar(color = Color.Blue)
HorizontalColorBar(color = Color.Red)
HorizontalColorBar(color = Color.Green)
HorizontalColorBar(color = Color.Yellow)
HorizontalColorBar(color = Color.Cyan)
}
}
}
@Composable
fun MainScreen2(){
Surface(color= Color.DarkGray,
modifier = Modifier.fillMaxSize()){
Column(
modifier=Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly,
) {
Row(
modifier=Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
VerticalColorBar(color = Color.LightGray)
VerticalColorBar(color = Color.Cyan)
}
VerticalColorBar(color = Color.Blue)
VerticalColorBar(color = Color.Red)
VerticalColorBar(color = Color.Green)
VerticalColorBar(color = Color.Cyan)
VerticalColorBar(color = Color.Yellow)
}
}
}
@Composable
fun HorizontalColorBar(color:Color){
Surface(color=color,
modifier = Modifier
.wrapContentSize(
align = Alignment.TopCenter
)
.width(50.dp)
.height(680.dp)
)
{
// Text(text="wrapped content",
//// modifier = Modifier.wrapContentSize(),
// style=MaterialTheme.typography.h4)
}
}
@Composable
fun VerticalColorBar(color:Color){
Surface(color=color,
modifier = Modifier
.wrapContentSize(
align = Alignment.TopCenter
)
.width(80.dp)
.height(80.dp)
)
{
// Text(text="wrapped content",
//// modifier = Modifier.wrapContentSize(),
// style=MaterialTheme.typography.h4)
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!",
modifier = Modifier
.height(240.dp)
.width(80.dp)
// .fillMaxWidth()
// .size(180.dp,80.dp)
// .fillMaxHeight()
)
}
@Preview(showBackground = true)
@Composable
fun UserProfileDetail() {
TutorialTheme() {
UserProfileDetailsScreen(userId = 0,null)
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
TutorialTheme() {
MainScreen4(userProfiles = userProfileList,null)
}
}
| MC_Assign1/app/src/main/java/com/example/tutorial/MainActivity.kt | 577759671 |
package com.codingtroops.profilecardlayout
data class UserProfile constructor(val id: Int, val name: String, val status: Boolean, val pictureUrl: String)
val userProfileList = arrayListOf(
UserProfile(
id = 0,
name = "Michaela Runnings",
status = true,
"https://images.unsplash.com/photo-1485290334039-a3c69043e517?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80"
),
UserProfile(
id = 1,
name = "John Pestridge",
status = false,
"https://images.unsplash.com/photo-1542178243-bc20204b769f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 2,
name = "Manilla Andrews",
status = true,
"https://images.unsplash.com/photo-1543123820-ac4a5f77da38?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDh8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 3,
name = "Dan Spicer",
status = false,
"https://images.unsplash.com/photo-1595152772835-219674b2a8a6?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDd8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 4,
name = "Keanu Dester",
status = false,
"https://images.unsplash.com/photo-1597528380214-aa94bde3fc32?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NTZ8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 5,
name = "Anichu Patel",
status = false,
"https://images.unsplash.com/photo-1598641795816-a84ac9eac40c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NjJ8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 6,
name = "Kienla Onso",
status = true,
"https://images.unsplash.com/photo-1566895733044-d2bdda8b6234?ixid=MXwxMjA3fDB8MHxzZWFyY2h8ODh8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 7,
name = "Andra Matthews",
status = false,
"https://images.unsplash.com/photo-1530577197743-7adf14294584?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NTV8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 8,
name = "Georgia S.", status = false,
"https://images.unsplash.com/photo-1547212371-eb5e6a4b590c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTA3fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 9,
name = "Matt Dengo",
status = false,
"https://images.unsplash.com/photo-1578176603894-57973e38890f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTE0fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
UserProfile(
id = 10,
name = "Marsha T.",
status = true,
"https://images.unsplash.com/photo-1605087880595-8cc6db61f3c6?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTI0fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
),
) | MC_Assign1/app/src/main/java/com/example/tutorial/UserProfile.kt | 2211528335 |
package com.example.android.roomwordssample
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
/**
* This is not meant to be a full set of tests. For simplicity, most of your samples do not
* include tests. However, when building the Room, it is helpful to make sure it works before
* adding the UI.
*/
@RunWith(AndroidJUnit4::class)
class WordDaoTest {
private lateinit var wordDao: WordDao
private lateinit var db: WordRoomDatabase
@Before
fun createDb() {
val context: Context = ApplicationProvider.getApplicationContext()
// Using an in-memory database because the information stored here disappears when the
// process is killed.
db = Room.inMemoryDatabaseBuilder(context, WordRoomDatabase::class.java)
// Allowing main thread queries, just for testing.
.allowMainThreadQueries()
.build()
wordDao = db.wordDao()
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
@Test
@Throws(Exception::class)
fun insertAndGetWord() = runBlocking {
val word = Word("word")
wordDao.insert(word)
val allWords = wordDao.getAlphabetizedWords().first()
assertEquals(allWords[0].word, word.word)
}
@Test
@Throws(Exception::class)
fun getAllWords() = runBlocking {
val word = Word("aaa")
wordDao.insert(word)
val word2 = Word("bbb")
wordDao.insert(word2)
val allWords = wordDao.getAlphabetizedWords().first()
assertEquals(allWords[0].word, word.word)
assertEquals(allWords[1].word, word2.word)
}
@Test
@Throws(Exception::class)
fun deleteAll() = runBlocking {
val word = Word("word")
wordDao.insert(word)
val word2 = Word("word2")
wordDao.insert(word2)
wordDao.deleteAll()
val allWords = wordDao.getAlphabetizedWords().first()
assertTrue(allWords.isEmpty())
}
}
| codelab-android-room-with-a-view-kotlin/app/src/androidTest/java/com/example/android/roomwordssample/WordDaoTest.kt | 4188374801 |
package com.example.android.roomwordssample
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class WordViewModel(private val repository: WordRepository) : ViewModel() {
val allWords: LiveData<List<Word>> = repository.allWords.asLiveData()
/**
* Launching a new coroutine to insert the data in a non-blocking way
*/
fun insert(word: Word) = viewModelScope.launch {
repository.insert(word)
}
}
class WordViewModelFactory(private val repository: WordRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(WordViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return WordViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/WordViewModel.kt | 246626362 |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val wordViewModel: WordViewModel by viewModels {
WordViewModelFactory((application as WordsApplication).repository)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
insertTestData()
}
private fun insertTestData() {
// Crea una instancia de la clase Word y llama a la función insert del ViewModel
val word = Word(word = "Prueba1")
wordViewModel.insert(word)
// Puedes repetir este proceso para insertar más datos de prueba si es necesario
}
} | codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/MainActivity.kt | 2911980947 |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import androidx.annotation.WorkerThread
import kotlinx.coroutines.flow.Flow
/**
* Abstracted Repository as promoted by the Architecture Guide.
* https://developer.android.com/topic/libraries/architecture/guide.html
*/
class WordRepository(private val wordDao: WordDao) {
val allWords: Flow<List<Word>> = wordDao.getAlphabetizedWords()
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun insert(word: Word) {
wordDao.insert(word)
}
}
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/WordRepository.kt | 434007874 |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "word_table")
data class Word(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Long = 0,
@ColumnInfo(name = "word")
val word: String
)
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/Word.kt | 996406005 |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlinx.coroutines.CoroutineScope
/**
* This is the backend. The database. This used to be done by the OpenHelper.
* The fact that this has very few comments emphasizes its coolness.
*/
@Database(entities = [Word::class], version = 1)
abstract class WordRoomDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao
companion object {
@Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(
context: Context,
scope: CoroutineScope
): WordRoomDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
WordRoomDatabase::class.java,
"word_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
// return instance
instance
}
}
}
}
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/WordRoomDatabase.kt | 3518933458 |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface WordDao {
@Query("SELECT * FROM word_table ORDER BY word ASC")
fun getAlphabetizedWords(): Flow<List<Word>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(word: Word)
@Query("DELETE FROM word_table")
suspend fun deleteAll()
}
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/WordDao.kt | 3304686357 |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.roomwordssample
import android.app.Application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
class WordsApplication : Application() {
val applicationScope = CoroutineScope(SupervisorJob())
val database by lazy { WordRoomDatabase.getDatabase(this, applicationScope) }
val repository by lazy { WordRepository(database.wordDao()) }
}
| codelab-android-room-with-a-view-kotlin/app/src/main/java/com/example/android/roomwordssample/WordsApplication.kt | 1702230108 |
package com.example.memorise
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.memorise", appContext.packageName)
}
} | MemoRise/app/src/androidTest/java/com/example/memorise/ExampleInstrumentedTest.kt | 1964984290 |
package com.example.memorise
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.memorise.ui.MainActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.regex.Pattern.matches
@RunWith(AndroidJUnit4::class)
class HomeFragmentUITest {
@get:Rule
var activityScenarioRule = activityScenarioRule<MainActivity>()
@Test
fun testNotesDisplay() {
// Given: The app is open
// When: Navigating to the home fragment
onView(withId(R.id.homeFragment)).perform(click())
// Then: Verify the RecyclerView is displayed
// onView(withId(R.id.lottie)).check(matches(isDisplayed()))
}
} | MemoRise/app/src/androidTest/java/com/example/memorise/HomeFragmentUITest.kt | 1209600885 |
package com.example.memorise
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)
}
} | MemoRise/app/src/test/java/com/example/memorise/ExampleUnitTest.kt | 2150490048 |
package com.example.memorise.viewModel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.memorise.model.Note
import com.example.memorise.repository.NoteRepo
import kotlinx.coroutines.launch
class NoteViewModel(
app: Application,
private val noteRepository: NoteRepo
) : AndroidViewModel(app) {
fun addNote(note: Note) =
viewModelScope.launch {
noteRepository.insertNote(note)
}
fun deleteNote(note: Note) =
viewModelScope.launch {
noteRepository.deleteNote(note)
}
fun getAllNote() = noteRepository.getNotes()
} | MemoRise/app/src/main/java/com/example/memorise/viewModel/NoteViewModel.kt | 68140703 |
package com.example.memorise.viewModel
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.memorise.repository.NoteRepo
class NoteViewModelProviderFactory(
val app: Application,
private val noteRepository: NoteRepo
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return NoteViewModel(app, noteRepository) as T
}
} | MemoRise/app/src/main/java/com/example/memorise/viewModel/NoteViewModelProviderFactory.kt | 706211901 |
package com.example.memorise.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.example.memorise.R
import com.example.memorise.data.database.NoteDatabase
import com.example.memorise.databinding.ActivityMainBinding
import com.example.memorise.repository.NoteRepo
import com.example.memorise.viewModel.NoteViewModel
import com.example.memorise.viewModel.NoteViewModelProviderFactory
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
lateinit var noteViewModel: NoteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
setUpViewModel()
}
private fun setUpViewModel() {
val noteRepository = NoteRepo(
NoteDatabase(this)
)
val viewModelProviderFactory =
NoteViewModelProviderFactory(
application, noteRepository
)
noteViewModel = ViewModelProvider(
this,
viewModelProviderFactory
).get(NoteViewModel::class.java)
}
} | MemoRise/app/src/main/java/com/example/memorise/ui/MainActivity.kt | 1465264277 |
package com.example.memorise.ui.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import com.example.memorise.R
import com.example.memorise.databinding.LayoutAdapterBinding
import com.example.memorise.model.Note
import com.example.memorise.fragments.EditNoteFragment
import com.example.memorise.fragments.HomeFragment
import com.example.memorise.fragments.HomeFragmentDirections
import com.example.memorise.fragments.NoteFragment
import java.util.Random
class NoteAdapter: RecyclerView.Adapter<NoteAdapter.NoteViewHolder>() {
class NoteViewHolder(val itemBinding: LayoutAdapterBinding) :
RecyclerView.ViewHolder(itemBinding.root)
private val differCallback =
object : DiffUtil.ItemCallback<Note>() {
override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean {
return oldItem.id == newItem.id &&
oldItem.description == newItem.description &&
oldItem.title == newItem.title
}
override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
return NoteViewHolder(
LayoutAdapterBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
)
}
override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
val currentNote = differ.currentList[position]
holder.itemBinding.tvTitle.text = currentNote.title
holder.itemBinding.tvDescription.text = currentNote.description
val random = Random()
fun generatePastelColorWithBlackText(): Int {
// Fijar el componente de alfa a 255 (totalmente opaco)
val alpha = 255
// Generar valores aleatorios para los componentes HSB (Tono, Saturación, Brillo)
val hue = random.nextFloat() * 360
val saturation = 0.5f + random.nextFloat() * 0.5f // Saturación en el rango 0.5 - 1.0
val brightness = 0.6f + random.nextFloat() * 0.4f // Brillo en el rango 0.6 - 1.0
// Convertir HSB a RGB
val rgb = FloatArray(3)
Color.colorToHSV(Color.BLACK, rgb)
rgb[0] = hue
rgb[1] = saturation
rgb[2] = brightness
// Convertir de nuevo a RGB
val pastelColor = Color.HSVToColor(alpha, rgb)
return pastelColor
}
val color = generatePastelColorWithBlackText()
holder.itemBinding.cardView.setBackgroundColor(color)
holder.itemView.setOnClickListener { view ->
val direction = HomeFragmentDirections
.actionHomeFragment2ToEditNoteFragment2(currentNote)
view.findNavController().navigate(direction)
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
} | MemoRise/app/src/main/java/com/example/memorise/ui/adapter/NoteAdapter.kt | 191191135 |
package com.example.memorise.repository
import com.example.memorise.data.database.NoteDatabase
import com.example.memorise.model.Note
class NoteRepo(private val database: NoteDatabase) {
suspend fun insertNote(note: Note) = database.getDao().insert(note)
suspend fun deleteNote(note: Note) = database.getDao().delete(note)
fun getNotes() = database.getDao().getNotes()
} | MemoRise/app/src/main/java/com/example/memorise/repository/NoteRepo.kt | 3327494555 |
MemoRise/app/src/main/java/com/example/memorise/NoteApplication.kt | 0 |
|
package com.example.memorise.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import com.example.memorise.R
import com.example.memorise.databinding.FragmentNoteBinding
import com.example.memorise.model.Note
import com.example.memorise.ui.MainActivity
import com.example.memorise.viewModel.NoteViewModel
import com.google.android.material.snackbar.Snackbar
import kotlin.random.Random
class NoteFragment : Fragment(R.layout.fragment_note) {
private var _binding: FragmentNoteBinding? = null
private val binding get() = _binding!!
private lateinit var noteViewModel: NoteViewModel
private lateinit var mView: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentNoteBinding.inflate(
inflater,
container,
false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
noteViewModel = (activity as MainActivity).noteViewModel
mView = view
}
private fun generateRandomId(): Int {
return Random.nextInt(1, 9999)
}
private fun saveNote(view: View) {
val noteTitle = binding.etNoteTitle.text.toString().trim()
val noteBody = binding.etNoteBody.text.toString().trim()
val randomId = generateRandomId()
if (noteTitle.isNotEmpty()) {
val note = Note(randomId, noteTitle, noteBody)
noteViewModel.addNote(note)
Snackbar.make(
view, "Nota guardada",
Snackbar.LENGTH_SHORT
).show()
view.findNavController().navigate(R.id.action_noteFragment2_to_homeFragment2)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.new_note, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_save -> {
saveNote(mView)
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
}
| MemoRise/app/src/main/java/com/example/memorise/fragments/NoteFragment.kt | 4120211646 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.