Skip to content

Commit

Permalink
Firebase Storage 연결 및 MainActivity 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
moon0900 committed Nov 29, 2024
1 parent cc55ab0 commit c636330
Show file tree
Hide file tree
Showing 18 changed files with 250 additions and 123 deletions.
6 changes: 3 additions & 3 deletions .idea/appInsightsSettings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions .idea/runConfigurations.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ dependencies {
implementation("com.google.firebase:firebase-storage-ktx")
implementation("com.google.firebase:firebase-database-ktx")

// Glide (이미지 로드 라이브러리)
implementation("com.github.bumptech.glide:glide:4.16.0")

// google login
implementation ("com.google.android.gms:play-services-auth:21.2.0")

Expand Down
54 changes: 53 additions & 1 deletion app/src/main/java/com/dna/beyoureyes/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,32 @@ package com.dna.beyoureyes

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.dna.beyoureyes.databinding.ActivityMainBinding
import com.dna.beyoureyes.model.FoodHistory
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.Firebase
import com.google.firebase.Timestamp
import com.google.firebase.firestore.firestore
import java.util.Calendar

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

val foodHistoryItems = mutableListOf<FoodHistory>() // 음식 기록 리스트

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)


// 레이아웃 바인딩
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

// 하단 네비게이션 뷰 초기화
val navView: BottomNavigationView = binding.navView

Expand All @@ -28,6 +36,50 @@ class MainActivity : AppCompatActivity() {
val navController = findNavController(R.id.nav_host_fragment_activity_main)
navView.setupWithNavController(navController)

// 오늘의 시작 시간 (자정)
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
val startOfDay = calendar.time // 오늘 00:00:00

// 오늘의 끝 시간 (23:59:59)
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
calendar.set(Calendar.SECOND, 59)
calendar.set(Calendar.MILLISECOND, 999)
val endOfDay = calendar.time // 오늘 23:59:59

// Firestore 쿼리에 사용할 Timestamp 생성(오늘 날짜에 해당하는 timestamp 범위 검색)
val startTimestamp = Timestamp(startOfDay)
val endTimestamp = Timestamp(endOfDay)

// Firebase에서 사용자의 오늘 섭취량 데이터 가져오기
val db = Firebase.firestore // Firebase 연결을 위한 설정값

// DB에서 총 섭취량 가져오기
db.collection("userIntakeNutrition")
.whereEqualTo("userId", AppUser.id)
.whereEqualTo("userId", AppUser.id)
.whereGreaterThanOrEqualTo("date", startTimestamp)
.whereLessThanOrEqualTo("date", endTimestamp) // 오늘 날짜 해당하는 것만
.get()
.addOnSuccessListener { result -> // DB 연결 성공
if (!result.isEmpty) {
// 쿼리 결과 있는지 검사 = 오늘 섭취 기록 존재.
for (document in result) {
val history = FoodHistory(document) // 문서로부터 음식 기록 객체 생성
foodHistoryItems.add(history) // 리스트에 저장
}
}
}
.addOnFailureListener { exception -> // DB 연결 실패 처리
Log.w("HOME", "Error getting documents.", exception)
}.addOnCompleteListener {
// 데이터 로드를 마친 후 프래그먼트 화면 갱신
navController.navigate(R.id.navigation_home)
}
}

private fun Float.toDp(context: Context): Float {
Expand Down
8 changes: 6 additions & 2 deletions app/src/main/java/com/dna/beyoureyes/model/Carbs.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class Carbs(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,7 +15,8 @@ class Carbs(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)

override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)

// static 영역
companion object {
Expand All @@ -30,5 +31,8 @@ class Carbs(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return milligram < 100 * 1000 // 성별, 나이 무관 평균 필요량 100g (최소한의 섭취 기준)
}
fun fromFirestore(document: DocumentSnapshot): Carbs? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Carbs(it) }
}
}
}
7 changes: 6 additions & 1 deletion app/src/main/java/com/dna/beyoureyes/model/Cholesterol.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class Cholesterol(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,6 +15,8 @@ class Cholesterol(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)
override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)


// static 영역
Expand All @@ -40,5 +42,8 @@ class Cholesterol(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return getDailyValue() <= milligram
}
fun fromFirestore(document: DocumentSnapshot): Cholesterol? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Cholesterol(it) }
}
}
}
7 changes: 6 additions & 1 deletion app/src/main/java/com/dna/beyoureyes/model/Fat.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class Fat(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,7 +16,8 @@ class Fat(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)

override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)

// static 영역
companion object {
Expand All @@ -41,5 +43,8 @@ class Fat(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return milligram > getDailyValue() // 권장 범위를 초과하는지 검사
}
fun fromFirestore(document: DocumentSnapshot): Fat? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Fat(it) }
}
}
}
41 changes: 39 additions & 2 deletions app/src/main/java/com/dna/beyoureyes/model/FoodHistory.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,42 @@
package com.dna.beyoureyes.model

