Compare commits

...

2 Commits

Author SHA1 Message Date
7f9450d02e 3 Lab 2023-11-09 09:56:31 +04:00
750e362438 2 Lab 2023-10-26 00:00:08 +04:00
28 changed files with 1137 additions and 60 deletions

View File

@ -1,6 +1,7 @@
plugins { plugins {
id("com.android.application") id("com.android.application")
id("org.jetbrains.kotlin.android") id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp")
} }
android { android {
@ -23,21 +24,24 @@ android {
buildTypes { buildTypes {
release { release {
isMinifyEnabled = false isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
} }
} }
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_17
} }
kotlinOptions { kotlinOptions {
jvmTarget = "1.8" jvmTarget = "17"
} }
buildFeatures { buildFeatures {
compose = true compose = true
} }
composeOptions { composeOptions {
kotlinCompilerExtensionVersion = "1.4.3" kotlinCompilerExtensionVersion = "1.4.5"
} }
packaging { packaging {
resources { resources {
@ -45,17 +49,33 @@ android {
} }
} }
} }
//kotlin {
//// jvmToolchain(11)
//}
dependencies { dependencies {
// Core
implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
implementation("androidx.activity:activity-compose:1.7.0")
// UI
implementation("androidx.activity:activity-compose:1.7.2")
implementation(platform("androidx.compose:compose-bom:2023.03.00")) implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.navigation:navigation-compose:2.6.0")
implementation("androidx.compose.ui:ui") implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics") implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview") implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3") implementation("androidx.compose.material3:material3")
// Room
val room_version = "2.5.2"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
ksp("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$room_version")
implementation("androidx.room:room-paging:$room_version")
// Tests
testImplementation("junit:junit:4.13.2") testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")

View File

@ -0,0 +1,51 @@
package com.example.myapplication.Dishes.Model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
//enum class Category(
// val value: String,
//) {
// CHICKEN("Chicken"),
// BEEF("Beef"),
// SOUP("Soup"),
// DESSERT("Dessert"),
// VEGETARIAN("Vegetarian"),
// MILK("Milk"),
// VEGAN("Vegan"),
// PIZZA("Pizza"),
// DONUT("Donut");
//
// companion object {
// val allDishCategories = listOf(
// CHICKEN, BEEF, SOUP, DESSERT, VEGETARIAN, MILK, VEGAN, PIZZA, DONUT
// )
//
// fun getDishCategory(value: String): Category? {
// val map = Category.values().associateBy(Category::value)
// return map[value]
// }
// }
//}
@Entity(tableName="categories")
data class Category(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name="category_id")
val uid: Int?,
@ColumnInfo(name = "category_name")
val name: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Category
if (uid != other.uid) return false
return true
}
override fun hashCode(): Int {
return uid ?: -1
}
}

View File

@ -0,0 +1,84 @@
package com.example.myapplication.Dishes.Model
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.example.myapplication.R
import com.example.myapplication.User.Model.User
import java.io.Serializable
//data class Dish (
// val name: String,
// val description: Int,
// val author: User,
// val category: Category,
// val favorite: Boolean,
// val image: Int?
//) : Serializable
//fun getAllDishes(): List<Dish> {
// return listOf(
//
//}
@Entity(tableName = "dishes", foreignKeys = [
ForeignKey(
entity = User::class,
parentColumns = ["user_id"],
childColumns = ["user_id"],
onDelete = ForeignKey.NO_ACTION,
onUpdate = ForeignKey.NO_ACTION
),
ForeignKey(
entity = Category::class,
parentColumns = ["category_id"],
childColumns = ["category_id"],
onDelete = ForeignKey.NO_ACTION,
onUpdate = ForeignKey.NO_ACTION
)
])
data class Dish(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "dish_id")
val uid: Int?,
@ColumnInfo(name = "dish_name")
val name: String,
val description: String,
@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
val image: ByteArray?,
@ColumnInfo(name="user_id", index = true)
val userId: Int?,
@ColumnInfo(name="category_id", index = true)
val categoryId: Int?
) {
@Ignore
constructor(
uid: Int?,
name: String,
description: String,
image: ByteArray?,
user: User,
category: Category
) : this (uid, name, description, image, user.uid, category.uid)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Dish
if (uid != other.uid) return false
return true
}
override fun hashCode(): Int {
return uid ?: -1
}
fun getBitmapFromByteArray(): Bitmap? {
if (image == null) return null
return BitmapFactory.decodeByteArray(image, 0, image.size)
}
}

