Skip to content

Commit

Permalink
hide nav bar for news fragment when open
Browse files Browse the repository at this point in the history
  • Loading branch information
joemacd committed Dec 6, 2024
1 parent 0360ff1 commit f1b71f4
Show file tree
Hide file tree
Showing 5 changed files with 330 additions and 54 deletions.
1 change: 1 addition & 0 deletions PennMobile/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ dependencies {
}
implementation 'com.google.android.gms:play-services-location:21.0.1'
implementation 'com.google.android.gms:play-services-maps:18.2.0'
implementation 'com.google.android.libraries.places:places:2.6.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-crashlytics-ktx:18.6.0'
Expand Down
3 changes: 3 additions & 0 deletions PennMobile/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDFOB7fgIQubKyOjjrmsgNoDt-xRvlBDrk"/>

<receiver
android:name=".LaundryBroadcastReceiver"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,68 +1,281 @@
package com.pennapps.labs.pennmobile.Subletting
package com.pennapps.labs.pennmobile


import android.app.DatePickerDialog
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.fragment.app.Fragment
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.widget.ArrayAdapter
import android.widget.Button
import android.widget.DatePicker
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.pennapps.labs.pennmobile.MainActivity
import com.pennapps.labs.pennmobile.R
import com.google.android.gms.common.api.ApiException
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.AutocompleteSessionToken
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest
import com.google.android.libraries.places.api.net.PlacesClient
import com.pennapps.labs.pennmobile.Subletting.SubletteeMarketplace
import com.pennapps.labs.pennmobile.api.StudentLife
import com.pennapps.labs.pennmobile.databinding.FragmentSubletteeViewBinding
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale


class SubletteeFragment : Fragment() {

//create binding
private var _binding : FragmentSubletteeViewBinding? = null

// Create binding
private var _binding: FragmentSubletteeViewBinding? = null
private val binding get() = _binding!!

//api manager

// API manager
private lateinit var mStudentLife: StudentLife


private lateinit var mActivity: MainActivity
//private lateinit var dataModel : SublesseeViewModel
private lateinit var placesClient: PlacesClient
private val sessionToken = AutocompleteSessionToken.newInstance()


// Calendar related variables
private lateinit var btnStartDate: Button
private lateinit var btnEndDate: Button
private var startCalendar: Calendar = Calendar.getInstance()
private var endCalendar: Calendar = Calendar.getInstance()
private val dateFormat = SimpleDateFormat("MMM dd, yyyy", Locale.US)


// Address adapter for autocomplete
private lateinit var addressAdapter: ArrayAdapter<String>


// Default addresses to display when input is empty
private val defaultAddresses = listOf(
"3600 Chestnut St, Philadelphia, PA",
"3700 Walnut St, Philadelphia, PA",
"3800 Spruce St, Philadelphia, PA"
)


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mStudentLife = MainActivity.studentLifeInstance
mActivity = activity as MainActivity
mActivity.closeKeyboard()

val bundle = Bundle()

//edit this later for firebase
/* bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "0")
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "GSR")
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature")
FirebaseAnalytics.getInstance(mActivity).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle) */
val applicationInfo = requireContext().packageManager
.getApplicationInfo(requireContext().packageName, PackageManager.GET_META_DATA)
val apiKey = applicationInfo.metaData.getString("com.google.android.geo.API_KEY")
?: throw IllegalStateException("API key not found in AndroidManifest.xml")


// Initialize Places SDK with API key from manifest
if (!Places.isInitialized()) {
Places.initialize(requireContext(), apiKey)
}
placesClient = Places.createClient(requireContext())
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentSubletteeViewBinding.inflate(inflater, container, false)
return binding.root
}


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)


// Initialize address adapter with default addresses
addressAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, defaultAddresses)
binding.subletteeLocationEdittext.setAdapter(addressAdapter)
binding.subletteeLocationEdittext.threshold = 0


setupAddressAutocomplete()
setupDatePickers()


val marketplaceButton: Button = view.findViewById(R.id.sublettee_enter_subletting_button)