class FoodHistory(val label: String, val kcal: Int, val img:Int) {
import android.net.Uri
import android.util.Log
import com.bumptech.glide.Glide
import com.google.firebase.Firebase
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.storage.storage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await

}
class FoodHistory(
val timestamp:Timestamp? = null,
val kcal: Int? = null,
val nutritions: List<Nutrition>,
var imgUri: Uri? = null) {

constructor(document: DocumentSnapshot) : this(
timestamp = document.getTimestamp("date"),
kcal = document.getLong("calories")?.toInt() ?:0,
nutritions = listOf(
Natrium(), Carbs(), Sugar(), Protein(), Fat(), SaturatedFat(), Cholesterol()
).mapNotNull { type -> type.fromFirestore(document) })
{
val imgPath = document.getString("imgPath")
// 이미지 Uri 로드는 파이어스토어와의 통신이 필요하므로 CouroutineScoope에서 정의하여 값 동기화
CoroutineScope(Dispatchers.Main).launch {
imgUri = try {
imgPath?.let {
val storageRef = Firebase.storage.reference.child(it)
storageRef.downloadUrl.await() // 비동기 작업을 동기적으로 기다림
}
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
}
6 changes: 6 additions & 0 deletions app/src/main/java/com/dna/beyoureyes/model/Natrium.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class Natrium(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,6 +16,8 @@ class Natrium(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)
override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)


// static 영역
Expand Down Expand Up @@ -45,5 +48,8 @@ class Natrium(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return getDailyValue() < milligram
}
fun fromFirestore(document: DocumentSnapshot): Natrium? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Natrium(it) }
}
}
}
3 changes: 3 additions & 0 deletions app/src/main/java/com/dna/beyoureyes/model/Nutrition.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.dna.beyoureyes.model

import com.google.firebase.firestore.DocumentSnapshot

interface Nutrition {

val name : String // 영양소명
Expand All @@ -10,4 +12,5 @@ interface Nutrition {
fun getDailyValueText() : String // 영양소의 일일 권장량 문자열 반환
fun isInWarningRange() : Boolean // 영양소의 질량이 권장량 대비 경고 범위에 포함되었는지 검사

fun fromFirestore(document: DocumentSnapshot): Nutrition? // 파이어스토어 문서 파싱하여 객체 생성
}
6 changes: 6 additions & 0 deletions app/src/main/java/com/dna/beyoureyes/model/Protein.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.dna.beyoureyes.Gender
import com.google.firebase.firestore.DocumentSnapshot

class Protein(override var milligram: Int = 0) : Nutrition {

Expand All @@ -16,6 +17,8 @@ class Protein(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)
override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)


// static 영역
Expand Down Expand Up @@ -63,5 +66,8 @@ class Protein(override var milligram: Int = 0) : Nutrition {
return lower > milligram
}
}
fun fromFirestore(document: DocumentSnapshot): Protein? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Protein(it) }
}
}
}
6 changes: 6 additions & 0 deletions app/src/main/java/com/dna/beyoureyes/model/SaturatedFat.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class SaturatedFat(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,6 +16,8 @@ class SaturatedFat(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)
override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)


// static 영역
Expand All @@ -32,5 +35,8 @@ class SaturatedFat(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return milligram > getDailyValue()
}
fun fromFirestore(document: DocumentSnapshot): SaturatedFat? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { SaturatedFat(it) }
}
}
}
6 changes: 6 additions & 0 deletions app/src/main/java/com/dna/beyoureyes/model/Sugar.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dna.beyoureyes.model

import com.dna.beyoureyes.AppUser
import com.google.firebase.firestore.DocumentSnapshot

class Sugar(override var milligram: Int = 0) : Nutrition {

Expand All @@ -15,6 +16,8 @@ class Sugar(override var milligram: Int = 0) : Nutrition {
= Companion.getDailyValueText()
override fun isInWarningRange(): Boolean
= Companion.isInWarningRange(milligram)
override fun fromFirestore(document: DocumentSnapshot): Nutrition?
= Companion.fromFirestore(document)


// static 영역
Expand All @@ -32,5 +35,8 @@ class Sugar(override var milligram: Int = 0) : Nutrition {
fun isInWarningRange(milligram: Int): Boolean {
return milligram > getDailyValue()*2 // 일일 권장 칼로리의 20% 이내인지 검사
}
fun fromFirestore(document: DocumentSnapshot): Sugar? {
return document.getLong(DB_FIELD_NAME)?.toInt()?.let { Sugar(it) }
}
}
}
Loading

0 comments on commit c636330

Please sign in to comment.