View File

@ -0,0 +1,13 @@
package com.example.myapplication.Dishes.Model
import androidx.room.ColumnInfo
import androidx.room.Embedded
data class DishWithCategoryAndUser(
@Embedded
val dish: Dish?,
@ColumnInfo(name="nickname")
val nickname: String?,
@ColumnInfo(name="category_name")
val categoryName: String?,
)

View File

@ -0,0 +1,23 @@
package com.example.myapplication.Dishes.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.myapplication.Dishes.Model.Category
@Dao
interface CategoryDao {
@Query("select * from categories order by category_name collate nocase asc")
fun getAll(): List<Category>
@Insert
suspend fun insert(category: Category)
@Update
suspend fun update(category: Category)
@Delete
suspend fun delete(category: Category)
}

View File

@ -0,0 +1,31 @@
package com.example.myapplication.Dishes.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.myapplication.Dishes.Model.Dish
import com.example.myapplication.Dishes.Model.DishWithCategoryAndUser
import kotlinx.coroutines.flow.Flow
@Dao
interface DishDao {
@Query("select * from dishes order by dish_name collate nocase asc")
fun getAll(): Flow<List<Dish>>
@Query("select * from dishes left join categories on dishes.category_id = categories.category_id " +
"left join users on dishes.user_id = users.user_id where dishes.dish_id = :uid")
suspend fun getByUid(uid: Int): DishWithCategoryAndUser
@Query("select * from dishes where dishes.user_id = :uid")
fun getAllOFUser(uid: Int): Flow<List<Dish>>
@Insert
suspend fun insert(category: Dish)
@Update
suspend fun update(category: Dish)
@Delete
suspend fun delete(category: Dish)
}

View File

