content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.mobile_dev_endproject_jc_jvl.R
import com.google.android.material.bottomnavigation.BottomNavigationView
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.home_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
val container = findViewById<LinearLayout>(R.id.container)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_home).isChecked = true
// Add custom navigation items
addNavigationItem(
container,
"Book A court",
"Navigates to book a court",
EstablishmentsActivity::class.java
)
addNavigationItem(
container,
"Show Club Map",
"Shows all available clubs on a Map",
MapActivity::class.java
)
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
}
private fun addNavigationItem(
container: LinearLayout,
title: String,
description: String,
targetActivity: Class<*>
) {
val customNavItem =
layoutInflater.inflate(R.layout.custom_navigation_item, null) as ConstraintLayout
val titleTextView = customNavItem.findViewById<TextView>(R.id.titleTextView)
val descriptionTextView = customNavItem.findViewById<TextView>(R.id.descriptionTextView)
titleTextView.text = title
descriptionTextView.text = description
customNavItem.setOnClickListener {
launchActivity(targetActivity)
}
container.addView(customNavItem)
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/HomeActivity.kt | 415053955 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.mobile_dev_endproject_jc_jvl.R
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.MatchReservation
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.PlayerReservation
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import java.text.SimpleDateFormat
import java.util.*
class ReservationActivity : AppCompatActivity() {
private lateinit var establishmentTextView: TextView
private lateinit var courtNameTextView: TextView
private var startingTimePlay: String = ""
private var endingTimePlay: String = ""
private lateinit var createMatchCheckBox: CheckBox
private lateinit var orderFieldButton: Button
private lateinit var returnButton: Button
private lateinit var datePickerButton: Button
private lateinit var dateTextView: TextView
private lateinit var selectedDate: Date
private var yearReservation: Int = 0
private var monthReservation: Int = 0
private var dayReservation: Int = 0
private lateinit var timeGrid: LinearLayout
private var takenTimeSlots = mutableListOf<String>()
private lateinit var reservedTimeText: TextView
private var makeMatchCollections: Boolean = false
private lateinit var sentThroughEstablishment: String
private lateinit var sentThroughCourtName: String
private lateinit var sentThroughClubName: String
private lateinit var sentThroughEstablishmentAddress: String
private lateinit var usernameOfUserOne: String
private lateinit var avatarOfUserOne: String
private lateinit var typeOfMatchSpinner: Spinner
private lateinit var gendersAllowedSpinner: Spinner
private lateinit var genderOfPlayer: String
private var completedUpdates: Int = 0
private var expectedUpdates: Int = 0
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.reservation_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
sentThroughEstablishment = intent.getStringExtra("sentThroughClubEstablishment").toString()
sentThroughCourtName = intent.getStringExtra("sentThroughCourtName").toString()
sentThroughClubName = intent.getStringExtra("sentThroughClubName").toString()
sentThroughEstablishmentAddress =
intent.getStringExtra("sentThroughEstablishmentAddress").toString()
establishmentTextView = findViewById(R.id.establishmentTextView)
courtNameTextView = findViewById(R.id.courtNameTextView)
datePickerButton = findViewById(R.id.datePickerButton)
dateTextView = findViewById(R.id.dateTextView)
// Set up the initial date
val calendar1 = Calendar.getInstance()
calendar1.add(Calendar.DAY_OF_MONTH, 1)
selectedDate = calendar1.time
updateDateTextView()
// Set up default values for year, month, and day
setupDefaultValues()
// Set up the DatePickerDialog
datePickerButton.setOnClickListener {
showDatePickerDialog()
}
// Get the layout components (Time)
timeGrid = findViewById(R.id.timeGrid)
reservedTimeText = findViewById(R.id.reservedTimeText)
// Time
createMatchCheckBox = findViewById(R.id.createMatchCheckBox)
orderFieldButton = findViewById(R.id.orderFieldButton)
returnButton = findViewById(R.id.returnButton)
// Inside your onCreate method after initializing createMatchCheckBox
createMatchCheckBox = findViewById(R.id.createMatchCheckBox)
typeOfMatchSpinner = findViewById(R.id.typeOfMatchSpinner)
gendersAllowedSpinner = findViewById(R.id.gendersAllowedSpinner)
typeOfMatchSpinner.alpha = 0.5f
gendersAllowedSpinner.alpha = 0.5f
typeOfMatchSpinner.isEnabled = false
gendersAllowedSpinner.isEnabled = false
// Add an OnCheckedChangeListener to createMatchCheckBox
createMatchCheckBox.setOnCheckedChangeListener { _, isChecked ->
// Set the boolean variable makeMatchCollections based on checkbox state
makeMatchCollections = isChecked
Log.d("ReservationActivity", "Checkbox: $makeMatchCollections")
// Adjust transparency and usability of spinners based on checkbox state
val alphaValue = if (isChecked) 1.0f else 0.5f
typeOfMatchSpinner.alpha = alphaValue
typeOfMatchSpinner.isEnabled = isChecked
gendersAllowedSpinner.alpha = alphaValue
gendersAllowedSpinner.isEnabled = isChecked
// Declare genderOptions outside the loop
var genderOptions: Array<String>
// Fetch the gender of the player
fetchGenderFirestore { playerGender ->
// Update spinner options based on player's gender and checkbox state
genderOptions = if (isChecked) {
when (playerGender) {
"Male" -> arrayOf("Male", "Either") // First option for Male
else -> arrayOf(
"Female",
"Either"
) // Default to second option for other cases
}
} else {
when (playerGender) {
"Female" -> arrayOf("Female", "Either") // First option for Female
else -> arrayOf("Male", "Either") // Default to first option for other cases
}
}
val genderAdapter =
ArrayAdapter(this, android.R.layout.simple_spinner_item, genderOptions)
gendersAllowedSpinner.adapter = genderAdapter
// Set the default selection based on fetched gender
gendersAllowedSpinner.setSelection(getIndex(gendersAllowedSpinner, playerGender))
}
}
// Retrieve data from the intent and set the text views accordingly
establishmentTextView.text = sentThroughEstablishment
courtNameTextView.text = sentThroughCourtName
// Set up the time grid
val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 8)
calendar.set(Calendar.MINUTE, 0)
for (i in 0 until 6) { // 6 rows for 8:00 to 19:30
val rowLayout = LinearLayout(this)
rowLayout.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
rowLayout.orientation = LinearLayout.HORIZONTAL
for (j in 0 until 4) {
val startTime = sdf.format(calendar.time)
calendar.add(Calendar.MINUTE, 30)
val timeSquare = TextView(this)
val params = LinearLayout.LayoutParams(
50, // width in dp
140, // height in dp
1f
)
params.setMargins(24, 24, 24, 24)
timeSquare.layoutParams = params
timeSquare.text = startTime
timeSquare.tag = startTime
timeSquare.gravity = Gravity.CENTER
timeSquare.setBackgroundResource(R.drawable.selector_time_square)
timeSquare.setTextColor(
ContextCompat.getColorStateList(
this,
R.color.text_color
)
) // Add this line
timeSquare.setOnClickListener { view ->
// Clear the selection of all other time squares
if (timeSquare.tag != "disabled") {
clearSelection(timeGrid)
// Toggle the selection of the current time square
view.isSelected = !view.isSelected
val selectedTime = view.tag as String
val reservedEndTime = calculateReservedEndTime(selectedTime)
startingTimePlay = selectedTime;
endingTimePlay = reservedEndTime
reservedTimeText.text = "Time Reserved: $selectedTime to $reservedEndTime"
}
}
rowLayout.addView(timeSquare)
}
timeGrid.addView(rowLayout)
}
// Fetch reserved time slots and update UI
fetchReservedTimeSlots("$yearReservation-$monthReservation-$dayReservation")
// Set click listener for the "Order Field" button
orderFieldButton.setOnClickListener {
// Handle order field logic
if (startingTimePlay == "" || endingTimePlay == "") {
// Show a warning to the user
// You can display a toast, dialog, or any other suitable UI element to notify the user
// For example, using a Toast:
findViewById<View>(R.id.redBorder).visibility = View.VISIBLE
Toast.makeText(
this,
"Please select a time slot before ordering the field",
Toast.LENGTH_SHORT
).show()
} else if (takenTimeSlots.any {
it.contains(startingTimePlay) || it.contains(
endingTimePlay
)
}) {
findViewById<View>(R.id.redBorder).visibility = View.VISIBLE
Toast.makeText(this, "Times overlap! Can't make reservation!", Toast.LENGTH_SHORT)
.show()
} else {
findViewById<View>(R.id.redBorder).visibility = View.GONE
orderField { launchActivity(EstablishmentsActivity::class.java) }
}
}
// Set click listener for the "Return" button
returnButton.setOnClickListener {
// Handle return logic
finish()
}
}
private fun orderField(callback: () -> Unit) {
// Counter to track the number of completed updates
completedUpdates = 0
// Variable to store the expected number of updates
expectedUpdates = if (!makeMatchCollections) {
2
} else {
3
}
// Get the current user's ID from Firebase Authentication
val currentUser = FirebaseAuth.getInstance().currentUser
val currentUserId = currentUser?.uid
fetchUserNameandAvatarFireStore { usernameOfUserOne, avatarOfUserOne ->
val sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment")
val sanitizedCourtName = intent.getStringExtra("SanitizedCourtName")
val courtName = intent.getStringExtra("sentThroughCourtName")
val sanitizedClubName = intent.getStringExtra("SanitizedClubName")
val yearForFirestore = yearReservation
val monthForFirestore = monthReservation
val dayForFirestore = dayReservation
val startTimeForFireStoreInsert = startingTimePlay
val endTimeForFireStoreInsert = endingTimePlay
val dateReservation = "$yearForFirestore-$monthForFirestore-$dayForFirestore"
val dateReservationSanitized =
formatDate(yearForFirestore, monthForFirestore, dayForFirestore)
val timeslot = "$startTimeForFireStoreInsert-$endTimeForFireStoreInsert"
val sanitizedStartTimeMoment = startTimeForFireStoreInsert.replace(":", "")
val sanitizedEndTimeMoment = endTimeForFireStoreInsert.replace(":", "")
val sanitizedTimeslot = "$sanitizedStartTimeMoment$sanitizedEndTimeMoment"
// unique MatchId: Courtname_year_month_day_hour-begin_hour-end
val matchId = "$courtName$dateReservationSanitized$sanitizedTimeslot"
// Sample data with default values (initially set to default)
val reservationData = hashMapOf(
"DateReservation" to dateReservation,
"MatchId" to matchId,
"Timeslot" to timeslot,
"Participators" to hashMapOf(
"UserName_1" to usernameOfUserOne,
"UserAvatar_1" to avatarOfUserOne,
"UserId_1" to currentUserId,
"UserName_2" to "Default",
"UserAvatar_2" to "Default",
"UserId_2" to "Default",
"UserName_3" to "Default",
"UserAvatar_3" to "Default",
"UserId_3" to "Default",
"UserName_4" to "Default",
"UserAvatar_4" to "Default",
"UserId_4" to "Default"
)
)
Log.d("ReservationActivity", "Data: $dateReservationSanitized, $matchId, $timeslot")
Log.d(
"ReservationActivity",
"Data: $sanitizedClubName, $sanitizedClubEstablishment, $sanitizedCourtName"
)
// Update Firestore with the reservation data
if (sanitizedClubName != null && sanitizedClubEstablishment != null && sanitizedCourtName != null) {
val courtDocument = firestore.collection("TheClubDetails")
.document(sanitizedClubName)
.collection("TheClubEstablishments")
.document(sanitizedClubEstablishment)
.collection("TheClubCourts")
.document(sanitizedCourtName)
// Check if the "CourtReservations" field exists
courtDocument.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val documentSnapshot = task.result
val existingReservations =
documentSnapshot?.get("CourtReservations") as? HashMap<String, Any>
?: hashMapOf()
// Create or update the "DateReservation" entry with a list of reservations
val dateReservationData =
existingReservations[dateReservation] as? ArrayList<HashMap<String, Any>>
?: arrayListOf()
val reservationDataJava = reservationData as HashMap<String, Any>
dateReservationData.add(reservationDataJava)
existingReservations[dateReservation] = dateReservationData
// Update "CourtReservations" field
courtDocument.update("CourtReservations", existingReservations)
.addOnSuccessListener {
Log.d("ReservationActivity", "Yeey the update was successful")
completedUpdates++
checkAndUpdateCompletion(callback)
}
.addOnFailureListener { e ->
Log.e("ReservationActivity", "Update failed", e)
}
} else {
Log.e("ReservationActivity", "Document check failed", task.exception)
}
}
}
// Replace these variables with actual values
val playerReservation = PlayerReservation(
clubName = sentThroughClubName,
clubEstablishmentName = sentThroughEstablishment,
courtName = sentThroughCourtName,
matchId = matchId,
clubEstablishmentAddress = sentThroughEstablishmentAddress,
timeslot = timeslot,
dateReservation = dateReservation
)
val db = FirebaseFirestore.getInstance()
// Reference to the document in the sub-collection
val documentReference =
db.collection("ThePlayers/$currentUserId/ThePlayerReservationsCourts")
.document(matchId)
// Add data to Firestore
documentReference.set(playerReservation)
.addOnSuccessListener {
// Successfully added data
completedUpdates++
checkAndUpdateCompletion(callback)
// Handle success as needed
}
.addOnFailureListener { e ->
// Handle error
// e.g., Log.e("TAG", "Error adding document", e)
}
if (makeMatchCollections) {
val preferredTypeMatch = typeOfMatchSpinner.selectedItem.toString()
val gendersAllowed = gendersAllowedSpinner.selectedItem.toString()
// Replace these variables with actual values
val matchReservation = MatchReservation(
clubName = sentThroughClubName,
clubEstablishmentName = sentThroughEstablishment,
courtName = sentThroughCourtName,
matchId = matchId,
clubEstablishmentAddress = sentThroughEstablishmentAddress,
timeslot = timeslot,
dateReservation = dateReservation,
typeOfMatch = preferredTypeMatch,
gendersAllowed = gendersAllowed,
participators = hashMapOf(
"UserName_1" to usernameOfUserOne,
"UserAvatar_1" to avatarOfUserOne,
"UserId_1" to (currentUserId ?: ""),
"UserName_2" to "Default",
"UserAvatar_2" to "Default",
"UserId_2" to "Default",
"UserName_3" to "Default",
"UserAvatar_3" to "Default",
"UserId_3" to "Default",
"UserName_4" to "Default",
"UserAvatar_4" to "Default",
"UserId_4" to "Default"
)
)
val db = FirebaseFirestore.getInstance()
// Reference to the document in the sub-collection
val documentReference = db.collection("TheMatches")
.document(matchId)
// Add data to Firestore
documentReference.set(matchReservation)
.addOnSuccessListener {
// Successfully added data
completedUpdates++
checkAndUpdateCompletion(callback)
// Handle success as needed
}
.addOnFailureListener { e ->
// Handle error
// e.g., Log.e("TAG", "Error adding document", e)
}
}
}
}
private fun formatDate(year: Int, month: Int, day: Int): String {
val calendar = Calendar.getInstance()
calendar.set(year, month, day)
val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
return dateFormat.format(calendar.time)
}
// Function to clear the selection of all time squares in the grid
private fun clearSelection(parentLayout: LinearLayout) {
for (i in 0 until parentLayout.childCount) {
val rowLayout = parentLayout.getChildAt(i) as LinearLayout
for (j in 0 until rowLayout.childCount) {
val timeSquare = rowLayout.getChildAt(j) as TextView
timeSquare.isSelected = false
}
}
}
private fun calculateReservedEndTime(selectedTime: String): String {
val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
val calendar = Calendar.getInstance()
val startTime = sdf.parse(selectedTime)
if (startTime != null) {
calendar.time = startTime
}
calendar.add(Calendar.MINUTE, 90)
return sdf.format(calendar.time)
}
private fun showDatePickerDialog() {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_MONTH, 1)
val datePickerDialog = DatePickerDialog(
this,
{ _: DatePicker, year: Int, month: Int, dayOfMonth: Int ->
val selectedCalendar = Calendar.getInstance()
selectedCalendar.set(year, month, dayOfMonth)
selectedDate = selectedCalendar.time
yearReservation = year
monthReservation = month
dayReservation = dayOfMonth
updateDateTextView()
enableAllTimeSlots(timeGrid)
fetchReservedTimeSlots("$yearReservation-$monthReservation-$dayReservation")
},
yearReservation,
monthReservation,
dayReservation
)
// Set the minimum and maximum date
calendar.add(Calendar.DAY_OF_MONTH, 30) // 31 days in the future
datePickerDialog.datePicker.maxDate = calendar.timeInMillis
datePickerDialog.datePicker.minDate = System.currentTimeMillis()
datePickerDialog.show()
}
@SuppressLint("SetTextI18n")
private fun updateDateTextView() {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
val formattedDate = dateFormat.format(selectedDate)
dateTextView.text = "Date picked: $formattedDate"
}
private fun setupDefaultValues() {
val defaultCalendar = Calendar.getInstance()
defaultCalendar.add(Calendar.DAY_OF_MONTH, 1)
yearReservation = defaultCalendar.get(Calendar.YEAR)
monthReservation = defaultCalendar.get(Calendar.MONTH)
dayReservation = defaultCalendar.get(Calendar.DAY_OF_MONTH)
}
private fun fetchTimeSlots(
sanitizedClubName: String,
sanitizedClubEstablishment: String,
sanitizedCourtName: String,
dateToFetchLeTimeSlots: String,
onTimeSlotsFetched: (List<String>) -> Unit,
onError: (Exception) -> Unit
) {
val firestore = FirebaseFirestore.getInstance()
// Reference to the CourtReservations collection
val courtReservationsRef = firestore.collection("TheClubDetails")
.document(sanitizedClubName)
.collection("TheClubEstablishments")
.document(sanitizedClubEstablishment)
.collection("TheClubCourts")
.document(sanitizedCourtName)
// Fetch the CourtReservations document
courtReservationsRef.get()
.addOnSuccessListener { documentSnapshot ->
val timeSlots = mutableListOf<String>()
if (documentSnapshot.exists()) {
// Extract the CourtReservations map field
val courtReservations = documentSnapshot.get("CourtReservations") as? Map<*, *>
Log.d("ReservationActivity", "0) Fetch Successful $courtReservations")
// Check if DetailsReservation exists
val detailsReservations =
courtReservations?.get(dateToFetchLeTimeSlots) as? List<Map<*, *>>
Log.d("ReservationActivity", "0.1) Fetch Successful $detailsReservations")
// Iterate over the entries in the DetailsReservations list
detailsReservations?.forEach { details ->
// Extract Timeslot if it exists
val timeslot = details["Timeslot"] as? String
if (timeslot != null) {
Log.d("ReservationActivity", "1) Fetch Successful: $timeslot")
timeSlots.add(timeslot)
}
}
// Disable reserved time slots in the UI
Log.d("ReservationActivity", "2.0) Reaches here?")
disableReservedTimeSlots(timeGrid, timeSlots)
}
// Invoke the callback with the list of time slots
onTimeSlotsFetched(timeSlots)
}
.addOnFailureListener { e ->
// Invoke the error callback in case of failure
onError(e)
}
}
private fun fetchReservedTimeSlots(dateToFetchLeTimeSlots: String) {
val sanitizedClubName = intent.getStringExtra("SanitizedClubName")
val sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment")
val sanitizedCourtName = intent.getStringExtra("SanitizedCourtName")
if (sanitizedClubName != null) {
if (sanitizedClubEstablishment != null) {
if (sanitizedCourtName != null) {
fetchTimeSlots(sanitizedClubName,
sanitizedClubEstablishment,
sanitizedCourtName,
dateToFetchLeTimeSlots,
onTimeSlotsFetched = { reservedTimeSlots ->
Log.d("ReservationActivity", "3) reservedTimeSlots: $reservedTimeSlots")
updateReservedTimeSlotsUI(reservedTimeSlots)
},
onError = { e ->
Log.e("ReservationActivity", "Error fetching reserved time slots", e)
}
)
}
}
}
}
private fun updateReservedTimeSlotsUI(reservedTimeSlots: List<String>) {
Log.d("ReservationActivity", "4) UpdateUI called")
val timeGrid: LinearLayout = findViewById(R.id.timeGrid)
for (i in 0 until timeGrid.childCount) {
val rowLayout = timeGrid.getChildAt(i) as LinearLayout
for (j in 0 until rowLayout.childCount) {
val timeSquare = rowLayout.getChildAt(j) as TextView
val timeSlot = timeSquare.text.toString()
// Disable the time square if the time slot is reserved
timeSquare.isEnabled = !reservedTimeSlots.contains(timeSlot)
}
}
}
private fun disableReservedTimeSlots(
parentLayout: LinearLayout,
reservedTimeSlots: List<String>
) {
val updatedReservedTimeSlots = mutableListOf<String>()
Log.d("ReservationActivity", "before Show list:$reservedTimeSlots")
for (element in reservedTimeSlots) {
val startTime = element.split("-")[0].trim()
val endTime = element.split("-")[1].trim()
// Add the original time slot to the updated list
updatedReservedTimeSlots.add(startTime)
if (endTime.endsWith("30")) {
// If the ending timeslot ends with "30"
val hour = endTime.split(":")[0].toInt()
var firstTime: String
var secondTime: String
if (hour <= 10) {
firstTime = "0${hour - 1}:30"
secondTime = "0${hour}:00"
} else {
firstTime = "${hour - 1}:30"
secondTime = "${hour}:00"
}
// Add the new timeslots to the updatedReservedTimeSlots list
updatedReservedTimeSlots.add("$firstTime-$secondTime")
} else if (endTime.endsWith("00")) {
// If the ending timeslot ends with "00"
val hour = endTime.split(":")[0].toInt() - 1
var firstTime: String
var secondTime: String
if (hour <= 10) {
firstTime = "0$hour:00"
secondTime = "0$hour:30"
} else {
firstTime = "$hour:00"
secondTime = "$hour:30"
}
// Add the new timeslots to the updatedReservedTimeSlots list
updatedReservedTimeSlots.add("$firstTime-$secondTime")
}
}
Log.d("ReservationActivity", "Show list:$updatedReservedTimeSlots")
takenTimeSlots = updatedReservedTimeSlots
// Apply the disabled state to the UI
for (i in 0 until parentLayout.childCount) {
val rowLayout = parentLayout.getChildAt(i) as LinearLayout
for (j in 0 until rowLayout.childCount) {
val timeSquare = rowLayout.getChildAt(j) as TextView
val time = timeSquare.text.toString()
Log.d("ReservationActivity", "Which tags are applied? ${timeSquare.tag}")
if (updatedReservedTimeSlots.any { it.contains(time) }) {
timeSquare.isEnabled = false
timeSquare.setBackgroundResource(R.drawable.selector_disabled_time_square)
timeSquare.tag = "disabled"
}
}
}
}
private fun enableAllTimeSlots(parentLayout: LinearLayout) {
// Enable all time squares in the UI
val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 8)
calendar.set(Calendar.MINUTE, 0)
for (i in 0 until parentLayout.childCount) {
val rowLayout = parentLayout.getChildAt(i) as LinearLayout
for (j in 0 until rowLayout.childCount) {
val timeSquare = rowLayout.getChildAt(j) as TextView
val startTime = sdf.format(calendar.time)
timeSquare.isEnabled = true
timeSquare.setBackgroundResource(R.drawable.selector_time_square)
timeSquare.tag = startTime
timeSquare.isSelected = false // Clear selection
calendar.add(Calendar.MINUTE, 30)
}
}
reservedTimeText.text = "" // Set reservedTimeText to an empty string
startingTimePlay = ""
endingTimePlay = ""
}
private fun fetchUserNameandAvatarFireStore(callback: (String, String) -> Unit) {
val currentUser = FirebaseAuth.getInstance().currentUser
val currentUserId = currentUser?.uid
val db = FirebaseFirestore.getInstance()
val userReference = currentUserId?.let {
db.collection("ThePlayers")
.document(it)
}
// Fetch the username from the user's document
userReference?.get()?.addOnSuccessListener { userDocumentSnapshot ->
if (userDocumentSnapshot.exists()) {
// User document exists, extract the username
val username = userDocumentSnapshot.getString("username")
// Sanitize the username and use it in the sub-collection reference
val sanitizedUsername = sanitizeUsername(username)
// Reference to the user's profile details document
val profileDetailsReference = db.collection("ThePlayers")
.document(currentUserId)
.collection("TheProfileDetails")
.document(sanitizedUsername)
// Fetch data from Firestore
profileDetailsReference.get()
.addOnSuccessListener { profileDetailsSnapshot ->
if (profileDetailsSnapshot.exists()) {
// Document exists, extract Avatar and Username
avatarOfUserOne = profileDetailsSnapshot.getString("Avatar").toString()
usernameOfUserOne =
profileDetailsSnapshot.getString("Username").toString()
callback(usernameOfUserOne, avatarOfUserOne)
Log.d(
"ReservationActivity",
"avatar: $usernameOfUserOne, $avatarOfUserOne"
)
} else {
// Document does not exist
Log.d("ReservationActivity", "Profile details not found for the user.")
}
}
.addOnFailureListener { e ->
// Handle errors
Log.d("ReservationActivity", "Error fetching profile details: $e")
}
} else {
// User document does not exist
Log.d("ReservationActivity", "User not found.")
}
}?.addOnFailureListener { e ->
// Handle errors
Log.d("ReservationActivity", "Error fetching user data: $e")
}
}
// Helper function to sanitize the username
private fun sanitizeUsername(username: String?): String {
// Remove symbols "/" "\", and " "
return username?.replace("[/\\\\ ]".toRegex(), "") ?: ""
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
// Add this function to find the index of an item in the spinner's adapter
private fun getIndex(spinner: Spinner, value: String): Int {
val adapter = spinner.adapter
for (i in 0 until adapter.count) {
if (adapter.getItem(i).toString() == value) {
return i
}
}
return 0 // Default to the first item if not found
}
private fun fetchGenderFirestore(callback: (String) -> Unit) {
// Get the current user's ID from Firebase Authentication
val currentUser = FirebaseAuth.getInstance().currentUser
val currentUserId = currentUser?.uid
val db = FirebaseFirestore.getInstance()
// Reference to the document in the sub-collection
val documentReference =
currentUserId?.let {
db.collection("ThePlayers")
.document(it)
}
// Add data to Firestore
documentReference?.get()?.addOnSuccessListener { documentSnapshot ->
// Successfully fetched data
if (documentSnapshot.exists()) {
// Check if the document exists
genderOfPlayer = documentSnapshot.getString("gender").toString()
// Now 'gender' contains the value of the 'gender' field
// Handle the gender data as needed
callback(genderOfPlayer)
} else {
// Document does not exist
// Handle accordingly
callback("Unknown")
}
}?.addOnFailureListener { e ->
// Handle error
// e.g., Log.e("TAG", "Error getting document", e)
callback("Unknown")
}
}
// Function to check and update the completion status
private fun checkAndUpdateCompletion(callback: () -> Unit) {
Log.d(
"ReservationActivity",
"CompletedUpdates: $completedUpdates | CompletedUpdates: $expectedUpdates"
)
if (completedUpdates == expectedUpdates) {
callback()
}
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/ReservationActivity.kt | 1492543678 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mobile_dev_endproject_jc_jvl.R
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class JoinMatchActivity : AppCompatActivity() {
private lateinit var dateReservationTextView: TextView
private lateinit var timeslotTextView: TextView
private lateinit var positionSquareTextView: TextView
private lateinit var typeOfMatchTextview: TextView
private lateinit var gendersAllowedTextview: TextView
private lateinit var joinMatchButton: Button
private var completedUpdates: Int = 0
private var expectedUpdates: Int = 0
private lateinit var matchId: String
private lateinit var positionSquare: String
private val userId: String
get() = FirebaseAuth.getInstance().currentUser?.uid ?: ""
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.joinmatch_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
dateReservationTextView = findViewById(R.id.dateReservationTextView)
timeslotTextView = findViewById(R.id.timeslotTextView)
positionSquareTextView = findViewById(R.id.positionSquareTextView)
typeOfMatchTextview = findViewById(R.id.typeOfMatchTextview)
gendersAllowedTextview = findViewById(R.id.gendersAllowedTextview)
joinMatchButton = findViewById(R.id.joinMatchButton)
val intent = intent
matchId = intent.getStringExtra("matchId") ?: ""
positionSquare = intent.getStringExtra("PositionSquare") ?: ""
Log.d("JoinMatchActivity", "Data $positionSquare")
// Set values from intent
dateReservationTextView.text = "Date Match: ${intent.getStringExtra("dateReservation")}"
timeslotTextView.text = "Time Match: ${intent.getStringExtra("timeslot")}"
positionSquareTextView.text = "Place you join: $positionSquare"
typeOfMatchTextview.text = "Type of match: ${intent.getStringExtra("typeOfMatch")}"
gendersAllowedTextview.text =
"Genders allowed in match: ${intent.getStringExtra("gendersAllowed")}"
joinMatchButton.setOnClickListener {
joinMatch { launchActivity(MatchActivity::class.java) }
}
val returnButton: Button = findViewById(R.id.returnButton)
returnButton.setOnClickListener {
finish()
}
}
private fun joinMatch(callback: () -> Unit) {
// Counter to track the number of completed updates
completedUpdates = 0
// Variable to store the expected number of updates
expectedUpdates = 3
val auth = FirebaseAuth.getInstance()
val userId = auth.currentUser?.uid
if (userId != null) {
val db = FirebaseFirestore.getInstance()
val matchRef = db.collection("TheMatches").document(matchId)
// Fetch current user details
val userRef = db.collection("ThePlayers").document(userId)
userRef.get().addOnSuccessListener { userSnapshot ->
if (userSnapshot.exists()) {
val username = userSnapshot.getString("username") ?: ""
val sanitizedUsername = sanitizeUsername(username)
Log.d(
"JoinMatchActivity",
"1) username $username, sanitizedUsername, $sanitizedUsername"
)
// Fetch user profile details
val profileRef =
userRef.collection("TheProfileDetails").document(sanitizedUsername)
profileRef.get().addOnSuccessListener { profileSnapshot ->
if (profileSnapshot.exists()) {
val avatar = profileSnapshot.getString("Avatar") ?: ""
Log.d("JoinMatchActivity", " 2) avatar $avatar")
// Update ThePlayerReservationsCourts subcollection
val reservationsRef =
userRef.collection("ThePlayerReservationsCourts").document(matchId)
val reservationsData = hashMapOf(
"matchId" to matchId
)
matchRef.get().addOnSuccessListener { documentSnapshot ->
Log.d(
"JoinMatchActivity",
" 2.1) document ${documentSnapshot.data}"
)
if (documentSnapshot.exists()) {
val participators =
documentSnapshot["participators"] as Map<*, *>?
Log.d("JoinMatchActivity", " 3) participators $participators")
// Check if the user is already in the match
if (participators == null || participators.values.none { it == userId }) {
Log.d("JoinMatchActivity", " 4) Triggers?")
// Update the participator map with the user's information
val updatedParticipators =
participators?.toMutableMap() ?: mutableMapOf()
val userKey =
"UserName_$positionSquare"
val avatarKey =
"UserAvatar_$positionSquare"
val userIdKey =
"UserId_$positionSquare"
updatedParticipators[userKey] = username
updatedParticipators[avatarKey] = avatar
updatedParticipators[userIdKey] = userId
// Check and update only if the fields have the value "Default"
var hasDefaultValues = false
for ((key, value) in updatedParticipators) {
if (value == "Default") {
hasDefaultValues = true
// Set the actual values from the user's details
updatedParticipators[userKey] = username
updatedParticipators[avatarKey] = avatar
updatedParticipators[userIdKey] = userId
}
}
// Update the document with the new participators if there are "Default" values
if (hasDefaultValues) {
matchRef.update("participators", updatedParticipators)
Toast.makeText(
this,
"Joined the match!",
Toast.LENGTH_SHORT
).show()
completedUpdates++
checkAndUpdateCompletion(callback)
reservationsRef.set(reservationsData)
.addOnSuccessListener {
Log.d("JoinMatchActivity", "Added matchId to ThePlayerReservationsCourts")
completedUpdates++
checkAndUpdateCompletion(callback)
}
.addOnFailureListener { e ->
// Handle failure
}
} else {
Toast.makeText(
this,
"Another player already joined!",
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(
this,
"You are already in this match",
Toast.LENGTH_SHORT
).show()
}
}
}
val sentThroughClubName =
intent.getStringExtra("sentThroughClubName") ?: ""
val sentThroughClubEstablishmentName =
intent.getStringExtra("sentThroughClubEstablishmentName") ?: ""
val sentThroughCourtName =
intent.getStringExtra("sentThroughCourtName") ?: ""
val dateReservation = intent.getStringExtra("dateReservation")
val matchId = intent.getStringExtra("matchId")
positionSquare = intent.getStringExtra("PositionSquare") ?: ""
val db = FirebaseFirestore.getInstance()
// Reference to the document in the sub-collection
val documentReference =
db.collection("TheClubDetails/$sentThroughClubName/TheClubEstablishments/$sentThroughClubEstablishmentName/TheClubCourts")
.document(sentThroughCourtName)
documentReference.get()
.addOnSuccessListener { documentSnapshot ->
if (documentSnapshot.exists()) {
// Get CourtReservations map
val courtReservations =
documentSnapshot.get("CourtReservations") as? Map<*, *>
if (courtReservations != null) {
// Get the specific array object based on dateReservation
val reservationsArray =
courtReservations[dateReservation] as? List<*>
if (reservationsArray != null) {
// Find the object with matching matchId
val matchingReservation = reservationsArray.find {
(it as? Map<*, *>)?.get("MatchId") == matchId
}
if (matchingReservation != null) {
// Get the Participators map
val participators =
(matchingReservation as Map<*, *>)["Participators"] as? MutableMap<String, Any>
// Update values based on positionSquare
participators?.let {
it["UserName_$positionSquare"] = username
it["UserAvatar_$positionSquare"] = avatar
it["UserId_$positionSquare"] = userId
// Update the Participators map in Firestore
documentReference.update(
"CourtReservations.$dateReservation",
reservationsArray
)
.addOnSuccessListener {
completedUpdates++
checkAndUpdateCompletion(callback)
}
.addOnFailureListener { e ->
// Handle failure
}
}
}
}
}
}
}
.addOnFailureListener { e ->
// Handle failure
}
}
}
}
}
}
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
private fun sanitizeUsername(username: String): String {
// Implement your logic to sanitize the username (remove spaces or special characters)
// For example, you can replace spaces with underscores
return username.replace("\\s+".toRegex(), "")
}
// Function to check and update the completion status
private fun checkAndUpdateCompletion(callback: () -> Unit) {
Log.d(
"ReservationActivity",
"CompletedUpdates: $completedUpdates | CompletedUpdates: $expectedUpdates"
)
if (completedUpdates == expectedUpdates) {
callback()
}
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/JoinMatchActivity.kt | 2773841766 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mobile_dev_endproject_jc_jvl.R
import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.CourtAdapter
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.firestore.FirebaseFirestore
class CourtListActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: CourtAdapter
private lateinit var sanitizedClubName: String
private lateinit var sanitizedClubEstablishment: String
private lateinit var sentThroughClubName: String
private lateinit var sentThroughClubEstablishment: String
private lateinit var sentThroughEstablishmentAddress: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.courtslist_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
sentThroughEstablishmentAddress =
intent.getStringExtra("sentThroughEstablishmentAddress").toString()
// Retrieve sanitized club and establishment names from the intent
sanitizedClubName = intent.getStringExtra("SanitizedClubName") ?: ""
sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment") ?: ""
sentThroughClubName = intent.getStringExtra("sentThroughClubName") ?: ""
sentThroughClubEstablishment = intent.getStringExtra("sentThroughClubEstablishment") ?: ""
Log.d(
"CourtListActivity",
"1) Sent along?: $sanitizedClubName, $sanitizedClubEstablishment"
)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter = CourtAdapter { sentThroughCourtName ->
// Handle item click, and navigate to AccountActivity
navigateToAccountActivity(sentThroughCourtName)
}
recyclerView.adapter = adapter
// Fetch courts from Firebase Firestore
fetchCourts()
}
private fun fetchCourts() {
val db = FirebaseFirestore.getInstance()
// Reference to the club's courts collection
val courtsRef = db.collection("TheClubDetails")
.document(sanitizedClubName)
.collection("TheClubEstablishments")
.document(sanitizedClubEstablishment)
.collection("TheClubCourts")
Log.d(
"CourtListActivity",
"1.2) Sent along?: $sanitizedClubName, $sanitizedClubEstablishment"
)
courtsRef.get()
.addOnSuccessListener { documents ->
Log.d("CourtListActivity", "2) Reaches here?: ${documents.documents}")
// Clear existing data
adapter.clearData()
for (document in documents) {
val courtName = document.getString("CourtName") ?: ""
Log.d("CourtListActivity", "3) Fetch?: $courtName")
adapter.addData(courtName)
}
}
.addOnFailureListener { exception ->
Toast.makeText(this, "Error fetching courts: $exception", Toast.LENGTH_SHORT).show()
}
}
private fun navigateToAccountActivity(sentThroughCourtName: String) {
// Create an explicit intent to navigate to AccountActivity
val sanitizedCourtName = sentThroughCourtName.replace("[\\s,\\\\/]".toRegex(), "")
Log.d(
"CourtListActivity",
"The right stuff sent? $sentThroughCourtName, $sanitizedCourtName"
)
val intent = Intent(this, ReservationActivity::class.java).apply {
putExtra("SanitizedClubName", sanitizedClubName)
putExtra("SanitizedClubEstablishment", sanitizedClubEstablishment)
putExtra("SanitizedCourtName", sanitizedCourtName)
putExtra("sentThroughClubName", sentThroughClubName)
putExtra("sentThroughClubEstablishment", sentThroughClubEstablishment)
putExtra("sentThroughCourtName", sentThroughCourtName)
putExtra("sentThroughEstablishmentAddress", sentThroughEstablishmentAddress)
}
startActivity(intent)
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/CourtListActivity.kt | 1013657700 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mobile_dev_endproject_jc_jvl.R
import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.MatchAdapter
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Match
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.tabs.TabLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class MatchActivity : AppCompatActivity() {
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.match_screen)
// Fetch current user's gender from Firestore
val currentUserUid = FirebaseAuth.getInstance().currentUser?.uid
if (currentUserUid != null) {
fetchUserGender(currentUserUid)
}
val tabLayout: TabLayout = findViewById(R.id.tabLayout_Establishments)
// Add tabs with titles
val allMatchesTab = tabLayout.newTab().setText("All Matches")
val yourMatchesTab = tabLayout.newTab().setText("Your Matches")
tabLayout.addTab(allMatchesTab)
tabLayout.addTab(yourMatchesTab)
// Set up a tab selected listener
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> {
// Start EstablishmentsActivity
//launchActivity(ClubEstablishmentsActivity::class.java)
}
1 -> {
// Start YourCourtReservationsActivity
launchActivity(YourMatchesActivity::class.java)
}
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {
// Handle tab unselection if needed
}
override fun onTabReselected(tab: TabLayout.Tab) {
// Handle tab reselection if needed
}
})
// Select the tab you want (e.g., "Your Courts Reservations")
allMatchesTab.select()
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
//fetchDataFromFirestore()
}
private fun displayMatches(matches: List<Match>) {
val adapter = MatchAdapter(matches)
recyclerView.adapter = adapter
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
private fun fetchUserGender(userId: String) {
firestore.collection("ThePlayers")
.document(userId)
.get()
.addOnSuccessListener { documentSnapshot ->
val userGender = documentSnapshot.getString("gender")
if (userGender != null) {
// Now that you have the user's gender, fetch and display matches
fetchDataFromFirestore(userGender)
} else {
Log.e("MatchActivity", "User gender not found")
}
}
.addOnFailureListener { exception ->
Log.e("MatchActivity", "Error fetching user gender: $exception")
}
}
private fun fetchDataFromFirestore(userGender: String) {
firestore.collection("TheMatches")
.get()
.addOnSuccessListener { querySnapshot ->
val matches = mutableListOf<Match>()
for (document in querySnapshot.documents) {
val match = document.toObject(Match::class.java)
Log.d("MatchActivity", "$match")
match?.let {
// Check if the match should be displayed based on user's gender and gendersAllowed
if (shouldDisplayMatch(it, userGender)) {
matches.add(it)
}
}
}
displayMatches(matches)
}
.addOnFailureListener { exception ->
Log.e("Firestore", "Error fetching data: $exception")
}
}
private fun shouldDisplayMatch(match: Match, userGender: String): Boolean {
val gendersAllowed = match.gendersAllowed
// Check if the match should be displayed based on user's gender and gendersAllowed
return when (userGender) {
"Male" -> gendersAllowed != "Female"
"Female" -> gendersAllowed != "Male"
else -> true // Handle other cases or use a default value as needed
}
}
} | Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/MatchActivity.kt | 3996558639 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mobile_dev_endproject_jc_jvl.R
import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.CourtReservationAdapter
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.CourtReservation
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.tabs.TabLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class YourCourtReservationsActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var courtReservationAdapter: CourtReservationAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.yourreservationscourts_screen)
val tabLayout: TabLayout = findViewById(R.id.tabLayout_reservationCourt)
// Add tabs with titles
val establishmentsTab = tabLayout.newTab().setText("Establishments")
val reservationsTab = tabLayout.newTab().setText("Your Courts Reservations")
tabLayout.addTab(establishmentsTab)
tabLayout.addTab(reservationsTab)
// Set up a tab selected listener
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> {
// Start EstablishmentsActivity
launchActivity(EstablishmentsActivity::class.java)
}
1 -> {
// Start YourCourtReservationsActivity
//launchActivity(YourCourtReservationsActivity::class.java)
}
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {
// Handle tab unselection if needed
}
override fun onTabReselected(tab: TabLayout.Tab) {
// Handle tab reselection if needed
}
})
// Select the tab you want (e.g., "Your Courts Reservations")
reservationsTab.select()
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
val userId = FirebaseAuth.getInstance().currentUser?.uid
val query = FirebaseFirestore.getInstance()
.collection("ThePlayers")
.document(userId!!)
.collection("ThePlayerReservationsCourts")
query.get().addOnSuccessListener { documents ->
val courtReservations = mutableListOf<CourtReservation>()
for (document in documents) {
val isEmpty = document.getString("clubEstablishmentName") ?: ""
val courtReservation = CourtReservation(
document.getString("clubEstablishmentName") ?: "",
document.getString("clubEstablishmentAddress") ?: "",
document.getString("courtName") ?: "",
document.getString("dateReservation") ?: "",
document.getString("timeslot") ?: ""
)
if (isEmpty != "") {
courtReservations.add(courtReservation)
}
}
courtReservationAdapter = CourtReservationAdapter(courtReservations)
recyclerView.adapter = courtReservationAdapter
}.addOnFailureListener { exception ->
// Handle failure
}
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
} | Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/YourCourtReservationsActivity.kt | 4202251540 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage;
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.example.mobile_dev_endproject_jc_jvl.R
class AccountActivity : AppCompatActivity() {
private lateinit var profileImage: ImageView
private lateinit var usernameText: TextView
private lateinit var locationText: TextView
private lateinit var genderText: TextView
private lateinit var followersText: TextView
private lateinit var followingText: TextView
private lateinit var levelText: TextView
private lateinit var editProfileButton: Button
private lateinit var changePasswordButton: Button
private lateinit var preferencesTitle: TextView
private lateinit var typeMatchText: TextView
private lateinit var handPlayText: TextView
private lateinit var timeToPlayText: TextView
private lateinit var courtPositionText: TextView
private lateinit var genderToPlayAgainstText: TextView
private lateinit var logoutButton: Button
private lateinit var pickImageLauncher: ActivityResultLauncher<Intent>
private lateinit var userId: String
private val db = FirebaseFirestore.getInstance()
private val auth = FirebaseAuth.getInstance()
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.account_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
bottomNavigationView.menu.findItem(R.id.navigation_account).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
// Initialize views
profileImage = findViewById(R.id.profileImage)
usernameText = findViewById(R.id.usernameText)
locationText = findViewById(R.id.locationText)
genderText = findViewById(R.id.genderText)
followersText = findViewById(R.id.followersText)
followingText = findViewById(R.id.followingText)
levelText = findViewById(R.id.levelText)
editProfileButton = findViewById(R.id.editProfileButton)
changePasswordButton = findViewById(R.id.changePasswordButton)
preferencesTitle = findViewById(R.id.preferencesTitle)
typeMatchText = findViewById(R.id.typeMatchText)
handPlayText = findViewById(R.id.handPlayText)
timeToPlayText = findViewById(R.id.timeToPlayText)
courtPositionText = findViewById(R.id.courtPositionText)
genderToPlayAgainstText = findViewById(R.id.genderToPlayAgainstText)
logoutButton = findViewById(R.id.logoutButton)
var sentThroughUserId: String = ""
Log.d("AccountActivity", "Hello? $sentThroughUserId")
sentThroughUserId = intent.getStringExtra("sentThroughUserId") ?: ""
Log.d("AccountActivity", "Hello? $sentThroughUserId")
// Fetch data from Firestore
if (sentThroughUserId == "") {
userId = auth.currentUser?.uid.toString()
Log.d("AccountActivity", "Hello1? $userId")
} else {
userId = sentThroughUserId
Log.d("AccountActivity", "Hello2? $userId")
}
var sanitizedUsername: String? = null
if (userId != null) {
val userRef = db.collection("ThePlayers").document(userId)
userRef.get().addOnSuccessListener { document ->
if (document != null && document.exists()) {
// Retrieve the "TheProfileDetails" sub-collection
val profileDetailsRef = userRef.collection("TheProfileDetails")
profileDetailsRef.get().addOnSuccessListener { profileDetailsSnapshot ->
for (profileDetailsDocument in profileDetailsSnapshot.documents) {
// Now you have access to each document in the "TheProfileDetails" sub-collection
val profileDetailsData = profileDetailsDocument.data
if (profileDetailsData != null) {
// Extract fields
val levelInformation =
profileDetailsData["Level"]?.toString()?.toInt()
val followersInformation =
profileDetailsData["Followers"]?.toString()?.toInt()
val followingInformation =
profileDetailsData["Following"]?.toString()?.toInt()
val avatarUrl = profileDetailsData["Avatar"] as? String
val username = profileDetailsData["Username"] as? String
val gender = profileDetailsData["Gender"] as? String
// Sanitize username
sanitizedUsername = username?.replace("[\\s,\\\\/]".toRegex(), "")
// Check if any of the required fields is null before updating UI
if (avatarUrl != null && username != null && levelInformation != null && followersInformation != null && followingInformation != null) {
// Update UI with fetched data
Glide.with(this).load(avatarUrl).into(profileImage)
usernameText.text = username
followersText.text = "Followers: $followersInformation"
followingText.text = "Following: $followingInformation"
levelText.text = "Level: $levelInformation"
genderText.text = "$gender"
// Fetch "ThePreferencesPlayer" sub-collection
val preferencesRef = userRef.collection("ThePreferencesPlayer")
preferencesRef.get()
.addOnSuccessListener { preferencesSnapshot ->
for (preferencesDocument in preferencesSnapshot.documents) {
// Now you have access to each document in the "ThePreferencesPlayer" sub-collection
val preferencesData = preferencesDocument.data
// Extract fields from the "ThePreferencesPlayer" document
val typeMatch =
preferencesData?.get("preferredTypeMatch") as? String
val handPlay =
preferencesData?.get("preferredHandPlay") as? String
val timeToPlay =
preferencesData?.get("preferredTimeToPlay") as? String
val courtPosition =
preferencesData?.get("preferredCourtPosition") as? String
val genderToPlayAgainst =
preferencesData?.get("preferredGenderToPlayAgainst") as? String
val playLocation =
preferencesData?.get("preferredPlayLocation") as? String
// Check if any of the required preference fields is null before updating UI
if (typeMatch != null && handPlay != null && timeToPlay != null
&& courtPosition != null && genderToPlayAgainst != null && playLocation != null
) {
// Update UI with fetched preferences
locationText.text = playLocation
typeMatchText.text = "Type Match: $typeMatch"
handPlayText.text = "Preferred Hand: $handPlay"
timeToPlayText.text =
"Preferred Time: $timeToPlay"
courtPositionText.text =
"Preferred Court Position: $courtPosition"
genderToPlayAgainstText.text =
"Preferred Gender to play against: $genderToPlayAgainst"
} else {
// Handle the case where some preference fields are null
// Show an error message or take appropriate action
}
}
}
} else {
// Handle the case where some fields in "Nickname" document are null
// Show an error message or take appropriate action
}
} else {
// Handle the case where "Nickname" document is null
// Show an error message or take appropriate action
}
}
}
// additional code
}
}
}
pickImageLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data: Intent? = result.data
if (data != null && data.data != null) {
val imageUri: Uri = data.data!!
sanitizedUsername?.let { uploadImageToFirebaseStorage(imageUri, it) }
}
}
}
profileImage.setOnClickListener {
// Open the image picker or camera to choose a new avatar
// You can use an external library like Intent.ACTION_PICK or Intent.ACTION_GET_CONTENT
// or implement your own image picker logic
openImagePicker()
}
// Set up the rest of your UI and handle button clicks as needed
editProfileButton = findViewById(R.id.editProfileButton);
editProfileButton.setOnClickListener {
startActivity(Intent(this, EditProfileActivity::class.java))
}
changePasswordButton.setOnClickListener {
startActivity(Intent(this, ChangePasswordActivity::class.java))
}
logoutButton.setOnClickListener {
auth.signOut()
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
private fun openImagePicker() {
val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
pickImageLauncher.launch(galleryIntent)
}
private fun uploadImageToFirebaseStorage(imageUri: Uri, sanitizedUsername: String) {
// Implement logic to upload the image to Firebase Storage
// You can use the Firebase Storage API to upload the image
// Example:
val storageRef = FirebaseStorage.getInstance().reference
val imageRef = storageRef.child("avatars/${auth.currentUser?.uid}.jpg")
// Upload file to Firebase Storage
imageRef.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
// Image uploaded successfully
// Get the download URL and update the user's profile
imageRef.downloadUrl.addOnSuccessListener { uri ->
// Update the user's avatar URL in Firestore
updateAvatarUrl(uri.toString(), sanitizedUsername)
}
}
.addOnFailureListener { e ->
Log.e("AccountActivity", "Image upload failed: ${e.message}")
}
}
private fun updateAvatarUrl(avatarUrl: String, sanitizedUsername: String) {
// Update the "Avatar" field in Firestore
val userId = auth.currentUser?.uid
if (userId != null) {
val userRef = db.collection("ThePlayers").document(userId)
val profileDetailsRef =
userRef.collection("TheProfileDetails").document(sanitizedUsername)
// Update the "Avatar" field with the new URL
profileDetailsRef.update("Avatar", avatarUrl)
.addOnSuccessListener {
// Avatar URL updated successfully
// Update the UI with the new avatar
Glide.with(this).load(avatarUrl).into(profileImage)
}
.addOnFailureListener { e ->
Log.e("AccountActivity", "Failed to update avatar URL: ${e.message}")
}
}
}
companion object {
private const val PICK_IMAGE_REQUEST = 1
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/AccountActivity.kt | 4028384997 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mobile_dev_endproject_jc_jvl.R
import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.MatchAdapter
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Match
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.tabs.TabLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FieldPath
class YourMatchesActivity : AppCompatActivity() {
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.yourmatches_screen)
val tabLayout: TabLayout = findViewById(R.id.tabLayout_Establishments)
// Add tabs with titles
val allMatchesTab = tabLayout.newTab().setText("All Matches")
val yourMatchesTab = tabLayout.newTab().setText("Your Matches")
tabLayout.addTab(allMatchesTab)
tabLayout.addTab(yourMatchesTab)
// Set up a tab selected listener
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> {
// Start EstablishmentsActivity
launchActivity(MatchActivity::class.java)
}
1 -> {
// Start YourCourtReservationsActivity
//launchActivity(YourCourtReservationsActivity::class.java)
}
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {
// Handle tab unselection if needed
}
override fun onTabReselected(tab: TabLayout.Tab) {
// Handle tab reselection if needed
}
})
// Select the tab you want (e.g., "Your Courts Reservations")
yourMatchesTab.select()
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
fetchDataFromFirestore()
}
private fun fetchDataFromFirestore() {
val currentUser = FirebaseAuth.getInstance().currentUser
val userId = currentUser?.uid
userId?.let { uid ->
val playersCollection = firestore.collection("ThePlayers").document(uid)
val reservationsCollection = playersCollection.collection("ThePlayerReservationsCourts")
reservationsCollection.get()
.addOnSuccessListener { reservationSnapshot ->
Log.d("YourMatchesActivity", " 1) data ${reservationSnapshot.documents}")
val matchIds = mutableListOf<String>()
Log.d("YourMatchesActivity", " 2) data $matchIds")
for (reservationDocument in reservationSnapshot.documents) {
Log.d("YourMatchesActivity", " 3) data $reservationDocument")
val matchId = reservationDocument.getString("matchId")
matchId?.let {
if (it.isNotEmpty()) { // Check if MatchId is not empty
matchIds.add(it)
}
}
}
if (matchIds.isNotEmpty()) { // Check if matchIds list is not empty
val matchesCollection = firestore.collection("TheMatches")
val matchesQuery =
matchesCollection.whereIn(FieldPath.documentId(), matchIds)
matchesQuery.get()
.addOnSuccessListener { matchSnapshot ->
val matches = mutableListOf<Match>()
for (matchDocument in matchSnapshot.documents) {
val match = matchDocument.toObject(Match::class.java)
match?.let {
matches.add(it)
}
}
displayMatches(matches)
}
.addOnFailureListener { exception ->
Log.e("Firestore", "Error fetching matches: $exception")
}
} else {
Log.d("Firestore", "No valid MatchIds found")
// Handle the case where there are no valid MatchIds
}
}
.addOnFailureListener { exception ->
Log.e("Firestore", "Error fetching matchIds: $exception")
}
}
}
private fun displayMatches(matches: List<Match>) {
val adapter = MatchAdapter(matches)
recyclerView.adapter = adapter
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
} | Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/YourMatchesActivity.kt | 1335854163 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import android.os.Parcelable
import com.example.mobile_dev_endproject_jc_jvl.R
import com.google.android.material.bottomnavigation.BottomNavigationView
import org.osmdroid.util.GeoPoint
class EstablishmentDetailsActivity : AppCompatActivity() {
private lateinit var firestore: FirebaseFirestore
private var sanitizedClubName: String? = null
private var sanitizedEstablishmentName: String? = null
private lateinit var sentThroughClubName: String
private lateinit var sentThroughClubEstablishment: String
private lateinit var sentThroughEstablishmentAddress: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.establishmentdetails_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
sentThroughEstablishmentAddress =
intent.getStringExtra("ClubEstablishmentAddress").toString()
firestore = FirebaseFirestore.getInstance()
val intent = intent
sentThroughClubName = intent.getStringExtra("ClubName").toString()
if (sentThroughClubName != null) {
sanitizedClubName = sentThroughClubName.replace("[\\s,\\\\/]".toRegex(), "")
}
val courtAddress = intent.getStringExtra("ClubEstablishmentAddress")
sentThroughClubEstablishment = intent.getStringExtra("EstablishmentName").toString()
if (sentThroughClubEstablishment != null) {
sanitizedEstablishmentName =
sentThroughClubEstablishment.replace("[\\s,\\\\/]".toRegex(), "")
}
findViewById<TextView>(R.id.textViewCourtAddress).text = courtAddress
findViewById<TextView>(R.id.textViewClubEstablishmentName).text =
sentThroughClubEstablishment
fetchClubData(sentThroughClubName)
}
private fun fetchClubData(clubName: String?) {
if (clubName == null) {
// Handle the case where clubName is null
return
}
val clubDocumentRef = firestore.collection("TheClubDetails").document(clubName)
clubDocumentRef.get()
.addOnSuccessListener { documentSnapshot: DocumentSnapshot? ->
if (documentSnapshot != null && documentSnapshot.exists()) {
// DocumentSnapshot exists, extract data
val clubNameWithSpaces = documentSnapshot.getString("ClubName")
val clubDescription = documentSnapshot.getString("ClubDescription")
val imageURL = documentSnapshot.getString("ClubLogo")
// Set data to the corresponding TextViews
findViewById<TextView>(R.id.textViewClubName).text = clubNameWithSpaces
findViewById<TextView>(R.id.textViewClubDescription).text = clubDescription
loadClubLogo(imageURL)
} else {
// Handle the case where the document doesn't exist
}
}
.addOnFailureListener { exception: Exception ->
Log.e(
"EstablishmentDetailsActivity",
"Exception occurred: ${exception.message}",
exception
)
}
}
private fun loadClubLogo(imageURL: String?) {
if (imageURL != null) {
Log.d("EstablishmentDetailsActivity", "Image URL: $imageURL")
// Load club logo using an image loading library like Picasso or Glide
val imageViewClubLogo = findViewById<ImageView>(R.id.imageViewClubLogo)
Glide.with(this)
.load(imageURL)
.into(imageViewClubLogo)
}
}
fun onReserveClicked(view: View) {
val mapIntent = Intent(this, CourtListActivity::class.java)
mapIntent.putExtra("SanitizedClubName", sanitizedClubName)
mapIntent.putExtra("SanitizedClubEstablishment", sanitizedEstablishmentName)
mapIntent.putExtra("sentThroughClubName", sentThroughClubName)
mapIntent.putExtra("sentThroughClubEstablishment", sentThroughClubEstablishment)
mapIntent.putExtra("sentThroughEstablishmentAddress", sentThroughEstablishmentAddress)
startActivity(mapIntent)
}
// .xml relies on view!!!!
fun onReturnClicked(view: View) {
val receivedCoordinates =
intent.getParcelableExtra<Parcelable>("TheMapCoordinates") as? GeoPoint
if (receivedCoordinates != null) {
val mapIntent = Intent(this, MapActivity::class.java)
mapIntent.putExtra("TheMapCoordinates", receivedCoordinates as Parcelable)
startActivity(mapIntent)
} else {
val clubIntent = Intent(this, EstablishmentsActivity::class.java)
startActivity(clubIntent)
}
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/EstablishmentDetailsActivity.kt | 3634827596 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Preferences
import com.example.mobile_dev_endproject_jc_jvl.R
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class EditProfileActivity : AppCompatActivity() {
private lateinit var playLocationEditText: EditText
private lateinit var typeMatchSpinner: Spinner
private lateinit var handPlaySpinner: Spinner
private lateinit var timeToPlaySpinner: Spinner
private lateinit var courtPositionSpinner: Spinner
private lateinit var genderSpinner: Spinner
private lateinit var saveButton: Button
private lateinit var returnButton: Button
private lateinit var userId: String
private lateinit var firestore: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.edit_profile_screen)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
// Right Icon active
bottomNavigationView.menu.findItem(R.id.navigation_account).isChecked = true
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
launchActivity(HomeActivity::class.java)
true
}
R.id.navigation_establishment -> {
launchActivity(EstablishmentsActivity::class.java)
true
}
R.id.navigation_match -> {
launchActivity(MatchActivity::class.java)
true
}
R.id.navigation_account -> {
item.isChecked = true
launchActivity(AccountActivity::class.java)
true
}
else -> false
}
}
// Initialize UI components
playLocationEditText = findViewById(R.id.playLocationEditText)
typeMatchSpinner = findViewById(R.id.typeMatchSpinner)
handPlaySpinner = findViewById(R.id.handPlaySpinner)
timeToPlaySpinner = findViewById(R.id.timeToPlaySpinner)
courtPositionSpinner = findViewById(R.id.courtPositionSpinner)
genderSpinner = findViewById(R.id.genderSpinner)
saveButton = findViewById(R.id.saveButton)
returnButton = findViewById(R.id.returnButton)
// Initialize Firestore and current user ID
firestore = FirebaseFirestore.getInstance()
userId = FirebaseAuth.getInstance().currentUser?.uid ?: ""
// Populate UI with Firestore data
populateUIFromFirestore()
// Set onClickListener for buttons
returnButton.setOnClickListener {
startActivity(Intent(this, AccountActivity::class.java))
}
saveButton.setOnClickListener {
saveProfileDataToFirestore()
}
}
private fun populateUIFromFirestore() {
// Retrieve user preferences from Firestore and populate UI
firestore.collection("ThePlayers")
.document(userId)
.collection("ThePreferencesPlayer")
.document("UserId")
.get()
.addOnSuccessListener { documentSnapshot ->
val preferences = documentSnapshot.toObject(Preferences::class.java)
if (documentSnapshot.exists() && preferences != null) {
// Update fields with non-default values
val playLocation = preferences.preferredPlayLocation
if (playLocation != "Location Not Yet Stated") {
playLocationEditText.setText(preferences.preferredPlayLocation)
}
//playLocationEditText.setText(preferences.preferredPlayLocation)
typeMatchSpinner.setSelection(
getIndex(
typeMatchSpinner,
preferences.preferredTypeMatch
)
)
handPlaySpinner.setSelection(
getIndex(
handPlaySpinner,
preferences.preferredHandPlay
)
)
timeToPlaySpinner.setSelection(
getIndex(
timeToPlaySpinner,
preferences.preferredTimeToPlay
)
)
courtPositionSpinner.setSelection(
getIndex(
courtPositionSpinner,
preferences.preferredCourtPosition
)
)
genderSpinner.setSelection(
getIndex(
genderSpinner,
preferences.preferredGenderToPlayAgainst
)
)
} else {
// Error handling
}
}
}
private fun saveProfileDataToFirestore() {
// Get selected values from UI
val preferredPlayLocation = playLocationEditText.text.toString().trim()
val preferredTypeMatch = typeMatchSpinner.selectedItem.toString()
val preferredHandPlay = handPlaySpinner.selectedItem.toString()
val preferredTimeToPlay = timeToPlaySpinner.selectedItem.toString()
val preferredCourtPosition = courtPositionSpinner.selectedItem.toString()
val preferredGenderToPlayAgainst = genderSpinner.selectedItem.toString()
// Check if playLocationEditText is empty
if (preferredPlayLocation.isEmpty()) {
playLocationEditText.error = "Please fill in the location"
return
}
// Update Firestore with new values
val preferences = Preferences(
preferredPlayLocation,
preferredTypeMatch,
preferredHandPlay,
preferredTimeToPlay,
preferredCourtPosition,
preferredGenderToPlayAgainst
)
firestore.collection("ThePlayers")
.document(userId)
.collection("ThePreferencesPlayer")
.document("UserId")
.set(preferences)
.addOnSuccessListener {
// Data saved successfully
// You can add any additional logic here
setResult(RESULT_OK)
startActivity(Intent(this, AccountActivity::class.java))
}
.addOnFailureListener {
Toast.makeText(this, "Failed to save data", Toast.LENGTH_SHORT).show()
}
}
private fun getIndex(spinner: Spinner, value: String): Int {
for (i in 0 until spinner.count) {
if (spinner.getItemAtPosition(i).toString() == value) {
return i
}
}
return 0 // Default to the first item if not found
}
private fun launchActivity(cls: Class<*>) {
val intent = Intent(this, cls)
startActivity(intent)
}
}
| Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/EditProfileActivity.kt | 3824033184 |
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.mobile_dev_endproject_jc_jvl.R
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : AppCompatActivity() {
private lateinit var emailEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var forgotPasswordTextView: TextView
private lateinit var loginButton: Button
private lateinit var registerButton: Button
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_screen)
auth = FirebaseAuth.getInstance()
emailEditText = findViewById(R.id.emailEditText)
passwordEditText = findViewById(R.id.passwordEditText)
forgotPasswordTextView = findViewById(R.id.forgotPasswordTextView)
loginButton = findViewById(R.id.loginButton)
registerButton = findViewById(R.id.registerButton)
loginButton.setOnClickListener {
val email = emailEditText.text.toString().trim()
val password = passwordEditText.text.toString().trim()
if (email.isNotEmpty() && password.isNotEmpty()) {
loginUser(email, password)
} else {
// empty fields
if (email.isEmpty()) {
emailEditText.setBackgroundResource(R.drawable.edit_text_error_border)
} else {
emailEditText.setBackgroundResource(R.drawable.edit_text_default_border)
}
if (password.isEmpty()) {
passwordEditText.setBackgroundResource(R.drawable.edit_text_error_border)
} else {
passwordEditText.setBackgroundResource(R.drawable.edit_text_default_border)
}
}
}
forgotPasswordTextView.setOnClickListener {
// Handle forgot password
}
registerButton.setOnClickListener {
startActivity(Intent(this, RegisterActivity::class.java))
}
}
private fun loginUser(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Login successful
startActivity(Intent(this, HomeActivity::class.java))
} else {
// If login fails, display a message to the user.
// You can customize the error message based on the task.exception
// For example, task.exception?.message
// Handle authentication errors
}
val errorMessage = task.exception?.message ?: "Login failed"
showSnackbar(errorMessage)
// Set red contour for email and password fields
emailEditText.setBackgroundResource(R.drawable.edit_text_error_border)
passwordEditText.setBackgroundResource(R.drawable.edit_text_error_border)
}
}
private fun showSnackbar(message: String) {
// Assuming your root view is a CoordinatorLayout, replace it with the appropriate view type if needed
val rootView = findViewById<View>(android.R.id.content)
Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show()
}
} | Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/LoginActivity.kt | 676657208 |
package com.wordle.client
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.wordle.client", appContext.packageName)
}
} | TranslateMe-App/client/app/src/androidTest/java/com/wordle/client/ExampleInstrumentedTest.kt | 2664295102 |
package com.wordle.client
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)
}
} | TranslateMe-App/client/app/src/test/java/com/wordle/client/ExampleUnitTest.kt | 842567638 |
package com.wordle.client
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.wordle.client.fragment.*
class MainActivity : AppCompatActivity() {
lateinit var demoButton: Button
var mContext:Context = this
// var g:SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(savedInstanceState == null) {
loadFragment(HomeFragment())
}
initView()
}
private lateinit var mBottomNavigationView: BottomNavigationView
private fun loadFragment(fragment: Fragment){
val transaction = supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out)
transaction.replace(R.id.container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun initView(){
mBottomNavigationView = findViewById(R.id.bottom_navigation_view)
mBottomNavigationView.setOnItemSelectedListener{
when (it.itemId){
R.id.home ->{
setTitle(R.string.home)
loadFragment(HomeFragment())
return@setOnItemSelectedListener true
}
R.id.favorite ->{
setTitle(R.string.favorite)
loadFragment(FavoriteFragment())
return@setOnItemSelectedListener true
}
R.id.currency ->{
setTitle(R.string.currency)
loadFragment(CurrencyFragment())
return@setOnItemSelectedListener true
}
}
false
}
}
}
| TranslateMe-App/client/app/src/main/java/com/wordle/client/MainActivity.kt | 753323058 |
package com.wordle.client.util
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
/**
* This LocalDBHelper will using sqlite to manage data created by the ap
*/
class LocalDBHelper(context: Context?):SQLiteOpenHelper(context, "translator", null,1) {
// first table store the supported translate languages
val table1 = "create table languages(id integer primary key,language text,name text, supports_formality text)"
// second table store user favorite translated language
val table2 = "create table favorites(id integer primary key, _from text, _to text, from_text text, to_text)"
// create those table when onCreate happen
override fun onCreate(p0: SQLiteDatabase?) {
p0?.execSQL(table1)
p0?.execSQL(table2)
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/util/LocalDBHelper.kt | 1654210871 |
package com.wordle.client.util
import com.wordle.client.interfaces.TranslateService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
// Free language translator api
const val DEEPL_TRANSLATE_BASE_URL = "https://api-free.deepl.com/"
// OKhttp logging setting
val loggingInterceptor = HttpLoggingInterceptor(HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY)
// OKhttp client register with logging
val okHttpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()
// Retrofit client with ok http
val retrofit = Retrofit.Builder().baseUrl(DEEPL_TRANSLATE_BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(
okHttpClient).build()
// Translate service created by retrofit client
val translateService = retrofit.create(TranslateService::class.java)
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/util/RetrofitClient.kt | 3525665958 |
//
//import android.app.AlertDialog
//import android.content.Context
//import android.os.Bundle
//import android.os.Handler
//import android.os.Looper
//import android.os.Message
//import com.wordle.client.util.ProgressDialog
//import okhttp3.*
//import java.io.IOException
//
///**
// * Asynchronous calls to server api helper classes
// * Created by Zhiqiang Liu
// */
//open class OkHttpUtil {
//
// // OKHttp instance
// val client = OkHttpClient()
//
// var mContext: Context? = null
//
// // Static Variable
// companion object {
// // The base server url
// const val BASE_URL = "http://10.0.2.2:5000/"
//
// // Bundle message
// const val MSG = "msg"
// const val TITLE = "title"
// const val DEFAULT_MSG = 0x0
// const val ALL_USER_MSG = 0x1
// const val LOGIN_MSG = 0x2
// const val SERVER_ERROR="Server Error"
// const val PROGRESS_DIALOG_SHOW = 0x11
// const val PROGRESS_DIALOG_CLOSE = 0x12
// const val ALERT_DIALOG_SHOW = 0x13
// }
//
// /**
// * This handler handle the dialog show and close
// *
// */
// var dialogHandler = object : Handler(Looper.getMainLooper()) {
//
// // Progress Dialog
// var progressDialog: ProgressDialog? =null
//
// fun openProgressDialog(){
// if(progressDialog == null) {
// progressDialog = ProgressDialog()
// }
// // non null call
// progressDialog!!.showProgress(mContext)
// }
//
// fun closeProgressDialog(){
// progressDialog?.closeProgress()
// }
//
// fun showMessage(title:String, msg:String){
// var dialog = AlertDialog.Builder(mContext)
// dialog.create()
// dialog.setMessage(msg)
// dialog.setTitle(title)
// dialog.show()
// }
//
// override fun handleMessage(msg: Message) {
// super.handleMessage(msg)
// when(msg?.what){
// PROGRESS_DIALOG_SHOW->{
// openProgressDialog()
// }
// PROGRESS_DIALOG_CLOSE->{
// closeProgressDialog()
// }
// ALERT_DIALOG_SHOW->{
// var title = msg.data.getString(TITLE)
// var message = msg.data.getString(MSG)
// if (title != null && message!=null) {
// showMessage(title, message)
// }
// }
// }
// }
// }
//
// /**
// * To receive the message
// * You must implement a handler in the activity, and pass it in.
// */
// open fun notifyActivity(mHandler: Handler, mBundle: Bundle?, what: Int){
// mHandler.sendMessage(createMessage(mBundle,what))
// }
//
// /**
// * Create a Message and return
// */
// open fun createMessage(mBundle: Bundle? , what: Int): Message {
// val mMessage = Message()
// mMessage.data = mBundle
// mMessage.what = what
// return mMessage
// }
//
// /**
// * Send a message to dialog handler
// */
// open fun sendMessage(mBundle: Bundle?, what:Int){
// dialogHandler?.sendMessage(createMessage(mBundle, what))
// }
//
// /**
// * Send message to show ProgressDialog
// */
// open fun sendProgressDialogShowMessage() {
// sendMessage(Bundle(), PROGRESS_DIALOG_SHOW)
// }
//
// /**
// * Send message to close ProgressDialog
// */
// open fun sendProgressDialogCloseMessage() {
// sendMessage(Bundle(), PROGRESS_DIALOG_CLOSE)
// }
//
// /**
// * Send message to show AlertDialog
// */
// open fun sendMessage(message: String, title: String) {
// val mBundle = Bundle()
// mBundle.putString(MSG, message)
// mBundle.putString(TITLE, title)
// sendMessage(mBundle, ALERT_DIALOG_SHOW)
// }
//
//
// /**
// * Get request
// * Asynchronous calls to server api
// * func, the api
// * handleMsg, the message type
// * handler, the handler that deal with the data returned by server.
// */
// open fun get(func: String, handleMsg: Int, handler: Handler, mContext:Context) {
// this.mContext = mContext
// sendProgressDialogShowMessage()
// val request = Request.Builder()
// .url(BASE_URL + func)
// .build()
// client.newCall(request).enqueue(object : Callback {
//
// override fun onFailure(call: Call, e: IOException) {
// sendProgressDialogCloseMessage()
// e.printStackTrace()
// }
//
// override fun onResponse(call: Call, response: Response) {
// response.use {
// sendProgressDialogCloseMessage()
//
// if (!response.isSuccessful) {
// sendMessage("Cannot connect to the local web server.",SERVER_ERROR)
// throw IOException()
// }
// var data = response.body!!.string()
//
// var bundle = Bundle()
// bundle.putString(MSG, data)
// notifyActivity(mHandler = handler, bundle, ALL_USER_MSG)
// }
// }
// })
// }
//
// /**
// * Post request
// * Asynchronous calls to server api
// * func, the api
// * handleMsg, the message type
// * handler, the handler that deal with the data returned by server.
// */
// open fun login(
// username: String,
// password: String,
// handler: Handler,
// mContext: Context
// ) {
// this.mContext = mContext
// val builder = FormBody.Builder()
// builder.add("username", username)
// builder.add("password", password)
// post("login", builder, handler, ALL_USER_MSG)
// }
//
// open fun post(
// func: String,
// params:FormBody.Builder,
// handler: Handler,
// what: Int
// ) {
//
// sendProgressDialogShowMessage()
// val formBody = params.build()
// val request = Request.Builder()
// .url(BASE_URL + func)
// .post(formBody)
// .build()
// client.newCall(request).enqueue(object : Callback {
//
// override fun onFailure(call: Call, e: IOException) {
// sendProgressDialogCloseMessage()
// e.printStackTrace()
// }
//
// override fun onResponse(call: Call, response: Response) {
// response.use {
// sendProgressDialogCloseMessage()
// if (response.code == 401) {
// sendMessage("Incorrect user or password input", "Login fail")
// }
// else if (!response.isSuccessful) {
// sendMessage("Cannot connect to the local web server.",SERVER_ERROR)
// throw IOException()
// }
// var data = response.body!!.string()
// val mBundle = Bundle()
// mBundle.putString(MSG, data)
// notifyActivity(handler, mBundle, what)
// }
// }
// })
// }
//} | TranslateMe-App/client/app/src/main/java/com/wordle/client/util/OkHttpUtil.kt | 4038095867 |
package com.wordle.client.util
import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
/**
* Using code to show the progress dialog when we need to let the user waiting
*/
open class ProgressDialog {
lateinit var dialog: AlertDialog
/**
* Close the dialog
*/
fun closeProgress(){
if(dialog!=null){
dialog.dismiss()
}
}
/**
* Show the dialog
*/
fun showProgress(mContext: Context?){
val llPadding = 30
val ll = LinearLayout(mContext)
ll.orientation = LinearLayout.HORIZONTAL
ll.setPadding(llPadding, llPadding, llPadding, llPadding)
ll.gravity = Gravity.CENTER
var llParam = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
llParam.gravity = Gravity.CENTER
ll.layoutParams = llParam
val progressBar = ProgressBar(mContext)
progressBar.isIndeterminate = true
progressBar.setPadding(0, 0, llPadding, 0)
progressBar.layoutParams = llParam
llParam = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
llParam.gravity = Gravity.CENTER
val tvText = TextView(mContext)
tvText.text = "Loading ..."
tvText.setTextColor(Color.parseColor("#000000"))
tvText.textSize = 20f
tvText.layoutParams = llParam
ll.addView(progressBar)
ll.addView(tvText)
val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
builder.setCancelable(false)
builder.setView(ll)
dialog = builder.create()
dialog.show()
val window: Window? = dialog.window
if (window != null) {
val layoutParams = WindowManager.LayoutParams()
layoutParams.copyFrom(window.getAttributes())
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
window.setAttributes(layoutParams)
}
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/util/ProgressDialog.kt | 3882120602 |
package com.wordle.client.util
import android.util.Log
import okhttp3.logging.HttpLoggingInterceptor
class HttpLogger: HttpLoggingInterceptor.Logger {
/**
* Log the request and response
*/
override fun log(message: String) {
Log.d("TranslateMe, Http Info:", message)
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/util/HttpLogger.kt | 947671958 |
package com.wordle.client.entity
/**
* The response body is :
*
* {
"data": {
"translations": [{"translatedText": "¡Hola Mundo!"}]
}
}
*/
class Favorites(from:String, to:String, from_text:String, to_Text:String) {
private lateinit var from: String
private lateinit var to: String
private lateinit var from_text: String
private lateinit var to_text: String
fun getFrom():String{
return from
}
fun getTo():String{
return to
}
fun getFromText():String{
return from_text
}
fun getToText():String{
return to_text
}
init{
this.from = from
this.to = to
this.from_text = from_text
this.to_text = to_Text
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Favorites.kt | 3071400127 |
package com.wordle.client.entity
/**
* The response body is :
*
* {
"data": {
"translations": [{"translatedText": "¡Hola Mundo!"}]
}
}
*/
class Translation {
private lateinit var translations: List<Translations>
fun getTranslations():List<Translations>{
return translations
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Translation.kt | 3722426191 |
package com.wordle.client.entity
import org.intellij.lang.annotations.Language
/**
* The response body is :
*
* {
"data": {
"translations": [{"translatedText": "¡Hola Mundo!"}]
}
}
*/
class Languages {
private lateinit var language: String
private lateinit var name: String
private var supports_formality: Boolean = false
fun getLanguage():String{
return language
}
fun getName():String{
return name
}
fun getSupportsFormality():Boolean{
return supports_formality
}
fun setLanguage(language: String){
this.language = language
}
fun setName(name: String){
this.name = name
}
fun setSupportsFormality(supports_formality: Boolean){
this.supports_formality = supports_formality
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Languages.kt | 678272777 |
package com.wordle.client.entity
class Currency(
// BASE CURRENCY = US DOLLARS
// var USD: Double,
// NEW ZEALAND DOLLARS
var NZD: Double,
// AUSTRALIA DOLLARS
var AUD: Double,
// BRITISH POUND
var GBP: Double,
// EUROPE EUROS
var EUR: Double,
// CANADA DOLLARS
var CAD: Double,
// MEXICO PESOS
var MXN: Double,
) | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Currency.kt | 767415519 |
package com.wordle.client.entity
class Request(
// ALL VARIABLE BELOW REFER TO DATA FROM JSON FILE: SEE README.md
// SUCCESS OR FAILURE
var result: String,
// LAST TIME DATA WAS UPDATED
var time_last_update_utc: String,
// NEXT TIME DATA WILL BE UPDATED
var time_next_update_utc: String,
// IMPLEMENT BASE CODE: USD = US DOLLARS
var base_code: String,
// CURRENT RATE OF CURRENCY
var rates: Currency
) | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Request.kt | 216357645 |
package com.wordle.client.entity
class Translations {
private lateinit var detected_source_language: String
private lateinit var text:String
fun getDetectedSourceLanguage():String{
return detected_source_language
}
fun getText():String{
return text
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Translations.kt | 764375623 |
package com.wordle.client
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.WindowManager
import android.widget.ProgressBar
import android.widget.TextView
@Suppress("DEPRECATION")
class LoadingActivity : AppCompatActivity() {
private var progressBar: ProgressBar? = null
private var i = 0
private var txtView: TextView? = null
private val handler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loading)
// finding progressbar by its id
progressBar = findViewById<ProgressBar>(R.id.progress_Bar) as ProgressBar
// finding textview by its id
txtView = findViewById<TextView>(R.id.text_view)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
// we used the postDelayed(Runnable, time) method
// to send a message with a delayed time.
//Normal Handler is deprecated , so we have to change the code little bit
// Handler().postDelayed({
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}, 1000) // 5000 is the delayed time in milliseconds.
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/LoadingActivity.kt | 3601957561 |
package com.wordle.client.fragment
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
// the text before translated
var translateText:String=""
// the text after translated
var translatedText:String=""
// from which language
var from:String=""
// to which language
var to:String="ES"
// is darkmode
var isDarkMode: Boolean=false
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/HomeViewModel.kt | 3483509916 |
package com.wordle.client.fragment
import androidx.lifecycle.ViewModel
class FavoriteViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/FavoriteViewModel.kt | 2779030655 |
package com.wordle.client.fragment
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wordle.client.R
class SettingsFragment : Fragment() {
companion object {
fun newInstance() = SettingsFragment()
}
private lateinit var viewModel: SettingsViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_settings, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(SettingsViewModel::class.java)
// TODO: Use the ViewModel
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/SettingsFragment.kt | 1384273578 |
package com.wordle.client.fragment
import androidx.lifecycle.ViewModel
class CurrencyViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/CurrencyViewModel.kt | 3344356406 |
package com.wordle.client.fragment
import androidx.lifecycle.ViewModel
class SettingsViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/SettingsViewModel.kt | 1553774175 |
package com.wordle.client.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import com.andrefrsousa.superbottomsheet.SuperBottomSheetFragment
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.wordle.client.R
import com.wordle.client.entity.Languages
open class BottomDialogSheetFragment(isFrom:Boolean, homeFragment: HomeFragment): SuperBottomSheetFragment() {
var isFrom:Boolean = false
var homeFragment: HomeFragment
init{
this.isFrom = isFrom
this.homeFragment = homeFragment
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
// the layout for the dialog
var root = layoutInflater.inflate(R.layout.dialog_show_from_bottom, null)
// the listview for the dialog
var listView: ListView = root.findViewById(R.id.listview)
var title: TextView = root.findViewById(R.id.title)
var detectButton: Button = root.findViewById(R.id.detect_language)
var searchView:androidx.appcompat.widget.SearchView = root.findViewById(R.id.searchview)
var languageList:MutableList<Languages> = homeFragment.loadLanguagesLocally()
// listview adapter
listView.adapter = HomeFragment.LanguagesAdapter(context, languageList)
// listview item click listener
listView.setOnItemClickListener(languagesItemClickListener)
if(isFrom){
listView.tag=homeFragment.TAG_FROM_LANGUAGE
title.setText(R.string.translate_from)
} else {
listView.tag=homeFragment.TAG_TO_LANGUAGE
title.setText(R.string.translate_to)
detectButton.visibility = View.INVISIBLE
}
detectButton.setOnClickListener {
// only supports from original text
homeFragment.binding.fromLanguage.setText(R.string.detect_language)
homeFragment.viewModel.from = ""
dismiss()
}
searchView.setOnQueryTextListener(object:
androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(p0: String?): Boolean {
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
val filterList = mutableListOf<Languages>()
languageList.forEach {
if(it.getName().contains(p0!!)){
filterList.add(it)
}
}
listView.adapter = HomeFragment.LanguagesAdapter(context, filterList)
return false
}
})
return root
}
/**
* The languages list item click listener
*/
var languagesItemClickListener: AdapterView.OnItemClickListener = AdapterView.OnItemClickListener{ adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
if(adapterView.tag!=null) {
// get which language the user click
var language: Languages = adapterView.getItemAtPosition(i) as Languages
if(adapterView.tag == homeFragment.TAG_FROM_LANGUAGE){
// update the text of the language
homeFragment.binding.fromLanguage.text = language.getName()
// set the abbreviation for the language, this will be send to the
homeFragment.viewModel.from = language.getLanguage()
} else if (adapterView.tag == homeFragment.TAG_TO_LANGUAGE){
// update the text of the language
homeFragment.binding.toLanguage.text = language.getName()
// set the abbreviation for the language, this will be send to the
homeFragment.viewModel.to = language.getLanguage()
}
dismiss()
}
}
override fun getPeekHeight(): Int {
super.getPeekHeight()
with(resources.displayMetrics) {
return heightPixels - 300
}
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/BottomDialogSheetFragment.kt | 847278712 |
package com.wordle.client.fragment
import android.content.Context
import android.content.res.Configuration
import android.database.sqlite.SQLiteDatabase
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wordle.client.R
import com.wordle.client.databinding.FragmentFavoriteBinding
import com.wordle.client.databinding.FragmentHomeBinding
import com.wordle.client.entity.Favorites
import com.wordle.client.entity.Languages
import com.wordle.client.util.LocalDBHelper
import java.lang.Exception
class FavoriteFragment : Fragment() {
companion object {
fun newInstance() = FavoriteFragment()
}
private val viewModel: FavoriteViewModel by activityViewModels()
// Using binding to init all layout elements
private lateinit var binding: FragmentFavoriteBinding
// Local db util helper
private var dbHelper: LocalDBHelper? =null
// Local db object
private var db:SQLiteDatabase? = null
private val TAG = FavoriteFragment::class.java.name
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Using binding to do the findViewbyId things
binding = FragmentFavoriteBinding.inflate(layoutInflater)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// TODO: Use the ViewModel
// Initialize the local db helper
dbHelper = LocalDBHelper(context)
var layoutManager:RecyclerView.LayoutManager?= null
// Dynamically choose layout based on the orientation of device
if(resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE){
layoutManager = GridLayoutManager(context,3)
layoutManager.orientation = LinearLayoutManager.VERTICAL
} else if(resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT){
layoutManager = LinearLayoutManager(context)
}
binding.listview.layoutManager = layoutManager
binding.listview.adapter = FavoritesRecyclearViewAdapter(context, loadFavoritesLocally())
}
/**
* Load languages from the local database
*/
fun loadFavoritesLocally():MutableList<Favorites>{
var favorites:MutableList<Favorites> = mutableListOf()
// find all the languages like "select * from languages" statement
var cursor = getDB()?.query("favorites",null,null,null,null,null,null)
if(cursor!!.moveToFirst()){
do{
var fav = Favorites(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4))
favorites.add(fav)
} while(cursor.moveToNext())
}
return favorites
}
inner class FavoritesRecyclearViewAdapter(val context: Context?, var data:MutableList<Favorites>):RecyclerView.Adapter<FavoritesRecyclearViewAdapter.ViewHolder>(){
inner class ViewHolder(view: View):RecyclerView.ViewHolder(view) {
val from:TextView = view.findViewById(R.id.from_language)
val to:TextView = view.findViewById(R.id.to_language)
val fromText:TextView = view.findViewById(R.id.from_text_language)
val toText:TextView = view.findViewById(R.id.to_text_language)
val deleteButton:Button = view.findViewById(R.id.deleteButton)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoritesRecyclearViewAdapter.ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.listview_item_favorite, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(vh: ViewHolder, position: Int) {
var favorite:Favorites = data.get(position)
vh.from.text = favorite.getFrom()
vh.to.text = favorite.getTo()
vh.fromText.text = favorite.getFromText()
vh.toText.text = favorite.getToText()
vh.deleteButton.setOnClickListener{
try {
if(removeFromDB(favorite)) {
Log.d(TAG, "Delete item succeesfully!")
data.remove(favorite)
binding.listview.adapter = FavoritesRecyclearViewAdapter(context, data)
} else{
Log.d(TAG, "Delete item failed!")
}
} catch (e:Exception){
Log.d(TAG, "Delete item failed!")
Toast.makeText(context, "Failed to remove item", Toast.LENGTH_SHORT).show()
}
}
}
}
/**
* Delete a favorite item from local database
*/
fun removeFromDB(favorites: Favorites):Boolean{
return getDB()?.delete("favorites", "from_text=? and to_text=?", arrayOf(favorites.getFromText(), favorites.getToText()))!! >0
}
/**
* Get the local database object
*/
fun getDB(): SQLiteDatabase?{
if (db==null){
try {
db = dbHelper?.writableDatabase
Log.d(TAG, "SQLite write mode")
} catch (e: Exception){
db = dbHelper?.readableDatabase
Log.d(TAG, "SQLite read mode")
}
}
return db
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/FavoriteFragment.kt | 418743 |
package com.wordle.client.fragment
import android.app.Activity
import android.content.*
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatDelegate
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.wordle.client.R
import com.wordle.client.databinding.FragmentHomeBinding
import com.wordle.client.entity.Favorites
import com.wordle.client.entity.Languages
import com.wordle.client.entity.Translation
import com.wordle.client.util.LocalDBHelper
import com.wordle.client.util.ProgressDialog
import com.wordle.client.util.RetrofitClient
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class HomeFragment : Fragment() {
companion object {
fun newInstance() = HomeFragment()
}
// Using binding to init all layout elements
lateinit var binding:FragmentHomeBinding
// Using videModel to store data
val viewModel: HomeViewModel by activityViewModels()
// Local db util helper
private var dbHelper:LocalDBHelper? =null
// Local db object
private var db:SQLiteDatabase? = null
// The tag for this Fragment
private val TAG = HomeFragment::class.java.name
// The tag of the textview
val TAG_FROM_LANGUAGE = 0x3
// The tag of the textview
val TAG_TO_LANGUAGE = 0x4
var initListener = TextToSpeech.OnInitListener {
if(it == TextToSpeech.SUCCESS){
Log.d(TAG, "TTS is speaking")
} else {
Log.d(TAG, "TTS can't work")
}
}
lateinit var tts:TextToSpeech
// val NIGHT_MODE = "night_mode"
//
// private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name=NIGHT_MODE)
//
// object PreferenceKeys{
// val NIGHT_MODE_KEY = stringPreferencesKey("mode_key")
// }
//
// private suspend fun Context.saveNightMode(mode:String){
// dataStore.edit {
// it[PreferenceKeys.NIGHT_MODE_KEY] = mode
// }
// }
//
// suspend fun Context.getNightMode() = dataStore.data.catch {exception->
// emit(emptyPreferences())
// }.map {
// val mode = it[PreferenceKeys.NIGHT_MODE_KEY]?:-1
//
// return@map mode
// }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.i(TAG, " onCreateView")
// Using binding to do the findViewbyId things
binding = FragmentHomeBinding.inflate(layoutInflater)
// Set the onclick event for the textview(from language)
binding.fromLanguage.setOnClickListener(buttonClickListener)
// Set the onclick event for the textview((to language)
binding.toLanguage.setOnClickListener(buttonClickListener)
// set the translate button click listener
binding.translateToButton.setOnClickListener(buttonClickListener)
binding.markButton.setOnClickListener(buttonClickListener)
binding.copyButton.setOnClickListener(buttonClickListener)
binding.swapImage.setOnClickListener(buttonClickListener)
binding.fromEdittext.setText(viewModel.translateText)
binding.play1Button.setOnClickListener(buttonClickListener)
binding.play2Button.setOnClickListener(buttonClickListener)
binding.darkmodeButton.setOnCheckedChangeListener{ buttonView, isChecked->
viewModel.isDarkMode = isChecked
if (isChecked) {
Log.e("Msg","Night mode button switch on")
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
else {
Log.e("Msg","Night mode button switch off")
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
binding.fromEdittext.addTextChangedListener (
object :TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
viewModel.translateText = p0.toString()
if(isBookmarkExisted()!=null){
binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24)
} else{
binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_border_24)
}
}
})
binding.translatedTextview.setText(viewModel.translatedText)
binding.darkmodeButton.isChecked = viewModel.isDarkMode
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Initialize the local db helper
dbHelper = LocalDBHelper(context)
// Load all the languages from local database
var languages = loadLanguagesLocally()
// if the data is empty in the local database, then fetch from restful api
if(languages == null || languages.size<1){
fetchLanguages()
}
if(isBookmarkExisted()!=null){
binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24)
}
tts = TextToSpeech(context,initListener)
}
/**
* Handle all button clicklistener in one function
*/
private var buttonClickListener:View.OnClickListener = View.OnClickListener {
if(it == binding.fromLanguage || it == binding.toLanguage){
chooseLanguage(it==binding.fromLanguage)
} else if (it == binding.translateToButton){
translate()
} else if (it == binding.markButton){
bookmark()
} else if (it == binding.copyButton) run {
if(binding.translatedTextview.text.toString().isEmpty()){
Toast.makeText(context, R.string.error_copy_translated_language, Toast.LENGTH_SHORT).show()
return@OnClickListener
}
var cm: ClipboardManager = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var clipData:ClipData = ClipData.newPlainText("Label", binding.toLanguage.text.toString())
cm.setPrimaryClip(clipData)
Toast.makeText(context,R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show()
} else if (it==binding.swapImage){
if(viewModel.from.equals("")){
Toast.makeText(context,R.string.error_from_language, Toast.LENGTH_SHORT).show()
return@OnClickListener
}
// exchange
val tempFrom = viewModel.from
val tempText = binding.fromLanguage.text
binding.fromLanguage.text = binding.toLanguage.text
binding.toLanguage.text = tempText
viewModel.from = viewModel.to
viewModel.to = tempFrom
} else if (it == binding.play2Button){
tts.speak(binding.translatedTextview.text.toString(), TextToSpeech.QUEUE_FLUSH, null, null)
} else if (it==binding.play1Button){
tts.speak(binding.fromEdittext.text.toString(), TextToSpeech.QUEUE_FLUSH, null, null)
}
}
/**
* Choose a language from a pop up dialog
*/
private fun chooseLanguage(isFrom:Boolean){
// The bottom sheet dialog will show
BottomDialogSheetFragment(isFrom, this).show(requireActivity().supportFragmentManager,"BottomDialogSheetFragment")
}
/**
* Check if the book mark is already existed
*/
private fun isBookmarkExisted(): Favorites? {
var cursor = getDB()?.query("favorites",null,"from_text=? and to_text=?", arrayOf(binding.fromEdittext.text.toString(), binding.translatedTextview.text.toString()),null,null,null)
if(cursor!!.moveToFirst()){
do{
var fav = Favorites(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4))
return fav
} while(cursor.moveToNext())
}
return null
}
/**
* Book mark
*/
private fun bookmark(){
// If the book mark is existed
val fav = isBookmarkExisted()
if(fav!=null){
if(getDB()?.delete("favorites", "from_text=? and to_text=?", arrayOf(fav.getFromText(), fav.getToText()))!! >0){
binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_border_24)
Log.d(TAG, "bookmark remove!")
} else{
Log.d(TAG, "bookmark remove failed!")
}
} else {
val content = ContentValues().apply {
// only save those supported language
put("_from", binding.fromLanguage.text.toString())
put("_to", binding.toLanguage.text.toString())
put("from_text", binding.fromEdittext.text.toString())
put("to_text", binding.translatedTextview.text.toString())
}
getDB()?.insert("favorites", null, content)
binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24)
}
}
private fun translate(){
val inputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view?.windowToken, 0)
// record the click event
Log.i(TAG, "Translate button are clicked.")
// get the text user input
val text = binding.fromEdittext.text.toString()
if (checkTranslateText(text)){
// translate service api
val api = RetrofitClient.translateService
// progress dialog
var dialog = ProgressDialog()
// show the progress
dialog.showProgress(context)
var from = ""
if(viewModel.from!=null){
from = viewModel.from
var fromList:List<String> = from.split("-")
if(fromList.size>1){
from = fromList.get(0)
}
}
// call restful api, post request.
api.translate(text,from, viewModel.to).enqueue(object : Callback<Translation> {
override fun onResponse(
call: Call<Translation>,
response: Response<Translation>
) {
println(response.body())
var translated: Translation? = response.body()
if (translated != null) {
Log.d(TAG, "Translated success, $text")
Log.d(
TAG,
"detected_source_language: ${translated.getTranslations()[0].getDetectedSourceLanguage()}"
)
Log.d(TAG, "text: ${translated.getTranslations()[0].getText()}")
binding.translatedTextview.setText(translated.getTranslations()[0].getText())
viewModel.translatedText = binding.translatedTextview.text.toString()
}
dialog.closeProgress()
}
override fun onFailure(call: Call<Translation>, t: Throwable) {
Log.e(TAG, "Translated failed, $text")
dialog.closeProgress()
}
})
}
}
private fun checkTranslateText(text:String):Boolean{
if (text.isEmpty()){
Toast.makeText(context, R.string.empty_string_checking, Toast.LENGTH_SHORT).show()
}
return !text.isEmpty()
}
/**
* Load languages from the local database
*/
fun loadLanguagesLocally():MutableList<Languages>{
var languages:MutableList<Languages> = mutableListOf()
// find all the languages like "select * from languages" statement
var cursor = getDB()?.query("languages",null,null,null,null,null,null)
if(cursor!!.moveToFirst()){
do{
var lan = Languages()
lan.setLanguage(cursor.getString(1))
lan.setName(cursor.getString(2))
lan.setSupportsFormality(cursor.getInt(3)>0)
// add the languages to a mutable list
languages?.add(lan)
} while(cursor.moveToNext())
}
return languages
}
/**
* Fetch all languages from the remote restful service.
*/
fun fetchLanguages(){
// custom progress dialog
var dialog = ProgressDialog()
// show the progress dialog to let the user wait
dialog.showProgress(context)
// translate service api
val api = RetrofitClient.translateService
// async run
api.languages().enqueue(object : Callback<List<Languages>> {
override fun onResponse(call: Call<List<Languages>>, response: Response<List<Languages>>) {
Log.d(TAG,response.body().toString())
if(response.isSuccessful){
var languages: List<Languages>? = response.body()
if (languages != null) {
for (language in languages){
val content = ContentValues().apply {
// only save those supported language
put("language", language.getLanguage())
put("name", language.getName())
put("supports_formality", language.getSupportsFormality())
}
if(content!=null)
getDB()?.insert("languages", null , content)
}
Log.d(TAG, "Fetched all languages")
}
} else{
Toast.makeText(context, R.string.fetch_data_fail, Toast.LENGTH_SHORT).show()
}
dialog.closeProgress()
}
override fun onFailure(call: Call<List<Languages>>, t: Throwable) {
Log.e(TAG,"Fetch languages failed!")
Toast.makeText(context, R.string.fetch_data_fail, Toast.LENGTH_SHORT).show()
dialog.closeProgress()
}
})
}
/**
* Get the local database object
*/
fun getDB():SQLiteDatabase?{
if (db==null){
try {
db = dbHelper?.writableDatabase
Log.d(TAG, "SQLite write mode")
} catch (e:Exception){
db = dbHelper?.readableDatabase
Log.d(TAG, "SQLite read mode")
}
}
return db
}
/**
* The languages adapter for the bottom sheet dialog
*/
open class LanguagesAdapter(val context: Context?, var data:MutableList<Languages>): BaseAdapter() {
override fun getCount(): Int {
return data.size
}
override fun getItem(p0: Int): Any {
return data.get(p0)
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
inner class ViewHolder(v: View) {
val name: TextView = v.findViewById(R.id.name)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var vh: ViewHolder? =null
val view: View
if (convertView == null) {
view = LayoutInflater.from(context).inflate(R.layout.listview_item_language, parent, false)
vh = ViewHolder(view)
view.tag = vh
} else{
view = convertView
vh = view.tag as ViewHolder
}
var languages:Languages = getItem(position) as Languages
if (languages!=null){
if (vh != null) {
vh.name.text = languages.getName()
}
}
return view
}
}
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/HomeFragment.kt | 3105312738 |
@file:Suppress("DEPRECATION")
package com.wordle.client.fragment
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
import com.wordle.client.databinding.FragmentCurrencyBinding
import com.wordle.client.entity.Request
import java.io.InputStreamReader
import java.net.URL
import javax.net.ssl.HttpsURLConnection
class CurrencyFragment : Fragment() {
// SET VARIABLE FOR VIDEO VIEW
// SET VARIABLE BINDING TO FRAGMENT CURRENCY BINDING
private lateinit var binding: FragmentCurrencyBinding
// SET VARIABLE VIEW MODEL TO FRAGMENT CURRENCY VIEW-MODEL
private lateinit var viewModel: CurrencyViewModel
// private var youTubePlayerView: YouTubePlayerView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentCurrencyBinding.inflate(layoutInflater)
fetchCurrencyData().start()
return binding.root
}
@Deprecated("Deprecated in Java")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this)[CurrencyViewModel::class.java]
}
override fun onStop() {
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
}
override fun onResume() {
super.onResume()
}
// FETCH DATA FROM API
@SuppressLint("SetTextI18n")
private fun fetchCurrencyData(): Thread
{
return Thread {
// PLACE API URL IN A VARIABLE
val url = URL("https://open.er-api.com/v6/latest/USD")
// USE VARIABLE CONNECTION AS HTTPS CONNECTION
val connection = url.openConnection() as HttpsURLConnection
// IF CONNECTION RESPONSE IS EQUAL TO 200 (OK)
if (connection.responseCode == 200) {
//
val inputSystem = connection.inputStream
// THEN LOG (LOGCAT) RESULTS
// println(inputSystem.toString())
val inputStreamReader = InputStreamReader(inputSystem, "UTF-8")
//
val request = Gson().fromJson(inputStreamReader, Request::class.java)
// UPDATE OUR FUNCTION UI REQUEST
updateUI(request)
inputStreamReader.close()
inputSystem.close()
}
else {
// ELSE LOG "FAILED TO CONNECT"
binding.baseCurrency.text = "Failed to Connect!"
}
}
}
private fun updateUI(request: Request) {
//
requireActivity().runOnUiThread {
kotlin.run {
binding.lastUpdated.text = String.format("Updated: " + request.time_last_update_utc)
binding.nextUpdated.text = String.format("Next Update: " + request.time_next_update_utc)
binding.nzd.text = String.format("NZD: %.2f", request.rates.NZD)
binding.aud.text = String.format("AUD: %.2f", request.rates.AUD)
binding.gbp.text = String.format("GBP: %.2f", request.rates.GBP)
binding.eur.text = String.format("EUR: %.2f", request.rates.EUR)
binding.cad.text = String.format("CAD: %.2f", request.rates.CAD)
binding.mxn.text = String.format("MXN: %.2f", request.rates.MXN)
}
}
}
}
| TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/CurrencyFragment.kt | 3181761521 |
package com.wordle.client.interfaces
import com.wordle.client.entity.Languages
import com.wordle.client.entity.Translation
import retrofit2.Call
import retrofit2.http.*
/**
* Deeply translate service
* translate: Post
* fetch supported languages: Get
*/
interface TranslateService {
@FormUrlEncoded
@Headers("Authorization: DeepL-Auth-Key 07db4d6f-087c-fd9e-4432-39527b7ba521:fx")
@POST("v2/translate")
fun translate(@Field("text") q:String, @Field("source_lang") source_lang:String, @Field("target_lang") target_lang:String): Call<Translation>
@Headers("Authorization: DeepL-Auth-Key 07db4d6f-087c-fd9e-4432-39527b7ba521:fx")
@GET("v2/languages?type=target")
fun languages(): Call<List<Languages>>
} | TranslateMe-App/client/app/src/main/java/com/wordle/client/interfaces/TranslateService.kt | 1469214367 |
package com.example.detectdepression
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.detectdepression", appContext.packageName)
}
} | Depression.Detection./app/src/androidTest/java/com/example/detectdepression/ExampleInstrumentedTest.kt | 112820263 |
package com.example.detectdepression
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)
}
} | Depression.Detection./app/src/test/java/com/example/detectdepression/ExampleUnitTest.kt | 1835145531 |
package com.example.detectdepression
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityDoctorLoginBinding
class DoctorLoginActivity : AppCompatActivity() {
private lateinit var binding : ActivityDoctorLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this@DoctorLoginActivity,R.layout.activity_doctor_login)
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/DoctorLoginActivity.kt | 1508493995 |
package com.example.detectdepression
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
| Depression.Detection./app/src/main/java/com/example/detectdepression/PersonalInfoFragment.kt | 3037044697 |
package com.example.detectdepression.operationFragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.detectdepression.R
import com.example.detectdepression.databinding.FragmentAddPatientBinding
class AddPatientFragment : Fragment() {
private lateinit var binding : FragmentAddPatientBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentAddPatientBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnGenerateID.setOnClickListener {
}
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/AddPatientFragment.kt | 1500517751 |
package com.example.detectdepression.operationFragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.detectdepression.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [SettingsFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class SettingsFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SettingsFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
SettingsFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/SettingsFragment.kt | 2224449234 |
package com.example.detectdepression.operationFragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.detectdepression.R
import com.example.detectdepression.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding : FragmentHomeBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentHomeBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/HomeFragment.kt | 1864221888 |
package com.example.detectdepression
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityMainBinding
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Objects
class MainActivity : AppCompatActivity() {
//binding
private lateinit var binding : ActivityMainBinding
//firestore
private lateinit var db : FirebaseFirestore
//collection name
private var PATIENT_DETAIL_COLLECTION = "PatientDetails"
//arraylist of questions
var questions = ArrayList<String>()
//details
lateinit var patientName : String
lateinit var patientAge : String
lateinit var patientPhoneNumber : String
lateinit var patientEmail : String
lateinit var date : String
private val PATIENT_ID = "PatientId"
private var DOC_NAME = "DoctorName"
lateinit var docName : String
lateinit var patientId : String
lateinit var patientGender : String
var score : String = "none"
var objectiveDepressionLevel = "none"
var subjectiveDepressionLevel = "none"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
db = FirebaseFirestore.getInstance()
docName = intent.getStringExtra(DOC_NAME)!!
patientId = intent.getStringExtra(PATIENT_ID)!!
binding.progressBar.visibility = View.INVISIBLE
}
// private fun loadData() {
// GlobalScope.launch(Dispatchers.IO) {
//
// }
// }
// private fun applyEditTextChnages() {
// binding.apply {
// edtName.addTextChangedListener(changeBackground(binding.edtName))
// edtAge.addTextChangedListener(changeBackground(binding.edtAge))
// edtPhoneNumber.addTextChangedListener(changeBackground(binding.edtPhoneNumber))
// edtEmail.addTextChangedListener(changeBackground(binding.edtEmail))
// }
// }
@RequiresApi(Build.VERSION_CODES.O)
fun btnNextClicked(view : View) {
binding.apply {
progressBar.visibility = View.VISIBLE
patientName = edtName.text.toString().trim()
patientAge = edtAge.text.toString().trim()
patientPhoneNumber = edtPhoneNumber.text.toString().trim()
patientEmail = edtEmail.text.toString().trim()
//deal with it
if (TextUtils.isEmpty(patientName)) {
edtName.setBackgroundColor(resources.getColor(R.color.purple_200))
} else {
edtName.background = null
}
if (TextUtils.isEmpty(patientAge)) {
edtAge.setBackgroundColor(resources.getColor(R.color.purple_200))
} else {
edtAge.background = null
}
if (TextUtils.isEmpty(patientPhoneNumber)) {
edtPhoneNumber.setBackgroundColor(resources.getColor(R.color.purple_200))
} else {
edtPhoneNumber.background = null
}
if (TextUtils.isEmpty(patientEmail)) {
edtEmail.setBackgroundColor(resources.getColor(R.color.purple_200))
} else {
edtEmail.background = null
}
if (radioGroupGender.checkedRadioButtonId != -1) {
patientGender = when(radioGroupGender.checkedRadioButtonId) {
R.id.rbMale -> "Male"
R.id.rbFemale -> "Female"
else -> "Other"
}
} else {
rbFemale.setBackgroundColor(resources.getColor(R.color.purple_200))
rbMale.setBackgroundColor(resources.getColor(R.color.purple_200))
rbOther.setBackgroundColor(resources.getColor(R.color.purple_200))
}
if (!(TextUtils.isEmpty(patientName) || TextUtils.isEmpty(patientAge) || TextUtils.isEmpty(patientPhoneNumber) || TextUtils.isEmpty(patientEmail))) {
var details = hashMapOf(
"Id" to patientId,
"Name" to patientName,
"Age" to patientAge,
"Gender" to patientGender,
"Phone Number" to patientPhoneNumber,
"Email" to patientEmail,
"Doc Name" to docName,
"Date" to FieldValue.serverTimestamp(),
"Score" to 0,
"Result" to "No"
)
db.collection(PATIENT_DETAIL_COLLECTION).document(patientId).set(details).addOnSuccessListener {
val intent = Intent(this@MainActivity,InfoActivty::class.java)
intent.putExtra(PATIENT_ID,patientId)
intent.putExtra(DOC_NAME,docName)
startActivity(intent)
finish()
}.addOnFailureListener {
Toast.makeText(this@MainActivity,"Ooops!! Something went wrong...",Toast.LENGTH_SHORT).show()
}
}
}
}
// fun changeBackground(editText : EditText) : TextWatcher{
//
// val textWatcher = object : TextWatcher {
// override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//
// }
//
// override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//
// }
//
// @SuppressLint("UseCompatLoadingForDrawables")
// override fun afterTextChanged(s: Editable?) {
// if (s.isNullOrBlank()) {
// editText.setBackgroundDrawable(getDrawable(R.drawable.empty_editext_background))
// } else {
// editText.background = null
// }
// }
//
// }
// return textWatcher
//
// }
} | Depression.Detection./app/src/main/java/com/example/detectdepression/MainActivity.kt | 2684226484 |
package com.example.detectdepression
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityInfoActivtyBinding
class InfoActivty : AppCompatActivity() {
private lateinit var binding : ActivityInfoActivtyBinding
private val PATIENT_ID = "PatientId"
private var DOC_NAME = "DoctorName"
lateinit var docName : String
lateinit var patientId : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this@InfoActivty,R.layout.activity_info_activty)
docName = intent.getStringExtra(DOC_NAME)!!
patientId = intent.getStringExtra(PATIENT_ID)!!
}
fun btnNext(view : View) {
var intent = Intent(this@InfoActivty,ObjectiveQuestionsActivity::class.java)
intent.putExtra(PATIENT_ID,patientId)
intent.putExtra(DOC_NAME,docName)
startActivity(intent)
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/InfoActivty.kt | 2469205858 |
package com.example.detectdepression
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivitySplashScreenBinding
class SplashScreenActivity : AppCompatActivity() {
private lateinit var binding : ActivitySplashScreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_splash_screen)
Handler().postDelayed(
Runnable {},2000
)
startActivity(Intent(this@SplashScreenActivity,MainActivity::class.java))
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/SplashScreenActivity.kt | 3217726547 |
package com.example.detectdepression
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.example.detectdepression.databinding.ActivityOperationsBinding
import com.example.detectdepression.models.PatientListItemInfo
import com.example.detectdepression.operationFragments.AddPatientFragment
import com.example.detectdepression.operationFragments.HomeFragment
import com.example.detectdepression.operationFragments.SettingsFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
class OperationsActivity : AppCompatActivity() {
private lateinit var binding : ActivityOperationsBinding
var patientListItemInfo = ArrayList<PatientListItemInfo>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this@OperationsActivity,R.layout.activity_operations)
binding.apply {
bottomNavigationOperation.selectedItemId = R.id.homeNavigation
bottomNavigationOperation.setOnItemSelectedListener(navListener)
}
supportFragmentManager.beginTransaction().replace(
binding.frameLayout.id,
HomeFragment()
).commit()
}
private val navListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
var selectedFragment: Fragment? = null
when (item.itemId) {
R.id.addPatientNavigation -> selectedFragment = AddPatientFragment()
R.id.homeNavigation -> selectedFragment = HomeFragment()
R.id.settingsNavigation -> selectedFragment = SettingsFragment()
}
supportFragmentManager.beginTransaction().replace(
binding.frameLayout.id,
selectedFragment!!
).commit()
true
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/OperationsActivity.kt | 1521604172 |
package com.example.detectdepression
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
| Depression.Detection./app/src/main/java/com/example/detectdepression/PatientListFragment.kt | 3037044697 |
package com.example.detectdepression.models
data class PatientListItemInfo(
var patientName : String,
var patientId : String,
var date : String,
var score : Int
)
| Depression.Detection./app/src/main/java/com/example/detectdepression/models/PatientListItemInfo.kt | 2860831969 |
package com.example.detectdepression.models
data class PatientLoginInfo(
var patientId : String,
var docName : String
)
| Depression.Detection./app/src/main/java/com/example/detectdepression/models/PatientLoginInfo.kt | 1824263934 |
package com.example.detectdepression
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivitySubjectiveQuestionsBinding
import com.example.detectdepression.ml.Dd
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.nio.ByteBuffer
class SubjectiveQuestionsActivity : AppCompatActivity() {
private lateinit var binding : ActivitySubjectiveQuestionsBinding
private var QUESTION_NUMBER = 1
private var SUBJECTIVE_QUESTIONS = "SubjectiveQuestions"
private var questions = ArrayList<String>()
private var TOTAL_QUESTIONS = 0
private var score = 0
private lateinit var reference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this@SubjectiveQuestionsActivity,R.layout.activity_subjective_questions)
reference = FirebaseDatabase.getInstance().getReference(SUBJECTIVE_QUESTIONS)
// if (questions.size == 0) {
// loadQuestions()
// } else {
// setQuestion()
// }
binding.btnPrevious.setOnClickListener {
btnPrevious()
}
binding.btnNext.setOnClickListener {
btnNext()
}
}
private fun loadQuestions() {
binding.apply {
progressBar2.visibility = View.VISIBLE
constraintLayout.visibility = View.INVISIBLE
reference.get().addOnSuccessListener {
for (question in it.children) {
questions.add(question.value.toString())
TOTAL_QUESTIONS++
}
progressBar2.visibility = View.INVISIBLE
constraintLayout.visibility = View.VISIBLE
setQuestion()
}.addOnFailureListener {
Toast.makeText(this@SubjectiveQuestionsActivity,"Oops! Something went wrong",Toast.LENGTH_SHORT).show()
}
}
}
private fun setQuestion() {
binding.apply {
// var text = binding.edtAns.text.toString()
// val model = Dd.newInstance(this@SubjectiveQuestionsActivity)
//
//// Creates inputs for reference.
// val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 500), DataType.FLOAT32)
// inputFeature0.loadBuffer(ByteBuffer.wrap(text.toByteArr
//
//// Runs model inference and gets result.
// val outputs = model.process(inputFeature0)
// val outputFeature0 = outputs.outputFeature0AsTensorBuffer
//
// Toast.makeText(this@SubjectiveQuestionsActivity,outputFeature0.toString(),Toast.LENGTH_SHORT).show()
//
//// Releases model resources if no longer used.
// model.close()
//
// txtQuestion.text = questions[QUESTION_NUMBER-1]
if (QUESTION_NUMBER == 1) {
btnPrevious.visibility = View.INVISIBLE
btnPrevious.isClickable = false
} else {
btnPrevious.visibility = View.VISIBLE
btnPrevious.isClickable = true
btnPrevious.text = "Previous"
}
if (QUESTION_NUMBER == TOTAL_QUESTIONS) {
btnNext.text = "Submit"
} else {
btnNext.text = "Next"
}
}
}
private fun btnPrevious() {
if (QUESTION_NUMBER > 1) {
QUESTION_NUMBER--
setQuestion()
}
}
fun btnNext() {
if (QUESTION_NUMBER == TOTAL_QUESTIONS) {
startActivity(Intent(this@SubjectiveQuestionsActivity,TestResultActivity::class.java))
} else {
QUESTION_NUMBER++
setQuestion()
binding.edtAns.setText("")
}
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/SubjectiveQuestionsActivity.kt | 2091694763 |
package com.example.detectdepression
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.ui.text.toLowerCase
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityPatientLoginBinding
import com.example.detectdepression.models.PatientLoginInfo
import com.google.firebase.Firebase
import com.google.firebase.database.database
class PatientLoginActivity : AppCompatActivity() {
private lateinit var binding : ActivityPatientLoginBinding
private val PATIENT_ID = "PatientId"
private var DOC_NAME = "DoctorName"
private val ASSIGNED_PATIENT_LIST = "Assigned Patient List"
private var assignedPatientList = ArrayList<PatientLoginInfo>()
private var PATIENT_LIST = "Patient Login List"
private val databaseReference = Firebase.database
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_patient_login)
}
fun btnNext(view : View) {
binding.apply {
var temp = 0
var patientId = edtPatientIdLogin.text.toString().trim()
var docName = edtDocNameLogin.text.toString().trim()
if (!TextUtils.isEmpty(patientId) && !TextUtils.isEmpty(docName)) {
for (patient in assignedPatientList) {
if (patient.patientId == patientId.trim() && patient.docName.toLowerCase() == docName.trim().toLowerCase()) {
temp = 1
break;
}
}
if (temp == 1) {
var intent = Intent(this@PatientLoginActivity,InfoActivty::class.java)
intent.putExtra(PATIENT_ID,patientId)
intent.putExtra(DOC_NAME,docName)
startActivity(intent)
finish()
} else {
Toast.makeText(this@PatientLoginActivity,"Authentication Failed!!",Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onStart() {
super.onStart()
databaseReference.getReference(ASSIGNED_PATIENT_LIST).get().addOnSuccessListener {
for (patient in it.children) {
Log.d("TAGY",patient.key.toString() + " " + patient.value.toString())
assignedPatientList.add(PatientLoginInfo(patient.key.toString(),patient.value.toString()))
}
}.addOnFailureListener {
Toast.makeText(this@PatientLoginActivity,"Authentication Failed !!",Toast.LENGTH_SHORT).show()
}
}
fun loginAsDoctor(view: View) {
startActivity(Intent(this@PatientLoginActivity,DoctorLoginActivity::class.java))
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/PatientLoginActivity.kt | 2633561224 |
package com.example.detectdepression
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
| Depression.Detection./app/src/main/java/com/example/detectdepression/HomeFragment.kt | 3037044697 |
package com.example.detectdepression
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.detectdepression.databinding.PatientListItemBinding
import com.example.detectdepression.models.PatientListItemInfo
class PatientListRecyclerViewAdapter(var context: Context,var patientList : MutableList<PatientListItemInfo>) : RecyclerView.Adapter<PatientListRecyclerViewAdapter.MyViewHolder>() {
class MyViewHolder(var binding : PatientListItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data : PatientListItemInfo) {
binding.patientListItemInfo = data
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(PatientListItemBinding.inflate(LayoutInflater.from(context),parent,false))
}
override fun getItemCount(): Int {
return patientList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(patientList[position])
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/PatientListRecyclerViewAdapter.kt | 417081186 |
package com.example.detectdepression
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityTestResultBinding
class TestResultActivity : AppCompatActivity() {
private lateinit var binding : ActivityTestResultBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this@TestResultActivity,R.layout.activity_test_result)
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/TestResultActivity.kt | 4250050642 |
package com.example.detectdepression
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.example.detectdepression.databinding.ActivityObjectiveQuestionsBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ktx.database
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
import io.grpc.Server
class ObjectiveQuestionsActivity : AppCompatActivity() {
private lateinit var firestore : FirebaseFirestore
private lateinit var binding : ActivityObjectiveQuestionsBinding
private lateinit var database: FirebaseDatabase
private lateinit var reference : DatabaseReference
private var PATIENT_RESULTS_COLLECTION = "PatientResults"
private var QUESTION_NUMBER = 1
private var SCORE = "score"
private var score = 0
private var scoreArray = ArrayList<Int>()
private var TOTAL_QUESTIONS = 9
private var questions = ArrayList<String>()
private var SCORE_ARRAY = "Score Array"
private var OBJECTIVE_QUESTIONS = "ObjectiveQuestions"
private val PATIENT_ID = "PatientId"
private var DOC_NAME = "DoctorName"
lateinit var docName : String
lateinit var patientId : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_objective_questions)
database = Firebase.database
firestore = FirebaseFirestore.getInstance()
patientId = intent.getStringExtra(PATIENT_ID)!!
docName = intent.getStringExtra(DOC_NAME)!!
if (questions.size == 0) {
loadQuestions()
} else {
setQuestions()
}
binding.btnNext.setOnClickListener {
btnNext()
}
binding.btnPrevious.setOnClickListener {
btnPrevious()
}
}
private fun btnPrevious() {
if(QUESTION_NUMBER == 1) {
startActivity(Intent(this@ObjectiveQuestionsActivity,InfoActivty::class.java))
finish()
} else {
QUESTION_NUMBER--
setQuestions()
}
}
private fun loadQuestions() {
reference = database.getReference(OBJECTIVE_QUESTIONS)
reference.get().addOnSuccessListener {
for (question in it.children) {
questions.add(question.value.toString())
scoreArray.add(0)
Log.d("TGAY",question.value.toString())
}
binding.progressBar2.visibility = View.INVISIBLE
binding.constraintLayout.visibility = View.VISIBLE
setQuestions()
}.addOnFailureListener {
Toast.makeText(this@ObjectiveQuestionsActivity,"Oops!! Something went wrong...", Toast.LENGTH_SHORT).show()
}
}
private fun btnNext() {
binding.apply {
if (options.checkedRadioButtonId == -1) {
Toast.makeText(this@ObjectiveQuestionsActivity,"Select one of the above options !!",Toast.LENGTH_SHORT).show()
} else {
when (options.checkedRadioButtonId) {
opt1.id -> {
scoreArray[QUESTION_NUMBER-1] = 0
}opt2.id -> {
scoreArray[QUESTION_NUMBER-1] = 1
}opt3.id -> {
scoreArray[QUESTION_NUMBER-1] = 2
} else -> {
scoreArray[QUESTION_NUMBER-1] = 3
}
}
options.clearCheck()
if (QUESTION_NUMBER == TOTAL_QUESTIONS || btnNext.text.toString() == "Submit") {
binding.progressBar.progress = 90
//calculate total score
for (i in scoreArray) {
score += i
}
Toast.makeText(this@ObjectiveQuestionsActivity, "SCORE : $score", Toast.LENGTH_SHORT).show()
//next activity
var intent = Intent(this@ObjectiveQuestionsActivity,SubjectiveQuestionsActivity::class.java)
intent.putIntegerArrayListExtra(SCORE_ARRAY,scoreArray)
intent.putExtra(SCORE,score)
intent.putExtra(PATIENT_ID,patientId)
startActivity(intent)
finish()
} else {
QUESTION_NUMBER++
setQuestions()
}
}
}
}
private fun setQuestions() {
binding.apply {
txtQuestion.text = questions[QUESTION_NUMBER-1]
binding.progressBar.progress = (QUESTION_NUMBER-1)*10
if (QUESTION_NUMBER == 1) {
binding.btnPrevious.visibility = View.GONE
} else {
binding.btnPrevious.visibility = View.VISIBLE
btnPrevious.text = "Previous"
}
if (QUESTION_NUMBER == TOTAL_QUESTIONS) {
btnNext.text = "Submit"
} else {
btnNext.text = "Next"
}
}
}
} | Depression.Detection./app/src/main/java/com/example/detectdepression/ObjectiveQuestionsActivity.kt | 1856246273 |
package com.example.gymforce
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.gymforce", appContext.packageName)
}
} | GymForce/app/src/androidTest/java/com/example/gymforce/ExampleInstrumentedTest.kt | 249399386 |
package com.example.gymforce
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)
}
} | GymForce/app/src/test/java/com/example/gymforce/ExampleUnitTest.kt | 481696382 |
package com.example.gymforce.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val orange = Color(0xFFF34336) | GymForce/app/src/main/java/com/example/gymforce/ui/theme/Color.kt | 3839003479 |
package com.example.gymforce.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.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun GymForceTheme(
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
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | GymForce/app/src/main/java/com/example/gymforce/ui/theme/Theme.kt | 1122311933 |
package com.example.gymforce.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.unit.sp
// Set of Material typography styles to start with
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
)
*/
) | GymForce/app/src/main/java/com/example/gymforce/ui/theme/Type.kt | 985565317 |
package com.example.gymforce.navigation
import com.example.gymforce.R
sealed class BottomNavItem(var title:String, var icon:Int, var screen_route:String) {
data object Setting : BottomNavItem("Setting", R.drawable.setting, "setting")
data object Exercises : BottomNavItem("Exercises", R.drawable.img_2, "exercises")
data object Tools : BottomNavItem("Tools", R.drawable.img_1, "tools")
} | GymForce/app/src/main/java/com/example/gymforce/navigation/BottomNavItem.kt | 3882552941 |
package com.example.gymforce.navigation
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.gymforce.R
@Composable
fun MyBottomNavigation(navController: NavController) {
val items = listOf(
BottomNavItem.Setting,
BottomNavItem.Exercises,
BottomNavItem.Tools
)
BottomNavigation(
backgroundColor = colorResource(id = R.color.orange),
contentColor = Color.Black, modifier = Modifier.height(55.dp),
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = {
Icon(
painterResource(id = item.icon),
modifier = Modifier
.padding(top = 6.dp)
.size(25.dp),
contentDescription = item.title
)
},
label = {
Text(
text = item.title,
fontSize = 12.sp
)
},
selectedContentColor = Color.Black,
unselectedContentColor = Color.White.copy(0.7f),
alwaysShowLabel = true,
selected = currentRoute == item.screen_route,
onClick = {
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
} | GymForce/app/src/main/java/com/example/gymforce/navigation/BottomNavigation.kt | 2880913657 |
package com.example.gymforce.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.gymforce.screens.Exercises.ExercisesScreen
import com.example.gymforce.screens.setting.SettingScreen
import com.example.gymforce.screens.tools.ToolsScreen
import com.example.gymforce.screens.type.TypeScreen
@Composable
fun NavigationGraph(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = BottomNavItem.Exercises.screen_route
) {
composable(BottomNavItem.Setting.screen_route) {
SettingScreen()
}
composable(BottomNavItem.Exercises.screen_route) {
ExercisesScreen(navController)
}
composable(BottomNavItem.Tools.screen_route) {
ToolsScreen(navController)
}
composable("type training screen"){
TypeScreen(navController)
}
}
} | GymForce/app/src/main/java/com/example/gymforce/navigation/NavigationGraph.kt | 1212457380 |
package com.example.gymforce.models
import com.example.gymforce.R
sealed class TrainingCardItem(
var numOfDay: String,
var workOutName: String,
var workOutImage: Int
) {
data object ChestDay : TrainingCardItem("Day 1", "Chest", R.drawable.icon_app)
data object BackDay : TrainingCardItem("Day 2", "Back", R.drawable.icon_app)
data object ShoulderDay : TrainingCardItem("Day 3", "Shoulder", R.drawable.icon_app)
data object ArmsDay : TrainingCardItem("Day 4", "Arms", R.drawable.icon_app)
data object LegDay : TrainingCardItem("Day 5", "Leg", R.drawable.icon_app)
data object Off : TrainingCardItem("Day 6", "Off", R.drawable.icon_app)
} | GymForce/app/src/main/java/com/example/gymforce/models/TrainingCardItem.kt | 1198705512 |
package com.example.gymforce.models
class TrainingTypeItem
(
) {
} | GymForce/app/src/main/java/com/example/gymforce/models/TrainingTypeItem.kt | 3683506393 |
package com.example.gymforce.screens.splash.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Color.kt | 3965027970 |
package com.example.gymforce.screens.splash.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.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun GymForceTheme(
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
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Theme.kt | 2179957717 |
package com.example.gymforce.screens.splash.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.unit.sp
// Set of Material typography styles to start with
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
)
*/
) | GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Type.kt | 2106438172 |
package com.example.gymforce.screens.splash
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import com.example.gymforce.R
@Composable
fun SplashContent() {
Column(
modifier = Modifier
.fillMaxSize()
.background(color = colorResource(id = R.color.orange))
.paint(
painterResource(id = R.drawable.icon_app),
)
) {
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/splash/SplashContent.kt | 3813851426 |
package com.example.gymforce.screens.splash
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.gymforce.screens.MainActivity
import com.example.gymforce.screens.splash.ui.theme.GymForceTheme
class SplashActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GymForceTheme {
// A surface container using the 'background' color from the theme
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(intent)
finish()
},2500)
SplashContent()
}
}
}
}
| GymForce/app/src/main/java/com/example/gymforce/screens/splash/SplashActivity.kt | 2346088553 |
package com.example.gymforce.screens.tools
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun ToolsScreen(navHostController: NavHostController) {
ToolsContent(navHostController)
} | GymForce/app/src/main/java/com/example/gymforce/screens/tools/ToolsScreen.kt | 2831859166 |
package com.example.gymforce.screens.tools
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
@Composable
fun ToolsContent(navHostController: NavHostController) {
Column(modifier = Modifier.fillMaxSize(),Arrangement.Center) {
Text(text = "Tools Screen")
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/tools/ToolsContent.kt | 3272780063 |
package com.example.gymforce.screens
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.navigation.compose.rememberNavController
import com.example.gymforce.ui.theme.GymForceTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
MainScreenView(navController)
}
}
}
| GymForce/app/src/main/java/com/example/gymforce/screens/MainActivity.kt | 2226121826 |
package com.example.gymforce.screens.type
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.gymforce.R
@Composable
fun TypeScreenTopBar(trainingScreenName: String) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.drawable.icon_back),
contentDescription = "icon back",
modifier = Modifier.padding(end = 120.dp, top = 10.dp)
)
Text(
text = trainingScreenName,
color = Color.Black,
fontFamily = FontFamily.Default,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(end = 150.dp, top = 10.dp)
.align(
Alignment.CenterVertically
)
)
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreenTopBar.kt | 3585904976 |
package com.example.gymforce.screens.type
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun TypeScreen(navHostController: NavHostController) {
TypeScreenContent(navHostController = navHostController)
} | GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreen.kt | 3085556269 |
package com.example.gymforce.screens.type
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import com.example.gymforce.models.TrainingCardItem
@Composable
fun TypeScreenContent(navHostController: NavHostController) {
Column(
modifier = Modifier.fillMaxSize(),
Arrangement.Top,
Alignment.CenterHorizontally)
{
TypeScreenTopBar(trainingScreenName = TrainingCardItem.ChestDay.workOutName)
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreenContent.kt | 3038866041 |
package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.gymforce.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TrainingCard(name: String, day: String, image: Int, navController: NavHostController) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(115.dp)
.padding(8.dp),
colors = CardDefaults.cardColors(
containerColor = Color.Gray.copy(0.9f)
),
shape = RoundedCornerShape(10.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 7.dp
),
onClick = {
navController.navigate("type training screen")
}
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(8.dp)
) {
Image(
painter = painterResource(id = image),
contentDescription = "",
modifier = Modifier
.size(90.dp)
.padding(end = 8.dp, top = 2.dp)
.align(Alignment.CenterVertically)
)
Column (modifier= Modifier.fillMaxWidth(.7f).padding(start = 8.dp)){
Text(text = day, fontSize = 22.sp, fontWeight = FontWeight.Bold)
Text(text = name, fontSize = 22.sp, fontWeight = FontWeight.Normal)
}
Icon(
painter = painterResource(id = R.drawable.icon_arrow),
contentDescription = "icon go to training Screen ",
modifier = Modifier.weight(0.2f)
)
}
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/TrainingCard.kt | 2817614677 |
package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun ExercisesTopBar() {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Text(
text = "Exercises",
color = Color.Black,
fontFamily = FontFamily.Default,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(10.dp)
.align(
Alignment.CenterVertically
)
)
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesTopBar.kt | 2391339692 |
package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.gymforce.models.TrainingCardItem
@Composable
fun ExercisesLazyColumn(navHostController: NavHostController) {
val list = listOf(
TrainingCardItem.ChestDay,
TrainingCardItem.BackDay,
TrainingCardItem.ShoulderDay,
TrainingCardItem.ArmsDay,
TrainingCardItem.LegDay,
TrainingCardItem.Off,
)
LazyColumn (
modifier = Modifier
.fillMaxSize()
.padding(bottom = 55.dp)
) {
item {
list.forEach { item ->
TrainingCard(
name = item.workOutName,
day = item.numOfDay,
image = item.workOutImage,
navHostController
)
}
}
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesLazyColumn.kt | 2895789151 |
package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
@Composable
fun ExercisesContent(navHostController: NavHostController) {
Column(
modifier = Modifier.fillMaxSize(),
Arrangement.Top,
Alignment.CenterHorizontally
)
{
ExercisesTopBar()
ExercisesLazyColumn(navHostController)
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesContent.kt | 8893835 |
package com.example.gymforce.screens.Exercises
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun ExercisesScreen(navHostController: NavHostController) {
ExercisesContent(navHostController)
} | GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesScreen.kt | 3280228017 |
package com.example.gymforce.screens.setting
import androidx.compose.runtime.Composable
@Composable
fun SettingScreen() {
SettingContent()
} | GymForce/app/src/main/java/com/example/gymforce/screens/setting/SettingScreen.kt | 3903746527 |
package com.example.gymforce.screens.setting
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun SettingContent() {
Column(modifier = Modifier.fillMaxSize(),Arrangement.Center) {
Text(text = "Setting Screen")
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/setting/SettingContent.kt | 3012612995 |
package com.example.gymforce.screens
import android.annotation.SuppressLint
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.gymforce.navigation.MyBottomNavigation
import com.example.gymforce.navigation.NavigationGraph
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainScreenView(navController: NavHostController) {
Scaffold(
bottomBar = { MyBottomNavigation(navController = navController) }
) {
NavigationGraph(navController = navController)
}
} | GymForce/app/src/main/java/com/example/gymforce/screens/MainScreen.kt | 3255350445 |
package com.musicify
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "Musicify"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
| Musicify-Frontend/android/app/src/main/java/com/musicify/MainActivity.kt | 2262849672 |
package com.musicify
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
| Musicify-Frontend/android/app/src/main/java/com/musicify/MainApplication.kt | 1746667819 |
package uz.boxodir.test2048game
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.test2048game", appContext.packageName)
}
} | Legend_2048_Game/app/src/androidTest/java/uz/boxodir/test2048game/ExampleInstrumentedTest.kt | 2072309904 |
package uz.boxodir.test2048game
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)
}
} | Legend_2048_Game/app/src/test/java/uz/boxodir/test2048game/ExampleUnitTest.kt | 1391882498 |
package uz.boxodir.test2048game.settings
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
class Settings constructor(context: Context) {
fun savePos(txt: String) {
editor.putString("CURRENT_MATRIX", txt).apply()
}
fun saveLastMatrix(txt: String) {
editor.putString("LAST", txt).apply()
}
fun saveState(boolean: Boolean) {
editor.putBoolean("STATE", boolean).apply()
}
fun isPlaying() = pref.getBoolean("STATE", false)
fun getItems(): String? {
return pref.getString("CURRENT_MATRIX", "")
}
fun lastItems(): String? {
return pref.getString("LAST", "")
}
fun saveScore(score: Int) {
editor.putInt("SCORE", score).apply()
}
fun saveLastScore(lastScore: Int) {
editor.putInt("LAST_SCORE", lastScore).apply()
}
fun saveRecord(record: Int) {
editor.putInt("RECORD", record).apply()
}
fun getScore(): Int = pref.getInt("SCORE", 0)
fun getScoreLast(): Int = pref.getInt("LAST_SCORE", 0)
fun getRecord(): Int = pref.getInt("RECORD", 0)
private var pref: SharedPreferences = context.getSharedPreferences("2048", Context.MODE_PRIVATE)
private var editor: SharedPreferences.Editor = pref.edit()
companion object {
@SuppressLint("StaticFieldLeak")
private lateinit var instance: Settings
fun init(context: Context) {
if (!(Companion::instance.isInitialized)) {
instance = Settings(context)
}
}
fun getInstance(): Settings {
return instance
}
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/settings/Settings.kt | 2878834548 |
package uz.boxodir.test2048game.repository
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.widget.Toast
import uz.boxodir.test2048game.settings.Settings
import kotlin.random.Random
class AppRepository private constructor() {
var level = 0
private var lastLevel = 0
private var record = 0
companion object {
@SuppressLint("StaticFieldLeak")
private lateinit var settings: Settings
@SuppressLint("StaticFieldLeak")
private var instance: AppRepository? = null
@SuppressLint("StaticFieldLeak")
private lateinit var context: Context
fun init(context: Context) {
Companion.context = context
settings = Settings.getInstance()
}
fun getInstance(): AppRepository {
if (instance == null)
instance = AppRepository()
return instance!!
}
}
init {
record = settings.getRecord()
}
fun getRecord() = record
private val NEW_ELEMENT = 2
val matrix = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
val lastMatrix = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
init {
if (settings.isPlaying()) {
Log.d("OOO", "Load Data")
loadData()
} else {
addFirst()
addFirst()
}
}
fun backOldState() {
/*for (i in lastMatrix.indices) {
for (j in lastMatrix.indices) {
matrix[i][j] = lastMatrix[i][j]
Log.d("OOO", "${lastMatrix[i][j]}")
}
}*/
swap(matrix, lastMatrix)
/*swap(lastMatrix, lastMatrix2)
swap(lastMatrix2, lastMatrix3)*/
level = lastLevel
/*lastLevel = lastLevel2
lastLevel2 = lastLevel3*/
}
fun addFirst() {
val emptyList = ArrayList<Pair<Int, Int>>()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
emptyList.add(Pair(i, j))
}
}
}
val randomPos = Random.nextInt(0, emptyList.size)
matrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
lastMatrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
}
private fun addNewElement() {
val emptyList = ArrayList<Pair<Int, Int>>()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
emptyList.add(Pair(i, j))
}
}
}
Log.d("KKK", "${isClickable()}")
if (emptyList.isEmpty() && !isClickable()) {
Toast.makeText(context, "Game over", Toast.LENGTH_SHORT).show()
clear()
} else {
val randomPos = Random.nextInt(0, emptyList.size)
matrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
}
}
fun moveToLeft() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amounts = ArrayList<Int>(4)
var bool = true
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) continue
if (amounts.isEmpty()) amounts.add(matrix[i][j])
else {
if (amounts.last() == matrix[i][j] && bool) {
level += amounts.last()
record = if (record < level) level else record
amounts[amounts.size - 1] = amounts.last() * 2
bool = false
} else {
amounts.add(matrix[i][j])
bool = true
}
}
matrix[i][j] = 0
}
for (k in amounts.indices) {
matrix[i][k] = amounts[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveToRight() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amounts = ArrayList<Int>(4)
var bool = true
for (j in matrix[i].size - 1 downTo 0) {
if (matrix[i][j] == 0) continue
if (amounts.isEmpty()) amounts.add(matrix[i][j])
else {
if (amounts.last() == matrix[i][j] && bool) {
level += amounts.last()
record = if (record < level) level else record
amounts[amounts.size - 1] = amounts.last() * 2
bool = false
} else {
amounts.add(matrix[i][j])
bool = true
}
}
matrix[i][j] = 0
}
for (k in amounts.indices) {
matrix[i][matrix[i].size - k - 1] = amounts[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveUp() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amount = ArrayList<Int>()
var bool = true
for (j in matrix[i].indices) {
if (matrix[j][i] == 0) continue
if (amount.isEmpty()) amount.add(matrix[j][i])
else {
if (amount.last() == matrix[j][i] && bool) {
level += amount.last()
record = if (record < level) level else record
amount[amount.size - 1] = amount.last() * 2
bool = false
} else {
bool = true
amount.add(matrix[j][i])
}
}
matrix[j][i] = 0
}
for (j in 0 until amount.size) {
matrix[j][i] = amount[j]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveDown() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amount = ArrayList<Int>()
var bool = true
for (j in matrix[i].size - 1 downTo 0) {
if (matrix[j][i] == 0) continue
if (amount.isEmpty()) amount.add(matrix[j][i])
else {
if (amount.last() == matrix[j][i] && bool) {
level += amount.last()
record = if (record < level) level else record
amount[amount.size - 1] = amount.last() * 2
bool = false
} else {
bool = true
amount.add(matrix[j][i])
}
}
matrix[j][i] = 0
}
for (k in amount.size - 1 downTo 0) {
matrix[3 - k][i] = amount[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun clear() {
for (i in matrix.indices) {
for (j in matrix[i].indices) {
matrix[i][j] = 0
}
}
level = 0
lastLevel = 0
swap(lastMatrix, matrix)
settings.saveState(false)
addFirst()
addFirst()
}
fun saveItems() {
val sb: StringBuilder = StringBuilder()
val sbLast: StringBuilder = StringBuilder()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
sb.append(matrix[i][j].toString())
sbLast.append(lastMatrix[i][j])
sb.append("##")
sbLast.append("##")
}
}
settings.savePos(sb.toString())
settings.saveLastMatrix(sbLast.toString())
settings.saveScore(level)
settings.saveLastScore(lastLevel)
settings.saveState(true)
}
fun saveRecord(int: Int) {
settings.saveRecord(int)
}
fun loadData() {
level = settings.getScore()
lastLevel = settings.getScoreLast()
record = settings.getRecord()
val txt = settings.getItems()?.split("##")!!
val txtLast = settings.lastItems()?.split("##")!!
Log.d("YYY", txtLast.toString())
for (i in 0 until txt.size - 1) {
Log.d("PPP", "$i")
matrix[i / 4][i % 4] = txt[i].toInt()
if (!txtLast.isEmpty()) {
lastMatrix[i / 4][i % 4] = txtLast[i].toInt()
}
}
}
fun swap(a: Array<Array<Int>>, b: Array<Array<Int>>) {
for (i in b.indices) {
for (j in b[i].indices) {
a[i][j] = b[i][j]
}
}
}
fun setState(boolean: Boolean) {
settings.saveState(boolean)
}
fun isPlaying() = settings.isPlaying()
fun isClickable(): Boolean {
for (i in matrix.indices) {
val emptyList = ArrayList<Int>(4)
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
return true
}
if (emptyList.isEmpty()) {
emptyList.add(matrix[i][j])
} else {
if (emptyList.last() == matrix[i][j]) {
return true
} else {
emptyList.add(matrix[i][j])
}
}
}
}
for (i in matrix[0].indices) {
val emptyList = ArrayList<Int>(4)
for (j in matrix.indices) {
if (matrix[j][i] == 0) {
return true
}
if (emptyList.isEmpty()) {
emptyList.add(matrix[j][i])
} else {
if (emptyList.last() == matrix[j][i])
return true
else
emptyList.add(matrix[j][i])
}
}
}
return false
}
fun restart() {
clear()
instance = null
}
}
fun Array<Array<Int>>.copyData() = map { it.clone() }.toTypedArray()
| Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/repository/AppRepository.kt | 335284080 |
package uz.boxodir.test2048game.app
import android.app.Application
import uz.boxodir.test2048game.repository.AppRepository
import uz.boxodir.test2048game.settings.Settings
class App:Application() {
override fun onCreate() {
Settings.init(this)
AppRepository.init(this)
super.onCreate()
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/app/App.kt | 2507280380 |
package uz.boxodir.test2048game.utils
import uz.boxodir.test2048game.R
class BackgroundUtil {
private val backgroundMap = HashMap<Int, Int>()
private val backgroundText = HashMap<Int, Int>()
init {
loadMap()
}
private fun loadMap() {
backgroundMap[0] = R.drawable.bg_item_0
backgroundMap[2] = R.drawable.bg_item_2
backgroundMap[4] = R.drawable.bg_item_4
backgroundMap[8] = R.drawable.bg_item_8
backgroundMap[16] = R.drawable.bg_item_16
backgroundMap[32] = R.drawable.bg_item_32
backgroundMap[64] = R.drawable.bg_item_64
backgroundMap[128] = R.drawable.bg_item_128
backgroundMap[256] = R.drawable.bg_item_256
backgroundMap[512] = R.drawable.bg_item_512
backgroundMap[1024] = R.drawable.bg_item_1024
backgroundMap[2048] = R.drawable.bg_item_2048
backgroundMap[4096] = R.drawable.bg_corner4096
backgroundMap[8192] = R.drawable.bg_corner8192
backgroundMap[16384] = R.drawable.bg_corner16384
backgroundText[0] = R.color.white
backgroundText[8] = R.color.white
backgroundText[16] = R.color.white
backgroundText[32] = R.color.white
backgroundText[64] = R.color.white
backgroundText[128] = R.color.white
backgroundText[256] = R.color.white
backgroundText[512] = R.color.white
backgroundText[1024] = R.color.white
backgroundText[2048] = R.color.white
backgroundText[4096] = R.color.white
backgroundText[8192] = R.color.white
backgroundText[16384] = R.color.white
backgroundText[0] = R.color.white
// backgroundText[2] = R.color.qoraroq
// backgroundText[4] = R.color.qoraroq
}
fun colorByCount(amount: Int): Int {
return backgroundMap.getOrDefault(amount, R.drawable.empty_corner)
}
fun textColorByCount(i: Int): Int {
return backgroundText.getOrDefault(i, R.color.white)
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/utils/BackgroundUtil.kt | 2352654098 |
package uz.boxodir.test2048game.utils
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import uz.boxodir.test2048game.model.SideEnum
import kotlin.math.abs
class MyTouchListener(context:Context) : View.OnTouchListener {
private val myGestureDetector = GestureDetector(context, MyGestureListener())
private var myMovementSideListener : ((SideEnum) -> Unit)?= null
override fun onTouch(v: View, event: MotionEvent): Boolean {
myGestureDetector.onTouchEvent(event)
return true
}
inner class MyGestureListener: GestureDetector.SimpleOnGestureListener() {
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
if (abs(e2.x - e1!!.x)> 100 || abs(e2.y - e1.y) > 100){
if (abs(e2.x - e1.x) < abs(e2.y - e1.y)){
if (e2.y > e1.y){
myMovementSideListener?.invoke(SideEnum.DOWN)
}else{
myMovementSideListener?.invoke(SideEnum.UP)
}
}
else{
if (e2.x > e1.x){
myMovementSideListener?.invoke(SideEnum.RIGHT)
}else{
myMovementSideListener?.invoke(SideEnum.LEFT)
}
}
}
return super.onFling(e1, e2, velocityX, velocityY)
}
}
fun setMyMovementSideListener(block:(SideEnum) -> Unit){
myMovementSideListener = block
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/utils/MyTouchListener.kt | 3650243439 |
package uz.boxodir.test2048game.screen
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import uz.boxodir.test2048game.R
class MainActivity : AppCompatActivity() {
private lateinit var playgame: AppCompatButton
private lateinit var infoScreen: AppCompatButton
private var clickItem: AppCompatButton? = null
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
clickItem = null
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.start)
infoScreen = findViewById(R.id.infoScreen)
playgame = findViewById(R.id.button)
playgame.setOnClickListener {
if (clickItem == null) {
clickItem = playgame.findViewById(R.id.button)
playgame.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
playgame.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clickItem = null
startActivity(Intent(this, PlayActivity::class.java))
Log.d("TTT","playga o'tdi")
}.start()
}.start()
}
}
infoScreen.setOnClickListener {
if (clickItem == null) {
clickItem = infoScreen.findViewById(R.id.info)
infoScreen.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
infoScreen.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clickItem = null
startActivity(Intent(this, InfoActivity::class.java))
}.start()
}.start()
}
}
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/MainActivity.kt | 2632653780 |
package uz.boxodir.test2048game.screen
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import uz.boxodir.test2048game.R
class InfoActivity : AppCompatActivity() {
private var back: ImageView? = null
private lateinit var goback:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_info)
back = null
goback = findViewById(R.id.back_menu)
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.info)
findViewById<View>(R.id.back_menu).setOnClickListener { v: View? ->
if (back == null) {
back = goback
goback.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
goback.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
startActivity(Intent(this, MainActivity::class.java))
finish()
}.start()
}.start()
}
}
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/InfoActivity.kt | 817649179 |
package uz.boxodir.test2048game.screen
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.LinearLayoutCompat
import uz.boxodir.test2048game.R
import uz.boxodir.test2048game.model.SideEnum
import uz.boxodir.test2048game.repository.AppRepository
import uz.boxodir.test2048game.settings.Settings
import uz.boxodir.test2048game.utils.BackgroundUtil
import uz.boxodir.test2048game.utils.MyTouchListener
class PlayActivity : AppCompatActivity() {
private val items: MutableList<TextView> = ArrayList(16)
private lateinit var mainView: LinearLayoutCompat
private var clic: ImageView? = null
private var clicRestartDialog: AppCompatButton? = null
private var repository = AppRepository.getInstance()
private var settings: Settings = Settings.getInstance()
private val util = BackgroundUtil()
private lateinit var level: TextView
private var record = 0
private var clickBackCount = 0
private lateinit var home_icon: ImageView
@SuppressLint("MissingInflatedId", "ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
clic = null
clicRestartDialog = null
setContentView(R.layout.activity_play)
setContentView(R.layout.activity_play)
level = findViewById(R.id.txt_score)
mainView = findViewById(R.id.mainView)
home_icon = findViewById(R.id.home_icon)
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.gamescreen)
loadViews()
describeMatrixToViews()
loadTochLisener()
funtions()
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
private fun loadTochLisener() {
if (clickBackCount == 1 || !repository.isPlaying()) {
findViewById<ImageView>(R.id.back).alpha = 0.2f
findViewById<ImageView>(R.id.back).isClickable = false
}
val myTouchListener = MyTouchListener(this)
myTouchListener.setMyMovementSideListener {
findViewById<ImageView>(R.id.back).alpha = 1f
findViewById<ImageView>(R.id.back).isClickable = true
clickBackCount = 0
when (it) {
SideEnum.DOWN -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveDown()
describeMatrixToViews()
}
SideEnum.UP -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveUp()
describeMatrixToViews()
}
SideEnum.RIGHT -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveToRight()
describeMatrixToViews()
}
SideEnum.LEFT -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveToLeft()
describeMatrixToViews()
}
}
}
mainView.setOnTouchListener(myTouchListener)
}
fun openGameOverDialog() {
val gameOverDialog = Dialog(this)
gameOverDialog.setContentView(R.layout.gameover)
gameOverDialog.setCancelable(false)
gameOverDialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
gameOverDialog.findViewById<TextView>(R.id.textView3).text = repository.level.toString()
gameOverDialog.findViewById<ImageView>(R.id.imageView4).setOnClickListener {
repository.clear()
repository = AppRepository.getInstance()
describeMatrixToViews()
gameOverDialog.dismiss()
}
gameOverDialog.findViewById<ImageView>(R.id.imageView3).setOnClickListener {
repository.restart()
repository = AppRepository.getInstance()
gameOverDialog.dismiss()
finish()
}
gameOverDialog.show()
}
private fun loadViews() {
for (i in 0 until mainView.childCount) {
val linear = mainView.getChildAt(i) as LinearLayoutCompat
for (j in 0 until linear.childCount) {
items.add(linear.getChildAt(j) as TextView)
}
}
}
private fun funtions() {
findViewById<ImageView>(R.id.play_activity_restart).setOnClickListener {
if (clic == null) {
clic = findViewById<ImageView>(R.id.play_activity_restart)
findViewById<ImageView>(R.id.play_activity_restart).animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
findViewById<ImageView>(R.id.play_activity_restart).animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
showRestartGameDialog()
}.start()
}.start()
}
}
findViewById<ImageView>(R.id.back).setOnClickListener {
if (clic == null) {
clic = findViewById<ImageView>(R.id.back)
findViewById<ImageView>(R.id.back).animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
findViewById<ImageView>(R.id.back).animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
clickBackCount++
repository.backOldState()
describeMatrixToViews()
}.start()
}.start()
}
}
home_icon.setOnClickListener {
home_icon.setOnClickListener {
if (clic == null) {
clic = home_icon
home_icon.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
home_icon.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
Log.d("TTT","play finish bo'ldi")
finish()
}.start()
}.start()
}
}
}
}
private fun showRestartGameDialog() {
val restartDialog = Dialog(this)
restartDialog.setContentView(R.layout.gameover)
restartDialog.setCancelable(true)
restartDialog.window?.setBackgroundDrawableResource(android.R.color.transparent);
restartDialog.setContentView(R.layout.item_restart)
val yesBtn = restartDialog.findViewById(R.id.button) as AppCompatButton
val noBtn = restartDialog.findViewById(R.id.button2) as AppCompatButton
yesBtn.setOnClickListener {
if (clicRestartDialog == null) {
clicRestartDialog = yesBtn
yesBtn.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
yesBtn.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clicRestartDialog = null
repository.clear()
repository = AppRepository.getInstance()
describeMatrixToViews()
restartDialog.dismiss()
}
.start()
}
.start()
}
}
noBtn.setOnClickListener {
if (clicRestartDialog == null) {
clicRestartDialog = noBtn
noBtn.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
noBtn.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clicRestartDialog = null
restartDialog.dismiss()
}.start()
}.start()
}
}
restartDialog.show()
}
@SuppressLint("ResourceAsColor")
private fun describeMatrixToViews() {
if (clickBackCount == 1 || !repository.isPlaying()) {
findViewById<ImageView>(R.id.back).alpha = 0.2f
findViewById<ImageView>(R.id.back).isClickable = false
}
var txt_best = findViewById<TextView>(R.id.txt_bestscore)
level.text = repository.level.toString()
record = txt_best.text.toString().toInt()
record = repository.getRecord()
if (repository.level > record) {
record = repository.level
}
txt_best.text = record.toString()
val _matrix = repository.matrix
for (i in _matrix.indices) {
for (j in _matrix[i].indices) {
items[i * _matrix.size + j].apply {
text = if (_matrix[i][j] == 0) ""
else _matrix[i][j].toString()
setBackgroundResource(util.colorByCount(_matrix[i][j]))
}
if (_matrix[i][j] == 16384) {
openGameOverDialog()
}
}
}
}
override fun onStop() {
super.onStop()
repository.saveRecord(record)
repository.saveItems()
}
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/PlayActivity.kt | 3644211720 |
package uz.boxodir.test2048game.model
enum class SideEnum {
LEFT, UP, RIGHT, DOWN
} | Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/model/SideEnum.kt | 1852745598 |
package com.example.petlover
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.petlover", appContext.packageName)
}
} | PetLover/app/src/androidTest/java/com/example/petlover/ExampleInstrumentedTest.kt | 3419834747 |
package com.example.petlover
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)
}
} | PetLover/app/src/test/java/com/example/petlover/ExampleUnitTest.kt | 2014333515 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.