From d26434eadbeb82699d67e8c5ed70f37d449af8a8 Mon Sep 17 00:00:00 2001 From: Skeletrobro <67814129+baronhsieh2005@users.noreply.github.com> Date: Fri, 23 Aug 2024 15:46:08 +0800 Subject: [PATCH] Added try catch blocks in Network requests to prevent timeout issues from crashing the app --- .../labs/pennmobile/BookGsrFragment.kt | 88 ++--- .../labs/pennmobile/DiningFragment.kt | 108 +++--- .../labs/pennmobile/DiningHallListWidget.kt | 72 ++++ .../labs/pennmobile/DiningSettingsFragment.kt | 83 +++-- .../pennapps/labs/pennmobile/FlingFragment.kt | 16 +- .../pennapps/labs/pennmobile/GsrFragment.kt | 344 +++++++++--------- .../pennmobile/GsrReservationsFragment.kt | 60 +-- .../labs/pennmobile/HuntsmanGSRLogin.kt | 102 +++--- .../labs/pennmobile/LoginWebviewFragment.kt | 68 ++-- .../labs/pennmobile/PottruckFragment.kt | 96 ++--- .../labs/pennmobile/adapters/DiningAdapter.kt | 26 +- .../pennmobile/adapters/DiningCardAdapter.kt | 20 +- .../adapters/DiningHallListWidgetAdapter.kt | 212 +++++++++++ .../adapters/DiningHallWidgetAdapter.kt | 32 +- .../pennmobile/adapters/FitnessAdapter.kt | 30 +- .../adapters/GsrReservationsAdapter.kt | 70 ++-- .../labs/pennmobile/adapters/HomeAdapter.kt | 100 ++--- .../classes/FitnessPreferenceViewModel.kt | 40 +- .../pennmobile/classes/HomepageViewModel.kt | 230 +++++++----- .../pennmobile/viewmodels/LaundryViewModel.kt | 166 +++++---- .../res/layout/dining_hall_list_widget.xml | 33 ++ .../layout/dining_hall_list_widget_item.xml | 6 + .../src/main/res/layout/home_post_card.xml | 2 +- 23 files changed, 1232 insertions(+), 772 deletions(-) create mode 100644 PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningHallListWidget.kt create mode 100644 PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallListWidgetAdapter.kt create mode 100644 PennMobile/src/main/res/layout/dining_hall_list_widget.xml create mode 100644 PennMobile/src/main/res/layout/dining_hall_list_widget_item.xml diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/BookGsrFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/BookGsrFragment.kt index a880e11f..b91578a0 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/BookGsrFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/BookGsrFragment.kt @@ -142,49 +142,53 @@ class BookGsrFragment : Fragment() { Log.i("BookGSRFragment", "ID $roomId") Log.i("BookGSRFragment", "Room Name $roomName") - mStudentLife.bookGSR( - // Passing the values - bearerToken, - startTime, - endTime, - gid, - roomId, - roomName, - // Creating an anonymous callback - object : Callback { - override fun success( - result: GSRBookingResult, - response: Response, - ) { - // Displaying the output as a toast and go back to GSR fragment - if (result.getDetail().equals("success")) { - Toast.makeText(activity, "GSR successfully booked", Toast.LENGTH_LONG).show() - - // Save user info in shared preferences - val sp = PreferenceManager.getDefaultSharedPreferences(activity) - val editor = sp.edit() - editor.putString(getString(R.string.first_name), firstNameEt.text.toString()) - editor.putString(getString(R.string.last_name), lastNameEt.text.toString()) - editor.putString(getString(R.string.email_address), emailEt.text.toString()) - editor.apply() - } else { - Toast.makeText(activity, "GSR booking failed", Toast.LENGTH_LONG).show() - Log.e("BookGsrFragment", "GSR booking failed with " + result.getError()) + try { + mStudentLife.bookGSR( + // Passing the values + bearerToken, + startTime, + endTime, + gid, + roomId, + roomName, + // Creating an anonymous callback + object : Callback { + override fun success( + result: GSRBookingResult, + response: Response, + ) { + // Displaying the output as a toast and go back to GSR fragment + if (result.getDetail().equals("success")) { + Toast.makeText(activity, "GSR successfully booked", Toast.LENGTH_LONG).show() + + // Save user info in shared preferences + val sp = PreferenceManager.getDefaultSharedPreferences(activity) + val editor = sp.edit() + editor.putString(getString(R.string.first_name), firstNameEt.text.toString()) + editor.putString(getString(R.string.last_name), lastNameEt.text.toString()) + editor.putString(getString(R.string.email_address), emailEt.text.toString()) + editor.apply() + } else { + Toast.makeText(activity, "GSR booking failed", Toast.LENGTH_LONG).show() + Log.e("BookGsrFragment", "GSR booking failed with " + result.getError()) + } + // go back to GSR fragment + binding.loading.loadingPanel.visibility = View.GONE + activity?.onBackPressed() } - // go back to GSR fragment - binding.loading.loadingPanel.visibility = View.GONE - activity?.onBackPressed() - } - - override fun failure(error: RetrofitError) { - // If any error occurred displaying the error as toast - Log.e("BookGSRFragment", "Error booking gsr", error) - Toast.makeText(activity, "An error has occurred. Please try again.", Toast.LENGTH_LONG).show() - binding.loading.loadingPanel.visibility = View.GONE - activity?.onBackPressed() - } - }, - ) + + override fun failure(error: RetrofitError) { + // If any error occurred displaying the error as toast + Log.e("BookGSRFragment", "Error booking gsr", error) + Toast.makeText(activity, "An error has occurred. Please try again.", Toast.LENGTH_LONG).show() + binding.loading.loadingPanel.visibility = View.GONE + activity?.onBackPressed() + } + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningFragment.kt index 1bc22d24..4f445185 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningFragment.kt @@ -153,42 +153,46 @@ class DiningFragment : Fragment() { } // Map each item in the list of venues to a Venue Observable, then map each Venue to a DiningHall Observable - mStudentLife.venues() - .flatMap { venues -> Observable.from(venues) } - .flatMap { venue -> - val hall = createHall(venue) - Observable.just(hall) - } - .toList() - .subscribe({ diningHalls -> - mActivity.runOnUiThread { - getMenus(diningHalls) - val adapter = DiningAdapter(diningHalls) - loadingPanel?.visibility = View.GONE - if (diningHalls.size > 0) { - no_results?.visibility = View.GONE + try { + mStudentLife.venues() + .flatMap { venues -> Observable.from(venues) } + .flatMap { venue -> + val hall = createHall(venue) + Observable.just(hall) + } + .toList() + .subscribe({ diningHalls -> + mActivity.runOnUiThread { + getMenus(diningHalls) + val adapter = DiningAdapter(diningHalls) + loadingPanel?.visibility = View.GONE + if (diningHalls.size > 0) { + no_results?.visibility = View.GONE + } + + // Log non-fatal error to crashyltics if null + // this error should not really be happening + // it is *possible* but be rare: ideally network stuff + // is decoupled with UI updates + try { + binding.diningHallsRecyclerView.adapter = adapter + binding.diningSwiperefresh.isRefreshing = false + } catch (e: Exception) { + FirebaseCrashlytics.getInstance().recordException(e) + } + view?.let { displaySnack("Just Updated") } } - - // Log non-fatal error to crashyltics if null - // this error should not really be happening - // it is *possible* but be rare: ideally network stuff - // is decoupled with UI updates - try { - binding.diningHallsRecyclerView.adapter = adapter + }, { + Log.e("DiningFragment", "Error getting dining halls", it) + mActivity.runOnUiThread { + Log.e("Dining", "Could not load Dining page", it) + loadingPanel?.visibility = View.GONE binding.diningSwiperefresh.isRefreshing = false - } catch (e: Exception) { - FirebaseCrashlytics.getInstance().recordException(e) } - view?.let { displaySnack("Just Updated") } - } - }, { - Log.e("DiningFragment", "Error getting dining halls", it) - mActivity.runOnUiThread { - Log.e("Dining", "Could not load Dining page", it) - loadingPanel?.visibility = View.GONE - binding.diningSwiperefresh.isRefreshing = false - } - }) + }) + } catch (e: Exception) { + e.printStackTrace() + } } override fun onResume() { @@ -221,23 +225,27 @@ class DiningFragment : Fragment() { companion object { // Gets the dining hall menus fun getMenus(venues: MutableList) { - val idVenueMap = mutableMapOf() - venues.forEach { idVenueMap[it.id] = it } - val current = LocalDateTime.now() - val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") - val formatted = current.format(formatter) - val studentLife = MainActivity.studentLifeInstance - studentLife.getMenus(formatted).subscribe({ menus -> - menus.forEach { menu -> - val id = menu.venue?.venueId - val diningHall = idVenueMap[id] - val diningHallMenus = diningHall?.menus ?: mutableListOf() - diningHallMenus.add(menu) - diningHall?.sortMeals(diningHallMenus) - } - }, { throwable -> - Log.e("DiningFragment", "Error getting Menus", throwable) - }) + try { + val idVenueMap = mutableMapOf() + venues.forEach { idVenueMap[it.id] = it } + val current = LocalDateTime.now() + val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") + val formatted = current.format(formatter) + val studentLife = MainActivity.studentLifeInstance + studentLife.getMenus(formatted).subscribe({ menus -> + menus.forEach { menu -> + val id = menu.venue?.venueId + val diningHall = idVenueMap[id] + val diningHallMenus = diningHall?.menus ?: mutableListOf() + diningHallMenus.add(menu) + diningHall?.sortMeals(diningHallMenus) + } + }, { throwable -> + Log.e("DiningFragment", "Error getting Menus", throwable) + }) + } catch (e: Exception) { + e.printStackTrace() + } } // Takes a venue then adds an image and modifies venue name if name is too long diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningHallListWidget.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningHallListWidget.kt new file mode 100644 index 00000000..f12767ef --- /dev/null +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningHallListWidget.kt @@ -0,0 +1,72 @@ +package com.pennapps.labs.pennmobile + +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.widget.RemoteViews +import com.google.gson.GsonBuilder +import com.google.gson.reflect.TypeToken +import com.pennapps.labs.pennmobile.adapters.DiningHallWidgetAdapter +import com.pennapps.labs.pennmobile.api.DiningRequest +import com.pennapps.labs.pennmobile.api.Serializer +import com.pennapps.labs.pennmobile.classes.Venue +import com.squareup.okhttp.OkHttpClient +import retrofit.RestAdapter +import retrofit.client.OkClient +import retrofit.converter.GsonConverter +import java.util.concurrent.TimeUnit + +class DiningHallListWidget : AppWidgetProvider() { + override fun onUpdate( + context: Context?, + appWidgetManager: AppWidgetManager?, + appWidgetIds: IntArray? + ) { + super.onUpdate(context, appWidgetManager, appWidgetIds) + } + + override fun onEnabled(context: Context?) { + super.onEnabled(context) + } + + override fun onDisabled(context: Context?) { + super.onDisabled(context) + } + + companion object { + private var mDiningRequest : DiningRequest? = null; + val ACTION_AUTO_UPDATE = "AUTO_UPDATE" + + @JvmStatic + val diningRequestInstance : DiningRequest + get() { + if (mDiningRequest == null) { + val gsonBuilder = GsonBuilder() + + gsonBuilder.registerTypeAdapter( + object : TypeToken?>() {}.type, + Serializer.VenueSerializer() + ) + + val gson = gsonBuilder.create() + val okHttpClient = OkHttpClient() + okHttpClient.setConnectTimeout(35, TimeUnit.SECONDS) + okHttpClient.setReadTimeout(35, TimeUnit.SECONDS) + okHttpClient.setWriteTimeout(35, TimeUnit.SECONDS) + + val restAdapter = + RestAdapter.Builder() + .setConverter(GsonConverter(gson)) + .setClient(OkClient(okHttpClient)) + .setEndpoint("https://pennmobile.org/api") + .build() + mDiningRequest = restAdapter.create(DiningRequest::class.java) + } + return mDiningRequest!! + } + } + +} \ No newline at end of file diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningSettingsFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningSettingsFragment.kt index 404a4b25..9c91611e 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningSettingsFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningSettingsFragment.kt @@ -92,25 +92,30 @@ class DiningSettingsFragment(dataModel: HomepageDataModel) : Fragment() { private fun getDiningHalls() { // Map each item in the list of venues to a Venue Observable, then map each Venue to a DiningHall Observable originalPreferences = dataModel.getDiningHallPrefs() - mStudentLife.venues() - .flatMap { venues -> Observable.from(venues) } - .flatMap { venue -> - val hall = DiningFragment.createHall(venue) - Observable.just(hall) - } - .toList() - .subscribe({ diningHalls -> - mActivity.runOnUiThread { - halls = diningHalls - try { - binding.diningHallRv.adapter = DiningSettingsAdapter(diningHalls) - } catch (e: Exception) { - FirebaseCrashlytics.getInstance().recordException(e) - } + try { + mStudentLife.venues() + .flatMap { venues -> Observable.from(venues) } + .flatMap { venue -> + val hall = DiningFragment.createHall(venue) + Observable.just(hall) } - }, { - Log.e("DiningSettings", "error fetching dining halls") - }) + .toList() + .subscribe({ diningHalls -> + mActivity.runOnUiThread { + halls = diningHalls + try { + binding.diningHallRv.adapter = DiningSettingsAdapter(diningHalls) + } catch (e: Exception) { + FirebaseCrashlytics.getInstance().recordException(e) + } + } + }, { + Log.e("DiningSettings", "error fetching dining halls") + }) + } catch (e: Exception) { + e.printStackTrace() + } + } override fun onDestroyView() { @@ -146,25 +151,29 @@ class DiningSettingsFragment(dataModel: HomepageDataModel) : Fragment() { mActivity.mNetworkManager.getAccessToken { val bearerToken = "Bearer " + sp.getString(getString(R.string.access_token), "").toString() - mStudentLife.sendDiningPref( - bearerToken, - DiningRequest(favoriteDiningHalls), - object : ResponseCallback() { - override fun success(response: Response) { - Log.i("Dining", "Dining preferences saved") - mActivity.onBackPressed() - } - - override fun failure(error: RetrofitError) { - Log.e("Dining", "Error saving dining preferences: $error") - Toast.makeText( - mActivity, - "Error saving dining preferences", - Toast.LENGTH_SHORT, - ).show() - } - }, - ) + try { + mStudentLife.sendDiningPref( + bearerToken, + DiningRequest(favoriteDiningHalls), + object : ResponseCallback() { + override fun success(response: Response) { + Log.i("Dining", "Dining preferences saved") + mActivity.onBackPressed() + } + + override fun failure(error: RetrofitError) { + Log.e("Dining", "Error saving dining preferences: $error") + Toast.makeText( + mActivity, + "Error saving dining preferences", + Toast.LENGTH_SHORT, + ).show() + } + }, + ) + } catch (e : Exception) { + e.printStackTrace() + } } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/FlingFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/FlingFragment.kt index 802f8741..126af103 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/FlingFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/FlingFragment.kt @@ -61,12 +61,16 @@ class FlingFragment : Fragment() { _binding = FragmentFlingBinding.inflate(inflater, container, false) val view = binding.root val labs = MainActivity.studentLifeInstance - labs.flingEvents.subscribe({ flingEvents -> - activity?.runOnUiThread { - binding.flingFragmentRecyclerview.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) - binding.flingFragmentRecyclerview.adapter = FlingRecyclerViewAdapter(context, flingEvents) - } - }, { activity?.runOnUiThread { Toast.makeText(activity, "Could not retrieve Spring Fling schedule", Toast.LENGTH_LONG).show() } }) + try { + labs.flingEvents.subscribe({ flingEvents -> + activity?.runOnUiThread { + binding.flingFragmentRecyclerview.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) + binding.flingFragmentRecyclerview.adapter = FlingRecyclerViewAdapter(context, flingEvents) + } + }, { activity?.runOnUiThread { Toast.makeText(activity, "Could not retrieve Spring Fling schedule", Toast.LENGTH_LONG).show() } }) + } catch (e: Exception) { + e.printStackTrace() + } return view } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrFragment.kt index cf0a2460..b67beb0c 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrFragment.kt @@ -231,18 +231,22 @@ class GsrFragment : Fragment() { if (bearerToken.isEmpty()) { Toast.makeText(activity, "You are not logged in!", Toast.LENGTH_LONG).show() } else { - mStudentLife.isWharton( - "Bearer $bearerToken", - ) - ?.subscribe( - { status -> - isWharton = status.isWharton - }, - { - Log.e("GsrFragment", "Error getting Wharton status", it) - isWharton = false - }, + try { + mStudentLife.isWharton( + "Bearer $bearerToken", ) + ?.subscribe( + { status -> + isWharton = status.isWharton + }, + { + Log.e("GsrFragment", "Error getting Wharton status", it) + isWharton = false + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } } @@ -313,82 +317,86 @@ class GsrFragment : Fragment() { Log.i("GsrFragment", "Bearer Token: $bearerToken") Log.i("GsrFragment", "Wharton Status: $isWharton") - mStudentLife.gsrRoom( - "Bearer $bearerToken", - location, - gId, - adjustedDateString, - ) - ?.subscribe( - { gsr -> - activity?.let { activity -> - activity.runOnUiThread { - val gsrRooms = gsr.rooms - var timeSlotLengthZero = true - - if (gsrRooms == null) { - // a certification error causes "room" field to remain null - showNoResults() - } else { - for (i in gsrRooms.indices) { - val gsrRoom = gsrRooms[i] - val gsrTimeSlots = gsrRoom.slots - // checks if the time slots are ever nonzero - val size = gsrTimeSlots?.size ?: 0 - if (size > 0) { - timeSlotLengthZero = false - } - if (gsrTimeSlots != null) { - filterInsertTimeSlots(gsrRoom, gsrTimeSlots, gId) + try { + mStudentLife.gsrRoom( + "Bearer $bearerToken", + location, + gId, + adjustedDateString, + ) + ?.subscribe( + { gsr -> + activity?.let { activity -> + activity.runOnUiThread { + val gsrRooms = gsr.rooms + var timeSlotLengthZero = true + + if (gsrRooms == null) { + // a certification error causes "room" field to remain null + showNoResults() + } else { + for (i in gsrRooms.indices) { + val gsrRoom = gsrRooms[i] + val gsrTimeSlots = gsrRoom.slots + // checks if the time slots are ever nonzero + val size = gsrTimeSlots?.size ?: 0 + if (size > 0) { + timeSlotLengthZero = false + } + if (gsrTimeSlots != null) { + filterInsertTimeSlots(gsrRoom, gsrTimeSlots, gId) + } } } - } - // remove loading icon - loadingPanel.visibility = View.GONE - noResultsPanel.visibility = View.GONE - // stop refreshing - binding.gsrRoomsList.visibility = View.VISIBLE - binding.gsrRefreshLayout.isRefreshing = false - - if (timeSlotLengthZero) { - binding.gsrNoRooms.visibility = View.VISIBLE - } - - binding.gsrRoomsList.adapter = ( - context?.let { - GsrBuildingAdapter( - it, - mGSRS, - location, - (durationDropDown.selectedItemPosition + 1) * 30, - sortByTime, - ) + // remove loading icon + loadingPanel.visibility = View.GONE + noResultsPanel.visibility = View.GONE + // stop refreshing + binding.gsrRoomsList.visibility = View.VISIBLE + binding.gsrRefreshLayout.isRefreshing = false + + if (timeSlotLengthZero) { + binding.gsrNoRooms.visibility = View.VISIBLE } - ) - mGSRS = ArrayList() - selectDateButton.isClickable = true - selectTimeButton.isClickable = true - gsrLocationDropDown.isEnabled = true - durationDropDown.isEnabled = true - sortingSwitch.isClickable = true + binding.gsrRoomsList.adapter = ( + context?.let { + GsrBuildingAdapter( + it, + mGSRS, + location, + (durationDropDown.selectedItemPosition + 1) * 30, + sortByTime, + ) + } + ) + + mGSRS = ArrayList() + selectDateButton.isClickable = true + selectTimeButton.isClickable = true + gsrLocationDropDown.isEnabled = true + durationDropDown.isEnabled = true + sortingSwitch.isClickable = true + } } - } - }, - { - Log.e("GsrFragment", "Error getting gsr times", it) - activity?.let { activity -> - activity.runOnUiThread { - showNoResults() - selectDateButton.isClickable = true - selectTimeButton.isClickable = true - gsrLocationDropDown.isEnabled = true - durationDropDown.isEnabled = true - sortingSwitch.isClickable = true + }, + { + Log.e("GsrFragment", "Error getting gsr times", it) + activity?.let { activity -> + activity.runOnUiThread { + showNoResults() + selectDateButton.isClickable = true + selectTimeButton.isClickable = true + gsrLocationDropDown.isEnabled = true + durationDropDown.isEnabled = true + sortingSwitch.isClickable = true + } } - } - }, - ) + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } @@ -450,95 +458,99 @@ class GsrFragment : Fragment() { } private fun populateDropDownGSR() { - mStudentLife.location() - ?.subscribe( - { locations -> - activity?.let { activity -> - populatedDropDownGSR = true - activity.runOnUiThread { - // reset the drop down - val emptyArray = arrayOfNulls(0) - val emptyAdapter = - ArrayAdapter( - activity, - android.R.layout.simple_spinner_dropdown_item, - emptyArray, - ) - gsrLocationDropDown.adapter = emptyAdapter - - val numLocations = locations.size - var i = 0 - // go through all the rooms - while (i < numLocations) { - val locationName = locations[i]?.name ?: "" - if (locationName.isEmpty()) { - Log.w( - "Empty location name", - locations[i].id ?: locations[i].gid.toString(), + try { + mStudentLife.location() + ?.subscribe( + { locations -> + activity?.let { activity -> + populatedDropDownGSR = true + activity.runOnUiThread { + // reset the drop down + val emptyArray = arrayOfNulls(0) + val emptyAdapter = + ArrayAdapter( + activity, + android.R.layout.simple_spinner_dropdown_item, + emptyArray, ) + gsrLocationDropDown.adapter = emptyAdapter + + val numLocations = locations.size + var i = 0 + // go through all the rooms + while (i < numLocations) { + val locationName = locations[i]?.name ?: "" + if (locationName.isEmpty()) { + Log.w( + "Empty location name", + locations[i].id ?: locations[i].gid.toString(), + ) + } + gsrHashMap[locationName] = locations[i].id + gsrGIDHashMap[locationName] = locations[i].gid + i++ } - gsrHashMap[locationName] = locations[i].id - gsrGIDHashMap[locationName] = locations[i].gid - i++ - } - val gsrs = gsrHashMap.keys.toList().toTypedArray() + val gsrs = gsrHashMap.keys.toList().toTypedArray() - val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs) - gsrLocationDropDown.adapter = adapter + val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs) + gsrLocationDropDown.adapter = adapter - durationDropDown.adapter = - if (gsrLocationDropDown.selectedItem.toString() == "Huntsman" || - gsrLocationDropDown.selectedItem.toString() == "Academic Research" - ) { - whartonDurationAdapter - } else if (gsrLocationDropDown.selectedItem.toString() == "Biomedical") { - biotechDurationAdapter - } else { - durationAdapter - } - searchForGSR(false) + durationDropDown.adapter = + if (gsrLocationDropDown.selectedItem.toString() == "Huntsman" || + gsrLocationDropDown.selectedItem.toString() == "Academic Research" + ) { + whartonDurationAdapter + } else if (gsrLocationDropDown.selectedItem.toString() == "Biomedical") { + biotechDurationAdapter + } else { + durationAdapter + } + searchForGSR(false) + } } - } - }, - { - Log.e("Gsr Fragment", "Error getting gsr locations", it) - activity?.let { activity -> - activity.runOnUiThread { - // hard coded in case runs into error - gsrHashMap["VP Ground Floor"] = "1086" - gsrHashMap["Weigle"] = "1086" - gsrHashMap["Lippincott"] = "2587" - gsrHashMap["Edu Commons"] = "2495" - gsrHashMap["Biotech Commons"] = "2683" - gsrHashMap["Fisher"] = "2637" - gsrHashMap["Levin Building"] = "1090" - gsrHashMap["Museum Library"] = "2634" - gsrHashMap["VP Seminar"] = "2636" - gsrHashMap["VP Special Use"] = "2611" - gsrHashMap["Huntsman Hall"] = "JMHH" - gsrHashMap["Academic Research"] = "ARB" - gsrHashMap["PCPSE Building"] = "4370" - gsrGIDHashMap["PCPSE Building"] = 7426 - val gsrs = gsrHashMap.keys.toList().toTypedArray() - val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs) - gsrLocationDropDown.adapter = adapter - - durationDropDown.adapter = - if (gsrLocationDropDown.selectedItem.toString() == "Huntsman" || - gsrLocationDropDown.selectedItem.toString() == "Academic Research" - ) { - whartonDurationAdapter - } else if (gsrLocationDropDown.selectedItem.toString() == "Biotech Commons") { - biotechDurationAdapter - } else { - durationAdapter - } - searchForGSR(false) + }, + { + Log.e("Gsr Fragment", "Error getting gsr locations", it) + activity?.let { activity -> + activity.runOnUiThread { + // hard coded in case runs into error + gsrHashMap["VP Ground Floor"] = "1086" + gsrHashMap["Weigle"] = "1086" + gsrHashMap["Lippincott"] = "2587" + gsrHashMap["Edu Commons"] = "2495" + gsrHashMap["Biotech Commons"] = "2683" + gsrHashMap["Fisher"] = "2637" + gsrHashMap["Levin Building"] = "1090" + gsrHashMap["Museum Library"] = "2634" + gsrHashMap["VP Seminar"] = "2636" + gsrHashMap["VP Special Use"] = "2611" + gsrHashMap["Huntsman Hall"] = "JMHH" + gsrHashMap["Academic Research"] = "ARB" + gsrHashMap["PCPSE Building"] = "4370" + gsrGIDHashMap["PCPSE Building"] = 7426 + val gsrs = gsrHashMap.keys.toList().toTypedArray() + val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs) + gsrLocationDropDown.adapter = adapter + + durationDropDown.adapter = + if (gsrLocationDropDown.selectedItem.toString() == "Huntsman" || + gsrLocationDropDown.selectedItem.toString() == "Academic Research" + ) { + whartonDurationAdapter + } else if (gsrLocationDropDown.selectedItem.toString() == "Biotech Commons") { + biotechDurationAdapter + } else { + durationAdapter + } + searchForGSR(false) + } } - } - }, - ) + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } gsrLocationDropDown.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( @@ -550,9 +562,9 @@ class GsrFragment : Fragment() { // change possible durations depending on the location var durationPos = durationDropDown.selectedItemPosition if (durationPos >= 3 && ( - gsrLocationDropDown.selectedItem.toString() == "Huntsman" || - gsrLocationDropDown.selectedItem.toString() == "Academic Research" - ) + gsrLocationDropDown.selectedItem.toString() == "Huntsman" || + gsrLocationDropDown.selectedItem.toString() == "Academic Research" + ) ) { durationPos = 2 } else if (durationPos > 3 && gsrLocationDropDown.selectedItem.toString() != "Biotech Commons") { diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrReservationsFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrReservationsFragment.kt index b7a8e5b3..a65a597d 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrReservationsFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrReservationsFragment.kt @@ -98,37 +98,41 @@ class GsrReservationsFragment : Fragment() { val sessionID = sp.getString(getString(R.string.huntsmanGSR_SessionID), "") val email = sp.getString(getString(R.string.email_address), "") val token = sp.getString(getString(R.string.access_token), "") - labs.getGsrReservations("Bearer $token").subscribe({ reservations -> - mActivity.runOnUiThread { - loadingPanel?.visibility = View.GONE - - try { - binding.gsrReservationsRv.adapter = GsrReservationsAdapter(ArrayList(reservations)) - if (reservations.size > 0) { - binding.gsrNoReservations.visibility = View.GONE - } else { - binding.gsrNoReservations.visibility = View.VISIBLE + try { + labs.getGsrReservations("Bearer $token").subscribe({ reservations -> + mActivity.runOnUiThread { + loadingPanel?.visibility = View.GONE + + try { + binding.gsrReservationsRv.adapter = GsrReservationsAdapter(ArrayList(reservations)) + if (reservations.size > 0) { + binding.gsrNoReservations.visibility = View.GONE + } else { + binding.gsrNoReservations.visibility = View.VISIBLE + } + // stop refreshing + binding.gsrReservationsRefreshLayout.isRefreshing = false + } catch (e: Exception) { + FirebaseCrashlytics.getInstance().recordException(e) } - // stop refreshing - binding.gsrReservationsRefreshLayout.isRefreshing = false - } catch (e: Exception) { - FirebaseCrashlytics.getInstance().recordException(e) } - } - }, { throwable -> - mActivity.runOnUiThread { - Log.e("GsrReservationsFragment", "Error getting reservations", throwable) - throwable.printStackTrace() - loadingPanel?.visibility = View.GONE - try { - binding.gsrReservationsRv.adapter = GsrReservationsAdapter(ArrayList()) - binding.gsrNoReservations.visibility = View.VISIBLE - binding.gsrReservationsRefreshLayout.isRefreshing = false - } catch (e: Exception) { - FirebaseCrashlytics.getInstance().recordException(e) + }, { throwable -> + mActivity.runOnUiThread { + Log.e("GsrReservationsFragment", "Error getting reservations", throwable) + throwable.printStackTrace() + loadingPanel?.visibility = View.GONE + try { + binding.gsrReservationsRv.adapter = GsrReservationsAdapter(ArrayList()) + binding.gsrNoReservations.visibility = View.VISIBLE + binding.gsrReservationsRefreshLayout.isRefreshing = false + } catch (e: Exception) { + FirebaseCrashlytics.getInstance().recordException(e) + } } - } - }) + }) + } catch (e: Exception) { + e.printStackTrace() + } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/HuntsmanGSRLogin.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/HuntsmanGSRLogin.kt index 0427a09d..e8340b15 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/HuntsmanGSRLogin.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/HuntsmanGSRLogin.kt @@ -122,60 +122,64 @@ class HuntsmanGSRLogin : Fragment() { sessionID: String, ) { (activity as MainActivity).mNetworkManager.getAccessToken { - mStudentLife.bookGSR( - // Passing the values - bearerToken, - startTime, - endTime, - gid, - Integer.parseInt(gsrID), - roomName, - // Creating an anonymous callback - object : Callback { - override fun success( - result: GSRBookingResult?, - response: Response?, - ) { - // Display the output as a toast - if (result?.getResults() == true) { - Toast.makeText(mActivity, "GSR successfully booked", Toast.LENGTH_LONG) - .show() - } else { - Log.e("HuntsmanGSRLogin", "GSR booking failed: " + result?.getError()) - Toast.makeText(mActivity, "GSR booking failed", Toast.LENGTH_LONG) - .show() + try { + mStudentLife.bookGSR( + // Passing the values + bearerToken, + startTime, + endTime, + gid, + Integer.parseInt(gsrID), + roomName, + // Creating an anonymous callback + object : Callback { + override fun success( + result: GSRBookingResult?, + response: Response?, + ) { + // Display the output as a toast + if (result?.getResults() == true) { + Toast.makeText(mActivity, "GSR successfully booked", Toast.LENGTH_LONG) + .show() + } else { + Log.e("HuntsmanGSRLogin", "GSR booking failed: " + result?.getError()) + Toast.makeText(mActivity, "GSR booking failed", Toast.LENGTH_LONG) + .show() + val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) + val editor = sp.edit() + editor.remove(getString(R.string.huntsmanGSR_SessionID)) + editor.apply() + } + // redirect user + val gsrFragment = GsrTabbedFragment() + val fragmentManager = mActivity.supportFragmentManager + fragmentManager.beginTransaction() + .replace(R.id.content_frame, gsrFragment) + .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) + .commit() + } + + override fun failure(error: RetrofitError?) { + // If any error occurred display the error as toast + Log.e("HuntsmanGSRLogin", "GSR booking failed" + error.toString()) + Toast.makeText(mActivity, "GSR booking failed", Toast.LENGTH_LONG).show() val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) val editor = sp.edit() editor.remove(getString(R.string.huntsmanGSR_SessionID)) editor.apply() + // redirect user + val gsrFragment = GsrTabbedFragment() + val fragmentManager = mActivity.supportFragmentManager + fragmentManager.beginTransaction() + .replace(R.id.content_frame, gsrFragment) + .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) + .commit() } - // redirect user - val gsrFragment = GsrTabbedFragment() - val fragmentManager = mActivity.supportFragmentManager - fragmentManager.beginTransaction() - .replace(R.id.content_frame, gsrFragment) - .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) - .commit() - } - - override fun failure(error: RetrofitError?) { - // If any error occurred display the error as toast - Log.e("HuntsmanGSRLogin", "GSR booking failed" + error.toString()) - Toast.makeText(mActivity, "GSR booking failed", Toast.LENGTH_LONG).show() - val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) - val editor = sp.edit() - editor.remove(getString(R.string.huntsmanGSR_SessionID)) - editor.apply() - // redirect user - val gsrFragment = GsrTabbedFragment() - val fragmentManager = mActivity.supportFragmentManager - fragmentManager.beginTransaction() - .replace(R.id.content_frame, gsrFragment) - .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) - .commit() - } - }, - ) + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/LoginWebviewFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/LoginWebviewFragment.kt index 8c0fdd7f..8686cb58 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/LoginWebviewFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/LoginWebviewFragment.kt @@ -218,40 +218,44 @@ class LoginWebviewFragment : Fragment() { } private fun getUser(accessToken: String?) { - mPlatform?.getUser( - "Bearer $accessToken", - accessToken, - object : Callback { - override fun success( - t: GetUserResponse?, - response: Response?, - ) { - val user = t?.user - val editor = sp.edit() - editor.putString(getString(R.string.first_name), user?.firstName) - editor.putString(getString(R.string.last_name), user?.lastName) - var initials = "" - try { - initials = initials + user?.firstName?.first() + user?.lastName?.first() - initials.capitalize() - } catch (ignored: Exception) { + try { + mPlatform?.getUser( + "Bearer $accessToken", + accessToken, + object : Callback { + override fun success( + t: GetUserResponse?, + response: Response?, + ) { + val user = t?.user + val editor = sp.edit() + editor.putString(getString(R.string.first_name), user?.firstName) + editor.putString(getString(R.string.last_name), user?.lastName) + var initials = "" + try { + initials = initials + user?.firstName?.first() + user?.lastName?.first() + initials.capitalize() + } catch (ignored: Exception) { + } + editor.putString(getString(R.string.initials), initials) + editor.putString(getString(R.string.email_address), user?.email) + editor.putString(getString(R.string.pennkey), user?.username) + editor.apply() + mActivity.startHomeFragment() + // saveAccount(Account(user?.firstName, user?.lastName, + // user?.username, user?.pennid, user?.email, user?.affiliation), user?.username.toString(), accessToken) } - editor.putString(getString(R.string.initials), initials) - editor.putString(getString(R.string.email_address), user?.email) - editor.putString(getString(R.string.pennkey), user?.username) - editor.apply() - mActivity.startHomeFragment() - // saveAccount(Account(user?.firstName, user?.lastName, - // user?.username, user?.pennid, user?.email, user?.affiliation), user?.username.toString(), accessToken) - } - override fun failure(error: RetrofitError) { - Log.e("Accounts", "Error getting user $error") - Toast.makeText(mActivity, "Error logging in", Toast.LENGTH_SHORT).show() - mActivity.startLoginFragment() - } - }, - ) + override fun failure(error: RetrofitError) { + Log.e("Accounts", "Error getting user $error") + Toast.makeText(mActivity, "Error logging in", Toast.LENGTH_SHORT).show() + mActivity.startLoginFragment() + } + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } private fun getCodeChallenge(codeVerifier: String): String { diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/PottruckFragment.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/PottruckFragment.kt index 6a52518e..6bcfe29f 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/PottruckFragment.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/PottruckFragment.kt @@ -91,54 +91,58 @@ class PottruckFragment : Fragment() { // displays banner if not connected if (!getConnected()) return - mStudentLife.fitnessRooms - .subscribe({ fitnessRooms -> - for (room in fitnessRooms) { - Log.i("Fitness Room${room.roomId}", "${room.roomName}") - } - val sortedRooms = fitnessRooms.sortedBy { it.roomName } - - dataModel = FitnessPreferenceViewModel(mStudentLife, sortedRooms) - - mActivity.runOnUiThread { - mActivity.mNetworkManager.getAccessToken { - val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) - val context = mActivity.applicationContext - val bearerToken = - "Bearer " + - sp.getString(context.getString(R.string.access_token), "") - .toString() - - mStudentLife.getFitnessPreferences(bearerToken).subscribe({ favorites -> - mActivity.runOnUiThread { - for (roomId in favorites) { - dataModel.addId(roomId) + try { + mStudentLife.fitnessRooms + .subscribe({ fitnessRooms -> + for (room in fitnessRooms) { + Log.i("Fitness Room${room.roomId}", "${room.roomName}") + } + val sortedRooms = fitnessRooms.sortedBy { it.roomName } + + dataModel = FitnessPreferenceViewModel(mStudentLife, sortedRooms) + + mActivity.runOnUiThread { + mActivity.mNetworkManager.getAccessToken { + val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) + val context = mActivity.applicationContext + val bearerToken = + "Bearer " + + sp.getString(context.getString(R.string.access_token), "") + .toString() + + mStudentLife.getFitnessPreferences(bearerToken).subscribe({ favorites -> + mActivity.runOnUiThread { + for (roomId in favorites) { + dataModel.addId(roomId) + } + dataModel.updatePositionMap() + + setAdapters() + } + }, { throwable -> + mActivity.runOnUiThread { + // empty preferences + setAdapters() + Log.e( + "Pottruck Fragment", + "Could not load Fitness Preferences", + throwable, + ) } - dataModel.updatePositionMap() - - setAdapters() - } - }, { throwable -> - mActivity.runOnUiThread { - // empty preferences - setAdapters() - Log.e( - "Pottruck Fragment", - "Could not load Fitness Preferences", - throwable, - ) - } - }) + }) + } } - } - }, { - Log.e("PottruckFragment", "Error getting fitness rooms", it) - mActivity.runOnUiThread { - Log.e("Fitness", "Could not load Pottruck page", it) - loadingPanel.visibility = View.GONE - swipeRefresh.isRefreshing = false - } - }) + }, { + Log.e("PottruckFragment", "Error getting fitness rooms", it) + mActivity.runOnUiThread { + Log.e("Fitness", "Could not load Pottruck page", it) + loadingPanel.visibility = View.GONE + swipeRefresh.isRefreshing = false + } + }) + } catch (e: Exception) { + e.printStackTrace() + } } private fun setAdapters() { diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningAdapter.kt index 7e50274b..ce403754 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningAdapter.kt @@ -83,17 +83,21 @@ class DiningAdapter(private var diningHalls: List) : RecyclerView.Ad // Load the menu for each dining hall if (diningHall.isResidential && !loaded[position]) { holder.progressBar?.visibility = View.VISIBLE - mStudentLife.daily_menu(diningHall.id) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ newDiningHall -> - diningHall.sortMeals(newDiningHall.menus) - holder.progressBar?.visibility = View.INVISIBLE - holder.menuArrow?.visibility = View.VISIBLE - loaded[position] = true - }, { - holder.progressBar?.visibility = View.VISIBLE - holder.menuArrow?.visibility = View.GONE - }) + try { + mStudentLife.daily_menu(diningHall.id) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ newDiningHall -> + diningHall.sortMeals(newDiningHall.menus) + holder.progressBar?.visibility = View.INVISIBLE + holder.menuArrow?.visibility = View.VISIBLE + loaded[position] = true + }, { + holder.progressBar?.visibility = View.VISIBLE + holder.menuArrow?.visibility = View.GONE + }) + } catch (e: Exception) { + e.printStackTrace() + } } else { holder.progressBar?.visibility = View.GONE holder.menuArrow?.visibility = View.VISIBLE diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningCardAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningCardAdapter.kt index ab045c12..9f1b43cd 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningCardAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningCardAdapter.kt @@ -63,14 +63,18 @@ class DiningCardAdapter(halls: ArrayList) : RecyclerView.Adapter - currentHall.sortMeals(newDiningHall.menus) - }, { - Log.e("DiningCard", "Error loading menus", it) - Toast.makeText(mContext, "Error loading menus", Toast.LENGTH_SHORT).show() - }) + try { + mStudentLife.daily_menu(currentHall.id) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ newDiningHall -> + currentHall.sortMeals(newDiningHall.menus) + }, { + Log.e("DiningCard", "Error loading menus", it) + Toast.makeText(mContext, "Error loading menus", Toast.LENGTH_SHORT).show() + }) + } catch (e: Exception) { + e.printStackTrace() + } } holder.itemView.setOnClickListener { diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallListWidgetAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallListWidgetAdapter.kt new file mode 100644 index 00000000..bdfc1399 --- /dev/null +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallListWidgetAdapter.kt @@ -0,0 +1,212 @@ +package com.pennapps.labs.pennmobile.adapters + +import android.content.Context +import android.content.Intent +import android.widget.RemoteViews +import android.widget.RemoteViewsService +import com.pennapps.labs.pennmobile.R +import com.pennapps.labs.pennmobile.classes.DiningHall +import com.pennapps.labs.pennmobile.classes.Venue + +class DiningHallListWidgetAdapter : RemoteViewsService() { + override fun onGetViewFactory(p0: Intent?): RemoteViewsFactory { + TODO("Not yet implemented") + } + + class DiningWidgetFactory(private val context: Context, intent: Intent) : RemoteViewsFactory { + override fun onCreate() { + TODO("Not yet implemented") + } + + override fun onDataSetChanged() { + } + + override fun onDestroy() { + } + + override fun getCount(): Int { + TODO("Not yet implemented") + } + + override fun getViewAt(p0: Int): RemoteViews { + TODO("Not yet implemented") + } + + override fun getLoadingView(): RemoteViews? { + return null + } + + override fun getViewTypeCount(): Int { + return 1 + } + + override fun getItemId(position: Int): Long { + return position.toLong() + } + + override fun hasStableIds(): Boolean { + return true + } + + companion object { + fun createHall(venue: Venue): DiningHall { + when (venue.id) { + 593 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_commons, + ) + + 636 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_hill_house, + ) + + 637 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_kceh, + ) + + 638 -> return DiningHall( + venue.id, + "Falk Kosher\nDining", + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_hillel, + ) + + 639 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_houston, + ) + + 640 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_marks, + ) + + 641 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_accenture, + ) + + 642 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_joes_cafe, + ) + + 1442 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_nch, + ) + + 747 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_mcclelland, + ) + + 1057 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_gourmet_grocer, + ) + + 1058 -> return DiningHall( + venue.id, + "Tortas Frontera", + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_tortas, + ) + + 1163 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_commons, + ) + + 1731 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_nch, + ) + + 1732 -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_mba_cafe, + ) + + 1733 -> return DiningHall( + venue.id, + "Pret a Manger Locust", + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_pret_a_manger, + ) + + else -> return DiningHall( + venue.id, + venue.name, + venue.isResidential, + venue.getHours(), + venue, + R.drawable.dining_commons, + ) + } + } + } + + + } +} \ No newline at end of file diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallWidgetAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallWidgetAdapter.kt index 4691b489..a7911a00 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallWidgetAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningHallWidgetAdapter.kt @@ -114,20 +114,24 @@ class DiningHallWidgetAdapter : RemoteViewsService() { } private fun getWidgetDiningHalls() { - if (mDiningRequest != null) { - mDiningRequest!!.venues() - .flatMap { venues -> Observable.from(venues) } - .flatMap { venue -> - val hall = createHall(venue) - Observable.just(hall) - } - .toList() - .subscribe { diningHalls -> - dataSet = diningHalls - val appWidgetManager: AppWidgetManager = - AppWidgetManager.getInstance(context) - appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.stackview) - } + try { + if (mDiningRequest != null) { + mDiningRequest!!.venues() + .flatMap { venues -> Observable.from(venues) } + .flatMap { venue -> + val hall = createHall(venue) + Observable.just(hall) + } + .toList() + .subscribe { diningHalls -> + dataSet = diningHalls + val appWidgetManager: AppWidgetManager = + AppWidgetManager.getInstance(context) + appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.stackview) + } + } + } catch (e: Exception) { + e.printStackTrace(); } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FitnessAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FitnessAdapter.kt index 397f5c5e..ede7f8bf 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FitnessAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FitnessAdapter.kt @@ -76,19 +76,23 @@ class FitnessAdapter(private val isFavorite: Boolean, private val dataModel: Fit ) { if (hasExtraData) return room.roomId?.let { - studentLife.getFitnessRoomUsage(it, 3, "week").subscribe( - { roomUsage -> - createBarChart(context, roomUsage) - activity.runOnUiThread { - hasExtraData = true - showExtra() - } - }, - { - Log.e("Fitness Adapter", "Error loading room usage", it) - Toast.makeText(context, "Error loading room", Toast.LENGTH_SHORT).show() - }, - ) + try { + studentLife.getFitnessRoomUsage(it, 3, "week").subscribe( + { roomUsage -> + createBarChart(context, roomUsage) + activity.runOnUiThread { + hasExtraData = true + showExtra() + } + }, + { + Log.e("Fitness Adapter", "Error loading room usage", it) + Toast.makeText(context, "Error loading room", Toast.LENGTH_SHORT).show() + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/GsrReservationsAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/GsrReservationsAdapter.kt index d010f0a7..6a6dedc0 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/GsrReservationsAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/GsrReservationsAdapter.kt @@ -85,41 +85,45 @@ class GsrReservationsAdapter(private var reservations: ArrayList val labs = MainActivity.studentLifeInstance val bearerToken = "Bearer " + sp.getString(mContext.getString(R.string.access_token), " ") - labs.cancelReservation( - bearerToken, - null, - bookingID, - sessionID, - object : ResponseCallback() { - override fun success(response: Response) { - if (reservations.size > position) { - reservations.removeAt(position) - } - run { - if (reservations.size == 0) { - var intent = Intent("refresh") - LocalBroadcastManager.getInstance(mContext) - .sendBroadcast(intent) - } else { - notifyItemRemoved(position) + try { + labs.cancelReservation( + bearerToken, + null, + bookingID, + sessionID, + object : ResponseCallback() { + override fun success(response: Response) { + if (reservations.size > position) { + reservations.removeAt(position) + } + run { + if (reservations.size == 0) { + var intent = Intent("refresh") + LocalBroadcastManager.getInstance(mContext) + .sendBroadcast(intent) + } else { + notifyItemRemoved(position) + } } } - } - - override fun failure(error: RetrofitError) { - Log.e( - "GsrReservationsAdapter", - "Error canceling gsr reservation", - error, - ) - Toast.makeText( - mContext, - "Error deleting your GSR reservation.", - LENGTH_SHORT, - ).show() - } - }, - ) + + override fun failure(error: RetrofitError) { + Log.e( + "GsrReservationsAdapter", + "Error canceling gsr reservation", + error, + ) + Toast.makeText( + mContext, + "Error deleting your GSR reservation.", + LENGTH_SHORT, + ).show() + } + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeAdapter.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeAdapter.kt index 266f5864..60f0564d 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeAdapter.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeAdapter.kt @@ -207,33 +207,36 @@ class HomeAdapter(private val dataModel: HomepageDataModel) : .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit() } - - mStudentLife.venues() - .flatMap { venues -> Observable.from(venues) } - .flatMap { venue -> - val hall = DiningFragment.createHall(venue) - Observable.just(hall) - } - .toList() - .subscribe { diningHalls -> - mActivity.runOnUiThread { - val favorites: ArrayList = arrayListOf() - val favoritesIdList: List? = cell.venues - diningHalls.forEach { - if (favoritesIdList?.contains(it.id) == true) { - favorites.add(it) + try { + mStudentLife.venues() + .flatMap { venues -> Observable.from(venues) } + .flatMap { venue -> + val hall = DiningFragment.createHall(venue) + Observable.just(hall) + } + .toList() + .subscribe { diningHalls -> + mActivity.runOnUiThread { + val favorites: ArrayList = arrayListOf() + val favoritesIdList: List? = cell.venues + diningHalls.forEach { + if (favoritesIdList?.contains(it.id) == true) { + favorites.add(it) + } } + getMenus(favorites) + holder.itemView.home_card_rv.layoutManager = + LinearLayoutManager( + mContext, + LinearLayoutManager.VERTICAL, + false, + ) + holder.itemView.home_card_rv.adapter = DiningCardAdapter(favorites) } - getMenus(favorites) - holder.itemView.home_card_rv.layoutManager = - LinearLayoutManager( - mContext, - LinearLayoutManager.VERTICAL, - false, - ) - holder.itemView.home_card_rv.adapter = DiningCardAdapter(favorites) } - } + } catch (e: Exception) { + e.printStackTrace() + } } private fun bindNewsCell( @@ -399,13 +402,17 @@ class HomeAdapter(private val dataModel: HomepageDataModel) : holder.itemView.home_card_rv.layoutParams = params - mStudentLife.room(roomID).subscribe({ room -> - mActivity.runOnUiThread { - holder.itemView.home_card_title.text = room.name - val rooms = arrayListOf(room) - holder.itemView.home_card_rv.adapter = LaundryRoomAdapter(mContext, rooms, null, true) - } - }, { throwable -> mActivity.runOnUiThread { throwable.printStackTrace() } }) + try { + mStudentLife.room(roomID).subscribe({ room -> + mActivity.runOnUiThread { + holder.itemView.home_card_title.text = room.name + val rooms = arrayListOf(room) + holder.itemView.home_card_rv.adapter = LaundryRoomAdapter(mContext, rooms, null, true) + } + }, { throwable -> mActivity.runOnUiThread { throwable.printStackTrace() } }) + } catch (e: Exception) { + e.printStackTrace() + } } private fun bindPostCell( @@ -567,20 +574,25 @@ class HomeAdapter(private val dataModel: HomepageDataModel) : val sp = PreferenceManager.getDefaultSharedPreferences(mContext) val bearerToken = "Bearer " + sp.getString(mContext.getString(R.string.access_token), " ") - mStudentLife.createPollVote( - bearerToken, - idHash, - selectedOptions, - object : ResponseCallback() { - override fun success(response: Response?) { - Log.i("HomeAdapter", "Successfully voted for poll!") - } + try { + mStudentLife.createPollVote( + bearerToken, + idHash, + selectedOptions, + object : ResponseCallback() { + override fun success(response: Response?) { + Log.i("HomeAdapter", "Successfully voted for poll!") + } + + override fun failure(error: RetrofitError?) { + Log.e("HomeAdapter", "Error voting for poll", error) + } + }, + ) + } catch (e : Exception) { + e.printStackTrace() + } - override fun failure(error: RetrofitError?) { - Log.e("HomeAdapter", "Error voting for poll", error) - } - }, - ) } } } else { diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/FitnessPreferenceViewModel.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/FitnessPreferenceViewModel.kt index aaa7ce3e..1b7490de 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/FitnessPreferenceViewModel.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/FitnessPreferenceViewModel.kt @@ -99,24 +99,28 @@ class FitnessPreferenceViewModel( val bearerToken = "Bearer " + sp.getString(context.getString(R.string.access_token), "").toString() - studentLife.sendFitnessPref( - bearerToken, - FitnessRequest(ArrayList(favoriteRooms)), - object : ResponseCallback() { - override fun success(response: Response) { - Log.i("Fitness Preference View Model", "fitness preferences saved") - } - - override fun failure(error: RetrofitError) { - Log.e( - "Fitness Preference View Model", - "Error saving fitness " + - "preferences: $error", - error, - ) - } - }, - ) + try { + studentLife.sendFitnessPref( + bearerToken, + FitnessRequest(ArrayList(favoriteRooms)), + object : ResponseCallback() { + override fun success(response: Response) { + Log.i("Fitness Preference View Model", "fitness preferences saved") + } + + override fun failure(error: RetrofitError) { + Log.e( + "Fitness Preference View Model", + "Error saving fitness " + + "preferences: $error", + error, + ) + } + }, + ) + } catch (e: Exception) { + e.printStackTrace() + } } } } diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/HomepageViewModel.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/HomepageViewModel.kt index e9fc1093..148a2f33 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/HomepageViewModel.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/HomepageViewModel.kt @@ -189,57 +189,69 @@ class HomepageViewModel : HomepageDataModel, ViewModel() { latch: CountDownLatch, ) { val idHash = getSha256Hash(deviceID) - studentLife.browsePolls(bearerToken, idHash).subscribe({ poll -> - if (poll.size > 0) { - val pollCell = PollCell(poll[0]) - pollCell.poll.options.forEach { pollCell.poll.totalVotes += it.voteCount } - addCell(pollCell, POLL_POS) - } + try { + studentLife.browsePolls(bearerToken, idHash).subscribe({ poll -> + if (poll.size > 0) { + val pollCell = PollCell(poll[0]) + pollCell.poll.options.forEach { pollCell.poll.totalVotes += it.voteCount } + addCell(pollCell, POLL_POS) + } - Log.i(TAG, "Loaded polls") + Log.i(TAG, "Loaded polls") - latch.countDown() - }, { throwable -> - Log.i(TAG, "Could not load polls") - throwable.printStackTrace() - latch.countDown() - }) + latch.countDown() + }, { throwable -> + Log.i(TAG, "Could not load polls") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun getNews( studentLife: StudentLife, latch: CountDownLatch, ) { - studentLife.news.subscribe({ article -> - val newsCell = NewsCell(article) - addCell(newsCell, NEWS_POS) - - Log.i(TAG, "Loaded news") - - latch.countDown() - }, { throwable -> - Log.i(TAG, "Could not load news") - throwable.printStackTrace() - latch.countDown() - }) + try { + studentLife.news.subscribe({ article -> + val newsCell = NewsCell(article) + addCell(newsCell, NEWS_POS) + + Log.i(TAG, "Loaded news") + + latch.countDown() + }, { throwable -> + Log.i(TAG, "Could not load news") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun getCalendar( studentLife: StudentLife, latch: CountDownLatch, ) { - studentLife.calendar.subscribe({ events -> - val calendarCell = CalendarCell(events) - - Log.i(TAG, "Loaded calendar") - - addCell(calendarCell, CALENDAR_POS) - latch.countDown() - }, { throwable -> - Log.i(TAG, "Could not load calendar") - throwable.printStackTrace() - latch.countDown() - }) + try { + studentLife.calendar.subscribe({ events -> + val calendarCell = CalendarCell(events) + + Log.i(TAG, "Loaded calendar") + + addCell(calendarCell, CALENDAR_POS) + latch.countDown() + }, { throwable -> + Log.i(TAG, "Could not load calendar") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun getLaundry( @@ -247,19 +259,23 @@ class HomepageViewModel : HomepageDataModel, ViewModel() { bearerToken: String, latch: CountDownLatch, ) { - studentLife.getLaundryPref(bearerToken).subscribe({ preferences -> - val laundryCell = if (preferences.isNullOrEmpty()) LaundryCell(0) else LaundryCell(preferences[0]) - - Log.i(TAG, "Loaded laundry") - - addCell(laundryCell, LAUNDRY_POS) - latch.countDown() - }, { throwable -> - setNewsBlurView(true) - Log.i(TAG, "Could not load laundry") - throwable.printStackTrace() - latch.countDown() - }) + try { + studentLife.getLaundryPref(bearerToken).subscribe({ preferences -> + val laundryCell = if (preferences.isNullOrEmpty()) LaundryCell(0) else LaundryCell(preferences[0]) + + Log.i(TAG, "Loaded laundry") + + addCell(laundryCell, LAUNDRY_POS) + latch.countDown() + }, { throwable -> + setNewsBlurView(true) + Log.i(TAG, "Could not load laundry") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun getPosts( @@ -267,24 +283,28 @@ class HomepageViewModel : HomepageDataModel, ViewModel() { bearerToken: String, latch: CountDownLatch, ) { - studentLife.validPostsList(bearerToken).subscribe({ post -> - if (post.size >= 1) { // there exists a post - val postCell = PostCell(post[0]) - - addCell(postCell, POST_POS) - } else { - setPostBlurView(true) - } + try { + studentLife.validPostsList(bearerToken).subscribe({ post -> + if (post.size >= 1) { // there exists a post + val postCell = PostCell(post[0]) + + addCell(postCell, POST_POS) + } else { + setPostBlurView(true) + } - Log.i(TAG, "Loaded posts") + Log.i(TAG, "Loaded posts") - latch.countDown() - }, { throwable -> - Log.i(TAG, "Could not load posts") - setPostBlurView(true) - throwable.printStackTrace() - latch.countDown() - }) + latch.countDown() + }, { throwable -> + Log.i(TAG, "Could not load posts") + setPostBlurView(true) + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun getDiningPrefs( @@ -292,30 +312,34 @@ class HomepageViewModel : HomepageDataModel, ViewModel() { bearerToken: String, latch: CountDownLatch, ) { - studentLife.getDiningPreferences(bearerToken).subscribe({ preferences -> - val list = preferences.preferences - val venues = mutableListOf() - if (list?.isEmpty() == true) { - venues.add(593) - venues.add(1442) - venues.add(636) - } else { - list?.forEach { - it.id?.let { it1 -> venues.add(it1) } + try { + studentLife.getDiningPreferences(bearerToken).subscribe({ preferences -> + val list = preferences.preferences + val venues = mutableListOf() + if (list?.isEmpty() == true) { + venues.add(593) + venues.add(1442) + venues.add(636) + } else { + list?.forEach { + it.id?.let { it1 -> venues.add(it1) } + } } - } - val diningCell = DiningCell(venues) - addCell(diningCell, DINING_POS) + val diningCell = DiningCell(venues) + addCell(diningCell, DINING_POS) - Log.i(TAG, "Loaded dining") + Log.i(TAG, "Loaded dining") - latch.countDown() - }, { throwable -> - Log.i(TAG, "Could not load dining") - throwable.printStackTrace() - latch.countDown() - }) + latch.countDown() + }, { throwable -> + Log.i(TAG, "Could not load dining") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e: Exception) { + e.printStackTrace() + } } private fun getGSRReservations( @@ -323,21 +347,25 @@ class HomepageViewModel : HomepageDataModel, ViewModel() { bearerToken: String, latch: CountDownLatch, ) { - studentLife.getGsrReservations(bearerToken).subscribe({ reservationsList -> - if (reservationsList.isEmpty()) { - addCell(HomeCell(), GSR_POS) - } else { - val gsrCell = GSRCell(reservationsList) - Log.i(TAG, "Loaded GSR Reservations") - addCell(gsrCell, GSR_POS) - } - latch.countDown() - }, { - throwable -> - Log.i(TAG, "Could not load GSR reservations") - throwable.printStackTrace() - latch.countDown() - }) + try { + studentLife.getGsrReservations(bearerToken).subscribe({ reservationsList -> + if (reservationsList.isEmpty()) { + addCell(HomeCell(), GSR_POS) + } else { + val gsrCell = GSRCell(reservationsList) + Log.i(TAG, "Loaded GSR Reservations") + addCell(gsrCell, GSR_POS) + } + latch.countDown() + }, { + throwable -> + Log.i(TAG, "Could not load GSR reservations") + throwable.printStackTrace() + latch.countDown() + }) + } catch (e : Exception) { + e.printStackTrace() + } } private fun setPostBlurView(status: Boolean) = diff --git a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/viewmodels/LaundryViewModel.kt b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/viewmodels/LaundryViewModel.kt index 68b78487..a5ccc55b 100644 --- a/PennMobile/src/main/java/com/pennapps/labs/pennmobile/viewmodels/LaundryViewModel.kt +++ b/PennMobile/src/main/java/com/pennapps/labs/pennmobile/viewmodels/LaundryViewModel.kt @@ -70,29 +70,37 @@ class LaundryViewModel : ViewModel() { var addUsageSuccess = false val addRoom = CoroutineScope(context).launch { - val roomResponse = studentLife.room(roomId) - addRoomSuccess = - if (roomResponse.isSuccessful) { - val room = roomResponse.body()!! - room.id = roomId - rooms.add(room) - true - } else { - Log.i("Laundry", "Failed to get room data") - false - } + try { + val roomResponse = studentLife.room(roomId) + addRoomSuccess = + if (roomResponse.isSuccessful) { + val room = roomResponse.body()!! + room.id = roomId + rooms.add(room) + true + } else { + Log.i("Laundry", "Failed to get room data") + false + } + } catch (e: Exception) { + e.printStackTrace() + } } val addUsage = CoroutineScope(context).launch { - val usageResponse = studentLife.usage(roomId) - addUsageSuccess = - if (usageResponse.isSuccessful) { - usages.add(usageResponse.body()!!) - true - } else { - Log.i("Laundry", "Failed to get usage data") - false - } + try { + val usageResponse = studentLife.usage(roomId) + addUsageSuccess = + if (usageResponse.isSuccessful) { + usages.add(usageResponse.body()!!) + true + } else { + Log.i("Laundry", "Failed to get usage data") + false + } + } catch (e: Exception) { + e.printStackTrace() + } } addRoom.join() @@ -114,17 +122,21 @@ class LaundryViewModel : ViewModel() { bearerToken: String, ) { CoroutineScope(Dispatchers.IO).launch { - val favoriteIdList: MutableList = mutableListOf() - val response = studentLife.getLaundryPref(bearerToken) - if (response.isSuccessful) { - val prefs = response.body()!!.rooms - for (room in prefs!!) { - favoriteIdList.add(room) + try { + val favoriteIdList: MutableList = mutableListOf() + val response = studentLife.getLaundryPref(bearerToken) + if (response.isSuccessful) { + val prefs = response.body()!!.rooms + for (room in prefs!!) { + favoriteIdList.add(room) + } + } else { + Log.i("Laundry", "Failed to get preferences") } - } else { - Log.i("Laundry", "Failed to get preferences") + populateFavorites(coroutineContext, studentLife, favoriteIdList) + } catch (e: Exception) { + e.printStackTrace() } - populateFavorites(coroutineContext, studentLife, favoriteIdList) } } @@ -133,51 +145,55 @@ class LaundryViewModel : ViewModel() { return } CoroutineScope(Dispatchers.IO).launch { - val roomsResponse = studentLife.laundryRooms() - if (roomsResponse.isSuccessful) { - val rooms = roomsResponse.body()!! - laundryRooms.clear() - laundryHalls.clear() - - val numRooms = rooms.size - var i = 0 - // go through all the rooms - while (i < numRooms) { - // new list for the rooms in the hall - var roomList: MutableList = ArrayList() - - // if hall name already exists, get the list of rooms and add to that - var hallName = rooms[i].location ?: "" - - if (laundryHalls.contains(hallName)) { - roomList = laundryRooms[hallName] as MutableList - laundryRooms.remove(hallName) - laundryHalls.remove(hallName) - } + try { + val roomsResponse = studentLife.laundryRooms() + if (roomsResponse.isSuccessful) { + val rooms = roomsResponse.body()!! + laundryRooms.clear() + laundryHalls.clear() + + val numRooms = rooms.size + var i = 0 + // go through all the rooms + while (i < numRooms) { + // new list for the rooms in the hall + var roomList: MutableList = ArrayList() + + // if hall name already exists, get the list of rooms and add to that + var hallName = rooms[i].location ?: "" + + if (laundryHalls.contains(hallName)) { + roomList = laundryRooms[hallName] as MutableList + laundryRooms.remove(hallName) + laundryHalls.remove(hallName) + } - while (hallName == rooms[i].location) { - roomList.add(rooms[i]) + while (hallName == rooms[i].location) { + roomList.add(rooms[i]) - i += 1 - if (i >= rooms.size) { - break + i += 1 + if (i >= rooms.size) { + break + } } - } - // name formatting for consistency - if (hallName == "Lauder College House") { - hallName = "Lauder" - } + // name formatting for consistency + if (hallName == "Lauder College House") { + hallName = "Lauder" + } - // add the hall name to the list - laundryHalls.add(hallName) - laundryRooms[hallName] = roomList + // add the hall name to the list + laundryHalls.add(hallName) + laundryRooms[hallName] = roomList + } + } else { + Log.i("Laundry", "Failed to get laundry rooms") } - } else { - Log.i("Laundry", "Failed to get laundry rooms") - } - _loadedRooms.postValue(true) + _loadedRooms.postValue(true) + } catch (e: Exception) { + e.printStackTrace() + } } } @@ -208,12 +224,16 @@ class LaundryViewModel : ViewModel() { bearerToken: String, favoriteIdList: List, ) { - val laundryRequest = LaundryRequest(favoriteIdList) - val response = studentLife.sendLaundryPref(bearerToken, laundryRequest) - if (response.isSuccessful) { - Log.i("Laundry Preferences", "Successfully updated preferences") - } else { - Log.i("Laundry Preferences", "Error updating preferences") + try { + val laundryRequest = LaundryRequest(favoriteIdList) + val response = studentLife.sendLaundryPref(bearerToken, laundryRequest) + if (response.isSuccessful) { + Log.i("Laundry Preferences", "Successfully updated preferences") + } else { + Log.i("Laundry Preferences", "Error updating preferences") + } + } catch (e: Exception) { + e.printStackTrace() } } diff --git a/PennMobile/src/main/res/layout/dining_hall_list_widget.xml b/PennMobile/src/main/res/layout/dining_hall_list_widget.xml new file mode 100644 index 00000000..68636073 --- /dev/null +++ b/PennMobile/src/main/res/layout/dining_hall_list_widget.xml @@ -0,0 +1,33 @@ + + + + + + + + + \ No newline at end of file diff --git a/PennMobile/src/main/res/layout/dining_hall_list_widget_item.xml b/PennMobile/src/main/res/layout/dining_hall_list_widget_item.xml new file mode 100644 index 00000000..77d9ef65 --- /dev/null +++ b/PennMobile/src/main/res/layout/dining_hall_list_widget_item.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/PennMobile/src/main/res/layout/home_post_card.xml b/PennMobile/src/main/res/layout/home_post_card.xml index b0b58b60..b01da118 100644 --- a/PennMobile/src/main/res/layout/home_post_card.xml +++ b/PennMobile/src/main/res/layout/home_post_card.xml @@ -23,7 +23,7 @@