@ -0,0 +1,195 @@
package com.example.myapplication.Dishes.ui
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.Dishes.Model.Dish
//import com.example.myapplication.Dishes.Model.getAllDishes
import com.example.myapplication.R
import com.example.myapplication.User.Model.User
import com.example.myapplication.User.Model.UserFavorites
import com.example.myapplication.database.AppDatabase
import com.example.myapplication.ui.theme.MyApplicationTheme
import com.example.myapplication.ui.theme.textFont
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun DishList(navController: NavController?, onlyFavorites: Boolean = false, someUser: Int? = remember { null }, userPage: Boolean = false) {
val context = LocalContext.current
val dishes = remember { mutableStateListOf<Dish>() }
val favoriteDishes = remember { mutableStateListOf<Dish>() }
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
if (someUser != null && onlyFavorites) {
AppDatabase.getInstance(context).userFavoritesDao().getUserFavorites(someUser).collect() {data ->
dishes.clear()
favoriteDishes.clear()
dishes.addAll(data)
favoriteDishes.addAll(data)
}
}
else if (someUser != null && userPage) {
AppDatabase.getInstance(context).dishDao().getAllOFUser(someUser).collect() {data ->
dishes.clear()
favoriteDishes.clear()
dishes.addAll(data)
AppDatabase.getInstance(context).userFavoritesDao().getUserFavorites(someUser).collect() {data ->
favoriteDishes.addAll(data)
}
}
}
else {
AppDatabase.getInstance(context).dishDao().getAll().collect() { data ->
dishes.clear()
favoriteDishes.clear()
dishes.addAll(data)
AppDatabase.getInstance(context).userFavoritesDao().getUserFavorites(someUser).collect() {data ->
favoriteDishes.addAll(data)
}
}
}
}
}
Column(
Modifier
.fillMaxSize()
.verticalScroll(ScrollState(0))) {
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) {
Column {
var text = stringResource(R.string.all_dishes)
if (onlyFavorites) text = stringResource(id = R.string.favorite_dishes)
if (userPage) text = stringResource(id = R.string.user_dishes)
Text(text, fontFamily= textFont,
fontSize=26.sp, textAlign = TextAlign.Start)
}
}
dishes.forEachIndexed() {index, dish ->
Row(
Modifier
.padding(vertical = 5.dp)
.fillMaxSize()
.clickable {
navController?.navigate("dish/" + dish.uid!!)
}) {
Column() {
if (dish.image != null) { // TODO Image input check
Image(
bitmap = dish.getBitmapFromByteArray()!!.asImageBitmap(),
contentDescription = "Dish Image",
Modifier.width(150.dp)
)
}
else {
Image(
Icons.Filled.Warning,
contentDescription = "Dish Image",
Modifier.width(150.dp)
)
}
}
Column {
Text(dish.name, fontFamily=textFont,
fontSize=15.sp, textAlign=TextAlign.Center )
Text(
dish.description, fontFamily=textFont,
fontSize = 12.sp,
softWrap = true,
overflow = TextOverflow.Ellipsis,
maxLines = 3)
}
Column(
Modifier
.clickable {
scope.launch {
if (favoriteDishes.contains(dish)) {
AppDatabase
.getInstance(context)
.userFavoritesDao()
.delete(
UserFavorites(someUser!!, dish.uid!!)
).run { favoriteDishes.clear() }
}
else {
AppDatabase
.getInstance(context)
.userFavoritesDao()
.insert(
UserFavorites(someUser!!, dish.uid!!)
).run { favoriteDishes.clear() }
}
}
}
.padding(horizontal = 5.dp)
) {
if (favoriteDishes.contains(dish)) {
Icon(Icons.Filled.Favorite, contentDescription = "")
}
else {
Icon(Icons.Filled.FavoriteBorder, contentDescription = "")
}
}
}
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
@Preview
@Composable
fun ListDishes() {
MyApplicationTheme {
Surface(
color = MaterialTheme.colorScheme.background
) {
DishList(navController = null, onlyFavorites = false)
}
}
}

View File

@ -0,0 +1,115 @@
package com.example.myapplication.Dishes.ui
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.Dishes.Model.Dish
import com.example.myapplication.Dishes.Model.DishWithCategoryAndUser
import com.example.myapplication.R
import com.example.myapplication.database.AppDatabase
//import com.example.myapplication.Dishes.Model.getAllDishes
import com.example.myapplication.ui.theme.MyApplicationTheme
import com.example.myapplication.ui.theme.textFont
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun DishView(id: Int) {
var dish = remember { mutableStateOf(DishWithCategoryAndUser(
Dish(0, "", "", null, null, null),
null, null))
}
val context = LocalContext.current
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
dish.value = AppDatabase.getInstance(context).dishDao().getByUid(id)
}
}
Column(
Modifier
.fillMaxWidth()
.padding(vertical = 5.dp, horizontal = 10.dp)
.verticalScroll(ScrollState(0))) {
Row(Modifier.padding(vertical = 5.dp)) {
if (dish.value.dish?.image != null) { // TODO Image input check
Image(
bitmap = dish.value.dish!!.getBitmapFromByteArray()!!.asImageBitmap(),
contentDescription = "Dish Image",
Modifier.fillMaxSize()
)
}
else {
Image(
painterResource(id = R.drawable.sushi),
contentDescription = "Dish Image",
Modifier.fillMaxSize()
)
}
}
Row(horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth()) {
Column {
Text(dish.value.dish!!.name, fontFamily=textFont,
fontSize=15.sp, textAlign = TextAlign.Start)
}
Column {
Text("@" + dish.value.nickname, fontFamily=textFont,
fontSize=15.sp, textAlign = TextAlign.End)
}
}
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier
.fillMaxSize()
.padding(
horizontal = 30.dp, vertical = 10.dp
)) {
Text(
dish.value.dish!!.description,
fontFamily=textFont,
fontSize = 13.sp,
softWrap = true,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
@Preview
@Composable
fun DishPreview() {
MyApplicationTheme {
Surface(
color = MaterialTheme.colorScheme.background
) {
DishView(id = 0)
}
}
}

View File

@ -1,43 +1,40 @@
package com.example.myapplication package com.example.myapplication
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.database.AppDatabase
import com.example.myapplication.ui.navigation.MainNavbar
import com.example.myapplication.ui.theme.MyApplicationTheme import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.Q)
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContent { setContent {
MyApplicationTheme { MyApplicationTheme {
// A surface container using the 'background' color from the theme Surface(
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { modifier = Modifier.fillMaxSize(),
Greeting("Android") color = MaterialTheme.colorScheme.background
) {
MainNavbar();
} }
} }
} }
} }
} }
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
Greeting("Android")
}
}

