From 79e79b3811d1fdb0973f05a41398b95198db1ea4 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 5 Aug 2026 20:08:17 +0200 Subject: [PATCH] feat(adapter): replace notifyDataSetChanged with DiffUtil and enhance remote control Improved UI performance by implementing DiffUtil in CollectionAdapter and SearchResultAdapter. Updated the web remote control to display starred status and provide more accurate playback state reporting. - Replaced manual notify calls with DiffUtil for efficient list updates. - Added starred status to the web UI and remote control API. - Fixed station reordering and expansion logic in CollectionAdapter. - Improved playback resume logic in PlayerService to handle idle states. - Prevented potential memory leaks by properly managing TextWatchers in ViewHolders. --- README.md | 1 - app/src/main/assets/web/index.html | 13 +- app/src/main/assets/web/script.js | 24 +- app/src/main/assets/web/style.css | 31 +- .../com/michatec/radio/AddStationFragment.kt | 9 +- app/src/main/java/com/michatec/radio/Keys.kt | 1 + .../java/com/michatec/radio/PlayerService.kt | 11 +- .../radio/collection/CollectionAdapter.kt | 270 ++++++++++-------- .../radio/dialogs/FindStationDialog.kt | 10 +- .../radio/helpers/RemoteControlServer.kt | 16 +- .../radio/search/SearchResultAdapter.kt | 48 +++- 11 files changed, 271 insertions(+), 163 deletions(-) diff --git a/README.md b/README.md index c1858e1..b46474c 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,6 @@ You can help out the radio-browser.info community by [adding the missing station When **Edit Stations** is enabled: - Press **← (Left)** on the remote to open the detailed station editing area -- Press **3** or **Back** to close the editing area **General TV** Controls: - Press **0** or **DEL** to remove the selected radio station diff --git a/app/src/main/assets/web/index.html b/app/src/main/assets/web/index.html index a71c476..443b5be 100644 --- a/app/src/main/assets/web/index.html +++ b/app/src/main/assets/web/index.html @@ -19,7 +19,10 @@
-
Loading...
+
+
Loading...
+ +
Station @@ -56,8 +59,11 @@
 {
   "isPlaying": true,
+  "playWhenReady": true,
+  "playbackState": 3,
   "currentStationUuid": "fc080549-...",
-  "metadata": "Artist - Title"
+  "metadata": "Artist - Title",
+  "starred": true
 }                   
@@ -70,7 +76,8 @@ { "uuid": "fc080549-...", "name": "Station Name", - "hasImage": true + "hasImage": true, + "starred": true } ] diff --git a/app/src/main/assets/web/script.js b/app/src/main/assets/web/script.js index 3557f5a..81f2127 100644 --- a/app/src/main/assets/web/script.js +++ b/app/src/main/assets/web/script.js @@ -39,6 +39,7 @@ async function updateStatus() { const statusEl = document.getElementById('status'); const playPauseIcon = document.getElementById('playPauseIcon'); const currentNameEl = document.getElementById('currentName'); + const currentStarEl = document.getElementById('currentStar'); const currentMetadataEl = document.getElementById('currentMetadata'); const currentImageEl = document.getElementById('currentImage'); @@ -51,11 +52,14 @@ async function updateStatus() { statusEl.innerText = t('status_error') + ': ' + data.error; } else { let statusText = data.isPlaying ? t('status_playing') : t('status_paused'); + if (data.playWhenReady && !data.isPlaying) { + statusText = "Buffering..."; + } if (data.playbackState === STATE_BUFFERING) { statusText = "Buffering..."; } statusEl.innerText = statusText; - playPauseIcon.innerText = data.isPlaying ? 'pause' : 'play_arrow'; + playPauseIcon.innerText = (data.isPlaying || data.playWhenReady) ? 'pause' : 'play_arrow'; const stationUuid = data.currentStationUuid; updateActiveStation(stationUuid); @@ -63,10 +67,12 @@ async function updateStatus() { const station = allStations.find(s => s.uuid === stationUuid); if (station) { currentNameEl.innerText = station.name; + currentStarEl.classList.toggle('hidden', !data.starred); currentMetadataEl.innerText = data.metadata || ""; currentImageEl.src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; } else { currentNameEl.innerText = data.isPlaying ? 'Unknown Station' : 'No Station Selected'; + currentStarEl.classList.add('hidden'); currentMetadataEl.innerText = ""; currentImageEl.src = 'favicon.png'; } @@ -105,6 +111,9 @@ async function loadStations() { div.className = 'station-item'; div.id = 'station-' + station.uuid; + const content = document.createElement('div'); + content.className = 'station-item-content'; + const img = document.createElement('img'); img.className = 'station-img'; if (station.hasImage) { @@ -112,13 +121,21 @@ async function loadStations() { } else { img.src = 'favicon.png'; } - div.appendChild(img); + content.appendChild(img); const name = document.createElement('div'); name.className = 'station-name'; name.innerText = station.name || 'Unnamed Station'; - div.appendChild(name); + content.appendChild(name); + if (station.starred) { + const star = document.createElement('span'); + star.className = 'material-icons starred-icon'; + star.innerText = 'star'; + content.appendChild(star); + } + + div.appendChild(content); div.onclick = () => playStation(station.uuid); list.appendChild(div); }); @@ -143,6 +160,7 @@ async function playStation(uuid) { const station = allStations.find(s => s.uuid === uuid); if (station) { document.getElementById('currentName').innerText = station.name; + document.getElementById('currentStar').classList.toggle('hidden', !station.starred); document.getElementById('currentMetadata').innerText = ""; document.getElementById('currentImage').src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; } diff --git a/app/src/main/assets/web/style.css b/app/src/main/assets/web/style.css index af1a7ec..242aa52 100644 --- a/app/src/main/assets/web/style.css +++ b/app/src/main/assets/web/style.css @@ -88,6 +88,13 @@ body.light-theme .current-station-info { margin-right: 20px; } +.current-title-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; +} + .current-name { font-size: 1.4rem; font-weight: 800; @@ -96,7 +103,6 @@ body.light-theme .current-station-info { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - margin-bottom: 4px; } .current-metadata { @@ -194,6 +200,29 @@ body.light-theme .station-item { border-color: var(--accent-color); } +.station-item-content { + position: relative; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; +} + +.starred-icon { + color: #ffca28; + text-shadow: 0 0 10px rgba(255, 202, 40, 0.4); +} + +.station-item .starred-icon { + position: absolute; + top: -8px; + right: -8px; + font-size: 24px; + background: var(--bg-color); + border-radius: 50%; +} + .station-item.active { background: var(--accent-color); color: white; diff --git a/app/src/main/java/com/michatec/radio/AddStationFragment.kt b/app/src/main/java/com/michatec/radio/AddStationFragment.kt index 13a7ebe..e57696a 100644 --- a/app/src/main/java/com/michatec/radio/AddStationFragment.kt +++ b/app/src/main/java/com/michatec/radio/AddStationFragment.kt @@ -1,6 +1,5 @@ package com.michatec.radio -import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.LayoutInflater @@ -173,22 +172,18 @@ class AddStationFragment : Fragment(), positiveButton.isEnabled = false } - @SuppressLint("NotifyDataSetChanged") override fun onRadioBrowserSearchResults(results: Array) { if (results.isNotEmpty()) { - searchResultAdapter.searchResults = results.map { it.toStation() } - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(results.map { it.toStation() }) resetLayout(false) } else { showNoResultsError() } } - @SuppressLint("NotifyDataSetChanged") override fun onDirectInputCheck(stationList: MutableList) { if (stationList.isNotEmpty()) { - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(stationList) resetLayout(false) } else { showNoResultsError() diff --git a/app/src/main/java/com/michatec/radio/Keys.kt b/app/src/main/java/com/michatec/radio/Keys.kt index e37736f..14bc11d 100644 --- a/app/src/main/java/com/michatec/radio/Keys.kt +++ b/app/src/main/java/com/michatec/radio/Keys.kt @@ -117,6 +117,7 @@ object Keys { const val HOLDER_UPDATE_PLAYBACK_STATE: Int = 2 const val HOLDER_UPDATE_DOWNLOAD_STATE: Int = 3 const val HOLDER_UPDATE_PLAYBACK_PROGRESS: Int = 4 + const val HOLDER_UPDATE_EXPANSION: Int = 5 // dialog types const val DIALOG_UPDATE_COLLECTION: Int = 1 diff --git a/app/src/main/java/com/michatec/radio/PlayerService.kt b/app/src/main/java/com/michatec/radio/PlayerService.kt index f6429b1..532697f 100644 --- a/app/src/main/java/com/michatec/radio/PlayerService.kt +++ b/app/src/main/java/com/michatec/radio/PlayerService.kt @@ -65,11 +65,19 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc onPlayStation = { uuid -> playStation(uuid) } + onGetCollection = { + collection + } onPause = { player.pause() } onResume = { - player.play() + if (player.playbackState == Player.STATE_IDLE) { + val mediaId = player.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + playStation(mediaId) + } else { + player.play() + } } onNext = { playNextStation() @@ -444,6 +452,7 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc /* Starts playback of a radio station by UUID (centralized logic) */ fun playStation(uuid: String) { + Log.i(TAG, "playStation called for UUID: $uuid") val station = CollectionHelper.getStation(collection, uuid) if (station.isValid()) { playStation(station) diff --git a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt index fee7b26..eabac24 100644 --- a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt +++ b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt @@ -1,6 +1,5 @@ package com.michatec.radio.collection -import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.text.Editable @@ -116,26 +115,30 @@ class CollectionAdapter( return } - val stationList = collection.stations - val stationCount = stationList.size + val stationCount = filteredStations.size if (fromPosition !in 0 until stationCount || toPosition !in 0 until stationCount) { return } - val fromStation = stationList[fromPosition] - val toStation = stationList[toPosition] + val fromStation = filteredStations[fromPosition] + val toStation = filteredStations[toPosition] if (fromStation.starred != toStation.starred) { // Prevent moving a starred item into non-starred area or vice versa return } - // Move within the same group (either starred or non-starred) - Collections.swap(stationList, fromPosition, toPosition) + // Move within both lists to keep them in sync + Collections.swap(collection.stations, fromPosition, toPosition) + Collections.swap(filteredStations, fromPosition, toPosition) // Update the value of expandedStationPosition if necessary - expandedStationPosition = if (fromPosition == expandedStationPosition) toPosition else expandedStationPosition + if (expandedStationUuid == fromStation.uuid) { + expandedStationPosition = toPosition + } else if (expandedStationUuid == toStation.uuid) { + expandedStationPosition = fromPosition + } // Notify the adapter about the item move notifyItemMoved(fromPosition, toPosition) @@ -168,8 +171,8 @@ class CollectionAdapter( applyFilter() } - @SuppressLint("NotifyDataSetChanged") private fun applyFilter() { + val oldStations = filteredStations.toList() filteredStations = if (currentSearchQuery.isEmpty() && !currentOnlyFavorites) { collection.stations.toMutableList() } else { @@ -179,7 +182,8 @@ class CollectionAdapter( matchesQuery && matchesFavorite }.toMutableList() } - notifyDataSetChanged() + val diffResult = DiffUtil.calculateDiff(CollectionDiffCallback(oldStations, filteredStations)) + diffResult.dispatchUpdatesTo(this) } /* Overrides onBindViewHolder */ @@ -228,37 +232,7 @@ class CollectionAdapter( stationViewHolder.reorderCheckbox.isChecked = false } - // show / hide edit views - when (expandedStationPosition) { - // show edit views - position -> { - stationViewHolder.stationNameView.isVisible = false - stationViewHolder.playButtonView.isGone = true - stationViewHolder.stationStarredView.isGone = true - stationViewHolder.editViews.isVisible = true - if (editStationStreamsEnabled) { - stationViewHolder.stationUriEditView.isVisible = true - stationViewHolder.stationUriEditView.imeOptions = - EditorInfo.IME_ACTION_DONE - } else { - stationViewHolder.stationUriEditView.isGone = true - stationViewHolder.stationNameEditView.imeOptions = - EditorInfo.IME_ACTION_DONE - } - // Allow internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS - } - // hide edit views - else -> { - stationViewHolder.stationNameView.isVisible = true - //stationViewHolder.playButtonView.isVisible = true - stationViewHolder.stationStarredView.isVisible = station.starred - stationViewHolder.editViews.isGone = true - stationViewHolder.stationUriEditView.isGone = true - // Block internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS - } - } + updateVisibility(stationViewHolder, station) } } } @@ -270,13 +244,8 @@ class CollectionAdapter( positionPriorUpdate: Int, positionAfterUpdate: Int ) { - // check if position has changed after update and move stations around if necessary - if (positionPriorUpdate != positionAfterUpdate && positionPriorUpdate != -1 && positionAfterUpdate != -1) { - notifyItemMoved(positionPriorUpdate, positionAfterUpdate) - notifyItemChanged(positionPriorUpdate) - } - // update station (e.g. name) - notifyItemChanged(positionAfterUpdate) + this.collection = collection + applyFilter() } @@ -315,14 +284,23 @@ class CollectionAdapter( station.getStreamUri(), TextView.BufferType.EDITABLE ) - stationViewHolder.stationUriEditView.addTextChangedListener(object : TextWatcher { + + // Remove existing TextWatcher to prevent leaks and redundant updates + stationViewHolder.textWatcher?.let { + stationViewHolder.stationUriEditView.removeTextChangedListener(it) + } + + val newTextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable?) { handleStationUriInput(stationViewHolder, s, station.getStreamUri()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} - }) + } + stationViewHolder.textWatcher = newTextWatcher + stationViewHolder.stationUriEditView.addTextChangedListener(newTextWatcher) + stationViewHolder.cancelButton.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -333,7 +311,6 @@ class CollectionAdapter( toggleEditViews(position, station.uuid) saveStation( station, - position, stationViewHolder.stationNameEditView.text.toString(), stationViewHolder.stationUriEditView.text.toString() ) @@ -371,37 +348,64 @@ class CollectionAdapter( /* Shows / hides the edit view for a station */ - /* TODO: Remove @SuppressLint("NotifyDataSetChanged"), remove NotifyDataSetChanged */ - @SuppressLint("NotifyDataSetChanged") private fun toggleEditViews(position: Int, stationUuid: String) { - when (stationUuid) { - // CASE: this station's edit view is already expanded - expandedStationUuid -> { - isExpandedForEdit = false - // reset currently expanded info (both uuid and position) - saveStationListExpandedState() - // update station view - notifyItemChanged(position) + if (expandedStationUuid == stationUuid) { + // CASE: this station's edit view is already expanded -> collapse it + isExpandedForEdit = false + saveStationListExpandedState() + notifyItemChanged(position, Keys.HOLDER_UPDATE_EXPANSION) + } else { + // CASE: this station's edit view is not yet expanded -> expand it + isExpandedForEdit = true + + // Collapse previously expanded station if it exists and is visible + val previousUuid = expandedStationUuid + if (previousUuid.isNotEmpty()) { + val previousPosition = filteredStations.indexOfFirst { it.uuid == previousUuid } + if (previousPosition != -1) { + notifyItemChanged(previousPosition, Keys.HOLDER_UPDATE_EXPANSION) + } } - // CASE: this station's edit view is not yet expanded - else -> { - isExpandedForEdit = true - // remember previously expanded position - val previousExpandedStationPosition: Int = expandedStationPosition - // if station was expanded - collapse it - if (previousExpandedStationPosition > -1 && previousExpandedStationPosition < collection.stations.size) - notifyItemChanged(previousExpandedStationPosition) - // store current station as the expanded one - saveStationListExpandedState(position, stationUuid) - // update station view - notifyDataSetChanged() + + // Store current station as the expanded one + saveStationListExpandedState(position, stationUuid) + // Update the newly expanded station + notifyItemChanged(position, Keys.HOLDER_UPDATE_EXPANSION) + } + } + + + /* Updates the visibility of a station's views based on its expanded state */ + private fun updateVisibility(stationViewHolder: StationViewHolder, station: Station) { + val isExpanded = expandedStationUuid == station.uuid + if (isExpanded) { + stationViewHolder.stationNameView.isVisible = false + stationViewHolder.playButtonView.isGone = true + stationViewHolder.stationStarredView.isGone = true + stationViewHolder.editViews.isVisible = true + if (editStationStreamsEnabled) { + stationViewHolder.stationUriEditView.isVisible = true + stationViewHolder.stationUriEditView.imeOptions = EditorInfo.IME_ACTION_DONE + } else { + stationViewHolder.stationUriEditView.isGone = true + stationViewHolder.stationNameEditView.imeOptions = EditorInfo.IME_ACTION_DONE } + // Allow internal focus + stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS + } else { + stationViewHolder.stationNameView.isVisible = true + stationViewHolder.stationStarredView.isVisible = station.starred + stationViewHolder.editViews.isGone = true + stationViewHolder.stationUriEditView.isGone = true + // Block internal focus + stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS } } /* Toggles the starred icon */ private fun setStarredIcon(stationViewHolder: StationViewHolder, station: Station) { + val isExpanded = expandedStationUuid == station.uuid when (station.starred) { true -> { if (station.imageColor != -1) { @@ -409,7 +413,7 @@ class CollectionAdapter( } else { stationViewHolder.stationStarredView.clearColorFilter() } - stationViewHolder.stationStarredView.isVisible = true + stationViewHolder.stationStarredView.isVisible = !isExpanded } false -> { stationViewHolder.stationStarredView.clearColorFilter() @@ -496,13 +500,6 @@ class CollectionAdapter( return@setOnKeyListener true } } - KeyEvent.KEYCODE_NUMPAD_3, KeyEvent.KEYCODE_3, KeyEvent.KEYCODE_BACK -> { - if (expandedStationPosition == stationViewHolder.bindingAdapterPosition) { - val position: Int = stationViewHolder.bindingAdapterPosition - toggleEditViews(position, station.uuid) - return@setOnKeyListener true - } - } KeyEvent.KEYCODE_NUMPAD_0, KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_DEL -> { removeStation(context, stationViewHolder.bindingAdapterPosition) return@setOnKeyListener true @@ -570,13 +567,16 @@ class CollectionAdapter( if (input == streamUri) { // enable save button stationViewHolder.saveButton.isEnabled = true + stationViewHolder.validationJob?.cancel() } else { // 1. disable save button stationViewHolder.saveButton.isEnabled = false // 2. check for valid station uri - and re-enable button - if (input.startsWith("http")) { + if (input.length > 10 && input.startsWith("http")) { + // cancel previous validation job + stationViewHolder.validationJob?.cancel() // detect content type on background thread - CoroutineScope(IO).launch { + stationViewHolder.validationJob = CoroutineScope(IO).launch { val deferred: Deferred = async(Dispatchers.Default) { NetworkHelper.detectContentTypeSuspended(input) @@ -635,6 +635,10 @@ class CollectionAdapter( Keys.HOLDER_UPDATE_DOWNLOAD_STATE -> { setDownloadProgress(holder, station) } + Keys.HOLDER_UPDATE_EXPANSION -> { + setEditViews(holder, station) + updateVisibility(holder, station) + } } } } @@ -680,16 +684,24 @@ class CollectionAdapter( /* Toggles starred status of a station */ fun toggleStarredStation(context: Context, position: Int) { val station = filteredStations[position] - val originalPosition = collection.stations.indexOfFirst { it.uuid == station.uuid } - if (originalPosition == -1) return + val originalIndex = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalIndex == -1) return - // update view (reset "swipe" state of station card) - notifyItemChanged(position) - // mark starred - collection.stations[originalPosition].apply { starred = !starred } - // sort collection + // Create a copy of the station with toggled starred status + val updatedStation = collection.stations[originalIndex].deepCopy().apply { + starred = !starred + } + + // Update master list with the new instance + collection.stations[originalIndex] = updatedStation + + // Sort collection collection = CollectionHelper.sortCollection(collection) - // save collection and broadcast changes + + // Trigger immediate UI update via DiffUtil + applyFilter() + + // Save collection and broadcast changes CollectionHelper.saveCollection(context, collection) } @@ -697,30 +709,30 @@ class CollectionAdapter( /* Saves edited station */ private fun saveStation( station: Station, - position: Int, stationName: String, streamUri: String ) { - // update station name and stream uri - collection.stations.forEach { - if (it.uuid == station.uuid) { + // update station name and stream uri in master list + val originalIndex = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalIndex != -1) { + val updatedStation = collection.stations[originalIndex].deepCopy().apply { if (stationName.isNotEmpty()) { - it.name = stationName - it.nameManuallySet = true + name = stationName + nameManuallySet = true } if (streamUri.isNotEmpty()) { - it.streamUris[0] = streamUri + streamUris[0] = streamUri } } + collection.stations[originalIndex] = updatedStation } + // sort and save collection collection = CollectionHelper.sortCollection(collection) - // update list - val newPosition: Int = CollectionHelper.getStationPosition(collection, station.uuid) - if (position != newPosition && newPosition != -1) { - notifyItemMoved(position, newPosition) - notifyItemChanged(position) - } + + // Trigger immediate UI update + applyFilter() + // save collection and broadcast changes CollectionHelper.saveCollection(context, collection) } @@ -733,19 +745,9 @@ class CollectionAdapter( /* Updates the station list - redraws the views with changed content */ - @SuppressLint("NotifyDataSetChanged") - private fun updateRecyclerView(oldCollection: Collection, newCollection: Collection) { + private fun updateRecyclerView(newCollection: Collection) { collection = newCollection applyFilter() - if (oldCollection.stations.isEmpty() && newCollection.stations.isNotEmpty()) { - // data set has been initialized - redraw the whole list - notifyDataSetChanged() - } else { - // calculate differences between current collection and new collection - and inform this adapter about the changes - val diffResult = - DiffUtil.calculateDiff(CollectionDiffCallback(oldCollection, newCollection), true) - diffResult.dispatchUpdatesTo(this@CollectionAdapter) - } } @@ -763,7 +765,7 @@ class CollectionAdapter( /* Observe view model of station collection*/ private fun observeCollectionViewModel(owner: LifecycleOwner) { collectionViewModel.collectionLiveData.observe(owner) { newCollection -> - updateRecyclerView(collection, newCollection) + updateRecyclerView(newCollection) } } @@ -829,6 +831,9 @@ class CollectionAdapter( stationCardLayout.findViewById(R.id.place_on_home_screen_button) val cancelButton: MaterialButton = stationCardLayout.findViewById(R.id.cancel_button) val saveButton: MaterialButton = stationCardLayout.findViewById(R.id.save_button) + + var textWatcher: TextWatcher? = null + var validationJob: Job? = null } /* * End of inner class @@ -839,27 +844,44 @@ class CollectionAdapter( * Inner class: DiffUtil.Callback that determines changes in data - improves list performance */ private inner class CollectionDiffCallback( - val oldCollection: Collection, - val newCollection: Collection + private val oldStations: List, + private val newStations: List ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - val oldStation: Station = oldCollection.stations[oldItemPosition] - val newStation: Station = newCollection.stations[newItemPosition] + val isOldFooter = oldItemPosition == oldStations.size + val isNewFooter = newItemPosition == newStations.size + + if (isOldFooter && isNewFooter) return true + if (isOldFooter || isNewFooter) return false + + val oldStation: Station = oldStations[oldItemPosition] + val newStation: Station = newStations[newItemPosition] return oldStation.uuid == newStation.uuid } override fun getOldListSize(): Int { - return oldCollection.stations.size + return oldStations.size + 1 } override fun getNewListSize(): Int { - return newCollection.stations.size + return newStations.size + 1 } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - val oldStation: Station = oldCollection.stations[oldItemPosition] - val newStation: Station = newCollection.stations[newItemPosition] + val isOldFooter = oldItemPosition == oldStations.size + val isNewFooter = newItemPosition == newStations.size + + if (isOldFooter && isNewFooter) return true + if (isOldFooter || isNewFooter) return false + + val oldStation: Station = oldStations[oldItemPosition] + val newStation: Station = newStations[newItemPosition] + + // Compare expanded state using UUID + val wasExpanded = oldStation.uuid == expandedStationUuid + val isExpanded = newStation.uuid == expandedStationUuid + if (wasExpanded != isExpanded) return false // compare relevant contents of a station if (oldStation.isPlaying != newStation.isPlaying) return false diff --git a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt index 271f3ee..00f7624 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt @@ -1,6 +1,5 @@ package com.michatec.radio.dialogs -import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Handler @@ -73,13 +72,10 @@ class FindStationDialog ( /* Overrides onRadioBrowserSearchResults from RadioBrowserSearchListener */ - /* TODO: Remove @SuppressLint("NotifyDataSetChanged"), remove NotifyDataSetChanged */ - @SuppressLint("NotifyDataSetChanged") override fun onRadioBrowserSearchResults(results: Array) { if (results.isNotEmpty()) { val stationList: List = results.map {it.toStation()} - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(stationList) resetLayout(clearAdapter = false) } else { showNoResultsError() @@ -90,9 +86,7 @@ class FindStationDialog ( /* Overrides onDirectInputCheck from DirectInputCheck */ override fun onDirectInputCheck(stationList: MutableList) { if (stationList.isNotEmpty()) { - val startPosition = searchResultAdapter.searchResults.size - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyItemRangeInserted(startPosition, stationList.size) + searchResultAdapter.updateSearchResults(stationList) resetLayout(clearAdapter = false) } else { showNoResultsError() diff --git a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt index 1274b00..c5dedf0 100644 --- a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt +++ b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt @@ -26,6 +26,7 @@ class RemoteControlServer(private val context: Context) { private val serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val lifecycleMutex = Mutex() var onPlayStation: ((String) -> Unit)? = null + var onGetCollection: (() -> com.michatec.radio.core.Collection)? = null var onPause: (() -> Unit)? = null var onResume: (() -> Unit)? = null var onNext: (() -> Unit)? = null @@ -121,16 +122,24 @@ class RemoteControlServer(private val context: Context) { call.respond(HttpStatusCode.ServiceUnavailable, mapOf("error" to "Player not available")) } else { try { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + val status = withContext(Dispatchers.Main) { val metadataHistory = PreferencesHelper.loadMetadataHistory() val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else "" val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + val station = CollectionHelper.getStation(collection, mediaId) + mapOf( "isPlaying" to p.isPlaying, + "playWhenReady" to p.playWhenReady, "playbackState" to p.playbackState, "currentStationUuid" to mediaId, - "metadata" to currentTrack + "metadata" to currentTrack, + "starred" to station.starred ) } call.respond(status) @@ -142,14 +151,15 @@ class RemoteControlServer(private val context: Context) { get("/api/stations") { try { - val collection = withContext(Dispatchers.IO) { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { FileHelper.readCollection(context) } val simplifiedStations = collection.stations.map { mapOf( "uuid" to it.uuid, "name" to it.name, - "hasImage" to it.smallImage.isNotEmpty() + "hasImage" to it.smallImage.isNotEmpty(), + "starred" to it.starred ) } call.respond(simplifiedStations) diff --git a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt index bfd6e69..8e05aed 100644 --- a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt +++ b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt @@ -18,6 +18,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.audio.AudioSink import androidx.media3.exoplayer.audio.DefaultAudioSink +import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.google.android.material.textview.MaterialTextView import com.michatec.radio.R @@ -48,11 +49,6 @@ class SearchResultAdapter( } - init { - setHasStableIds(true) - } - - /* Overrides onCreateViewHolder from RecyclerView.Adapter */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val v = LayoutInflater.from(parent.context) @@ -67,10 +63,6 @@ class SearchResultAdapter( } - /* Overrides getItemCount from RecyclerView.Adapter */ - override fun getItemId(position: Int): Long = position.toLong() - - /* Overrides onBindViewHolder from RecyclerView.Adapter */ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // get reference to ViewHolder @@ -247,9 +239,7 @@ class SearchResultAdapter( val currentlySelected: Int = selectedPosition selectedPosition = RecyclerView.NO_POSITION if (clearAdapter) { - val previousItemCount = itemCount - searchResults = emptyList() - notifyItemRangeRemoved(0, previousItemCount) + updateSearchResults(emptyList()) } else { notifyItemChanged(currentlySelected) stopPrePlayback() @@ -257,6 +247,40 @@ class SearchResultAdapter( } + /* Updates the search results using DiffUtil */ + fun updateSearchResults(newList: List) { + val diffResult = DiffUtil.calculateDiff(SearchResultDiffCallback(searchResults, newList)) + searchResults = newList + diffResult.dispatchUpdatesTo(this) + } + + + /* + * Inner class: DiffUtil.Callback for search results + */ + private class SearchResultDiffCallback( + private val oldList: List, + private val newList: List + ) : DiffUtil.Callback() { + + override fun getOldListSize(): Int = oldList.size + override fun getNewListSize(): Int = newList.size + + override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + return oldList[oldItemPosition].uuid == newList[newItemPosition].uuid + } + + override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + val oldItem = oldList[oldItemPosition] + val newItem = newList[newItemPosition] + return oldItem.name == newItem.name && + oldItem.getStreamUri() == newItem.getStreamUri() && + oldItem.codec == newItem.codec && + oldItem.bitrate == newItem.bitrate + } + } + + /* * Inner class: ViewHolder for a radio station search result */