marketplaceButton.setOnClickListener {
//load new fragment, which will hold the subletting marketplace in whole
if (!validateDates()) {
Toast.makeText(context, "Please select valid start and end dates", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}


// Load new fragment, which will hold the subletting marketplace in whole
mActivity.supportFragmentManager.beginTransaction()
.replace(((view as ViewGroup).parent as View).id, SubletteeMarketplace())
.addToBackStack(null)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
.replace(((view as ViewGroup).parent as View).id, SubletteeMarketplace())
.addToBackStack(null)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}


// Handle selection from dropdown
binding.subletteeLocationEdittext.setOnItemClickListener { parent, _, position, _ ->
val selectedAddress = parent.getItemAtPosition(position) as String
// Update the address text view with the selected address
binding.subletteeLocationAddressView.text = selectedAddress
}
}


private fun setupDatePickers() {
// Start Date
btnStartDate = binding.subletteeStartDateButton
btnStartDate.setOnClickListener {
showDatePicker(btnStartDate, startCalendar)
}
btnEndDate = binding.subletteeEndDateButton
btnEndDate.setOnClickListener {
showDatePicker(btnEndDate, endCalendar)
}
}


private fun showDatePicker(btn: Button, cal: Calendar) {
val datePickerDialog = context?.let {
DatePickerDialog(
it,
{ _: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int ->
// Update calendar instance
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
// Update Button
val selectedDate = Calendar.getInstance()
selectedDate.set(year, monthOfYear, dayOfMonth)
val dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.getDefault())
val formattedDate = dateFormat.format(selectedDate.time)
btn.text = formattedDate
},
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
)
}
datePickerDialog?.show()
}


private fun validateDates(): Boolean {
val currentDate = Calendar.getInstance()
return !(startCalendar < currentDate || startCalendar > endCalendar)
}


override fun onDestroy() {
super.onDestroy()
_binding = null
}

}

private fun setupAddressAutocomplete() {
binding.subletteeLocationEdittext.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}


override fun onTextChanged(query: CharSequence?, p1: Int, p2: Int, p3: Int) {
getAddressPredictions(query.toString())
}


override fun afterTextChanged(p0: Editable?) {}
})


// Show the dropdown when the view gains focus and update when it loses focus
binding.subletteeLocationEdittext.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
binding.subletteeLocationEdittext.showDropDown()
} else {
// When the view loses focus, update the address text view
updateAddressTextView()
}
}
}


private fun updateAddressTextView() {
val query = binding.subletteeLocationEdittext.text.toString()
if (query.isNotEmpty()) {
val request = FindAutocompletePredictionsRequest.builder()
.setQuery(query)
.build()


placesClient.findAutocompletePredictions(request)
.addOnSuccessListener { response ->
val predictions = response.autocompletePredictions
if (predictions.isNotEmpty()) {
val bestPrediction = predictions[0].getFullText(null).toString()
binding.subletteeLocationAddressView.text = bestPrediction
} else {
// No predictions found; set to original query
binding.subletteeLocationAddressView.text = query
}
}
.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e("Places", "Place not found: ${exception.message}")
}
// On failure, set to original query
binding.subletteeLocationAddressView.text = query
}
} else {
// Clear the address text view if the query is empty
binding.subletteeLocationAddressView.text = ""
}
}


private fun getAddressPredictions(query: String) {
if (query.isEmpty()) {
// Show default addresses
addressAdapter.clear()
addressAdapter.addAll(defaultAddresses)
addressAdapter.notifyDataSetChanged()
} else {
val request = FindAutocompletePredictionsRequest.builder()
.setQuery(query)
.build()


placesClient.findAutocompletePredictions(request)
.addOnSuccessListener { response ->
val predictions = response.autocompletePredictions
val addresses = predictions.take(3).map { it.getFullText(null).toString() }
addressAdapter.clear()
addressAdapter.addAll(addresses)
addressAdapter.notifyDataSetChanged()
// Show the dropdown if the text box is focused
if (binding.subletteeLocationEdittext.hasFocus()) {
binding.subletteeLocationEdittext.showDropDown()
}
}
.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e("Places", "Place not found: ${exception.message}")
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package com.pennapps.labs.pennmobile.adapters

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.pennapps.labs.pennmobile.Subletting.SubletteeFragment
import com.pennapps.labs.pennmobile.SubletteeFragment
import com.pennapps.labs.pennmobile.Subletting.SubletterPostedListingsFragment

class SublettingPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
Expand Down
Loading

1 comment on commit f1b71f4

@joemacd
Copy link
Contributor Author

@joemacd joemacd commented on f1b71f4 Dec 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commit name not accurate: changed sublessee details fragment

Please sign in to comment.