View File

@ -0,0 +1,42 @@
package com.example.myapplication.User.Model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
//data class User (
// val nickname: String,
// val email: String,
// val password: String
//)
//
//val firstUser = User("UserNickname1", "UserEmail1", "UserPassword1")
//val secondUser = User("UserNickname2", "UserEmail2", "UserPassword2")
//fun getAllUsers(): List<User> {
// return listOf(
// firstUser, secondUser
// )
//}
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name="user_id")
val uid: Int?,
val nickname: String,
val email: String,
val password: String,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as User
if (uid != other.uid) return false
return true
}
override fun hashCode(): Int {
return uid ?: -1
}
}

View File

@ -0,0 +1,22 @@
package com.example.myapplication.User.Model;
import androidx.room.ColumnInfo
import androidx.room.Entity;
import androidx.room.ForeignKey
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.example.myapplication.Dishes.Model.Dish
@Entity(tableName = "user_favorites", primaryKeys = ["user_id", "dish_id"])
data class UserFavorites(
@ColumnInfo(name = "user_id")
val userId: Int,
@ColumnInfo(name="dish_id")
val dishId: Int
) {
@Ignore constructor(
user: User,
dish: Dish
) : this (user.uid!!, dish.uid!!)
}

View File

@ -0,0 +1,30 @@
package com.example.myapplication.User.Model
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Junction
import androidx.room.PrimaryKey
import androidx.room.Relation
import com.example.myapplication.Dishes.Model.Dish
data class FavoriteWithUsers(
@Embedded
val dish: Dish,
@Relation(
parentColumn = "dish_id",
entityColumn = "user_id",
associateBy = Junction(UserFavorites::class)
) val users: List<User>
)
data class UserWithFavorites(
@Embedded
val user: User,
@Relation(
parentColumn = "user_id",
entityColumn = "dish_id",
associateBy = Junction(UserFavorites::class)
) val favoriteDishes: List<Dish>
)

View File

@ -0,0 +1,33 @@
package com.example.myapplication.User.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.myapplication.Dishes.Model.Dish
import com.example.myapplication.User.Model.User
import com.example.myapplication.User.Model.UserWithFavorites
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Query("select * from users")
fun getAll(): Flow<List<User>>
@Query("select * from users where users.user_id = :uid")
suspend fun getByUid(uid: Int): User
@Query("select * from user_favorites left join users on user_favorites.user_id = users.user_id " +
"left join dishes on user_favorites.dish_id = dishes.dish_id WHERE user_favorites.user_id = :uid")
suspend fun getFavorites(uid: Int): List<UserWithFavorites>
@Insert
suspend fun insert(user: User)
@Update
suspend fun update(user: User)
@Delete
suspend fun delete(user: User)
}

View File

