Android SharedPreferences Tutorial and Example

Creating a social media feed with infinite scroll

A social media feed should respond immediately without downloading an entire timeline before the first item appears. This Android tutorial builds a feed with RecyclerView, a ViewModel and Paging 3, allowing posts to arrive as the user scrolls while old rows are recycled.

Creating a social media feed with infinite scroll involves more than an OnScrollListener. The screen needs page tracking, saved state, clear loading feedback and reliable recovery after a failed request. Paging 3 provides that lifecycle-aware foundation.

Start with small, testable data rather than a live platform account. A JSON endpoint you control, or a mock server, keeps the focus on pagination, empty states and retries. Each post can hold an author, message, image, timestamp and engagement counts.

This version targets Australian users, whose feeds are commonly opened on a Sydney train or Melbourne tram and across variable mobile coverage in regional WA. Compact images, useful error messages and sensible local timestamps therefore matter as much as smooth scrolling.

Set up the feed and its data model

Create a Kotlin project with one Activity and a screen containing a RecyclerView. Add Material components, androidx.paging:paging-runtime-ktx, Retrofit, Room and an image loader such as Coil. Use readable cards and adequate tap targets, with a stable identifier for every post.

Keep server data separate from Android views. A Post can include id, authorName, body, imageUrl, createdAt and reaction counts. Store selected reactions outside the row, since Paging 3 treats loaded pages as snapshots rather than an ordinary observable list.

Expose posts through a ViewModel so rotation does not restart requests. The repository owns the Pager, while the screen renders state and forwards actions. This separation also makes fake data useful for tests and allows the network implementation to change without rewriting the interface. Keep row dimensions consistent while remote images arrive.

Connect a remote paged data source

Define a Retrofit service with page and limit parameters. The PagingSource requests numbered pages, maps the response into Post objects and returns another page key only when a full page exists. A short or empty final page ends the stream naturally.

Return null from nextKey when fewer items arrive than the requested limit; otherwise, return the current page plus one. Implement getRefreshKey using the adapter’s anchor position so a refreshed feed can return near the user’s previous place. This explicit contract prevents requests for pages that cannot exist.

Turn timeouts and HTTP failures into LoadResult.Error, and reject malformed data before it reaches the adapter. Although Paging 3 can retry a failed load, use bounded exponential backoff and respect Retry-After when a service supplies it. Keep API credentials out of the APK by using a short-lived token from your backend.

Load posts as the list scrolls

Use PagingDataAdapter with a differ callback so the list compares old and new items. RecyclerView reuses rows as they leave the screen, making it practical to display a large timeline without creating a view for every post.

Begin with a page size of 20 and let the library prefetch nearby pages. Larger pages may reduce request overhead but consume more bandwidth and delay useful content. Measure both approaches on an ordinary mobile connection instead of assuming fewer requests always produce a better feed.

Submit paging data from the Activity’s lifecycle-aware coroutine scope. The ViewModel can expose Pager(PagingConfig(pageSize = 20)).flow.cachedIn(viewModelScope) as a Flow<PagingData<Post>>. The screen collects that flow using repeatOnLifecycle and collectLatest, while a footer indicator shows when another page is loading. Cancelling obsolete collections prevents stale pages from being submitted after navigation.

Handle refresh, errors and offline content

Put the RecyclerView inside SwipeRefreshLayout and call adapter.refresh() for pull-to-refresh. Distinguish a first-page refresh from a later-page failure using the combined LoadState. The refresh spinner should vanish once the first page succeeds, even if an older request later fails.

Give every error state a retry action that targets the failed operation. A timeout near the bottom must not blank visible posts. Show an explanation for an empty result rather than an endless spinner, and reserve the full-panel retry action for an unavailable first page.

Regional WA shows why offline content is valuable: a commuter moving between town centres and less-covered areas may lose connectivity while earlier posts remain relevant. Room can return saved pages first, then let remote updates replace them. Track freshness so cached content is not passed off as live, and limit cached image dimensions to avoid unnecessary storage use.

Polish and validate the complete feed

Add share and reaction actions through callbacks into the ViewModel. Update the backing store for an optimistic reaction, then reconcile the server result; never mutate an item inside the adapter because its snapshot may be replaced. Audio previews need separate playback ownership, and Android playlist handling demonstrates how to coordinate media controls without coupling them to recycled rows. Expose clear play and pause states, and stop playback when the feed leaves the screen.

Store timestamps as instants and render them in the relevant zone. Australia has three main civil time zones—Western, Central and Eastern—and daylight-saving changes affect some states. For a shared feed, choose a consistent local zone or clearly identify the author’s zone.

Light Australian language can make posts feel welcoming: “no worries” and “arvo” are ordinary expressions, not commands to interpret. Moderate according to community rules while allowing that voice. Labels for AFL, NRL and cricket fixtures suit audiences who follow different local competitions, while small-business promotions can display prices in Australian dollars with GST included.

Exercise the screen with slow 3G, unstable 4G, short responses and server errors. Drag quickly, rotate the device, leave the app and return, then retry after a failure. Profile rendering while images decode, and test next-page keys, an empty final page, an HTTP error, refresh behaviour and cached results.

Loading approach Network and memory behaviour Error handling Suitable use
Single request Downloads the complete list before display Basic retry Small fixed datasets
Manual pagination App calculates page keys and scroll thresholds Hand-written state handling Simple tutorial lists
Paging 3 with Room Loads bounded pages and reuses rows Built-in refresh and retry, with offline caching Social feeds that grow over time

Paging 3 gives this feed progressive loading, bounded memory use and an explicit recovery path when Australian mobile connections vary.