Implementing SwipeRefreshLayout in Android

A pull-to-refresh gesture gives Android users a familiar way to request the newest content without leaving the current screen. Implementing SwipeRefreshLayout adds that interaction around a single scrollable view, while a ViewModel keeps network work out of the UI thread. The result should feel immediate even when the request takes time, fails or returns no new records.

The default phpMyAdmin notice on this site belongs to the DigitalOcean Droplet hosting layer; it is not a prerequisite for an on-device refresh gesture. SwipeRefreshLayout needs no PHP session, SSH login or database, although a hosted API may later provide the data. Keep server administration separate from the Android interaction so a setup placeholder does not obscure the implementation.

Prepare the Android project

Use the AndroidX package rather than an obsolete support-library version. Add the current dependency to the app module and allow Gradle to synchronise:

dependencies {
    implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")
}

For a clean checkout, this first Android project guide covers project creation and the remaining Android Studio configuration before the refresh code is added. The linked workflow is useful when a machine has no SDK configured yet.

Keep remote data in a repository injected into a ViewModel. The Activity or Fragment should own the gesture binding, but it should not own networking, retry timing or error mapping. This separation also keeps the refresh action intact when the device rotates.

Build the refreshable screen

Place one direct scrollable child inside SwipeRefreshLayout. A RecyclerView works well for a feed, although a NestedScrollView is suitable for a short, fixed page:

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/newsList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

Choose the child container according to the content and the interaction it needs to support:

Content structure Preferred approach Refresh behaviour Main limitation
Short or static content NestedScrollView inside SwipeRefreshLayout One bounded scroll area supplies the downward drag Large collections need separate paging
Repeating feed RecyclerView inside SwipeRefreshLayout Efficient item recycling with list-driven updates Requires an adapter and stable item handling
Compose-only screen Material pull-to-refresh API Refresh state is observed directly in composables The Android View widget does not fit a Compose-only hierarchy

A RecyclerView suits news, property listings and public transport updates. Use ListAdapter with DiffUtil so a successful refresh does not make the list jump, and preserve the scroll position when new items arrive. Avoid nesting additional vertical scrolling containers inside the refresh layout unless nested scrolling is coordinated deliberately.

Connect refresh state to the UI

Wire the pull gesture to a ViewModel function. The ViewModel decides whether a request is needed and prevents duplicate work:

binding.swipeRefresh.setOnRefreshListener {
    viewModel.refresh()
}

Observe the ViewModel’s state while the screen is active rather than toggling the spinner directly from the listener:

lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { state ->
            binding.swipeRefresh.isRefreshing = state.isRefreshing
            binding.errorView.isVisible = state.error != null
        }
    }
}

Put the actual request in the ViewModel and release it with the ViewModel’s lifecycle. A guarded job stops rapid repeated gestures from creating parallel calls:

private var refreshJob: Job? = null

fun refresh() {
    if (refreshJob?.isActive == true) return

    refreshJob = viewModelScope.launch {
        _uiState.update { it.copy(isRefreshing = true, error = null) }
        try {
            val items = repository.fetchLatest()
            _uiState.update { it.copy(items = items) }
        } catch (error: IOException) {
            _uiState.update { it.copy(error = error) }
        } finally {
            _uiState.update { it.copy(isRefreshing = false) }
        }
    }
}

Handle loading, errors and accessibility

Treat isRefreshing as one state among several. It should be true only while a user-initiated refresh is running. An initial screen load can use a full-screen progress indicator, while an empty result should show an empty-state message that still leaves the gesture available. After a failed refresh, stop the spinner but keep the previous rows visible so the user does not lose their place.

Accessibility needs an equivalent action for people who cannot perform the drag. Provide a visible refresh control in the app bar or overflow menu, give status regions meaningful text and announce completion through announceForAccessibility. Pair the spinner with a textual status such as “Updating transport departures” instead of relying on colour or movement alone.

Australian content makes the behaviour easy to judge. A transport card used by Sydney or Melbourne commuters may show live platform changes after a swipe, while a regional NSW news app can encounter intermittent mobile coverage. Display the last successful update time and keep cached rows visible when a request fails. Copy should use Australian English; “updated this arvo” may suit a casual brand, while “no worries, try again” can soften recovery text, but neither should replace precise instructions. Australian releases also need clear Play Console privacy disclosures and permission prompts aligned with the Privacy Act and Australian Consumer Law.

Test and ship the interaction

Test the ViewModel’s transitions for success, empty data, timeouts and server errors. An instrumentation test can perform a downward swipe and verify that the loading state appears and disappears. Also rotate the device during a request, repeat the gesture quickly and confirm that existing content remains at a stable scroll position.

Before release, configure sensible network timeouts and retain the last successful response with its timestamp. If the API runs on a DigitalOcean Droplet, expose only the API endpoint through the reverse proxy. Keep phpMyAdmin behind authentication and an SSH tunnel or private network rather than making its login page publicly reachable.

Create the first build now: add the dependency, wrap the feed in the refresh container, route every request through the ViewModel, and release an internal APK for Australian testers across Sydney, Melbourne and regional areas.