@ -0,0 +1,32 @@
package com.example.myapplication.User.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.example.myapplication.Dishes.Model.Dish
import com.example.myapplication.User.Model.User
import com.example.myapplication.User.Model.UserFavorites
import kotlinx.coroutines.flow.Flow
@Dao
interface UserFavoritesDao {
@Insert
suspend fun insert(userFavorites: UserFavorites)
@Update
suspend fun update(userFavorites: UserFavorites)
@Delete
suspend fun delete(userFavorites: UserFavorites)
@Transaction
@Query("SELECT * FROM dishes")
fun getUserWithFavorites(): Flow<List<Dish>>
@Transaction
@Query("SELECT * FROM user_favorites us JOIN dishes d ON d.dish_id = us.dish_id WHERE us.user_id = :uid")
fun getUserFavorites(uid: Int?): Flow<List<Dish>>
}

View File

@ -0,0 +1,85 @@
package com.example.myapplication.User.ui
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.modifier.modifierLocalConsumer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
//import com.example.myapplication.Dishes.Model.getAllDishes
import com.example.myapplication.Dishes.ui.DishList
import com.example.myapplication.User.Model.User
import com.example.myapplication.database.AppDatabase
//import com.example.myapplication.User.Model.getAllUsers
import com.example.myapplication.ui.theme.MyApplicationTheme
import com.example.myapplication.ui.theme.textFont
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun UserView(id: Int, navController: NavController?) {
var user = remember { mutableStateOf(User(0, "", "", "")) }
val context = LocalContext.current
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
user.value = AppDatabase.getInstance(context).userDao().getByUid(id)
}
}
Column(
Modifier
.fillMaxWidth()
.padding(vertical = 5.dp, horizontal = 10.dp)) {
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) {
Column {
Text(user.value.nickname, fontFamily= textFont,
fontSize=26.sp, textAlign = TextAlign.Start)
}
}
Row(modifier = Modifier.fillMaxWidth()) {
// Button(onClick = { }, Modifier.fillMaxWidth()) {
// Text("Create New Dish")
// }
}
Row(modifier = Modifier.fillMaxSize()) {
DishList(navController, someUser = id, userPage = true)
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
@Preview
@Composable
fun UserPreview() {
MyApplicationTheme {
Surface(
color = MaterialTheme.colorScheme.background
) {
UserView(id = 0, null)
}
}
}

View File

@ -0,0 +1,95 @@
package com.example.myapplication.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.myapplication.Dishes.Model.Category
import com.example.myapplication.Dishes.Model.Dish
import com.example.myapplication.Dishes.dao.CategoryDao
import com.example.myapplication.Dishes.dao.DishDao
import com.example.myapplication.User.Model.User
import com.example.myapplication.User.Model.UserFavorites
import com.example.myapplication.User.Model.UserWithFavorites
import com.example.myapplication.User.dao.UserDao
import com.example.myapplication.User.dao.UserFavoritesDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Database(entities = [Dish::class, User::class, Category::class, UserFavorites::class],
version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun dishDao() : DishDao
abstract fun userDao() : UserDao
abstract fun categoryDao() : CategoryDao
abstract fun userFavoritesDao() : UserFavoritesDao
companion object {
private const val DB_NAME: String = "food_warriors.db"
@Volatile
private var INSTANCE: AppDatabase? = null
private suspend fun populateDatabase() {
INSTANCE?.let { database ->
// Groups
val categoryDao = database.categoryDao()
val category = Category(1, "Pizza")
val category1 = Category(2, "Sushi")
categoryDao.insert(category)
categoryDao.insert(category1)
// Students
val userDao = database.userDao()
val user = User(1, "Nick1", "1@1.1", "123")
val user1 = User(2, "Nick2", "1@1.1", "234")
val user2 = User(3, "Nick3", "1@1.1", "345")
val user3 = User(4, "Nick4", "1@1.1", "456")
val user4 = User(5, "Nick5", "1@1.1", "567")
userDao.insert(user)
userDao.insert(user1)
userDao.insert(user2)
userDao.insert(user3)
userDao.insert(user4)
val dishDao = database.dishDao()
val dish = Dish(1, "Peperoni", "Lorem ipsum", null, user, category)
val dish1 = Dish(2, "Fish roll", "Lorem ipsum", null, user, category1)
val dish2 = Dish(3, "Lazani", "Lorem ipsum", null, user1, category)
dishDao.insert(dish)
dishDao.insert(dish1)
dishDao.insert(dish2)
val userFavoritesDao = database.userFavoritesDao()
val userFavorites = UserFavorites(user, dish2)
val userFavorites1 = UserFavorites(user3, dish1)
val userFavorites2 = UserFavorites(user3, dish2)
val userFavorites3 = UserFavorites(user1, dish)
userFavoritesDao.insert(userFavorites)
userFavoritesDao.insert(userFavorites1)
userFavoritesDao.insert(userFavorites2)
userFavoritesDao.insert(userFavorites3)
}
}
fun getInstance(appContext: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
Room.databaseBuilder(
appContext,
AppDatabase::class.java,
DB_NAME
)
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
CoroutineScope(Dispatchers.IO).launch {
populateDatabase()
}
}
})
.build()
.also { INSTANCE = it }
}
}
}
}

