content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.sbscovidapp.domain.model
data class CovidStats(
val date: String,
val lastUpdate: String,
val confirmed: Long = 0,
val confirmedDiff: Long = 0,
val deaths: Long = 0,
val deathsDiff: Long = 0,
val recovered: Long = 0,
val recoveredDiff: Long = 0,
val active: Long = 0,
val activeDiff: Long = 0,
val fatalityRate: Double = 0.0,
) {
companion object {
val Empty = CovidStats("", "")
}
}
| SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/model/CovidStats.kt | 2968901915 |
package com.example.sbscovidapp.domain.model
data class Region(
val iso: String,
val name: String
) {
companion object {
val Global = Region("", "Global")
}
} | SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/model/Region.kt | 978421882 |
package com.example.sbscovidapp.domain.interactor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import java.util.concurrent.atomic.AtomicInteger
class LoadingStateObservable {
private val count = AtomicInteger(0)
private val loadingState = MutableStateFlow(count.get())
val isLoadingFlow: Flow<Boolean> = loadingState
.map { it > 0 }
.distinctUntilChanged()
fun addLoader() {
loadingState.value = count.incrementAndGet()
}
fun removeLoader() {
loadingState.value = count.decrementAndGet()
}
} | SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/interactor/LoadingState.kt | 2280114013 |
package com.example.sbscovidapp.domain.interactor
import com.example.sbscovidapp.domain.model.Region
import com.example.sbscovidapp.domain.repository.CovidDataRepository
import javax.inject.Inject
class GetRegionList
@Inject constructor(
private val repository: CovidDataRepository
) : Interactor<Unit, List<Region>>() {
override suspend fun doWork(params: Unit): Result<List<Region>> =
runCatching {
DefaultRegionList + repository.getRegionList()
}
companion object {
val DefaultRegionList = listOf(Region.Global)
}
} | SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/interactor/GetRegionList.kt | 3828652990 |
package com.example.sbscovidapp.domain.interactor
import android.util.Log
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.withTimeout
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
abstract class Interactor<P : Any, T> {
private val loadingState = LoadingStateObservable()
val isLoading = loadingState.isLoadingFlow
protected open val sharedFlow: MutableSharedFlow<Result<T>?> =
MutableSharedFlow(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val flow: Flow<Result<T>?> by lazy {
sharedFlow
}
suspend operator fun invoke(
params: P,
timeout: Duration = DefaultTimeout
) {
try {
withTimeout(timeout) {
loadingState.addLoader()
sharedFlow.emit(doWork(params))
}
} catch (e: Exception) {
sharedFlow.emit(Result.failure(e))
} finally {
loadingState.removeLoader()
}
}
protected abstract suspend fun doWork(params: P): Result<T>
companion object {
internal val DefaultTimeout = 5.minutes
}
}
suspend operator fun <R> Interactor<Unit, R>.invoke() = invoke(Unit) | SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/interactor/Interactor.kt | 123972439 |
package com.example.sbscovidapp.domain.interactor
import com.example.sbscovidapp.domain.model.CovidStats
import com.example.sbscovidapp.domain.repository.CovidDataRepository
import javax.inject.Inject
class GetCovidStats
@Inject constructor(
private val repository: CovidDataRepository,
) : Interactor<GetCovidStats.Params, CovidStats>() {
override suspend fun doWork(params: Params): Result<CovidStats> =
runCatching {
repository.getCovidStats(params.iso.ifBlank { null })
}
data class Params(val iso: String)
} | SbsCovidApp/domain/src/main/java/com/example/sbscovidapp/domain/interactor/GetCovidStats.kt | 1416820501 |
package com.example.mediphix_app
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.mediphix_app", appContext.packageName)
}
} | Mediphix-MobileApp/app/src/androidTest/java/com/example/mediphix_app/ExampleInstrumentedTest.kt | 1983576994 |
package com.example.mediphix_app
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)
}
} | Mediphix-MobileApp/app/src/test/java/com/example/mediphix_app/ExampleUnitTest.kt | 2372064506 |
package com.example.mediphix_app
import android.app.Application
class MedTrack : Application() {
var currentNurseDetail: Nurses? = null
var selectedRoomForCheck : String = "Knox Wing"
var roomDrugList = mutableListOf<Drugs>()
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/MedTrack.kt | 1342882914 |
package com.example.mediphix_app
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var navBottom: com.google.android.material.bottomnavigation.BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
navBottom = findViewById(R.id.bottom_nav)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.findNavController()
appBarConfiguration = AppBarConfiguration(
setOf(R.id.home, R.id.newDrug, R.id.profile)
)
navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.id == R.id.login || destination.id == R.id.register || destination.id == R.id.forgotPassword) {
// Hide bottom navigation
navBottom.visibility = View.GONE
} else {
// Show bottom navigation
navBottom.visibility = View.VISIBLE
}
}
setupActionBarWithNavController(navController, appBarConfiguration)
navBottom.setupWithNavController(navController)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
bottomNavigationView.visibility = View.GONE
}
override fun onBackPressed() {
// Back button always navigates to home page
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
val navController = findNavController(R.id.nav_host_fragment)
if (navController.currentDestination?.id == R.id.login) {
return
}else if (bottomNavigationView.visibility == View.VISIBLE) {
val action = NavGraphDirections.actionGlobalHome()
findNavController(R.id.nav_host_fragment).navigate(action)
} else {
// If on the home fragment, navigate to the home fragment using the back stack
navController.popBackStack()
}
}
fun navigateToHomePage() {
// Sets the bottom nav to visible
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
bottomNavigationView.visibility = View.VISIBLE
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/MainActivity.kt | 3531023820 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.checks.ChecksAdapter
import com.example.mediphix_app.databinding.ManageChecksPageBinding
import com.google.firebase.database.*
class ManageChecks : Fragment(R.layout.manage_checks_page) {
private var _binding: ManageChecksPageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private var checkList = mutableListOf<Checks>()
private var drugList = mutableListOf<Drugs>()
private lateinit var adapter: ChecksAdapter
private var originalCheckList = mutableListOf<Checks>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ManageChecksPageBinding.inflate(inflater, container, false)
val root: View = binding.root
database = FirebaseDatabase.getInstance().getReference("Checks")
adapter = ChecksAdapter(requireContext(), checkList)
binding.recyclerViewDrugs.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewDrugs.adapter = adapter
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
checkList.clear()
originalCheckList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val regNumber = snapshot.child("regNumber").value.toString()
val firstName = snapshot.child("nurse_first_name").value.toString()
val lastName = snapshot.child("nurse_last_name").value.toString()
val storageLocation = snapshot.child("storage_location").value.toString()
val imageUrl = snapshot.child("imageUrl").value.toString()
val drugsDataList = snapshot.child("drugList")
val currentDrugList = mutableListOf<Drugs>() // Create a new list for each check
for (drug in drugsDataList.children) {
val drugItem = Drugs(
name = drug.child("name").value.toString(),
id = drug.child("id").value.toString(),
drugType = drug.child("drugType").value.toString(),
securityType = drug.child("securityType").value.toString(),
storageLocation = drug.child("storageLocation").value.toString(),
expiryDate = drug.child("expiryDate").value.toString(),
drugLabel = (drug.child("drugLabel").value as Long?) ?: 1L // Default to 1L if null
)
currentDrugList.add(drugItem)
}
val checkDate = snapshot.child("checkDate").value.toString()
originalCheckList.add(Checks(regNumber, firstName, lastName, storageLocation, checkDate, imageUrl, currentDrugList))
}
originalCheckList = originalCheckList.sortedByDescending { it.checkDate } as MutableList<Checks>
adapter.updateList(originalCheckList)
} else {
Toast.makeText(requireContext(), "No Checks Info", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
return root
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/ManageChecks.kt | 831601023 |
package com.example.mediphix_app
data class DisposedDrug (
val name : String? = null,
val id : String? = null,
val drugType : String? = null,
val storageLocation : String? = null,
val expiryDate : String? = null,
val nurseName : String? = null
) {} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DisposedDrug.kt | 662384224 |
package com.example.mediphix_app
data class DisposedDrugsCheck (
val checkDate : String? = null,
val disposedDrugsList : List<DisposedDrug>? = null
) {} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DisposedDrugsCheck.kt | 3432882283 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.Spinner
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.databinding.DisposedDrugsPageBinding
import com.example.mediphix_app.drugs.DisposedDrugsCheckAdapter
import com.google.firebase.database.*
class DisposedDrugs : Fragment(R.layout.disposed_drugs_page) {
enum class FilterOptions {
All, Simple, Controlled
}
private var _binding: DisposedDrugsPageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private val disposedDrugsCheckList = mutableListOf<DisposedDrugsCheck>()
private lateinit var adapter: DisposedDrugsCheckAdapter
private var currentFilter: FilterOptions = FilterOptions.All
private val originalCheckList = mutableListOf<Checks>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DisposedDrugsPageBinding.inflate(inflater, container, false)
val root: View = binding.root
database = FirebaseDatabase.getInstance().getReference("Checks")
adapter = DisposedDrugsCheckAdapter(disposedDrugsCheckList)
binding.recyclerViewDrugs.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewDrugs.adapter = adapter
val spinner: Spinner = binding.filterDDL
val imageView: ImageView = binding.filterImageView
imageView.bringToFront()
imageView.setOnClickListener { spinner.performClick() }
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
when (position) {
0 -> currentFilter = FilterOptions.All
1 -> currentFilter = FilterOptions.Simple
2 -> currentFilter = FilterOptions.Controlled
}
createDisposedDrugsCheckList(originalCheckList)
}
override fun onNothingSelected(parent: AdapterView<*>) {
// Do nothing here
}
}
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
disposedDrugsCheckList.clear()
originalCheckList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val regNumber = snapshot.child("regNumber").value.toString()
val firstName = snapshot.child("nurse_first_name").value.toString()
val lastName = snapshot.child("nurse_last_name").value.toString()
val storageLocation = snapshot.child("storage_location").value.toString()
val imageUrl = snapshot.child("imageUrl").value.toString()
val drugsDataList = snapshot.child("drugList")
val currentDrugList = mutableListOf<Drugs>() // Create a new list for each check
for (drug in drugsDataList.children) {
val drugItem = Drugs(
name = drug.child("name").value.toString(),
id = drug.child("id").value.toString(),
drugType = drug.child("drugType").value.toString(),
securityType = drug.child("securityType").value.toString(),
storageLocation = drug.child("storageLocation").value.toString(),
expiryDate = drug.child("expiryDate").value.toString(),
drugLabel = (drug.child("drugLabel").value as Long?) ?: 3L // Default to 1L if null
)
currentDrugList.add(drugItem)
}
val checkDate = snapshot.child("checkDate").value.toString()
originalCheckList.add(Checks(regNumber, firstName, lastName, storageLocation, checkDate, imageUrl, currentDrugList))
}
createDisposedDrugsCheckList(originalCheckList)
} else {
Toast.makeText(requireContext(), "No Checks Info", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
return root
}
fun createDisposedDrugsCheckList(checksList: List<Checks>) {
val filteredChecks = checksList.filter { it.drugList.isNullOrEmpty().not() }
val groupedChecks = filteredChecks.groupBy { it.checkDate }
val updatedDisposedDrugCheckList = groupedChecks.entries.sortedByDescending { it.key }.mapNotNull { group ->
val checkDate = group.key ?: return@mapNotNull null
var combinedDrugsList = group.value
.flatMap { it.drugList.orEmpty() }
.distinctBy { it.id }
.mapNotNull { drug ->
if (drug.name == null || drug.id == null) return@mapNotNull null
DisposedDrug(
name = drug.name,
id = drug.id,
drugType = drug.drugType,
storageLocation = drug.storageLocation,
expiryDate = drug.expiryDate,
nurseName = "${group.value.first().nurse_first_name} ${group.value.first().nurse_last_name}"
)
}
combinedDrugsList = filterDrugList(combinedDrugsList)
if (combinedDrugsList.isNotEmpty()) {
DisposedDrugsCheck(
checkDate = checkDate,
disposedDrugsList = combinedDrugsList
)
} else null
}
adapter.updateList(updatedDisposedDrugCheckList as MutableList<DisposedDrugsCheck>)
}
private fun filterDrugList(disposedDrugList: List<DisposedDrug>) : List<DisposedDrug> {
val filteredList = mutableListOf<DisposedDrug>()
for (drug in disposedDrugList) {
val drugType = drug.drugType
when (currentFilter) {
FilterOptions.All -> {
filteredList.add(drug)
}
FilterOptions.Simple -> {
if (drugType.toString() == "Simple") {
filteredList.add(drug)
}
}
FilterOptions.Controlled -> {
if (drugType.toString() == "Controlled") {
filteredList.add(drug)
}
}
}
}
return filteredList
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DisposedDrugs.kt | 1576095476 |
package com.example.mediphix_app.drugs
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.mediphix_app.Drugs
import com.example.mediphix_app.R
import java.text.SimpleDateFormat
import java.util.*
class DrugsAdapter (private var drugList: MutableList<Drugs>,
private var isDrugCheckRoom: Boolean = false,
private val onDrugClickListener: OnDrugClickListener) : RecyclerView.Adapter<DrugsAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val drugName: TextView = itemView.findViewById(R.id.drug_name)
val drugType: TextView = itemView.findViewById(R.id.drug_type)
val drugId: TextView = itemView.findViewById(R.id.drug_number)
val drugExpiry: TextView = itemView.findViewById(R.id.drug_expiry)
val drugLabel: ImageView = itemView.findViewById(R.id.drugLabelImageView)
}
interface OnDrugClickListener {
fun onDrugClick(markedDrugList: MutableList<Drugs>)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.drug_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var currentDrugInfo = drugList[position]
holder.drugName.text = currentDrugInfo.name.toString().uppercase()
holder.drugType.text = "TYPE: " + currentDrugInfo.drugType
holder.drugId.text = "ID: " + currentDrugInfo.id;
holder.drugExpiry.text = currentDrugInfo.expiryDate
if(currentDrugInfo.drugLabel.toString() == "1"){ // Drug Label == 1 is for no marking
holder.drugLabel.setImageResource(R.drawable.ic_no_icon)
}
else if (currentDrugInfo.drugLabel.toString() == "2"){ // Drug Label == 2 is for Red label marking
holder.drugLabel.setImageResource(R.drawable.ic_red_label)
}
else if (currentDrugInfo.drugLabel.toString() == "3"){ // Drug Label == 3 is for Dispose/Expired label marking
holder.drugLabel.setImageResource(R.drawable.ic_dispose)
}
val button: Button = holder.itemView.findViewById(R.id.spinner_drug_item)
if(isDrugCheckRoom) {
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val currentDate: Date = sdf.parse(sdf.format(Date()))!!
val calendar = Calendar.getInstance()
calendar.time = currentDate
calendar.add(Calendar.DAY_OF_YEAR, 30)
val futureDate: Date = calendar.time
val expiredDate: Date = sdf.parse(currentDrugInfo.expiryDate)!!
if(expiredDate.before(currentDate) || expiredDate.before(futureDate)){
holder.drugExpiry.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.mediphix_red))
}
button.setOnClickListener {
if(currentDrugInfo.drugLabel.toString() == "1"){ // Drug Label == 1 is for no marking
holder.drugLabel.setImageResource(R.drawable.ic_red_label)
drugList[position].drugLabel = 2
}
else if (currentDrugInfo.drugLabel.toString() == "2"){ // Drug Label == 2 is for Red label marking
holder.drugLabel.setImageResource(R.drawable.ic_dispose)
drugList[position].drugLabel = 3
}
else if (currentDrugInfo.drugLabel.toString() == "3"){ // Drug Label == 3 is for Dispose/Expired label marking
holder.drugLabel.setImageResource(R.drawable.ic_no_icon)
drugList[position].drugLabel = 1
}
onDrugClickListener.onDrugClick(drugList)
}
}
}
fun updateList(newList: MutableList<Drugs>) {
drugList = newList.toMutableList();
notifyDataSetChanged()
}
override fun getItemCount() = drugList.size
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/drugs/DrugsAdapter.kt | 4129324737 |
package com.example.mediphix_app.drugs
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mediphix_app.DisposedDrug
import com.example.mediphix_app.DisposedDrugsCheck
import com.example.mediphix_app.R
class DisposedDrugsCheckAdapter (private var disposedDrugsList: MutableList<DisposedDrugsCheck>) : RecyclerView.Adapter<DisposedDrugsCheckAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val checkDate: TextView = itemView.findViewById(R.id.check_date_text_view)
private val recyclerView : RecyclerView = itemView.findViewById(R.id.disposed_drugs_recycler_view)
fun bind(disposedDrugs: DisposedDrugsCheck) {
checkDate.text = disposedDrugs.checkDate
recyclerView.layoutManager = LinearLayoutManager(itemView.context, RecyclerView.VERTICAL, false)
recyclerView.adapter = DisposedDrugsAdapter((disposedDrugs.disposedDrugsList ?: emptyList()) as MutableList<DisposedDrug>)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.disposed_drugs_check_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var currentCheckInfo = disposedDrugsList[position]
holder.bind(currentCheckInfo)
}
fun updateList(newList: MutableList<DisposedDrugsCheck>) {
disposedDrugsList = newList.toMutableList();
notifyDataSetChanged()
}
override fun getItemCount() = disposedDrugsList.size
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/drugs/DisposedDrugsCheckAdapter.kt | 3396654920 |
package com.example.mediphix_app.drugs
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.mediphix_app.Checks
import com.example.mediphix_app.DisposedDrug
import com.example.mediphix_app.Drugs
import com.example.mediphix_app.R
import java.text.SimpleDateFormat
import java.util.*
class DisposedDrugsAdapter (private var disposedDrugList: MutableList<DisposedDrug>) : RecyclerView.Adapter<DisposedDrugsAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val drugName: TextView = itemView.findViewById(R.id.drug_name)
val drugType: TextView = itemView.findViewById(R.id.drug_type)
val drugId: TextView = itemView.findViewById(R.id.drug_number)
val drugExpiry: TextView = itemView.findViewById(R.id.drug_expiry)
val nurseName: TextView = itemView.findViewById(R.id.nurse_name)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.disposed_drugs_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var currentDrugInfo = disposedDrugList[position]
holder.drugName.text = currentDrugInfo.name.toString().uppercase()
holder.drugType.text = "TYPE: " + currentDrugInfo.drugType.toString().uppercase()
holder.drugId.text = "ID: " + currentDrugInfo.id.toString().uppercase()
holder.drugExpiry.text = "EXPIRED: " + currentDrugInfo.expiryDate.toString().uppercase()
holder.nurseName.text = "NURSE: " + currentDrugInfo.nurseName.toString().uppercase()
}
fun updateList(newList: MutableList<DisposedDrug>) {
disposedDrugList = newList.toMutableList();
notifyDataSetChanged()
}
override fun getItemCount() = disposedDrugList.size
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/drugs/DisposedDrugsAdapter.kt | 1493403050 |
package com.example.mediphix_app.checks
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mediphix_app.Checks
import com.example.mediphix_app.R
import com.bumptech.glide.Glide
class ChecksAdapter (private val context : Context, private var checkList: MutableList<Checks>) : RecyclerView.Adapter<ChecksAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val checkDate: TextView = itemView.findViewById(R.id.checkDate)
val storageLocation: TextView = itemView.findViewById(R.id.storageLocation)
val nurseName: TextView = itemView.findViewById(R.id.nurseName)
val regNo: TextView = itemView.findViewById(R.id.regNo)
val drugList: TextView = itemView.findViewById(R.id.drugList)
val signatureImage : ImageView = itemView.findViewById(R.id.signatureImage)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.checks_item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentCheckInfo = checkList[position]
holder.checkDate.text = "CHECK DATE: " + currentCheckInfo.checkDate.toString()
holder.storageLocation.text ="Storage Location: " + currentCheckInfo.storage_location
holder.nurseName.text ="Done by: "+ currentCheckInfo.nurse_first_name.toString().uppercase() + " " + currentCheckInfo.nurse_last_name.toString().uppercase()
holder.regNo.text = "Reg No.: " +currentCheckInfo.regNumber
var drugText = "Drug List:"
for((i, drug) in currentCheckInfo.drugList?.withIndex()!!) {
drugText += "\n" + (i+1).toString() + ". " + drug.id + " - " + drug.name
}
if(drugText == "Drug List:") {
drugText += "\n No drugs disposed."
}
holder.drugList.text = drugText
Glide.with(context)
.load(currentCheckInfo.imageUrl)
.error(R.drawable.ic_image_not_found)
.into(holder.signatureImage)
}
fun updateList(newList: MutableList<Checks>) {
checkList = newList.toMutableList();
notifyDataSetChanged()
}
override fun getItemCount() = checkList.size
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/checks/ChecksAdapter.kt | 1779895199 |
package com.example.mediphix_app
import android.widget.DatePicker
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.AddNewDrugPageBinding
import com.example.mediphix_app.databinding.RegisterPageBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import java.text.SimpleDateFormat
import java.util.*
class NewDrug : Fragment(R.layout.add_new_drug_page) {
private lateinit var binding: AddNewDrugPageBinding
private lateinit var database: DatabaseReference
private lateinit var drugRoom: String
private lateinit var drugExpiry: EditText
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = AddNewDrugPageBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
drugExpiry = view.findViewById(R.id.drugExpiry)
drugExpiry.setOnClickListener {
closeKeyboard()
showDatePickerDialog()
}
val spinner = view.findViewById<Spinner>(R.id.drugStorage)
val drugSecurity = view.findViewById<EditText>(R.id.drugSecurity)
val drugType = view.findViewById<EditText>(R.id.drugType)
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
drugRoom = parent.getItemAtPosition(position).toString()
when(drugRoom) {
"Knox Wing" -> {
drugSecurity.setText("Safe")
drugType.setText("Controlled")
}
"Day Stay", "Ward Office" -> {
drugSecurity.setText("Cupboard")
drugType.setText("Simple")
}
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
// bind the register button
binding.registerDrugBtn.setOnClickListener {
// Get user input from EditText fields
val name = binding.DrugName.text.toString()
val id = binding.idNumber.text.toString()
val drugType = binding.drugType.text.toString()
val securityType = binding.drugSecurity.text.toString()
val storageLocation = drugRoom
val expiryDate = binding.drugExpiry.text.toString()
database = FirebaseDatabase.getInstance().getReference("Drugs")
if(name.isNullOrBlank() || id.isNullOrBlank() || expiryDate.isNullOrBlank()) {
if(name.isNullOrBlank()) {
Toast.makeText(requireContext(), "Please enter name of drug.", Toast.LENGTH_SHORT).show()
}
else if (id.isNullOrBlank()) {
Toast.makeText(requireContext(), "Please enter id of drug.", Toast.LENGTH_SHORT).show()
}
else if (expiryDate.isNullOrBlank()) {
Toast.makeText(requireContext(), "Please enter expiry date of drug.", Toast.LENGTH_SHORT).show()
}
}
else {
val drugs = Drugs(name, id, drugType, securityType, storageLocation, expiryDate)
database.child(id).setValue(drugs).addOnSuccessListener {
binding.DrugName.text.clear()
binding.idNumber.text.clear()
binding.drugType.text.clear()
binding.drugSecurity.text.clear()
spinner.setSelection(0)
binding.drugExpiry.text.clear()
// Success message
Toast.makeText(requireContext(), "Drug successfully saved", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
// Failure message
Toast.makeText(requireContext(), "Failed to save new drug", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun closeKeyboard() {
val view = activity?.currentFocus
if (view != null) {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
}
private fun showDatePickerDialog() {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = context?.let {
DatePickerDialog(
it,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
val calendar = Calendar.getInstance().apply {
set(Calendar.YEAR, year)
set(Calendar.MONTH, month)
set(Calendar.DAY_OF_MONTH, dayOfMonth)
}
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val selectedDate = dateFormat.format(calendar.time)
drugExpiry.setText(selectedDate)
},
year,
month,
day
)
}
// Set the minimum date to today to prevent selection of previous dates
if (datePickerDialog != null) {
datePickerDialog.datePicker.minDate = System.currentTimeMillis() - 1000
}
datePickerDialog?.show()
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/NewDrug.kt | 4224824488 |
package com.example.mediphix_app
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
class SignatureView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var path = Path()
private var paint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.mediphix_darkblue)
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
strokeWidth = 5f
}
private var bitmap: Bitmap? = null
private lateinit var canvas: Canvas
override fun onDraw(canvas: Canvas) {
// Fill the canvas with a white color
canvas.drawColor(android.graphics.Color.WHITE)
super.onDraw(canvas)
canvas.drawPath(path, paint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val x = event.x
val y = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
parent.requestDisallowInterceptTouchEvent(true)
path.moveTo(event.x, event.y)
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(event.x, event.y)
}
MotionEvent.ACTION_UP -> {
parent.requestDisallowInterceptTouchEvent(false)
}
}
invalidate()
return true
}
fun clear() {
path.reset()
invalidate()
}
fun getSignatureBitmap(): Bitmap {
if (bitmap == null) {
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
}
canvas = Canvas(bitmap!!)
draw(canvas)
return bitmap!!
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/SignatureView.kt | 2193911736 |
package com.example.mediphix_app
data class Nurses(val firstName : String? = null,
val lastName : String? = null,
val regNumber : String? = null,
val password : String? = null){} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Nurses.kt | 1645578382 |
package com.example.mediphix_app
import android.graphics.Typeface
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.LoginPageBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class Login : Fragment(R.layout.login_page) {
private lateinit var binding: LoginPageBinding
private lateinit var database: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = LoginPageBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Toggle password visibility
val passwordEditText = binding.password
val togglePasswordButton = binding.togglePassword
togglePasswordButton.setColorFilter(ContextCompat.getColor(requireContext(), R.color.mediphix_blue))
togglePasswordButton.setOnClickListener() {
if (passwordEditText.inputType == InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) {
// Show password
passwordEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
togglePasswordButton.setImageResource(R.drawable.eye_opened)
} else {
// Hide password
passwordEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
togglePasswordButton.setImageResource(R.drawable.eye_closed)
}
passwordEditText.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
}
// Register Button Start
binding.registerBtn.setOnClickListener {
val action = LoginDirections.loginToRegister()
findNavController().navigate(action)
}
// Forgot Password Button Start
binding.forgotBtn.setOnClickListener {
val action = LoginDirections.actionLoginToForgotPassword()
findNavController().navigate(action)
}
// Bind the Login data button
binding.loginBtn.setOnClickListener {
// Get the user's username
val regNum: String = binding.regNumber.text.toString()
val pass: String = binding.password.text.toString()
if (regNum.isNotEmpty() && pass.isNotEmpty()) {
// Verify username matches the password
checkData(regNum, pass)
} else {
// Notify user if the field is empty
Toast.makeText(requireContext(), "Please enter the Username and Password", Toast.LENGTH_SHORT).show()
}
}
}
private fun checkData(regNum: String, pass: String) {
// Initialize Firebase database
database = FirebaseDatabase.getInstance().getReference("Nurses")
// Read user data from the database
database.child(regNum).get().addOnSuccessListener {
if (it.exists()) {
// If user exists
val regNumber = it.child("regNumber").value
val password = it.child("password").value
val firstName = it.child("firstName").value
val lastName = it.child("lastName").value
database.child(pass).get().addOnSuccessListener {
if (pass == password) {
// Success
Toast.makeText(requireContext(), "Successfully Logged-In", Toast.LENGTH_SHORT).show()
val nurseApp = requireActivity().application as MedTrack
nurseApp.currentNurseDetail = Nurses(firstName.toString(), lastName.toString(), regNumber.toString())
val mainActivity = activity as? MainActivity
mainActivity?.navigateToHomePage()
// Use NavController to navigate to the next destination
val action = LoginDirections.loginAction()
findNavController().navigate(action)
} else {
// No matching user
Toast.makeText(requireContext(), "Password Is Incorrect", Toast.LENGTH_SHORT).show()
}
}
} else {
// No matching user
Toast.makeText(requireContext(), "User Doesn't Exist", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener {
// Failure message = The database operation failed
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Login.kt | 3192215716 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.databinding.DrugCheckRoomPageBinding
import com.example.mediphix_app.drugs.DrugsAdapter
import com.google.firebase.database.*
import java.text.SimpleDateFormat
import java.util.*
class DrugCheckRoom : Fragment(R.layout.drug_check_room_page) {
private var _binding: DrugCheckRoomPageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private val drugList = mutableListOf<Drugs>()
private lateinit var adapter: DrugsAdapter
private var originalDrugList = mutableListOf<Drugs>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DrugCheckRoomPageBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.NextBtn.setOnClickListener {
if(originalDrugList.isNullOrEmpty()){
Toast.makeText(requireContext(), "No Drugs Available", Toast.LENGTH_SHORT).show()
} else {
val action = DrugCheckRoomDirections.actionDrugCheckRoomToDrugCheckFinalize()
findNavController().navigate(action)
}
}
binding.backBtn.setOnClickListener {
val medTrack = requireActivity().application as MedTrack
medTrack.roomDrugList.clear()
val action = DrugCheckRoomDirections.actionDrugCheckRoomToDrugCheck()
findNavController().navigate(action)
}
database = FirebaseDatabase.getInstance().getReference("Drugs")
adapter = DrugsAdapter(drugList, true, object : DrugsAdapter.OnDrugClickListener {
override fun onDrugClick(markedDrugList: MutableList<Drugs>) {
// Call the function in ListOfDrugs from here
updateRoomDrugList(markedDrugList)
}
})
binding.recyclerViewRoomDrugs.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewRoomDrugs.adapter = adapter
val medTrack = requireActivity().application as MedTrack
var roomDrugList = medTrack.roomDrugList
var selectedRoomForCheck = medTrack.selectedRoomForCheck.toString()
binding.roomName.text = selectedRoomForCheck.split(" ")[0]
binding.roomNam3.text = selectedRoomForCheck.split(" ")[1]
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
drugList.clear()
originalDrugList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val drugType = snapshot.child("drugType").value.toString()
val expiryDate = snapshot.child("expiryDate").value.toString()
val drugId = snapshot.child("id").value.toString()
val drugName = snapshot.child("name").value.toString()
val securityType = snapshot.child("securityType").value.toString()
val storageLocation = snapshot.child("storageLocation").value.toString()
val drugLabel = snapshot.child("drugLabel").value as Long
originalDrugList.add(Drugs(drugName, drugId, drugType, securityType, storageLocation, expiryDate, drugLabel))
}
defaultSortFilterDrugList()
} else {
Toast.makeText(requireContext(), "No Drugs Available", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
return root
}
private fun updateRoomDrugList(markedDrugList: MutableList<Drugs>) {
val medTrack = requireActivity().application as MedTrack
medTrack.roomDrugList = markedDrugList
}
private fun defaultSortFilterDrugList() {
val medTrack = requireActivity().application as MedTrack
var roomDrugList = medTrack.roomDrugList
var selectedRoomForCheck = medTrack.selectedRoomForCheck
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val currentDate: Date = sdf.parse(sdf.format(Date()))!!
val calendar = Calendar.getInstance()
calendar.time = currentDate
calendar.add(Calendar.DAY_OF_YEAR, 30)
val futureDate: Date = calendar.time
val filteredList = mutableListOf<Drugs>()
if(roomDrugList.isEmpty() || roomDrugList[0]?.storageLocation.toString() != selectedRoomForCheck) {
for (drug in originalDrugList) {
if (drug.storageLocation.toString() == selectedRoomForCheck && (drug.drugLabel.toString() == "2" || drug.drugLabel.toString() == "1")) {
val expiredDate: Date = sdf.parse(drug.expiryDate)!!
if(expiredDate.before(currentDate)){
drug.drugLabel = 3;
}
else if(expiredDate.after(futureDate)){
drug.drugLabel = 1;
}
else {
drug.drugLabel = 2;
}
filteredList.add(drug)
}
}
originalDrugList = filteredList
roomDrugList = filteredList
medTrack.roomDrugList = filteredList
}
adapter.updateList(roomDrugList)
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DrugCheckRoom.kt | 1707578124 |
package com.example.mediphix_app
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
class DisclaimerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread.sleep(1000)
installSplashScreen()
supportActionBar?.hide()
setContentView(R.layout.activity_disclaimer)
val checkBox: CheckBox = findViewById(R.id.check_agree)
val nextButton: Button = findViewById(R.id.NextBtn)
checkBox.setOnCheckedChangeListener { _, isChecked ->
nextButton.isEnabled = isChecked
}
nextButton.setOnClickListener {
if (checkBox.isChecked) {
startActivity(Intent(this, MainActivity::class.java))
finish()
}else {
Toast.makeText(this, "Please tick the checkbox before proceeding", Toast.LENGTH_SHORT).show()
}
}
}
}
| Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DisclaimerActivity.kt | 1968597639 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.ForgotPasswordPageBinding
class ForgotPassword : Fragment(R.layout.forgot_password_page) {
private lateinit var binding: ForgotPasswordPageBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = ForgotPasswordPageBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.loginBtn.setOnClickListener {
val action = ForgotPasswordDirections.actionForgotPasswordToLogin()
findNavController().navigate(action)
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/ForgotPassword.kt | 21286988 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.HomePageBinding
class Home : Fragment(R.layout.home_page) {
private lateinit var binding: HomePageBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = HomePageBinding.inflate(inflater, container, false)
return binding.root
val medTrack = requireActivity().application as MedTrack
medTrack.roomDrugList.clear()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.startDrugCheckBtn.setOnClickListener {
val action = HomeDirections.actionHomeToDrugCheck()
findNavController().navigate(action)
}
binding.listOfDrugsBtn.setOnClickListener {
val action = HomeDirections.actionHomeToListOfDrugs()
findNavController().navigate(action)
}
binding.disposedDrugsBtn.setOnClickListener {
val action = HomeDirections.actionHomeToDisposedDrugs()
findNavController().navigate(action)
}
binding.manageChecksBtn.setOnClickListener {
val action = HomeDirections.actionHomeToManageChecks()
findNavController().navigate(action)
}
binding.aboutMediphixBtn.setOnClickListener {
val action = HomeDirections.actionHomeToAboutMediphix()
findNavController().navigate(action)
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Home.kt | 1394922362 |
package com.example.mediphix_app
data class Drugs(val name : String? = null,
val id : String? = null,
val drugType : String? = null,
val securityType : String? = null,
val storageLocation: String? = null,
val expiryDate: String? = null,
var drugLabel: Long = 1 // 1 = No Label, 2 = Red Sticker, 3 = Removed/Disposed/Expired
){} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Drugs.kt | 2356652281 |
package com.example.mediphix_app
import android.graphics.Typeface
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.RegisterPageBinding
import com.google.firebase.database.*
class Register : Fragment(R.layout.register_page) {
private lateinit var binding: RegisterPageBinding
private lateinit var database: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = RegisterPageBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Toggle password visibility
val passwordEditText = binding.password
val togglePasswordButton = binding.togglePassword
togglePasswordButton.setColorFilter(ContextCompat.getColor(requireContext(), R.color.mediphix_blue))
togglePasswordButton.setOnClickListener() {
if (passwordEditText.inputType == InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) {
// Show password
passwordEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
togglePasswordButton.setImageResource(R.drawable.eye_opened)
} else {
// Hide password
passwordEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
togglePasswordButton.setImageResource(R.drawable.eye_closed)
}
passwordEditText.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
}
binding.loginBtn.setOnClickListener {
val action = RegisterDirections.actionRegisterToLogin()
findNavController().navigate(action)
}
// bind the register button
binding.registerBtn.setOnClickListener {
binding.registerBtn.setOnClickListener {
// Get user input from EditText fields
val firstName = binding.firstName.text.toString()
val lastName = binding.lastName.text.toString()
val regNumber = binding.regNumber.text.toString()
val password = binding.password.text.toString()
// Create Firebase database reference
database = FirebaseDatabase.getInstance().getReference("Nurses")
// Check if the registration number already exists in the database
database.child(regNumber).addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
// Registration number already exists, show error message
Toast.makeText(requireContext(), "Registration number is already in use", Toast.LENGTH_SHORT).show()
} else {
// Registration number doesn't exist, proceed with registration
if (password.length in 8..12) {
// Create a Nurse instance
val nurses = Nurses(firstName, lastName, regNumber, password)
// Save the user object to the database using the username as the key
database.child(regNumber).setValue(nurses).addOnSuccessListener {
// Clear input fields after successful database operation
binding.firstName.text.clear()
binding.lastName.text.clear()
binding.regNumber.text.clear()
binding.password.text.clear()
// Success message
Toast.makeText(requireContext(), "Nurse successfully saved", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
// Failure message
Toast.makeText(requireContext(), "Failed to save new nurse", Toast.LENGTH_SHORT).show()
}
} else if (password.length >= 12) {
Toast.makeText(requireContext(), "Password is too long", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(requireContext(), "Password is too short", Toast.LENGTH_SHORT).show()
}
}
}
override fun onCancelled(error: DatabaseError) {
// Handle error
Toast.makeText(requireContext(), "Error occurred while checking registration number", Toast.LENGTH_SHORT).show()
}
})
}
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Register.kt | 2084293121 |
package com.example.mediphix_app
import androidx.fragment.app.Fragment
class AboutMediphix : Fragment(R.layout.about_mediphix) {
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/AboutMediphix.kt | 2849527483 |
package com.example.mediphix_app
import android.app.Dialog
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.databinding.DrugCheckFinalizePageBinding
import com.example.mediphix_app.drugs.DrugsAdapter
import com.google.firebase.database.*
import com.google.firebase.storage.FirebaseStorage
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*
class DrugCheckFinalize : Fragment(R.layout.drug_check_finalize_page) {
private var _binding: DrugCheckFinalizePageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private val drugList = mutableListOf<Drugs>()
private lateinit var redStickerDrugAdapter: DrugsAdapter
private lateinit var removedDrugAdapter: DrugsAdapter
private val redStickerDrugList = mutableListOf<Drugs>()
private val removedDrugList = mutableListOf<Drugs>()
private var imageUrl : String? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DrugCheckFinalizePageBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.backBtn.setOnClickListener {
val action = DrugCheckFinalizeDirections.actionDrugCheckFinalizeToDrugCheckRoom()
findNavController().navigate(action)
}
database = FirebaseDatabase.getInstance().getReference("Drugs")
redStickerDrugAdapter = DrugsAdapter(drugList, false, object : DrugsAdapter.OnDrugClickListener {
override fun onDrugClick(markedDrugList: MutableList<Drugs>) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_LONG).show()
}
})
binding.recyclerViewFinalizeRoomDrugs1.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewFinalizeRoomDrugs1.adapter = redStickerDrugAdapter
removedDrugAdapter = DrugsAdapter(drugList, false, object : DrugsAdapter.OnDrugClickListener {
override fun onDrugClick(markedDrugList: MutableList<Drugs>) {
// Do nothing here
}
})
binding.recyclerViewFinalizeRoomDrugs2.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewFinalizeRoomDrugs2.adapter = removedDrugAdapter
val medTrack = requireActivity().application as MedTrack
var roomDrugList = medTrack.roomDrugList
var selectedRoomForCheck = medTrack.selectedRoomForCheck.toString().uppercase()
var nurseData = medTrack.currentNurseDetail
binding.roomName.text = selectedRoomForCheck.split(" ")[0]
binding.roomNam3.text = selectedRoomForCheck.split(" ")[1]
binding.nurseFullNameTextView.text = "NURSE NAME: ${nurseData?.firstName.toString().uppercase()} ${nurseData?.lastName.toString().uppercase()}"
binding.nurseRegNoTextView.text = "REG NO.: ${nurseData?.regNumber.toString()}"
defaultSortFilterDrugList()
if (redStickerDrugList.isNullOrEmpty() && removedDrugList.isNullOrEmpty()){
Toast.makeText(requireContext(), "No Drugs Available", Toast.LENGTH_SHORT).show()
}
binding.SaveBtn.setOnClickListener {
it.isEnabled = false
binding.backBtn.isEnabled = false
Toast.makeText(requireContext(), "Saving check details", Toast.LENGTH_SHORT).show()
if (redStickerDrugList.isNullOrEmpty() && removedDrugList.isNullOrEmpty()){
Toast.makeText(requireContext(), "No Drugs Available", Toast.LENGTH_SHORT).show()
}
else
{
database = FirebaseDatabase.getInstance().getReference("Drugs")
val drugChildren = hashMapOf<String, Any>()
roomDrugList.forEach { updatedDrug ->
val key = updatedDrug.id
if (key != null) {
drugChildren["$key/drugLabel"] = updatedDrug.drugLabel
}
}
database.updateChildren(drugChildren).addOnCompleteListener { task ->
if (!task.isSuccessful) {
Toast.makeText(requireContext(), "Failed to save Drugs", Toast.LENGTH_SHORT).show()
}
}
database = FirebaseDatabase.getInstance().getReference("Checks")
val medTrack = requireActivity().application as MedTrack
var roomDrugList = medTrack.roomDrugList
var selectedRoomForCheck = medTrack.selectedRoomForCheck.toString().uppercase()
var nurseData = medTrack.currentNurseDetail
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val sdf2 = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val currentDate = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.time
val dateString = sdf.format(currentDate)
val dateDashString = sdf2.format(currentDate)
val bitmap = binding.signatureView.getSignatureBitmap()
// Convert bitmap to byte array
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
val data = baos.toByteArray()
// Save to Firebase
val storageRef = FirebaseStorage.getInstance().reference
val signatureRef = storageRef.child("signatures/${UUID.randomUUID()}.png")
val uploadTask = signatureRef.putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
// It's a good practice to provide more detail on the error to the user or in the logs.
Toast.makeText(requireContext(), "Upload failed: ${it.message}", Toast.LENGTH_LONG).show()
}.addOnSuccessListener { taskSnapshot ->
// Handle successful uploads on complete
// Get the download URL after the upload is successful
taskSnapshot.metadata?.reference?.downloadUrl?.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
//record only disposed drugs
val filteredList = roomDrugList.filter { drug ->
drug.drugLabel == 3L
}
// Create the Checks object here after you have the URL
val check = Checks(
nurseData?.regNumber,
nurseData?.firstName,
nurseData?.lastName,
selectedRoomForCheck,
dateString.toString(),
imageUrl,
filteredList
)
// Save the Checks object to the database
database.child(dateDashString.toString() + " - " + nurseData?.regNumber.toString() + " - " + selectedRoomForCheck)
.setValue(check)
.addOnSuccessListener {
medTrack.roomDrugList.clear()
showPopUp()
}.addOnFailureListener {
// Handle the error properly
Toast.makeText(requireContext(), "Failed to save check: ${it.message}", Toast.LENGTH_LONG).show()
}
}?.addOnFailureListener {
// Handle any errors in getting the download URL
Toast.makeText(requireContext(), "Failed to get download URL: ${it.message}", Toast.LENGTH_LONG).show()
}
}
}
}
return root
}
private fun showPopUp() {
val dialog = Dialog(requireContext())
val view = layoutInflater.inflate(R.layout.save_message, null)
view.setOnClickListener {
dialog.dismiss()
val action = DrugCheckFinalizeDirections.actionDrugCheckFinalizeToHome()
findNavController().navigate(action)
}
dialog.setContentView(view)
dialog.show()
dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))
}
private fun defaultSortFilterDrugList() {
val nurseApp = requireActivity().application as MedTrack
val selectedRoomForCheck = nurseApp.selectedRoomForCheck
val medTrack = requireActivity().application as MedTrack
var roomDrugList = medTrack.roomDrugList
roomDrugList.sortByDescending {it.drugLabel}
for (drug in roomDrugList) {
val storageLocation = drug.storageLocation
if (storageLocation.toString() == selectedRoomForCheck && drug.drugLabel.toString() == "2") {
redStickerDrugList.add(drug)
}
else if (storageLocation.toString() == selectedRoomForCheck && drug.drugLabel.toString() == "3") {
removedDrugList.add(drug)
}
}
redStickerDrugAdapter.updateList(redStickerDrugList)
removedDrugAdapter.updateList(removedDrugList)
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DrugCheckFinalize.kt | 3369334182 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.checks.ChecksAdapter
import com.example.mediphix_app.databinding.CheckHistoryPageBinding
import com.google.firebase.database.*
class CheckHistory : Fragment(R.layout.check_history_page) {
private var _binding: CheckHistoryPageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private var checkList = mutableListOf<Checks>()
private var drugList = mutableListOf<Drugs>()
private lateinit var adapter: ChecksAdapter
private var originalCheckList = mutableListOf<Checks>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = CheckHistoryPageBinding.inflate(inflater, container, false)
val root: View = binding.root
database = FirebaseDatabase.getInstance().getReference("Checks")
// Fetch the profile data for the currently logged-in user
val nurseData = requireActivity().application as MedTrack
val currentNurse = nurseData.currentNurseDetail
adapter = ChecksAdapter(requireContext(), checkList)
binding.recyclerViewDrugs.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewDrugs.adapter = adapter
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
checkList.clear()
originalCheckList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val regNumber = snapshot.child("regNumber").value.toString()
val firstName = snapshot.child("nurse_first_name").value.toString()
val lastName = snapshot.child("nurse_last_name").value.toString()
val storageLocation = snapshot.child("storage_Location").value.toString()
val imageUrl = snapshot.child("imageUrl").value.toString()
val drugsDataList = snapshot.child("drugList")
drugList.clear()
for (drug in drugsDataList.children){
val drugItem = Drugs(
name = drug.child("name").toString(),
id = drug.child("id").toString(),
drugType = drug.child("drugType").toString(),
securityType = drug.child("securityType").toString(),
storageLocation = drug.child("storageLocation").toString(),
expiryDate = drug.child("expiryDate").toString(),
drugLabel = drug.child("drugLabel").value as Long
)
drugList.add(drugItem)
}
val checkDate = snapshot.child("checkDate").value.toString()
if (currentNurse != null && (currentNurse.regNumber == regNumber)){
originalCheckList.add(Checks(regNumber, firstName, lastName, storageLocation, checkDate, imageUrl, drugList))
}
}
adapter.updateList(originalCheckList)
} else {
Toast.makeText(requireContext(), "No Checks Info", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
checkList.clear()
originalCheckList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val regNumber = snapshot.child("regNumber").value.toString()
val firstName = snapshot.child("nurse_first_name").value.toString()
val lastName = snapshot.child("nurse_last_name").value.toString()
val storageLocation = snapshot.child("storage_location").value.toString()
val imageUrl = snapshot.child("imageUrl").value.toString()
val drugsDataList = snapshot.child("drugList")
val currentDrugList = mutableListOf<Drugs>() // Create a new list for each check
for (drug in drugsDataList.children) {
val drugItem = Drugs(
name = drug.child("name").value.toString(),
id = drug.child("id").value.toString(),
drugType = drug.child("drugType").value.toString(),
securityType = drug.child("securityType").value.toString(),
storageLocation = drug.child("storageLocation").value.toString(),
expiryDate = drug.child("expiryDate").value.toString(),
drugLabel = (drug.child("drugLabel").value as Long?) ?: 1L // Default to 1L if null
)
currentDrugList.add(drugItem)
}
val checkDate = snapshot.child("checkDate").value.toString()
if (currentNurse != null && (currentNurse.regNumber == regNumber)){
originalCheckList.add(Checks(regNumber, firstName, lastName, storageLocation, checkDate, imageUrl, currentDrugList))
}
}
originalCheckList = originalCheckList.sortedByDescending { it.checkDate } as MutableList<Checks>
adapter.updateList(originalCheckList)
} else {
Toast.makeText(requireContext(), "No Checks Info", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
return root
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/CheckHistory.kt | 1308677176 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.DrugCheckPageBinding
import com.google.firebase.database.*
class DrugCheck : Fragment(R.layout.drug_check_page) {
private lateinit var binding: DrugCheckPageBinding
private lateinit var database: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = DrugCheckPageBinding.inflate(inflater, container, false)
database = FirebaseDatabase.getInstance().getReference("Checks")
// Query to order checks by checkDate
database.orderByChild("checkDate").addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val latestCheck = filterChecksByLocation(dataSnapshot, "Knox Wing").lastOrNull()
latestCheck?.let { check ->
binding.knoxTextView.text = "Last check: ${check.checkDate.toString()} \n Done by: ${check.nurse_first_name.toString().capitalizeFirstLetter()} ${check.nurse_last_name.toString().capitalizeFirstLetter()}"
}
val latestCheck1 = filterChecksByLocation(dataSnapshot, "Day Stay").lastOrNull()
latestCheck1?.let { check ->
binding.dayTextView.text = "Last check: ${check.checkDate.toString()} \n Done by: ${check.nurse_first_name.toString().capitalizeFirstLetter()} ${check.nurse_last_name.toString().capitalizeFirstLetter()}"
}
val latestCheck2 = filterChecksByLocation(dataSnapshot, "Ward Office").lastOrNull()
latestCheck2?.let { check ->
binding.wardTextView.text = "Last check: ${check.checkDate.toString()} \n Done by: ${check.nurse_first_name.toString().capitalizeFirstLetter()} ${check.nurse_last_name.toString().capitalizeFirstLetter()}"
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Handle error
}
})
return binding.root
}
fun String.capitalizeFirstLetter(): String {
if (this.isEmpty()) return this
return this.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
}
fun filterChecksByLocation(dataSnapshot: DataSnapshot, locationFilter: String): List<Checks> {
val checksList = mutableListOf<Checks>()
dataSnapshot.children.forEach { snapshot ->
// Extract the storage location from the key if the format allows
val parts = snapshot.key?.split(" - ") ?: listOf()
if (parts.size >= 3) {
val storageLocation = parts[2]
if (storageLocation.equals(locationFilter, ignoreCase = true)) {
// Manually parse the Checks object
val regNumber = snapshot.child("regNumber").value as String? ?: ""
val nurseFirstName = snapshot.child("nurse_first_name").value as String? ?: ""
val nurseLastName = snapshot.child("nurse_last_name").value as String? ?: ""
val storageLocation = snapshot.child("storage_Location").value as String? ?: ""
val checkDate = snapshot.child("checkDate").value as String? ?: ""
val imageUrl = snapshot.child("imageUrl").value as String? ?: ""
// Parse the drugList
val drugsSnapshot = snapshot.child("drugList")
val drugList = mutableListOf<Drugs>()
drugsSnapshot.children.forEach { drugSnapshot ->
val name = drugSnapshot.child("name").value as String? ?: ""
val id = drugSnapshot.child("id").value as String? ?: ""
val drugType = drugSnapshot.child("drugType").value as String? ?: ""
val securityType = drugSnapshot.child("securityType").value as String? ?: ""
val storageLocationDrug = drugSnapshot.child("storageLocation").value as String? ?: ""
val expiryDate = drugSnapshot.child("expiryDate").value as String? ?: ""
val drugLabel = drugSnapshot.child("drugLabel").value as Long? ?: 1L
drugList.add(Drugs(name, id, drugType, securityType, storageLocationDrug, expiryDate, drugLabel))
}
checksList.add(Checks(regNumber, nurseFirstName, nurseLastName, storageLocation, checkDate, imageUrl, drugList))
}
}
}
return checksList
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.knoxWingDrugRoomBtn.setOnClickListener {
val nurseApp = requireActivity().application as MedTrack
nurseApp.selectedRoomForCheck = "Knox Wing"
val action = DrugCheckDirections.actionDrugCheckToDrugCheckRoom()
findNavController().navigate(action)
}
binding.wardOfficeNursesStationBtn.setOnClickListener {
val nurseApp = requireActivity().application as MedTrack
nurseApp.selectedRoomForCheck = "Ward Office"
val action = DrugCheckDirections.actionDrugCheckToDrugCheckRoom()
findNavController().navigate(action)
}
binding.dayStayNursesStationBtn.setOnClickListener {
val nurseApp = requireActivity().application as MedTrack
nurseApp.selectedRoomForCheck = "Day Stay"
val action = DrugCheckDirections.actionDrugCheckToDrugCheckRoom()
findNavController().navigate(action)
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/DrugCheck.kt | 1183635341 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mediphix_app.databinding.ListOfDrugsPageBinding
import com.example.mediphix_app.drugs.DrugsAdapter
import com.google.firebase.database.*
import java.text.SimpleDateFormat
import java.util.*
class ListOfDrugs : Fragment(R.layout.list_of_drugs_page) {
enum class FilterOptions {
All, Red_Sticker, Expired, Simple, Controlled
}
private var _binding: ListOfDrugsPageBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
private val drugList = mutableListOf<Drugs>()
private lateinit var adapter: DrugsAdapter
private var currentFilter: FilterOptions = FilterOptions.All
private val originalDrugList = mutableListOf<Drugs>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ListOfDrugsPageBinding.inflate(inflater, container, false)
val root: View = binding.root
database = FirebaseDatabase.getInstance().getReference("Drugs")
adapter = DrugsAdapter(drugList, false, object : DrugsAdapter.OnDrugClickListener {
override fun onDrugClick(markedDrugList: MutableList<Drugs>) {
// Do nothing here
}
})
binding.recyclerViewDrugs.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewDrugs.adapter = adapter
val spinner: Spinner = binding.filterDDL
val imageView: ImageView = binding.filterImageView
imageView.bringToFront()
imageView.setOnClickListener { spinner.performClick() }
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
when (position) {
0 -> currentFilter = FilterOptions.All
1 -> currentFilter = FilterOptions.Red_Sticker
2 -> currentFilter = FilterOptions.Expired
3 -> currentFilter = FilterOptions.Simple
4 -> currentFilter = FilterOptions.Controlled
}
filterDrugList()
}
override fun onNothingSelected(parent: AdapterView<*>) {
// Do nothing here
}
}
database.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
drugList.clear()
originalDrugList.clear()
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
val drugType = snapshot.child("drugType").value.toString()
val expiryDate = snapshot.child("expiryDate").value.toString()
val drugId = snapshot.child("id").value.toString()
val drugName = snapshot.child("name").value.toString()
val securityType = snapshot.child("securityType").value.toString()
val storageLocation = snapshot.child("storageLocation").value.toString()
val drugLabel = snapshot.child("drugLabel").value as Long
originalDrugList.add(Drugs(drugName, drugId, drugType, securityType, storageLocation, expiryDate, drugLabel))
}
adapter.updateList(originalDrugList)
} else {
Toast.makeText(requireContext(), "No Drugs Info", Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_SHORT).show()
}
})
return root
}
private fun filterDrugList() {
val filteredList = mutableListOf<Drugs>()
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val currentDate: Date = sdf.parse(sdf.format(Date()))!!
val calendar = Calendar.getInstance()
calendar.time = currentDate
calendar.add(Calendar.DAY_OF_YEAR, 30)
val futureDate: Date = calendar.time
for (drug in originalDrugList) {
val drugType = drug.drugType
val drugLabel = drug.drugLabel
when (currentFilter) {
FilterOptions.All -> {
filteredList.add(drug)
}
FilterOptions.Red_Sticker -> {
if (drugLabel.toString() == "2") {
filteredList.add(drug)
}
}
FilterOptions.Expired -> {
if (drugLabel.toString() == "3") {
filteredList.add(drug)
}
}
FilterOptions.Simple -> {
if (drugType.toString() == "Simple") {
filteredList.add(drug)
}
}
FilterOptions.Controlled -> {
if (drugType.toString() == "Controlled") {
filteredList.add(drug)
}
}
}
}
adapter.updateList(filteredList)
}
}
| Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/ListOfDrugs.kt | 2424296850 |
package com.example.mediphix_app
import com.google.firebase.database.PropertyName
data class Checks(val regNumber : String? = null,
val nurse_first_name : String? = null,
val nurse_last_name : String? = null,
val storage_location : String? = null,
val checkDate : String? = null,
val imageUrl : String? = null,
val drugList : List<Drugs>? = null){} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Checks.kt | 1113954351 |
package com.example.mediphix_app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.mediphix_app.databinding.ProfilePageBinding
import com.google.firebase.database.FirebaseDatabase
class Profile : Fragment(R.layout.profile_page) {
private lateinit var binding: ProfilePageBinding
// Firebase reference
private val databaseReference = FirebaseDatabase.getInstance().getReference("Nurses")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = ProfilePageBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.checkHistoryBtn.setOnClickListener {
val action = ProfileDirections.actionProfileToCheckHistory()
findNavController().navigate(action)
}
binding.logoutBtn.setOnClickListener {
val action = ProfileDirections.actionProfileToLogin()
findNavController().navigate(action)
val medTrack = requireActivity().application as MedTrack
medTrack.roomDrugList.clear()
medTrack.currentNurseDetail = null
}
// Fetch the profile data for the currently logged-in user
val nurseApp = requireActivity().application as MedTrack
val currentNurse = nurseApp.currentNurseDetail
if (currentNurse != null) {
binding.firstName.setText(currentNurse.firstName.toString().uppercase())
}
if (currentNurse != null) {
binding.lastName.setText(currentNurse.lastName.toString().uppercase())
}
if (currentNurse != null) {
binding.regNumber.setText(currentNurse.regNumber.toString().uppercase())
}
}
} | Mediphix-MobileApp/app/src/main/java/com/example/mediphix_app/Profile.kt | 4008037602 |
package com.example.glowgetter
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.glowgetter", appContext.packageName)
}
} | glowgetter/app/src/androidTest/java/com/example/glowgetter/ExampleInstrumentedTest.kt | 2936021834 |
package com.example.glowgetter
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)
}
} | glowgetter/app/src/test/java/com/example/glowgetter/ExampleUnitTest.kt | 4220130201 |
package com.example.glowgetter.ui
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.navigationsuite.ExperimentalMaterial3AdaptiveNavigationSuiteApi
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import com.example.glowgetter.R
enum class AppDestinations(
@StringRes val label: Int,
val icon: ImageVector,
@StringRes val contentDescription: Int
){
HOME(label = R.string.home, icon = Icons.Filled.Home, contentDescription = R.string.home),
CATEGORIES(label = R.string.categories, icon = Icons.Filled.Info, contentDescription = R.string.categories),
FAVORITES(label = R.string.favorites, icon = Icons.Filled.Favorite, contentDescription = R.string.favorites),
GUIDES(label = R.string.guides, icon = Icons.Filled.Face, contentDescription = R.string.guides),
}
@OptIn(ExperimentalMaterial3AdaptiveNavigationSuiteApi::class)
@Composable
fun GlowGetterApp(
modifier: Modifier = Modifier
){
var currentDestination by rememberSaveable { mutableStateOf(AppDestinations.HOME) }
NavigationSuiteScaffold(
navigationSuiteItems = {
AppDestinations.entries.forEach {
item(
icon = {
Icon(
it.icon,
contentDescription = stringResource(it.contentDescription)
)
},
label = {
Text(stringResource(it.label))
},
selected = currentDestination == it,
onClick = { currentDestination = it }
)
}
}
) {
}
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/GlowGetterApp.kt | 1659026269 |
package com.example.glowgetter.ui.viewmodels
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.glowgetter.data.GlowGetterRepository
import com.example.glowgetter.GlowGetterApplication
import com.example.glowgetter.ui.ProductListUiState
import com.example.glowgetter.ui.ProductUiState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.io.IOException
class GlowGetterViewModel(private val glowGetterRepository: GlowGetterRepository) : ViewModel() {
var productListUiState: ProductListUiState by mutableStateOf(ProductListUiState.Loading)
private set
private val _productUiState = MutableStateFlow(ProductUiState())
val productUiState: StateFlow<ProductUiState> = _productUiState.asStateFlow()
private var brandQuery: String? = null
private var typeQuery: String = "eyeshadow"
init {
getProductListByBrand()
getProductListByType()
}
fun onBrandQueryChanged(query: String) {
brandQuery = query
getProductListByBrand()
}
fun onTypeQueryChanged(query: String) {
typeQuery = query
getProductListByType()
}
fun getProductListByBrand(brandQuery: String? = this.brandQuery) {
viewModelScope.launch {
productListUiState = ProductListUiState.Loading
productListUiState = try {
val productList = brandQuery?.let { glowGetterRepository.getProductsByBrand(it) }
if (productList == null) {
ProductListUiState.Error
} else {
ProductListUiState.Success(productList)
}
} catch (e: IOException) {
ProductListUiState.Error
} catch (e: HttpException) {
ProductListUiState.Error
}
}
}
fun getProductListByType(type: String = "eyeshadow") {
viewModelScope.launch {
productListUiState = ProductListUiState.Loading
productListUiState = try {
val productList = glowGetterRepository.getProductsByType("eyeshadowi")
if (productList == null) {
ProductListUiState.Error
} else {
ProductListUiState.Success(productList)
}
} catch (e: IOException) {
ProductListUiState.Error
} catch (e: HttpException) {
ProductListUiState.Error
}
}
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val application = (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]
as GlowGetterApplication)
val glowGetterRepository = application.glowGetterAppContainer.glowGetterRepository
GlowGetterViewModel(glowGetterRepository = glowGetterRepository)
}
}
}
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/viewmodels/GlowGetterViewModel.kt | 670172171 |
package com.example.glowgetter.ui
import com.example.glowgetter.Product
data class ProductUiState(
val product: Product? = null,
val products: List<Product> = emptyList()
) | glowgetter/app/src/main/java/com/example/glowgetter/ui/ProductUiState.kt | 1429811082 |
package com.example.glowgetter.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFFA43465)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFFFD9E3)
val md_theme_light_onPrimaryContainer = Color(0xFF3E001F)
val md_theme_light_secondary = Color(0xFF74565F)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFD9E3)
val md_theme_light_onSecondaryContainer = Color(0xFF2B151D)
val md_theme_light_tertiary = Color(0xFFA43B33)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDAD6)
val md_theme_light_onTertiaryContainer = Color(0xFF410002)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF201A1C)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF201A1C)
val md_theme_light_surfaceVariant = Color(0xFFF2DDE2)
val md_theme_light_onSurfaceVariant = Color(0xFF514347)
val md_theme_light_outline = Color(0xFF837377)
val md_theme_light_inverseOnSurface = Color(0xFFFAEEEF)
val md_theme_light_inverseSurface = Color(0xFF352F30)
val md_theme_light_inversePrimary = Color(0xFFFFB0CA)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFFA43465)
val md_theme_light_outlineVariant = Color(0xFFD5C2C6)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFFFB0CA)
val md_theme_dark_onPrimary = Color(0xFF640035)
val md_theme_dark_primaryContainer = Color(0xFF851A4D)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E3)
val md_theme_dark_secondary = Color(0xFFE2BDC7)
val md_theme_dark_onSecondary = Color(0xFF422931)
val md_theme_dark_secondaryContainer = Color(0xFF5A3F48)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9E3)
val md_theme_dark_tertiary = Color(0xFFFFB4AB)
val md_theme_dark_onTertiary = Color(0xFF640C0B)
val md_theme_dark_tertiaryContainer = Color(0xFF84241E)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDAD6)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF201A1C)
val md_theme_dark_onBackground = Color(0xFFEBE0E1)
val md_theme_dark_surface = Color(0xFF201A1C)
val md_theme_dark_onSurface = Color(0xFFEBE0E1)
val md_theme_dark_surfaceVariant = Color(0xFF514347)
val md_theme_dark_onSurfaceVariant = Color(0xFFD5C2C6)
val md_theme_dark_outline = Color(0xFF9E8C90)
val md_theme_dark_inverseOnSurface = Color(0xFF201A1C)
val md_theme_dark_inverseSurface = Color(0xFFEBE0E1)
val md_theme_dark_inversePrimary = Color(0xFFA43465)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFFFB0CA)
val md_theme_dark_outlineVariant = Color(0xFF514347)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFFEB6C9E)
| glowgetter/app/src/main/java/com/example/glowgetter/ui/theme/Color.kt | 3138911018 |
package com.example.glowgetter.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun GlowGetterTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/theme/Theme.kt | 613432816 |
package com.example.glowgetter.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.googlefonts.Font
import androidx.compose.ui.text.googlefonts.GoogleFont
import androidx.compose.ui.unit.sp
import com.example.glowgetter.R
//Properties:
//displayLarge - displayLarge is the largest display text.
//displayMedium - displayMedium is the second largest display text.
//displaySmall - displaySmall is the smallest display text.
//headlineLarge - headlineLarge is the largest headline, reserved for short, important text or numerals. For headlines, you can choose an expressive font, such as a display, handwritten, or script style. These unconventional font designs have details and intricacy that help attract the eye.
//headlineMedium - headlineMedium is the second largest headline, reserved for short, important text or numerals. For headlines, you can choose an expressive font, such as a display, handwritten, or script style. These unconventional font designs have details and intricacy that help attract the eye.
//headlineSmall - headlineSmall is the smallest headline, reserved for short, important text or numerals. For headlines, you can choose an expressive font, such as a display, handwritten, or script style. These unconventional font designs have details and intricacy that help attract the eye.
//titleLarge - titleLarge is the largest title, and is typically reserved for medium-emphasis text that is shorter in length. Serif or sans serif typefaces work well for subtitles.
//titleMedium - titleMedium is the second largest title, and is typically reserved for medium-emphasis text that is shorter in length. Serif or sans serif typefaces work well for subtitles.
//titleSmall - titleSmall is the smallest title, and is typically reserved for medium-emphasis text that is shorter in length. Serif or sans serif typefaces work well for subtitles.
//bodyLarge - bodyLarge is the largest body, and is typically used for long-form writing as it works well for small text sizes. For longer sections of text, a serif or sans serif typeface is recommended.
//bodyMedium - bodyMedium is the second largest body, and is typically used for long-form writing as it works well for small text sizes. For longer sections of text, a serif or sans serif typeface is recommended.
//bodySmall - bodySmall is the smallest body, and is typically used for long-form writing as it works well for small text sizes. For longer sections of text, a serif or sans serif typeface is recommended.
//labelLarge - labelLarge text is a call to action used in different types of buttons (such as text, outlined and contained buttons) and in tabs, dialogs, and cards. Button text is typically sans serif, using all caps text.
//labelMedium - labelMedium is one of the smallest font sizes. It is used sparingly to annotate imagery or to introduce a headline.
//labelSmall - labelSmall is one of the smallest font sizes. It is used sparingly to annotate imagery or to introduce a headline.
// Set of Material typography styles to start with
val provider = GoogleFont.Provider(
providerAuthority = "com.google.android.gms.fonts",
providerPackage = "com.google.android.gms",
certificates = R.array.com_google_android_gms_fonts_certs
)
val fontName = GoogleFont("Lobster Two")
val fontFamily = FontFamily(
Font(googleFont = fontName, fontProvider = provider)
)
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
// Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
) | glowgetter/app/src/main/java/com/example/glowgetter/ui/theme/Type.kt | 3972214612 |
package com.example.glowgetter.ui.homescreen
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.glowgetter.Product
import com.example.glowgetter.R
import com.example.glowgetter.data.ProductDataProvider
import kotlinx.coroutines.delay
@Composable
fun ProductCategories(
onEyesClick: () -> Unit,
onFaceClick: () -> Unit,
onLipsClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(modifier = modifier) {
Card(modifier = modifier.clickable { onEyesClick() }) {
Text(text = stringResource(R.string.eyes))
}
Card(modifier = modifier.clickable { onFaceClick() }) {
Text(text = stringResource(R.string.face))
}
Card(modifier = modifier.clickable { onLipsClick() }) {
Text(text = stringResource(R.string.lips))
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ProductCarousel(
autoScrollEnabled: Boolean = true,
autoScrollInterval: Int = 3000,
modifier: Modifier = Modifier,
) {
val photos = listOf(
R.mipmap.lipstick,
R.mipmap.eyeshadow,
R.mipmap.foundation
)
val pageCount = photos.size
val pagerState = rememberPagerState(initialPage = 0, pageCount = { 250 })
// infinitely loop through images every 2 seconds while app is live
LaunchedEffect(autoScrollEnabled, autoScrollInterval) {
if (autoScrollEnabled) {
while (true) {
pagerState.animateScrollToPage(pagerState.currentPage + 1)
delay(autoScrollInterval.toLong())
}
}
}
HorizontalPager(
contentPadding = PaddingValues(horizontal = 16.dp),
pageSpacing = 16.dp,
state = pagerState,
) { index ->
val page = index % pageCount
Image(
painter = painterResource(photos[page]),
contentDescription = photos[page].toString()
)
}
}
// possibly delete
@Composable
fun HomePaneMakeupProductsList(
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
) {
val productList = ProductDataProvider.products
LazyVerticalGrid(
columns = GridCells.Adaptive(157.dp),
state = rememberLazyGridState(),
modifier = modifier.padding(horizontal = 4.dp),
contentPadding = contentPadding,
) {
items(items = productList) { product ->
ProductItem(product = product)
}
}
}
//this should also go in the same file as the above composable/.....maybe
@Composable
fun ProductItem(
product: Product,
modifier: Modifier = Modifier
) {
Card(modifier = modifier.width(150.dp)) {
Column() {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(product.image)
.crossfade(true)
.build(),
contentDescription = product.productType,
)
Text(product.brand)
Text(product.name)
// add a lazy row of circles for product colors
product.price?.let { Text(it) }
}
}
}
@Composable
fun GgTopAppBar(
modifier: Modifier = Modifier,
onSearch: (String) -> Unit
) {
val text by remember {
mutableStateOf("")
}
Box(modifier = modifier) {
Image(
painter = painterResource(R.mipmap.top_app_bar_background),
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = modifier
.heightIn(96.dp)
.fillMaxWidth()
)
Column(modifier = modifier) {
Text(text = stringResource(R.string.find))
Text(text = stringResource(R.string.your_glow))
// Spacer(modifier = modifier.padding(16.dp))
BasicTextField(
value = text,
onValueChange = {
onSearch(it)
},
maxLines = 1,
singleLine = true,
textStyle = TextStyle(color = Color.Black),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
modifier = Modifier
.shadow(5.dp, CircleShape)
.background(Color.White, CircleShape)
// .padding(horizontal = 20.dp, vertical = 12.dp)
)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun HomeScreen(
onEyesClick: () -> Unit,
onFaceClick: () -> Unit,
onLipsClick: () -> Unit,
modifier: Modifier = Modifier
) {
val products1 = ProductDataProvider.products.subList(0, 2)
val products2 = ProductDataProvider.products.subList(2, 4)
val products3 = ProductDataProvider.products.subList(4, 6)
val products4 = ProductDataProvider.products.subList(6, 8)
val products5 = ProductDataProvider.products.subList(8, 10)
Scaffold(
topBar = {
GgTopAppBar(onSearch = { "search me" })
}
) {
Column(modifier = Modifier
.padding(it)
.verticalScroll(rememberScrollState())) {
ProductCategories(onEyesClick, onFaceClick, onLipsClick)
ProductCarousel()
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
products1.forEach { product ->
ProductItem(product = product)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
products2.forEach { product ->
ProductItem(product = product)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
products3.forEach { product ->
ProductItem(product = product)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
products4.forEach { product ->
ProductItem(product = product)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
products5.forEach { product ->
ProductItem(product = product)
}
}
}
}
}
// Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// LazyColumn() {
// item {
// GgTopAppBar(onSearch = { "search me" })
// }
// item {
// ProductCategories()
// }
// item {
// ProductCarousel()
// }
// items(count = products.size) { product ->
// ProductItem(product = products[product])
// }
// }
// LazyVerticalGrid(columns = GridCells.Fixed(2)) {
// items(count = products.size) { product ->
// ProductItem(product = products[product])
// }
// }
// }
//@Preview
//@Composable
//fun ProductItemPreview() {
// val product = Product(
// id = 1,
// brand = "brand",
// name = "name",
// price = "price",
// image = "image",
// productType = "productType",
// description = "description",
// rating = 5.0,
// category = "category",
// productColors = listOf("color", "color")
// )
// ProductItem(product)
//}
@Preview
@Composable
fun TopAppBarPreview() {
GgTopAppBar(onSearch = { "search me" })
}
@Preview
@Composable
fun CarouselPreview() {
ProductCarousel()
}
| glowgetter/app/src/main/java/com/example/glowgetter/ui/homescreen/HomeContent.kt | 98615260 |
package com.example.glowgetter.ui.productlist
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
import androidx.compose.material3.adaptive.layout.ListDetailPaneScaffold
import androidx.compose.material3.adaptive.layout.ListDetailPaneScaffoldRole
import androidx.compose.material3.adaptive.navigation.rememberListDetailPaneScaffoldNavigator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import com.example.glowgetter.Product
import com.example.glowgetter.ui.homescreen.HomeScreen
import com.example.glowgetter.ui.homescreen.ProductItem
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.glowgetter.R
import com.example.glowgetter.ui.ProductListUiState
import com.example.glowgetter.ui.viewmodels.GlowGetterViewModel
@Composable
fun EyesCategoryDetailPane(
onCardClick: () -> Unit,
onFirstClick: () -> Unit,
onSecondClick: () -> Unit,
onThirdClick: () -> Unit,
onFourthClick: () -> Unit,
modifier: Modifier = Modifier
) {
LazyVerticalGrid(columns = GridCells.Adaptive(157.dp)) {
item {
CategoryDetailCard(productType = "Eyebrow Pencils",
painter = R.mipmap.eyebrow_pencil,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = { },
onFirstClick = { },
onSecondClick = { },
onThirdClick = { },
onFourthClick = { })
}
item {
CategoryDetailCard(productType = "Mascara",
painter = R.mipmap.mascara,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = { },
onFirstClick = {},
onSecondClick = {},
onThirdClick = {},
onFourthClick = {})
}
item {
CategoryDetailCard(productType = "Eyeliner",
painter = R.mipmap.eyeliner,
firstSubCategory = "Liquid",
secondSubCategory = "Pencil",
thirdSubCategory = "Gel",
fourthSubCategory = "Cream",
onCardClick = { },
onFirstClick = {},
onSecondClick = {},
onThirdClick = {},
onFourthClick = {})
}
item {
CategoryDetailCard(productType = "Eyeshadow",
painter = R.mipmap.eyeshadow_product,
firstSubCategory = "Palette",
secondSubCategory = "Pencil",
thirdSubCategory = "Cream",
fourthSubCategory = null,
onCardClick = { },
onFirstClick = {},
onSecondClick = {},
onThirdClick = {},
onFourthClick = {})
}
}
}
@Composable
fun FaceCategoryDetailPane(
onCardClick: () -> Unit,
onFirstClick: () -> Unit,
onSecondClick: () -> Unit,
onThirdClick: () -> Unit,
onFourthClick: () -> Unit,
modifier: Modifier = Modifier
) {
LazyVerticalGrid(columns = GridCells.Adaptive(157.dp)) {
item {
CategoryDetailCard(
productType = "Foundation",
painter = R.mipmap.liquid_foundation,
firstSubCategory = "Liquid",
secondSubCategory = "BB & CC Cream",
thirdSubCategory = "Mineral",
fourthSubCategory = "Powder",
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Blush",
painter = R.mipmap.blush,
firstSubCategory = "Powder",
secondSubCategory = "Cream",
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Bronzer",
painter = R.mipmap.bronzer,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Concealer",
painter = R.mipmap.concealer,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Contour",
painter = R.mipmap.contour,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Highlighter",
painter = R.mipmap.highlighter,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
}
}
@Composable
fun LipsCategoryDetailPane(
onCardClick: () -> Unit,
onFirstClick: () -> Unit,
onSecondClick: () -> Unit,
onThirdClick: () -> Unit,
onFourthClick: () -> Unit,
modifier: Modifier = Modifier
) {
LazyVerticalGrid(columns = GridCells.Adaptive(157.dp)) {
item {
CategoryDetailCard(
productType = "Lip Gloss",
painter = R.mipmap.lip_gloss,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Lip Liner",
painter = R.mipmap.lipliner_pencil,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
item {
CategoryDetailCard(
productType = "Lipstick",
painter = R.mipmap.lipstick_product,
firstSubCategory = null,
secondSubCategory = null,
thirdSubCategory = null,
fourthSubCategory = null,
onCardClick = onCardClick,
onFirstClick = onFirstClick,
onSecondClick = onSecondClick,
onThirdClick = onThirdClick,
onFourthClick = onFourthClick
)
}
}
}
@Composable
fun CategoryDetailCard(
painter: Int,
productType: String,
onCardClick: () -> Unit,
firstSubCategory: String?,
secondSubCategory: String?,
thirdSubCategory: String?,
fourthSubCategory: String?,
onFirstClick: () -> Unit,
onSecondClick: () -> Unit,
onThirdClick: () -> Unit,
onFourthClick: () -> Unit,
modifier: Modifier = Modifier
) {
Card(modifier = modifier.clickable { onCardClick() }) {
Column {
Text(text = productType)
Image(
painter = painterResource(id = painter),
contentDescription = painter.toString(),
modifier = modifier
)
}
if (firstSubCategory != null) {
Text(text = firstSubCategory, modifier = Modifier.clickable { onFirstClick() })
}
if (secondSubCategory != null) {
Text(text = secondSubCategory, modifier = Modifier.clickable { onSecondClick() })
}
if (thirdSubCategory != null) {
Text(text = thirdSubCategory, modifier = Modifier.clickable { onThirdClick() })
}
if (fourthSubCategory != null) {
Text(text = fourthSubCategory, modifier = Modifier.clickable { onFourthClick() })
}
}
}
@Composable
fun DetailPane(
modifier: Modifier = Modifier, uiState: ProductListUiState
) {
when (uiState) {
is ProductListUiState.Loading -> {
// TODO
}
is ProductListUiState.Error -> {
// TODO
}
is ProductListUiState.Success -> {
MakeupListPane(productList = uiState.products)
}
}
}
enum class DetailList {
EYES, FACE, LIPS
}
@OptIn(ExperimentalMaterial3AdaptiveApi::class, ExperimentalMaterial3Api::class)
@Composable
fun ListDetailScreen(
onCardClick: () -> Unit,
onFirstClick: () -> Unit,
onSecondClick: () -> Unit,
onThirdClick: () -> Unit,
onFourthClick: () -> Unit,
modifier: Modifier = Modifier,
viewModel: GlowGetterViewModel = viewModel(factory = GlowGetterViewModel.Factory)
) {
val navigator = rememberListDetailPaneScaffoldNavigator<Nothing>()
var currentDestination by rememberSaveable { mutableStateOf(DetailList.EYES) }
val glowGetterViewModel: GlowGetterViewModel = viewModel(factory = GlowGetterViewModel.Factory)
val uiState by viewModel.productUiState.collectAsState()
BackHandler(navigator.canNavigateBack()) {
navigator.navigateBack()
}
ListDetailPaneScaffold(directive = navigator.scaffoldDirective,
value = navigator.scaffoldValue,
listPane = {
HomeScreen(onEyesClick = {
navigator.navigateTo(ListDetailPaneScaffoldRole.Detail)
}, onFaceClick = {
currentDestination = DetailList.FACE
navigator.navigateTo(ListDetailPaneScaffoldRole.Detail)
}, onLipsClick = {
currentDestination = DetailList.LIPS
navigator.navigateTo(ListDetailPaneScaffoldRole.Detail)
})
},
detailPane = {
when (currentDestination) {
DetailList.EYES -> EyesCategoryDetailPane(
onCardClick, onFirstClick, onSecondClick, onThirdClick, onFourthClick
)
DetailList.FACE -> FaceCategoryDetailPane(
onCardClick, onFirstClick, onSecondClick, onThirdClick, onFourthClick
)
DetailList.LIPS -> LipsCategoryDetailPane(
onCardClick, onFirstClick, onSecondClick, onThirdClick, onFourthClick
)
}
})
}
@Composable
fun MakeupListPane(
productList: List<Product>,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
) {
LazyVerticalGrid(
columns = GridCells.Adaptive(157.dp),
state = rememberLazyGridState(),
modifier = modifier.padding(horizontal = 4.dp),
contentPadding = contentPadding,
) {
items(items = productList) { product ->
ProductItem(product = product)
}
}
}
@Preview
@Composable
fun EyesCategoryDetailPanePreview(
) {
EyesCategoryDetailPane({ }, { }, { }, { }, { })
}
@Preview
@Composable
fun LipsCategoryDetailPanePreview() {
LipsCategoryDetailPane({ }, { }, { }, { }, { })
}
@Preview
@Composable
fun FaceCategoryDetailPanePreview() {
FaceCategoryDetailPane({ }, { }, { }, { }, { })
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/productlist/ProductListAndDetail.kt | 1519645598 |
package com.example.glowgetter.ui
import com.example.glowgetter.Product
sealed interface ProductListUiState {
data class Success(val products: List<Product>) : ProductListUiState
object Error : ProductListUiState
object Loading : ProductListUiState
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/ProductListUiState.kt | 2881083768 |
package com.example.glowgetter.ui.welcomescreen
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.glowgetter.R
@Composable
fun WelcomeScreen(
modifier: Modifier = Modifier,
onValueChange: (String) -> Unit = {},
) {
val text by remember { mutableStateOf("") }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = modifier
// .fillMaxSize()
.background(color = colorResource(id = R.color.white))
){
Text(text = stringResource(id = R.string.app_name))
Image(
painter = painterResource(id = R.mipmap.welcome_screen_graphic),
contentDescription = null,
contentScale = ContentScale.FillBounds,
// alignment = Alignment.Center,
modifier = modifier.size(400.dp)
)
Text(text = stringResource(R.string.tagline))
OutlinedTextField(
value = text,
onValueChange = onValueChange,
singleLine = true
)
}
}
@Preview
@Composable
fun WelcomeScreenPreview() {
WelcomeScreen()
} | glowgetter/app/src/main/java/com/example/glowgetter/ui/welcomescreen/WelcomeScreen.kt | 3874286902 |
package com.example.glowgetter
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ProductColor(
@SerialName("hex_value") val hexValue: String
)
@Serializable
data class Product (
val id: Int,
val brand: String,
val name: String,
val price: String?,
// @SerialName("price_sign")
//// val priceSign: Any? = null,
////
//// val currency: Any? = null,
@SerialName("image_link")
val image: String,
// @SerialName("product_link")
// val productLink: String,
// @SerialName("website_link")
// val websiteLink: String,
val description: String,
val rating: Double?,
val category: String?,
@SerialName("product_type")
val productType: String,
// @SerialName( "api_featured_image")
// val apiFeaturedImage: String,
@SerialName("product_colors")
val productColors: List<ProductColor>?
)
| glowgetter/app/src/main/java/com/example/glowgetter/Product.kt | 767096503 |
package com.example.glowgetter
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.glowgetter.ui.ProductListUiState
import com.example.glowgetter.ui.homescreen.HomeScreen
import com.example.glowgetter.ui.productlist.DetailPane
import com.example.glowgetter.ui.productlist.ListDetailScreen
import com.example.glowgetter.ui.theme.GlowGetterTheme
import com.example.glowgetter.ui.viewmodels.GlowGetterViewModel
import com.example.glowgetter.ui.welcomescreen.WelcomeScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GlowGetterTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val glowGetterViewModel: GlowGetterViewModel = viewModel(factory = GlowGetterViewModel.Factory)
WelcomeScreen()
}
}
}
}
} | glowgetter/app/src/main/java/com/example/glowgetter/MainActivity.kt | 2792691905 |
package com.example.glowgetter.network
import com.example.glowgetter.Product
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
// Return products by brand
@GET("")
suspend fun getProductsByBrand(@Query("brand") brand: String): Response<List<Product>>
// Return products by type
@GET("products.json")
suspend fun getProductsByType(@Query("product_type") type: String): Response<List<Product>>
} | glowgetter/app/src/main/java/com/example/glowgetter/network/ApiService.kt | 1045002580 |
package com.example.glowgetter
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.glowgetter.ui.viewmodels.GlowGetterViewModel
import com.example.glowgetter.ui.welcomescreen.WelcomeScreen
import kotlinx.coroutines.launch
enum class NavGraph {
WELCOME,
HOME,
DETAILS
}
@Composable
fun CahierNavHost(
viewModel: GlowGetterViewModel = viewModel(factory = GlowGetterViewModel.Factory),
navController: NavHostController = rememberNavController(),
) {
val startDestination: String = NavGraph.WELCOME.name
val coroutineScope = rememberCoroutineScope()
Scaffold {
NavHost(
navController = navController,
startDestination = startDestination,
modifier = Modifier.padding(it)
) {
composable(NavGraph.WELCOME.name) {
WelcomeScreen()
}
composable(NavGraph.HOME.name) {
}
composable(NavGraph.DETAILS.name) {
}
}
}
} | glowgetter/app/src/main/java/com/example/glowgetter/GlowGetterNavGraph.kt | 644882864 |
package com.example.glowgetter
import android.app.Application
import com.example.glowgetter.data.DefaultGlowGetterAppContainer
import com.example.glowgetter.data.GlowGetterAppContainer
class GlowGetterApplication : Application() {
// AppContainer instance used by the rest of classes to obtain dependencies
lateinit var glowGetterAppContainer: GlowGetterAppContainer
override fun onCreate() {
super.onCreate()
glowGetterAppContainer = DefaultGlowGetterAppContainer()
}
} | glowgetter/app/src/main/java/com/example/glowgetter/GlowGetterApplication.kt | 3074457138 |
package com.example.glowgetter.data
import com.example.glowgetter.Product
import com.example.glowgetter.network.ApiService
interface GlowGetterRepository {
suspend fun getProductsByBrand(brand: String): List<Product>?
suspend fun getProductsByType(type: String): List<Product>?
}
class DefaultGlowGetterRepository(private val apiService: ApiService) : GlowGetterRepository {
override suspend fun getProductsByBrand(brand: String): List<Product>? {
return try {
val res = apiService.getProductsByBrand(brand)
if (res.isSuccessful) {
res.body() ?: emptyList()
} else {
emptyList()
}
} catch (e: Exception) {
e.printStackTrace()
null
}
}
override suspend fun getProductsByType(type: String): List<Product>? {
return try {
val res = apiService.getProductsByType(type)
if (res.isSuccessful) {
res.body() ?: emptyList()
} else {
emptyList()
}
} catch (e: Exception) {
e.printStackTrace()
null
}
}
} | glowgetter/app/src/main/java/com/example/glowgetter/data/GlowGetterRepository.kt | 400677216 |
package com.example.glowgetter.data
import com.example.glowgetter.Product
object ProductDataProvider {
val products = listOf(
Product(
id = 1,
brand = "e.l.f.",
name = "Glow Reviver Lip Oil",
price = null,
image = "https://media.ulta.com/i/ulta/2615651?w=720&h=720&fmt=webp",
productType = "lipstick",
description = "description",
rating = 5.0,
category = "lip_gloss",
productColors = null
),
Product(
id = 2,
brand = "Morphe",
name = "Rich & Foiled Rose to Fame Eyeshadow Palette",
price = null,
image = "https://media.ulta.com/i/ulta/2623445?w=720&h=720&fmt=webp",
productType = "eyeshadow",
description = "Discover a wealth of possibilities in a flash with Morphe's Rich & Foiled Rose to Fame Eyeshadow Palette. Inspired by precious metals, this excessive and expressive 9-pan elevates artistry with luxe mattes, shimmers, and metallics plus, a crown jewel: a debut foil-effect molten metal eyeshadow",
rating = 5.0,
category = "palette",
productColors = null
),
Product(
id = 3,
brand = "IT Cosmetics",
name = "CC+ Cream with SPF 50+",
price = null,
image = "https://media.ulta.com/i/ulta/2599624?w=720&h=720&fmt=webp",
productType = "foundation",
description = "IT Cosmetics CC+ Cream with SPF 50+ goes beyond color-correcting to include your full coverage foundation, anti-aging serum and mineral sunscreen in one.",
rating = 5.0,
category = "category",
productColors = null
),
Product(
id = 4,
brand = "NARS",
name = "Blush",
price = null,
image = "https://media.ulta.com/i/ulta/2622065?w=720&h=720&fmt=webp",
productType = "blush",
description = "NARS' iconic Blush, now reimagined in an upgraded formula that lasts for up to 16 hours, featuring true-color payoff with a comfortable, weightless feel.",
rating = 5.0,
category = "category",
productColors = null
),
Product(
id = 5,
brand = "Essence",
name = "Lash Princess False Lash Effect Mascara",
price = null,
image = "https://media.ulta.com/i/ulta/2289595?w=720&h=720&fmt=webp",
productType = "mascara",
description = "Essence Lash Princess False Lash Effect Mascara creates an irresistible false lash effect with length, curl, and dramatic volume.",
rating = 5.0,
category = "category",
productColors = null
),
Product(
id = 6,
brand = "Tarte",
name = "Shape Tape Ultra Creamy Concealer",
price = null,
image = "https://media.ulta.com/i/ulta/2575050?w=720&h=720&fmt=webp",
productType = "foundation",
description = "Tarte's iconic Shape Tape Concealer, now with a built-in EYE CREAM for 24-hr hydration!",
rating = 5.0,
category = "category",
productColors = null
),
Product(
id = 7,
brand = "NYX Professional Makeup",
name = "Butter Gloss Non-Sticky Lip Gloss",
price = null,
image = "https://media.ulta.com/i/ulta/2268533?w=720&h=720&fmt=webp",
productType = "lipstick",
description = "Discover NYX Professional Makeup Butter Gloss, America's #1 silky-smooth non-sticky lip gloss that adds the perfect pop of shine to your makeup look.",
rating = 4.5,
category = "lip_gloss",
productColors = null
),
Product(
id = 8,
brand = "e.l.f.",
name = "Power Grip Dewy Setting Spray",
price = null,
image = "https://media.ulta.com/i/ulta/2621170?w=720&h=720&fmt=webp",
productType = "foundation",
description = "e.l.f. Cosmetics' shockingly fine bi-phase Power Grip Dewy Setting Spray features a water-based phase and moisturizing oil-based phase. Boosted with 5% aloe, plus hyaluronic acid, squalene, and green tea seed oil. Shake to activate the power of both phases for dewy, long-lasting makeup looks.",
rating = 5.0,
category = "setting",
productColors = null
),
Product(
id = 9,
brand = "L.A. Girl",
name = "HD Pro Corrector Concealer",
price = null,
image = "https://media.ulta.com/i/ulta/2540110?w=720&h=720&fmt=webp",
productType = "foundation",
description = "Camouflage blemishes, correct color, or highlight & contour with L.A Girl HD Pro Concealer. This lightweight formula provides buildable, long-wearing coverage.",
rating = 5.0,
category = "category",
productColors = null
),
Product(
id = 10,
brand = "MAC",
name = "M·A·Cximal Silky Matte Lipstick",
price = null,
image = "https://media.ulta.com/i/ulta/2621407?w=720&h=720&fmt=webp",
productType = "lipstick",
description = "description",
rating = 5.0,
category = "lipstick",
productColors = null
)
)
} | glowgetter/app/src/main/java/com/example/glowgetter/data/ProductDataProvider.kt | 19242396 |
package com.example.glowgetter.data
import com.example.glowgetter.network.ApiService
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
interface GlowGetterAppContainer {
val glowGetterRepository: GlowGetterRepository
}
// Implementation for the Dependency Injection container at the application level.
// Variables are initialized lazily and the same instance is shared across the whole app.
class DefaultGlowGetterAppContainer : GlowGetterAppContainer {
private val baseUrl = "https://makeup-api.herokuapp.com/api/v1/"
private val json = Json {
ignoreUnknownKeys = true // Set ignoreUnknownKeys to true
}
//Use the Retrofit builder to build a retrofit object using a kotlinx.serialization converter
private val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseUrl)
.build()
// Retrofit service object for creating api calls
private val retrofitService: ApiService by lazy {
retrofit.create(ApiService::class.java)
}
// DI implementation for the repository
override val glowGetterRepository: GlowGetterRepository by lazy {
DefaultGlowGetterRepository(retrofitService)
}
} | glowgetter/app/src/main/java/com/example/glowgetter/data/GlowGetterAppContainer.kt | 3919690951 |
package com.t2pellet.boycottisraelapi
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class BoycottApp
fun main(args: Array<String>) {
runApplication<BoycottApp>(*args)
}
| boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/BoycottApp.kt | 2923396747 |
package com.t2pellet.boycottisraelapi.repository
import com.t2pellet.boycottisraelapi.model.BarcodeEntry
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface BarcodeRepository: JpaRepository<BarcodeEntry, String> {
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/repository/BarcodeRepository.kt | 1298258743 |
package com.t2pellet.boycottisraelapi
import org.springframework.cache.annotation.EnableCaching
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration
@EnableCaching
class BoycottConfig: WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/**").allowedMethods("*")
}
override fun configurePathMatch(configurer: PathMatchConfigurer) {
configurer.setUseTrailingSlashMatch(true)
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/BoycottConfig.kt | 275650636 |
package com.t2pellet.boycottisraelapi.controller
import com.t2pellet.boycottisraelapi.model.*
import com.t2pellet.boycottisraelapi.service.BarcodeService
import com.t2pellet.boycottisraelapi.service.BoycottService
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException
import org.springframework.web.bind.annotation.PatchMapping
import org.springframework.web.bind.annotation.RequestParam
@RestController
@RequestMapping("/api/barcode")
class BarcodeController(
val barcodeService: BarcodeService,
val boycottService: BoycottService
) {
@GetMapping("/{barcode}")
fun getBarcode(@PathVariable barcode: String): BoycottBarcode {
val barcodeData = barcodeService.getBarcodeEntry(barcode)
if (barcodeData != null) {
val isFromCache = barcodeService.isCachedBarcode(barcodeData.barcode)
if (barcodeData.strapiId != null) {
val parent = boycottService.get(barcodeData.strapiId)
val result = BoycottBarcode(barcodeData, parent)
return result
} else if (!isFromCache) {
val result = boycottService.getForBarcode(barcodeData)
barcodeService.saveBarcode(barcodeData.barcode, result)
return result
} else {
val logo = if (barcodeData.company.isNotEmpty()) boycottService.getLogo(barcodeData.company) else null
return BoycottBarcode(barcodeData.product, barcodeData.company, false, null, logo)
}
}
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Barcode not found")
}
@GetMapping("/exists/{barcode}")
fun checkBarcode(@PathVariable barcode: String): BarcodeCheck {
val cached = barcodeService.isCachedBarcode(barcode)
return BarcodeCheck(barcode, cached)
}
@PostMapping("")
fun addBarcode(@RequestBody barcode: BarcodeData): BarcodeEntry {
if (barcodeService.isCachedBarcode(barcode.barcode)) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Cannot add an existing entry")
}
val match: BoycottEntry? = boycottService.getBest(barcode.company.ifEmpty { barcode.product })
if (match != null) {
val entry = BarcodeEntry(barcode.barcode, barcode.company, barcode.product, match.id)
barcodeService.saveBarcode(entry)
return entry
} else {
val entry = BarcodeEntry(barcode.barcode, barcode.company, barcode.product)
barcodeService.saveBarcode(entry)
return entry
}
}
@PatchMapping("/{barcode}")
fun fixBarcode(@PathVariable barcode: String, @RequestParam company: String): BarcodeEntry {
val match: BoycottEntry? = boycottService.getBest(company)
if (match != null) {
val result = barcodeService.saveBarcodeCompany(barcode, match.name, match.id)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Barcode not found")
return result
}
val result = barcodeService.saveBarcodeCompany(barcode, company)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Barcode not found")
return result
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/controller/BarcodeController.kt | 2263592055 |
package com.t2pellet.boycottisraelapi.controller
import com.t2pellet.boycottisraelapi.model.BoycottEntry
import com.t2pellet.boycottisraelapi.service.BoycottService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.*
@RestController
@RequestMapping("/api/boycott")
class BoycottController(val boycottService: BoycottService) {
@GetMapping("")
fun get(@RequestParam name: Optional<String>): List<BoycottEntry> {
if (name.isPresent) {
return boycottService.get(name.get())
}
return boycottService.getAll()
}
@GetMapping("{id}")
fun get(@PathVariable id: Number): BoycottEntry {
return boycottService.get(id)
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/controller/BoycottController.kt | 1562630705 |
package com.t2pellet.boycottisraelapi.controller
import com.t2pellet.boycottisraelapi.model.NameEntry
import com.t2pellet.boycottisraelapi.service.BoycottService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.*
@RestController
@RequestMapping("/api/names")
class NamesController(val boycottService: BoycottService) {
@GetMapping("")
fun get(@RequestParam name: Optional<String>): List<NameEntry> {
return if (name.isPresent) {
boycottService.getNames(name.get())
} else boycottService.getNames()
}
@GetMapping("{id}")
fun getNames(@PathVariable id: Number): NameEntry {
return boycottService.getName(id)
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/controller/NamesController.kt | 483052744 |
package com.t2pellet.boycottisraelapi.model
import com.fasterxml.jackson.annotation.JsonProperty
data class NameEntry(
@JsonProperty("id")
val id: Number,
@JsonProperty("name")
val name: String
) | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/NameEntry.kt | 2857578001 |
package com.t2pellet.boycottisraelapi.model
import com.fasterxml.jackson.annotation.JsonInclude
@JsonInclude(JsonInclude.Include.NON_NULL)
data class BoycottBarcode(
val product: String,
val company: String,
val boycott: Boolean,
val reason: String? = null,
val logo: String? = null,
val proof: String? = null,
val id: Int? = null,
) {
constructor(barcode: BarcodeEntry, parent: BoycottEntry): this(
barcode.product,
parent.name,
true,
parent.reason,
parent.logo,
parent.proof,
parent.id
)
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/BoycottBarcode.kt | 2354923596 |
package com.t2pellet.boycottisraelapi.model
data class BarcodeCheck(
val barcode: String,
val cached: Boolean,
)
| boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/BarcodeCheck.kt | 7219878 |
package com.t2pellet.boycottisraelapi.model
import com.fasterxml.jackson.annotation.JsonAlias
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Table(name = "barcodes")
data class BarcodeEntry (
@Id
@JsonProperty("barcode")
val barcode: String,
@JsonProperty("company")
@JsonAlias("brand")
val company: String,
@JsonProperty("product")
@JsonAlias("title")
val product: String,
@JsonIgnore
@JsonProperty("strapiId")
val strapiId: Int? = null
) | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/BarcodeEntry.kt | 1091326956 |
package com.t2pellet.boycottisraelapi.model
import jakarta.validation.constraints.NotEmpty
data class BarcodeData(
@NotEmpty
val barcode: String,
@NotEmpty
val product: String,
@NotEmpty
val company: String
) | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/BarcodeData.kt | 2505983521 |
package com.t2pellet.boycottisraelapi.model
import com.fasterxml.jackson.annotation.JsonProperty
data class BoycottEntry(
@JsonProperty("id")
val id: Int,
@JsonProperty("name")
val name: String,
@JsonProperty("description")
val description: String?,
@JsonProperty("reason")
val reason: String,
@JsonProperty("proof")
val proof: String,
@JsonProperty("logo")
val logo: String,
) | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/model/BoycottEntry.kt | 3765806567 |
package com.t2pellet.boycottisraelapi.service
import com.fasterxml.jackson.databind.ObjectMapper
import com.t2pellet.boycottisraelapi.model.BarcodeEntry
import com.t2pellet.boycottisraelapi.model.BoycottBarcode
import com.t2pellet.boycottisraelapi.repository.BarcodeRepository
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import java.util.*
@Service
class BarcodeService(
val barcodeRepository: BarcodeRepository
) {
val client = WebClient.builder()
.baseUrl("https://api.upcdatabase.org")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer ${System.getenv("BARCODE_KEY")}")
.build()
val mapper: ObjectMapper = ObjectMapper()
fun getBarcodeEntry(barcode: String): BarcodeEntry? {
// First try with DB
val dbResult: Optional<BarcodeEntry> = barcodeRepository.findById(barcode)
if (dbResult.isPresent) {
return dbResult.get()
}
// If not in DB we fetch from API
val response = client.get().uri("/product/${barcode}")
.exchangeToMono {
if (it.statusCode() != HttpStatus.OK) {
return@exchangeToMono Mono.empty()
} else {
return@exchangeToMono it.bodyToMono(String::class.java)
}
}
.block()
if (!response.isNullOrEmpty()) {
val jsonData = mapper.reader().readTree(response)
if (jsonData.get("success").asBoolean()) {
return mapper.convertValue(jsonData, BarcodeEntry::class.java)
}
}
return null
}
fun isCachedBarcode(barcode: String): Boolean {
return barcodeRepository.existsById(barcode)
}
fun saveBarcode(barcodeEntity: BarcodeEntry) {
if (!barcodeRepository.existsById(barcodeEntity.barcode)) {
barcodeRepository.saveAndFlush(barcodeEntity)
}
}
fun saveBarcode(barcode: String, barcodeData: BoycottBarcode) {
saveBarcode(BarcodeEntry(
barcode,
barcodeData.company,
barcodeData.product,
barcodeData.id,
))
}
fun saveBarcodeCompany(barcode: String, company: String, strapiId: Int? = null): BarcodeEntry? {
val entry = barcodeRepository.findById(barcode)
if (entry.isPresent) {
val data = entry.get()
if (data.company.isEmpty()) {
val newEntry = BarcodeEntry(data.barcode, company, data.product, strapiId)
barcodeRepository.saveAndFlush(newEntry)
return newEntry
}
}
return null
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/service/BarcodeService.kt | 3049587095 |
package com.t2pellet.boycottisraelapi.service
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import com.t2pellet.boycottisraelapi.model.BarcodeEntry
import com.t2pellet.boycottisraelapi.model.BoycottBarcode
import com.t2pellet.boycottisraelapi.model.BoycottEntry
import com.t2pellet.boycottisraelapi.model.NameEntry
import me.xdrop.fuzzywuzzy.FuzzySearch
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.Cacheable
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec
import java.util.function.Function
@Service
@CacheConfig(cacheNames = ["boycottServiceCache"])
class BoycottService {
val client: WebClient = WebClient.builder()
.baseUrl("https://strapi-production-0fb3.up.railway.app/api/")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + System.getenv("STRAPI_TOKEN"))
.build()
val mapper: ObjectMapper = ObjectMapper()
@Cacheable("boycotts")
fun getAll(): List<BoycottEntry> {
val response = client.get().uri("boycotts?populate=*").retrieve()
return parse(response, this::parseBoycottEntry)
}
// TODO : This is really inefficient
@Cacheable("boycotts")
fun get(name: String): List<BoycottEntry> {
val results = getAll()
val names = results.map { it.name }
val matches = FuzzySearch.extractSorted(name, names, { s1, s2 -> FuzzySearch.weightedRatio(s1, s2.take(s1.length)) }, 75).take(5)
return matches.map { match -> results.find { it.name == match.string } as BoycottEntry }
}
@Cacheable("boycott")
fun getBest(name: String): BoycottEntry? {
val results = getAll()
val names = results.map { it.name }
val match = FuzzySearch.extractOne(name, names) { s1, s2 -> FuzzySearch.weightedRatio(s1, s2) }
if (match.score >= 75) {
return results.find { it.name == match.string } as BoycottEntry
}
return null
}
@Cacheable("boycott")
fun get(id: Number): BoycottEntry {
val response = client.get().uri("boycotts/$id?populate=*").retrieve()
val responseData = response.bodyToMono(String::class.java).block()
val responseJson = mapper.reader().readTree(responseData).get("data") as ObjectNode
return parseBoycottEntry(responseJson)
}
@Cacheable("names")
fun getNames(): List<NameEntry> {
val response = client.get().uri("boycotts?populate=Subsidiary&fields[0]=name").retrieve()
val subsidiaries: List<NameEntry> = flatParse(response, this::parseSubsidiaryNames)
val names: List<NameEntry> = parse(response, this::parseName)
return names + subsidiaries
}
// TODO : This is really inefficient
@Cacheable("names")
fun getNames(name: String): List<NameEntry> {
val names = getNames()
val namesStr = names.map { it.name }
val matches = FuzzySearch.extractSorted(name, namesStr, { s1, s2 -> FuzzySearch.weightedRatio(s1, s2.take(s1.length)) }, 75).take(5)
return matches.map { match -> names.find { it.name == match.string } as NameEntry }
}
@Cacheable("name")
fun getName(id: Number): NameEntry {
val entry = get(id)
return NameEntry(entry.id, entry.name)
}
@Cacheable("barcode")
fun getForBarcode(barcode: BarcodeEntry): BoycottBarcode {
val entries = getAll()
val namesStr = entries.map { it.name }
val matchQuery = barcode.company.ifEmpty { barcode.product }
val match = FuzzySearch.extractOne(matchQuery, namesStr) { s1, s2 ->
FuzzySearch.weightedRatio(
s1,
s2
)
}
if (match.score >= 75) {
val idx = namesStr.indexOf(match.string)
val entry = entries[idx]
val product = get(entry.id)
return BoycottBarcode(barcode.product, product.name, true, product.reason, product.logo, product.proof, product.id)
}
val logo = getLogo(matchQuery)
return BoycottBarcode(barcode.product, barcode.company, false, null, logo)
}
fun getLogo(company: String): String? {
val response = WebClient.create("https://autocomplete.clearbit.com/v1/companies/")
.get().uri("suggest?query=$company").retrieve().bodyToMono(String::class.java).block()
val json = mapper.reader().readTree(response).toList()
if (json.isNotEmpty()) {
val logoEntry = json[0];
val logoCompany = logoEntry.get("name").asText()
if (FuzzySearch.weightedRatio(company, logoCompany) >= 75) {
return logoEntry.get("logo").asText()
}
}
return null
}
private fun <T> parse(response: ResponseSpec, parseFn: Function<JsonNode, T>): List<T> {
val responseData = response.bodyToMono(String::class.java).block()
val responseJson = mapper.reader().readTree(responseData)
val data = responseJson.get("data").toList()
return data.map { parseFn.apply(it) }
}
private fun <T> flatParse(response: ResponseSpec, parseFn: Function<JsonNode, List<T>>): List<T> {
val responseData = response.bodyToMono(String::class.java).block()
val responseJson = mapper.reader().readTree(responseData)
val data: List<JsonNode> = responseJson.get("data").toList()
return data.flatMap { parseFn.apply(it) }
}
private fun parseBoycottEntry(it: JsonNode): BoycottEntry {
val attributes = it.get("attributes") as ObjectNode
val logo = attributes.get("logo").get("data").get("attributes").get("url")
attributes.set<JsonNode>("logo", logo)
attributes.set<JsonNode>("id", it.get("id"))
attributes.remove("createdAt")
attributes.remove("updatedAt")
attributes.remove("publishedAt")
attributes.remove("Subsidiary")
return mapper.treeToValue(attributes, BoycottEntry::class.java)
}
private fun parseName(it: JsonNode): NameEntry {
val attributes = it.get("attributes")
val node = mapper.createObjectNode()
node.set<JsonNode>("id", it.get("id"))
node.set<JsonNode>("name", attributes.get("name"))
return mapper.treeToValue(node, NameEntry::class.java)
}
private fun parseSubsidiaryNames(it: JsonNode): List<NameEntry> {
val id = it.get("id")
val subsidiaries: JsonNode = it.get("attributes").get("Subsidiary")
return subsidiaries.map {
NameEntry(id.asInt(), it.get("name").asText())
}
}
} | boycott-israel-api/src/main/kotlin/com/t2pellet/boycottisraelapi/service/BoycottService.kt | 502281083 |
package com.azhar.absensi
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.azhar.absensi", appContext.packageName)
}
} | Aplikasi_Absensi/app/src/androidTest/java/com/azhar/absensi/ExampleInstrumentedTest.kt | 2394209830 |
package com.azhar.absensi
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)
}
} | Aplikasi_Absensi/app/src/test/java/com/azhar/absensi/ExampleUnitTest.kt | 113327217 |
package com.azhar.absensi.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.azhar.absensi.database.DatabaseClient.Companion.getInstance
import com.azhar.absensi.database.dao.DatabaseDao
import com.azhar.absensi.model.ModelDatabase
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.schedulers.Schedulers
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class AbsenViewModel(application: Application) : AndroidViewModel(application) {
var databaseDao: DatabaseDao? = getInstance(application)?.appDatabase?.databaseDao()
fun addDataAbsen(
foto: String, nama: String,
tanggal: String, lokasi: String, keterangan: String) {
Completable.fromAction {
val modelDatabase = ModelDatabase()
modelDatabase.fotoSelfie = foto
modelDatabase.nama = nama
modelDatabase.tanggal = tanggal
modelDatabase.lokasi = lokasi
modelDatabase.keterangan = keterangan
databaseDao?.insertData(modelDatabase)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/viewmodel/AbsenViewModel.kt | 2041195846 |
package com.azhar.absensi.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.azhar.absensi.database.DatabaseClient.Companion.getInstance
import com.azhar.absensi.database.dao.DatabaseDao
import com.azhar.absensi.model.ModelDatabase
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.schedulers.Schedulers
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class HistoryViewModel(application: Application) : AndroidViewModel(application) {
var dataLaporan: LiveData<List<ModelDatabase>>
var databaseDao: DatabaseDao? = getInstance(application)?.appDatabase?.databaseDao()
fun deleteDataById(uid: Int) {
Completable.fromAction {
databaseDao?.deleteHistoryById(uid)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
init {
dataLaporan = databaseDao!!.getAllHistory()
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/viewmodel/HistoryViewModel.kt | 3378342817 |
package com.azhar.absensi.database.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import com.azhar.absensi.model.ModelDatabase
import androidx.room.OnConflictStrategy
import androidx.room.Query
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
@Dao
interface DatabaseDao {
@Query("SELECT * FROM tbl_absensi")
fun getAllHistory(): LiveData<List<ModelDatabase>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertData(vararg modelDatabases: ModelDatabase)
@Query("DELETE FROM tbl_absensi WHERE uid= :uid")
fun deleteHistoryById(uid: Int)
@Query("DELETE FROM tbl_absensi")
fun deleteAllHistory()
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/database/dao/DatabaseDao.kt | 3195502745 |
package com.azhar.absensi.database
import android.content.Context
import androidx.room.Room
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class DatabaseClient private constructor(context: Context) {
var appDatabase: AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "absensi_db")
.fallbackToDestructiveMigration()
.build()
companion object {
private var mInstance: DatabaseClient? = null
@JvmStatic
@Synchronized
fun getInstance(context: Context): DatabaseClient? {
if (mInstance == null) {
mInstance = DatabaseClient(context)
}
return mInstance
}
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/database/DatabaseClient.kt | 2643199348 |
package com.azhar.absensi.database
import androidx.room.Database
import com.azhar.absensi.model.ModelDatabase
import androidx.room.RoomDatabase
import com.azhar.absensi.database.dao.DatabaseDao
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
@Database(entities = [ModelDatabase::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun databaseDao(): DatabaseDao?
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/database/AppDatabase.kt | 486548508 |
package com.azhar.absensi.utils
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.azhar.absensi.view.login.LoginActivity
/**
* Created by Azhar Rivaldi on 28-12-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class SessionLogin(var context: Context) {
var pref: SharedPreferences
var editor: SharedPreferences.Editor
var PRIVATE_MODE = 0
fun createLoginSession(nama: String) {
editor.putBoolean(IS_LOGIN, true)
editor.putString(KEY_NAMA, nama)
editor.commit()
}
fun checkLogin() {
if (!isLoggedIn()) {
val intent = Intent(context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
fun logoutUser() {
editor.clear()
editor.commit()
val intent = Intent(context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
fun isLoggedIn(): Boolean = pref.getBoolean(IS_LOGIN, false)
companion object {
private const val PREF_NAME = "AbsensiPref"
private const val IS_LOGIN = "IsLoggedIn"
const val KEY_NAMA = "NAMA"
}
init {
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
editor = pref.edit()
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/utils/SessionLogin.kt | 238489444 |
package com.azhar.absensi.utils
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import java.io.ByteArrayOutputStream
/**
* Created by Azhar Rivaldi on 17-10-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
object BitmapManager {
fun base64ToBitmap(base64: String): Bitmap {
val decodedString = Base64.decode(base64, Base64.DEFAULT)
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
}
fun bitmapToBase64(bitmap: Bitmap): String {
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 70, byteArrayOutputStream)
val byteArray = byteArrayOutputStream.toByteArray()
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/utils/BitmapManager.kt | 3935306008 |
package com.azhar.absensi.model
import androidx.room.PrimaryKey
import androidx.room.ColumnInfo
import androidx.room.Entity
import java.io.Serializable
/**
* Created by Azhar Rivaldi on 19-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
@Entity(tableName = "tbl_absensi")
class ModelDatabase : Serializable {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "uid")
var uid = 0
@ColumnInfo(name = "nama")
lateinit var nama: String
@ColumnInfo(name = "foto_selfie")
lateinit var fotoSelfie: String
@ColumnInfo(name = "tanggal")
lateinit var tanggal: String
@ColumnInfo(name = "lokasi")
lateinit var lokasi: String
@ColumnInfo(name = "keterangan")
lateinit var keterangan: String
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/model/ModelDatabase.kt | 1215005602 |
package com.azhar.absensi.view.absen
import android.Manifest
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.location.Geocoder
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.MenuItem
import android.view.View
import android.widget.DatePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.ViewModelProvider
import com.azhar.absensi.BuildConfig
import com.azhar.absensi.R
import com.azhar.absensi.utils.BitmapManager.bitmapToBase64
import com.azhar.absensi.viewmodel.AbsenViewModel
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.gms.location.LocationServices
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import kotlinx.android.synthetic.main.activity_absen.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class AbsenActivity : AppCompatActivity() {
var REQ_CAMERA = 101
var strCurrentLatitude = 0.0
var strCurrentLongitude = 0.0
var strFilePath: String = ""
var strLatitude = "0"
var strLongitude = "0"
lateinit var fileDirectoty: File
lateinit var imageFilename: File
lateinit var exifInterface: ExifInterface
lateinit var strBase64Photo: String
lateinit var strCurrentLocation: String
lateinit var strTitle: String
lateinit var strTimeStamp: String
lateinit var strImageName: String
lateinit var absenViewModel: AbsenViewModel
lateinit var progressDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_absen)
setInitLayout()
setCurrentLocation()
setUploadData()
}
private fun setCurrentLocation() {
progressDialog.show()
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return
}
fusedLocationClient.lastLocation
.addOnSuccessListener(this) { location ->
progressDialog.dismiss()
if (location != null) {
strCurrentLatitude = location.latitude
strCurrentLongitude = location.longitude
val geocoder = Geocoder(this@AbsenActivity, Locale.getDefault())
try {
val addressList =
geocoder.getFromLocation(strCurrentLatitude, strCurrentLongitude, 1)
if (addressList != null && addressList.size > 0) {
strCurrentLocation = addressList[0].getAddressLine(0)
inputLokasi.setText(strCurrentLocation)
}
} catch (e: IOException) {
e.printStackTrace()
}
} else {
progressDialog.dismiss()
Toast.makeText(this@AbsenActivity,
"Ups, gagal mendapatkan lokasi. Silahkan periksa GPS atau koneksi internet Anda!",
Toast.LENGTH_SHORT).show()
strLatitude = "0"
strLongitude = "0"
}
}
}
private fun setInitLayout() {
progressDialog = ProgressDialog(this)
strTitle = intent.extras?.getString(DATA_TITLE).toString()
if (strTitle != null) {
tvTitle.text = strTitle
}
setSupportActionBar(toolbar)
if (supportActionBar != null) {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
}
absenViewModel = ViewModelProvider(this, (ViewModelProvider.AndroidViewModelFactory
.getInstance(this.application) as ViewModelProvider.Factory)).get(AbsenViewModel::class.java)
inputTanggal.setOnClickListener {
val tanggalAbsen = Calendar.getInstance()
val date =
OnDateSetListener { _: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int ->
tanggalAbsen[Calendar.YEAR] = year
tanggalAbsen[Calendar.MONTH] = monthOfYear
tanggalAbsen[Calendar.DAY_OF_MONTH] = dayOfMonth
val strFormatDefault = "dd MMMM yyyy HH:mm"
val simpleDateFormat = SimpleDateFormat(strFormatDefault, Locale.getDefault())
inputTanggal.setText(simpleDateFormat.format(tanggalAbsen.time))
}
DatePickerDialog(
this@AbsenActivity, date,
tanggalAbsen[Calendar.YEAR],
tanggalAbsen[Calendar.MONTH],
tanggalAbsen[Calendar.DAY_OF_MONTH]
).show()
}
layoutImage.setOnClickListener {
Dexter.withContext(this@AbsenActivity)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport) {
if (report.areAllPermissionsGranted()) {
try {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(
"com.google.assistant.extra.USE_FRONT_CAMERA",
true
)
cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
cameraIntent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1)
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)
// Samsung
cameraIntent.putExtra("camerafacing", "front")
cameraIntent.putExtra("previous_mode", "front")
// Huawei
cameraIntent.putExtra("default_camera", "1")
cameraIntent.putExtra(
"default_mode",
"com.huawei.camera2.mode.photo.PhotoMode")
cameraIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
FileProvider.getUriForFile(
this@AbsenActivity,
BuildConfig.APPLICATION_ID + ".provider",
createImageFile()
)
)
startActivityForResult(cameraIntent, REQ_CAMERA)
} catch (ex: IOException) {
Toast.makeText(this@AbsenActivity,
"Ups, gagal membuka kamera", Toast.LENGTH_SHORT).show()
}
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: List<PermissionRequest>,
token: PermissionToken) {
token.continuePermissionRequest()
}
}).check()
}
}
private fun setUploadData() {
btnAbsen.setOnClickListener {
val strNama = inputNama.text.toString()
val strTanggal = inputTanggal.text.toString()
val strKeterangan = inputKeterangan.text.toString()
if (strFilePath.equals(null) || strNama.isEmpty() || strCurrentLocation.isEmpty()
|| strTanggal.isEmpty() || strKeterangan.isEmpty()) {
Toast.makeText(this@AbsenActivity,
"Data tidak boleh ada yang kosong!", Toast.LENGTH_SHORT).show()
} else {
absenViewModel.addDataAbsen(
strBase64Photo,
strNama,
strTanggal,
strCurrentLocation,
strKeterangan)
Toast.makeText(this@AbsenActivity,
"Laporan Anda terkirim, tunggu info selanjutnya ya!", Toast.LENGTH_SHORT).show()
finish()
}
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
strTimeStamp = SimpleDateFormat("dd MMMM yyyy HH:mm:ss").format(Date())
strImageName = "IMG_"
fileDirectoty = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "")
imageFilename = File.createTempFile(strImageName, ".jpg", fileDirectoty)
strFilePath = imageFilename.getAbsolutePath()
return imageFilename
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
convertImage(strFilePath)
}
private fun convertImage(imageFilePath: String?) {
val imageFile = File(imageFilePath)
if (imageFile.exists()) {
val options = BitmapFactory.Options()
var bitmapImage = BitmapFactory.decodeFile(strFilePath, options)
try {
exifInterface = ExifInterface(imageFile.absolutePath)
} catch (e: IOException) {
e.printStackTrace()
}
val orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)
val matrix = Matrix()
if (orientation == 6) {
matrix.postRotate(90f)
} else if (orientation == 3) {
matrix.postRotate(180f)
} else if (orientation == 8) {
matrix.postRotate(270f)
}
bitmapImage = Bitmap.createBitmap(
bitmapImage,
0,
0,
bitmapImage.width,
bitmapImage.height,
matrix,
true
)
if (bitmapImage == null) {
Toast.makeText(this@AbsenActivity,
"Ups, foto kamu belum ada!", Toast.LENGTH_LONG).show()
} else {
val resizeImage = (bitmapImage.height * (512.0 / bitmapImage.width)).toInt()
val scaledBitmap = Bitmap.createScaledBitmap(bitmapImage, 512, resizeImage, true)
Glide.with(this)
.load(scaledBitmap)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.ic_photo_camera)
.into(imageSelfie)
strBase64Photo = bitmapToBase64(scaledBitmap)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
for (grantResult in grantResults) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
val intent = intent
finish()
startActivity(intent)
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
const val DATA_TITLE = "TITLE"
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/view/absen/AbsenActivity.kt | 2527485185 |
package com.azhar.absensi.view.history
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.azhar.absensi.R
import com.azhar.absensi.model.ModelDatabase
import com.azhar.absensi.utils.BitmapManager.base64ToBitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.material.imageview.ShapeableImageView
import kotlinx.android.synthetic.main.list_history_absen.view.*
import java.lang.String
import kotlin.Int
/**
* Created by Azhar Rivaldi on 30-11-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class HistoryAdapter(
var mContext: Context,
var modelDatabase: MutableList<ModelDatabase>,
var mAdapterCallback: HistoryAdapterCallback) : RecyclerView.Adapter<HistoryAdapter.ViewHolder>() {
fun setDataAdapter(items: List<ModelDatabase>) {
modelDatabase.clear()
modelDatabase.addAll(items)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_history_absen, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = modelDatabase[position]
holder.tvNomor.text = String.valueOf(data.uid)
holder.tvNama.text = data.nama
holder.tvLokasi.text = data.lokasi
holder.tvAbsenTime.text = data.tanggal
holder.tvStatusAbsen.text = data.keterangan
Glide.with(mContext)
.load(base64ToBitmap(data.fotoSelfie))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.ic_photo_camera)
.into(holder.imageProfile)
when (data.keterangan) {
"Absen Masuk" -> {
holder.colorStatus.setBackgroundResource(R.drawable.bg_circle_radius)
holder.colorStatus.backgroundTintList = ColorStateList.valueOf(Color.GREEN)
}
"Absen Keluar" -> {
holder.colorStatus.setBackgroundResource(R.drawable.bg_circle_radius)
holder.colorStatus.backgroundTintList = ColorStateList.valueOf(Color.RED)
}
"Izin" -> {
holder.colorStatus.setBackgroundResource(R.drawable.bg_circle_radius)
holder.colorStatus.backgroundTintList = ColorStateList.valueOf(Color.BLUE)
}
}
}
override fun getItemCount(): Int {
return modelDatabase.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvStatusAbsen: TextView = itemView.tvStatusAbsen
var tvNomor: TextView = itemView.tvNomor
var tvNama: TextView = itemView.tvNama
var tvLokasi: TextView = itemView.tvLokasi
var tvAbsenTime: TextView = itemView.tvAbsenTime
var cvHistory: CardView = itemView.cvHistory
var imageProfile: ShapeableImageView = itemView.imageProfile
var colorStatus: View = itemView.colorStatus
init {
cvHistory.setOnClickListener {
val modelLaundry = modelDatabase[adapterPosition]
mAdapterCallback.onDelete(modelLaundry)
}
}
}
interface HistoryAdapterCallback {
fun onDelete(modelDatabase: ModelDatabase?)
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/view/history/HistoryAdapter.kt | 834710417 |
package com.azhar.absensi.view.history
import android.content.DialogInterface
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.azhar.absensi.R
import com.azhar.absensi.model.ModelDatabase
import com.azhar.absensi.view.history.HistoryAdapter.HistoryAdapterCallback
import com.azhar.absensi.viewmodel.HistoryViewModel
import kotlinx.android.synthetic.main.activity_history.*
class HistoryActivity : AppCompatActivity(), HistoryAdapterCallback {
var modelDatabaseList: MutableList<ModelDatabase> = ArrayList()
lateinit var historyAdapter: HistoryAdapter
lateinit var historyViewModel: HistoryViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
setInitLayout()
setViewModel()
}
private fun setInitLayout() {
setSupportActionBar(toolbar)
if (supportActionBar != null) {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
}
tvNotFound.visibility = View.GONE
historyAdapter = HistoryAdapter(this, modelDatabaseList, this)
rvHistory.setHasFixedSize(true)
rvHistory.layoutManager = LinearLayoutManager(this)
rvHistory.adapter = historyAdapter
}
private fun setViewModel() {
historyViewModel = ViewModelProviders.of(this).get(HistoryViewModel::class.java)
historyViewModel.dataLaporan.observe(this) { modelDatabases: List<ModelDatabase> ->
if (modelDatabases.isEmpty()) {
tvNotFound.visibility = View.VISIBLE
rvHistory.visibility = View.GONE
} else {
tvNotFound.visibility = View.GONE
rvHistory.visibility = View.VISIBLE
}
historyAdapter.setDataAdapter(modelDatabases)
}
}
override fun onDelete(modelDatabase: ModelDatabase?) {
val alertDialogBuilder = AlertDialog.Builder(this)
alertDialogBuilder.setMessage("Hapus riwayat ini?")
alertDialogBuilder.setPositiveButton("Ya, Hapus") { dialogInterface, i ->
val uid = modelDatabase!!.uid
historyViewModel.deleteDataById(uid)
Toast.makeText(this@HistoryActivity, "Yeay! Data yang dipilih sudah dihapus",
Toast.LENGTH_SHORT).show()
}
alertDialogBuilder.setNegativeButton("Batal") { dialogInterface: DialogInterface, i:
Int -> dialogInterface.cancel() }
val alertDialog = alertDialogBuilder.create()
alertDialog.show()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/view/history/HistoryActivity.kt | 638754313 |
package com.azhar.absensi.view.main
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.azhar.absensi.R
import com.azhar.absensi.utils.SessionLogin
import com.azhar.absensi.view.absen.AbsenActivity
import com.azhar.absensi.view.history.HistoryActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var strTitle: String
lateinit var session: SessionLogin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setInitLayout()
}
private fun setInitLayout() {
session = SessionLogin(this)
session.checkLogin()
cvAbsenMasuk.setOnClickListener {
strTitle = "Absen Masuk"
val intent = Intent(this@MainActivity, AbsenActivity::class.java)
intent.putExtra(AbsenActivity.DATA_TITLE, strTitle)
startActivity(intent)
}
cvAbsenKeluar.setOnClickListener {
strTitle = "Absen Keluar"
val intent = Intent(this@MainActivity, AbsenActivity::class.java)
intent.putExtra(AbsenActivity.DATA_TITLE, strTitle)
startActivity(intent)
}
cvPerizinan.setOnClickListener {
strTitle = "Izin"
val intent = Intent(this@MainActivity, AbsenActivity::class.java)
intent.putExtra(AbsenActivity.DATA_TITLE, strTitle)
startActivity(intent)
}
cvHistory.setOnClickListener {
val intent = Intent(this@MainActivity, HistoryActivity::class.java)
startActivity(intent)
}
imageLogout.setOnClickListener {
val builder = AlertDialog.Builder(this@MainActivity)
builder.setMessage("Yakin Anda ingin Logout?")
builder.setCancelable(true)
builder.setNegativeButton("Batal") { dialog, which -> dialog.cancel() }
builder.setPositiveButton("Ya") { dialog, which ->
session.logoutUser()
finishAffinity()
}
val alertDialog = builder.create()
alertDialog.show()
}
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/view/main/MainActivity.kt | 1585118558 |
package com.azhar.absensi.view.login
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.azhar.absensi.R
import com.azhar.absensi.utils.SessionLogin
import com.azhar.absensi.view.main.MainActivity
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
lateinit var session: SessionLogin
lateinit var strNama: String
lateinit var strPassword: String
var REQ_PERMISSION = 101
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setPermission()
setInitLayout()
}
private fun setPermission() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQ_PERMISSION
)
}
}
private fun setInitLayout() {
session = SessionLogin(applicationContext)
if (session.isLoggedIn()) {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
finish()
}
btnLogin.setOnClickListener {
strNama = inputNama.text.toString()
strPassword = inputPassword.text.toString()
if (strNama.isEmpty() || strPassword.isEmpty()) {
Toast.makeText(this@LoginActivity, "Form tidak boleh kosong!",
Toast.LENGTH_SHORT).show()
} else {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
session.createLoginSession(strNama)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
for (grantResult in grantResults) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
val intent = intent
finish()
startActivity(intent)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
} | Aplikasi_Absensi/app/src/main/java/com/azhar/absensi/view/login/LoginActivity.kt | 2002261419 |
package com.oyetech.denemelib
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.oyetech.denemelib.test", appContext.packageName)
}
} | denemeLib/src/androidTest/java/com/oyetech/denemelib/ExampleInstrumentedTest.kt | 3573582095 |
package com.oyetech.denemelib
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)
}
} | denemeLib/src/test/java/com/oyetech/denemelib/ExampleUnitTest.kt | 3815854748 |
package com.oyetech.denemelib
/**
Created by Erdi Özbek
-29.01.2024-
-16:05-
**/
class Denemememe {
} | denemeLib/src/main/java/com/oyetech/denemelib/denemeasdad.kt | 298920537 |
package com.oyetech.denemelib
/**
Created by Erdi Özbek
-29.01.2024-
-16:08-
**/
class Denememememememe {
} | denemeLib/src/main/java/com/oyetech/denemelib/Denememememememe.kt | 3089251322 |
package com.example.climate360
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.climate360", appContext.packageName)
}
} | Climate360/app/src/androidTest/java/com/example/climate360/ExampleInstrumentedTest.kt | 2005976238 |
package com.example.climate360
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)
}
} | Climate360/app/src/test/java/com/example/climate360/ExampleUnitTest.kt | 625070498 |
package com.example.climate360
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonActivity1: Button = findViewById(R.id.button1)
buttonActivity1.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
} | Climate360/app/src/main/java/com/example/climate360/MainActivity.kt | 1117516396 |
package com.example.climate360
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import okhttp3.Headers
data class WeatherData(val location: String, val condition: String, val temperature_f: String, val temperature_c: String, val imageUrl: String, val feel_f: String, val feel_c:String, val uv:String, val humid:String)
class SecondActivity : AppCompatActivity() {
private lateinit var weatherList: MutableList<WeatherData>
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: WeatherAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val buttonActivity2: Button = findViewById(R.id.button2)
buttonActivity2.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
recyclerView = findViewById(R.id.weather_recycler_view)
weatherList = mutableListOf()
adapter = WeatherAdapter(weatherList)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
// Set up an endless scrolling listener
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
/*
// Load more data if the user is near the end of the list
if (visibleItemCount + firstVisibleItem >= totalItemCount - 5) {
getWeather()
}
*/
}
})
getWeather()
}
private fun getWeather() {
val client = AsyncHttpClient()
val listOfCities = listOf(
"california", "new york", "philadelphia", "chicago", "boston",
"london", "paris", "tokyo", "hong kong", "dubai"
)
val baseUrl = "https://api.weatherapi.com/v1/current.json"
val apiKey = "e21cc8c788854b22960172017231211"
for (city in listOfCities) {
val url = "$baseUrl?key=$apiKey&q=$city&aqi=no"
client.get(url, null, object : JsonHttpResponseHandler() {
override fun onFailure(
statusCode: Int,
headers: Headers?,
response: String?,
throwable: Throwable?
) {
Log.e("WeatherFetch", "Failed to fetch weather data")
Log.e("WeatherFetch", "Status Code: $statusCode")
Log.e("WeatherFetch", "Response Headers: $headers")
Log.e("WeatherFetch", "Response: $response")
Log.e("WeatherFetch", "Throwable: $throwable")
}
override fun onSuccess(statusCode: Int, headers: Headers?, json: JSON?) {
try {
if (json != null) {
Log.d("JSON Obj :", json.jsonObject.toString());
val location = json.jsonObject.getJSONObject("location").getString("name")
val condition = json.jsonObject.getJSONObject("current").getJSONObject("condition").getString("text")
val temperature_f = (json.jsonObject.getJSONObject("current").getString("temp_f")) + " °F"
val temperature_c = (json.jsonObject.getJSONObject("current").getString("temp_c")) + " °C"
val imageUrl = json.jsonObject.getJSONObject("current").getJSONObject("condition").getString("icon")
val feel_f = "Feels Like: " + (json.jsonObject.getJSONObject("current").getString("feelslike_f")) + " °F"
val feel_c = "Feels Like: " +(json.jsonObject.getJSONObject("current").getString("feelslike_c")) + " °C"
val uv = "UV: " +(json.jsonObject.getJSONObject("current").getString("uv"))
val humid = "Humidity: " +(json.jsonObject.getJSONObject("current").getString("humidity"))
val weather = WeatherData(location, condition, temperature_f, temperature_c, imageUrl, feel_f, feel_c, uv, humid)
weatherList.add(weather)
runOnUiThread {
adapter.notifyDataSetChanged()
}
// Limit the number of items to 10
if (weatherList.size >= 10) {
return
}
} else {
Log.e("WeatherFetch", "Error parsing weather data: Invalid JSON format")
}
} catch (e: Exception) {
Log.e("WeatherFetch", "Error parsing weather data: $e")
}
}
})
}
}
} | Climate360/app/src/main/java/com/example/climate360/SecondActivity.kt | 2417737544 |
package com.example.climate360
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class WeatherAdapter(private val weatherList: MutableList<WeatherData>) : RecyclerView.Adapter<WeatherAdapter.ViewHolder>() {
private val itemColors = intArrayOf(
R.color.background_color_1,
R.color.background_color_2,
R.color.background_color_3,
R.color.background_color_4,
R.color.background_color_5,
R.color.background_color_6,
R.color.background_color_7,
R.color.background_color_8,
R.color.background_color_9,
R.color.background_color_10,
)
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val location: TextView
val condition: TextView
val temperature_f: TextView
val temperature_c: TextView
val image: ImageView
val moreInfoBtn : Button
val feel_f: TextView
val feel_c: TextView
val uv: TextView
val humid: TextView
init {
location = itemView.findViewById(R.id.location)
condition = itemView.findViewById(R.id.condition)
temperature_f = itemView.findViewById(R.id.temperature_f)
temperature_c = itemView.findViewById(R.id.temperature_c)
image = itemView.findViewById(R.id.image)
moreInfoBtn = itemView.findViewById(R.id.more_btn)
feel_f = itemView.findViewById(R.id.feel_f)
feel_c = itemView.findViewById(R.id.feel_c)
uv = itemView.findViewById(R.id.uv)
humid = itemView.findViewById(R.id.humidity)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.weather_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return weatherList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val weather = weatherList[position]
holder.location.text = weather.location
holder.condition.text = weather.condition
holder.temperature_f.text = weather.temperature_f
holder.temperature_c.text = weather.temperature_c
holder.feel_f.text = weather.feel_f
holder.feel_c.text = weather.feel_c
holder.uv.text = weather.uv
holder.humid.text = weather.humid
loadWeatherImage(holder.image, weather.imageUrl)
val colorIndex = position % itemColors.size
holder.itemView.setBackgroundResource(itemColors[colorIndex])
var isMore = true;
holder.moreInfoBtn.setOnClickListener{
holder.moreInfoBtn.text = if (isMore) "Less" else "More";
isMore = !isMore;
holder.feel_f.visibility = if (holder.feel_f.visibility == View.GONE)
View.VISIBLE else View.GONE
holder.feel_c.visibility = if (holder.feel_c.visibility == View.GONE)
View.VISIBLE else View.GONE
holder.uv.visibility = if (holder.uv.visibility == View.GONE)
View.VISIBLE else View.GONE
holder.humid.visibility = if (holder.humid.visibility == View.GONE)
View.VISIBLE else View.GONE
}
}
private fun loadWeatherImage(imageView: ImageView, imageUrl: String) {
Glide.with(imageView.context)
.load("https:$imageUrl")
.centerCrop()
.into(imageView)
}
}
| Climate360/app/src/main/java/com/example/climate360/WeatherAdapter.kt | 869288279 |
package com.wildfire.adv160421010week2
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.wildfire.adv160421010week2", appContext.packageName)
}
} | ANMP-160421010Week2/app/src/androidTest/java/com/wildfire/adv160421010week2/ExampleInstrumentedTest.kt | 3772560359 |
package com.wildfire.adv160421010week2
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)
}
} | ANMP-160421010Week2/app/src/test/java/com/wildfire/adv160421010week2/ExampleUnitTest.kt | 1820809024 |
package com.wildfire.adv160421010week2
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import com.wildfire.adv160421010week2.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController =
(supportFragmentManager.findFragmentById(R.id.hostFragment) as
NavHostFragment).navController
NavigationUI.setupActionBarWithNavController(this, navController)
binding.bottomNav.setupWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp()
}
} | ANMP-160421010Week2/app/src/main/java/com/wildfire/adv160421010week2/MainActivity.kt | 298824866 |
package com.wildfire.adv160421010week2
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.wildfire.adv160421010week2.databinding.ActivityMainBinding
import com.wildfire.adv160421010week2.databinding.FragmentOptionBinding
class OptionFragment : BottomSheetDialogFragment() {
private lateinit var binding: FragmentOptionBinding
private val LEVEL = arrayOf("Easy", "Medium", "Hard")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_option, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter: ArrayAdapter<String> = ArrayAdapter<String>(requireContext(),
android.R.layout.simple_dropdown_item_1line, LEVEL)
binding.txtLevel.setAdapter(adapter)
}
} | ANMP-160421010Week2/app/src/main/java/com/wildfire/adv160421010week2/OptionFragment.kt | 1005502043 |
package com.wildfire.adv160421010week2
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class HistoryFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_history, container, false)
}
} | ANMP-160421010Week2/app/src/main/java/com/wildfire/adv160421010week2/HistoryFragment.kt | 461256666 |
package com.wildfire.adv160421010week2
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.wildfire.adv160421010week2.databinding.FragmentMainBinding
import com.wildfire.adv160421010week2.databinding.FragmentResultBinding
class ResultFragment : Fragment() {
private lateinit var binding: FragmentResultBinding
override fun onCreateView( inflater: LayoutInflater, container:
ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentResultBinding.inflate(
inflater,
container, false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val score =
ResultFragmentArgs.fromBundle(requireArguments()).score
binding.txtScore.text = "Your score is $score"
}
binding.btnOver.setOnClickListener {
val action = ResultFragmentDirections.actionMainFragment()
Navigation.findNavController(it).navigate(action)
}
}
} | ANMP-160421010Week2/app/src/main/java/com/wildfire/adv160421010week2/ResultFragment.kt | 3308296981 |
package com.wildfire.adv160421010week2
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.wildfire.adv160421010week2.databinding.FragmentMainBinding
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
override fun onCreateView( inflater: LayoutInflater, container:
ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentMainBinding.inflate(
inflater,
container, false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnStart.setOnClickListener {
val playerName = binding.txtName.text.toString()
val action = MainFragmentDirections.actionGameFragment(playerName)
Navigation.findNavController(it).navigate(action)
}
binding.btnOption.setOnClickListener {
val action = MainFragmentDirections.actionOptionFragment()
Navigation.findNavController(it).navigate(action)
}
}
} | ANMP-160421010Week2/app/src/main/java/com/wildfire/adv160421010week2/MainFragment.kt | 4293391921 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.