View File

@ -0,0 +1,67 @@
package com.example.myapplication.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import com.example.myapplication.ui.navigation.Screen
import com.example.myapplication.ui.theme.MyApplicationTheme
@Composable
fun Navbar(
navController: NavHostController?,
currentDestination: NavDestination?,
modifier: Modifier = Modifier
) {
NavigationBar(modifier, containerColor = MaterialTheme.colorScheme.primary) {
Screen.navbarItems.forEach {screen ->
NavigationBarItem(
selected = currentDestination?.hierarchy?.any {it.route == screen.route} == true,
icon = {
if (screen.icon != null) {
Icon(screen.icon, contentDescription = null, modifier = Modifier.width(50.dp).height(50.dp))
}
else if (screen.icon_id != null){
Icon(painter = painterResource(id = screen.icon_id), contentDescription = null, modifier = Modifier.width(50.dp).height(50.dp))
}
},
onClick = {
navController?.navigate(screen.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = false
}
launchSingleTop = true
restoreState = true
} },
)
}
}
}
@Preview(name="Navbar")
@Composable
fun NavBarPreview() {
MyApplicationTheme {
Surface(
color = MaterialTheme.colorScheme.primary
) {
Navbar(navController = null, currentDestination = null)
}
}
}

View File

@ -0,0 +1,96 @@
package com.example.myapplication.ui.navigation
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.myapplication.Dishes.ui.DishList
import com.example.myapplication.Dishes.ui.DishView
import com.example.myapplication.User.Model.User
import com.example.myapplication.User.ui.UserView
import com.example.myapplication.database.AppDatabase
import com.example.myapplication.ui.components.Navbar
import com.example.myapplication.ui.theme.MyApplicationTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun Navhost(
navController: NavHostController,
innerPadding: PaddingValues, modifier:
Modifier = Modifier
) {
val context = LocalContext.current
var someUser: User? = null
NavHost(
navController,
startDestination = Screen.AllDishes.route,
modifier.padding(innerPadding)
) {
composable(Screen.AllDishes.route) { DishList(navController, someUser = 1) }
composable(Screen.FavoriteDishes.route) { DishList(navController, true, 1)}
composable(Screen.UserPage.route) {UserView(id = 1, navController = navController)} // TODO Remove hardcode
composable(Screen.DishView.route,
arguments = listOf(navArgument("id") { type = NavType.IntType })
) { backStackEntry ->
backStackEntry.arguments?.let { DishView(it.getInt("id")) }
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainNavbar() {
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
Scaffold(
bottomBar = {
Navbar(navController, currentDestination, Modifier.background(MaterialTheme.colorScheme.primary))
}
) { innerPadding ->
Navhost(navController, innerPadding)
}
}
@RequiresApi(Build.VERSION_CODES.Q)
@Preview(name = "Dark Mode")
@Composable
fun MainNavbarPreview() {
MyApplicationTheme {
Surface(
color = MaterialTheme.colorScheme.background
) {
MainNavbar()
}
}
}

View File

@ -0,0 +1,37 @@
package com.example.myapplication.ui.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.List
import androidx.compose.ui.graphics.vector.ImageVector
import com.example.myapplication.R
enum class Screen(
val route: String,
@StringRes val resourceId: Int,
val icon: ImageVector? = null,
val icon_id: Int? = null,
) {
AllDishes("all-dishes", R.string.all_dishes, icon_id = R.drawable.cooking_book),
DishView("dish/{id}", R.string.all_dishes, icon=Icons.Filled.Info),
FavoriteDishes("favorite-dishes", R.string.favorite_dishes, icon=Icons.Filled.Favorite),
UserPage("user", R.string.account_title, icon=Icons.Filled.AccountCircle);
companion object {
val navbarItems = listOf(
FavoriteDishes,
AllDishes,
UserPage
)
fun getItem(route: String): Screen? {
val findRoute = route.split("/").first()
return values().find { value -> value.route.startsWith(findRoute) }
}
}
}

View File

@ -2,10 +2,6 @@ package com.example.myapplication.ui.theme
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4) val GreyBackground = Color(0xFFE9DFDF);
val PurpleGrey40 = Color(0xFF625b71) val SkinExtra = Color(0xFFE6CF94)
val Pink40 = Color(0xFF7D5260)

View File

@ -0,0 +1,13 @@
package com.example.myapplication.ui.theme
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.ui.text.font.FontWeight
import com.example.myapplication.R
@RequiresApi(Build.VERSION_CODES.Q)
val textFont = FontFamily(
Font(R.font.header1, FontWeight.Light),
)

View File

@ -10,21 +10,15 @@ import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme( private val LightColorScheme = lightColorScheme(
primary = Purple40, background = GreyBackground,
secondary = PurpleGrey40, primary = SkinExtra
tertiary = Pink40
/* Other default colors to override /* Other default colors to override
background = Color(0xFFFFFBFE), background = Color(0xFFFFFBFE),
@ -44,26 +38,9 @@ fun MyApplicationTheme(
dynamicColor: Boolean = true, dynamicColor: Boolean = true,
content: @Composable () -> Unit content: @Composable () -> Unit
) { ) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme( MaterialTheme(
colorScheme = colorScheme, colorScheme = LightColorScheme,
typography = Typography, typography = Typography,
content = content content = content
) )

View File

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="800dp"
android:height="800dp"
android:viewportWidth="50"
android:viewportHeight="50">
<path
android:pathData="M12,39h32V2H12C8.691,2 6,4.691 6,8v34.417C6,45.496 8.691,48 12,48h32v-2H12c-2.168,0 -4,-1.641 -4,-3.583C8,40.501 9.757,39 12,39zM36.709,31.706C36.514,31.902 36.257,32 36,32c-0.255,0 -0.511,-0.097 -0.705,-0.292l-6.523,-6.494l-1.76,1.76l-1.846,-1.879l3.153,-3.153l8.387,8.349C37.097,30.681 37.099,31.314 36.709,31.706zM16.286,10.007l7.733,7.781l-3.044,3.044L16.23,16C14.568,14.338 14.594,11.637 16.286,10.007zM14.329,30.293l13.024,-13.024c-0.034,-0.085 -0.083,-0.163 -0.107,-0.252c-0.399,-1.509 -0.322,-3.426 1.045,-4.777c2.031,-2.094 5.497,-2.989 6.998,-1.505c1.501,1.571 0.596,4.909 -1.435,6.916c-1.444,1.428 -3.298,1.545 -4.8,1.16c-0.104,-0.027 -0.196,-0.081 -0.294,-0.122L14.743,31.707C14.548,31.902 15.292,32 15.036,32s-0.512,-0.098 -0.707,-0.293C13.938,31.316 13.938,30.684 14.329,30.293z"
android:fillColor="#000000"/>
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

View File

@ -1,3 +1,16 @@
<resources> <resources>
<string name="app_name">My Application</string> <string name="app_name">Food Warriors</string>
<string name="account_title">Account</string>
<string name="all_dishes">All Dishes</string>
<string name="favorite_dishes">Favorite Dishes</string>
<string name="user_dishes">User Dishes</string>
<string name="lorem_ipsum">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam risus orci, ultrices at risus pulvinar, volutpat dapibus ex. Pellentesque vel efficitur libero. Vestibulum consequat, mauris nec vehicula tempus, risus libero dignissim purus, quis porttitor risus metus et erat. Maecenas cursus justo a augue euismod, sed faucibus tortor consectetur. Praesent vitae feugiat ipsum. Sed nulla lacus, varius sit amet libero vitae, ornare auctor enim. Proin molestie arcu sapien, eget accumsan magna dignissim sed. Sed elementum vel nisi vitae sollicitudin. Suspendisse sollicitudin fermentum leo quis fermentum. Aenean semper sem leo, in scelerisque mi eleifend vitae.
Quisque efficitur, nunc vitae varius faucibus, turpis nunc ullamcorper neque, in semper nibh purus ac elit. Nulla dapibus sed sem eu fermentum. Mauris imperdiet sapien ut laoreet cursus. Fusce finibus augue et risus dignissim vehicula. Ut at mi fermentum, posuere nulla ornare, mollis neque. Quisque mattis accumsan odio at commodo. Nullam accumsan fermentum rhoncus. Donec ut sapien velit. Fusce id vulputate augue. Quisque faucibus dolor id leo feugiat feugiat.
Donec molestie scelerisque sollicitudin. Duis orci felis, lacinia laoreet scelerisque sed, molestie sed ipsum. Duis auctor aliquet laoreet. Mauris vitae commodo nibh. Sed pulvinar metus lacus, a faucibus nulla ornare ultricies. Aliquam varius sem a nibh dapibus congue. Phasellus dignissim nibh diam. Etiam elit nulla, bibendum ac quam sed, dictum condimentum ligula.
Phasellus eget ex sed tortor placerat suscipit quis quis magna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean mi quam, auctor quis ante nec, condimentum maximus justo. Morbi varius est massa. Integer nec semper mi. Fusce nisl neque, mollis quis tempus eget, vulputate vitae sem. Donec sit amet maximus augue. Quisque sit amet ante fermentum, bibendum mi ut, porta eros. Phasellus ultrices, augue a fringilla accumsan, elit arcu vehicula lectus, condimentum malesuada lectus enim nec tellus. Nunc ante erat, convallis a dui vitae, rhoncus rhoncus metus. Suspendisse in sapien odio.
Cras semper magna id libero gravida, at varius elit molestie. Quisque ullamcorper nisi tincidunt, feugiat justo nec, aliquam massa. Quisque sit amet quam semper, pretium justo non, tincidunt lorem. Proin rhoncus turpis orci, efficitur dignissim ex sollicitudin eget. Etiam porttitor est eget erat pellentesque, ut maximus mi dictum. Pellentesque ac mauris non eros mollis pharetra et eu augue. Nam a bibendum ipsum, vel pellentesque nisi. Nam gravida dolor sed risus ornare dignissim. Praesent semper, tellus sed posuere efficitur, neque justo efficitur dui, et mollis leo ex in quam. Fusce pulvinar turpis a justo pretium semper. Integer dapibus, risus vel facilisis porttitor, eros sapien venenatis risus, eget aliquet lectus ipsum a orci. Ut at arcu a augue varius gravida non sit amet quam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nullam eget enim eu mauris rutrum pulvinar.
</string>
</resources> </resources>

View File

@ -2,4 +2,5 @@
plugins { plugins {
id("com.android.application") version "8.1.1" apply false id("com.android.application") version "8.1.1" apply false
id("org.jetbrains.kotlin.android") version "1.8.10" apply false id("org.jetbrains.kotlin.android") version "1.8.10" apply false
id("com.google.devtools.ksp") version "1.8.20-1.0.11" apply false
} }