Android SharedPreferences Tutorial and Example

Creating a progress bar loading indicator

Creating a ProgressBar loading indicator in Android is more than placing a striped bar on a screen. It confirms that an action is running when people check a balance, order groceries or wait for a ride.

On Australian Android phones, including popular Samsung models, timely feedback makes waits feel predictable. Public transport, delivery and banking apps must work across screen sizes and changing signal conditions.

Connectivity varies beyond major cities. Users in regional Western Australia or northern Australia may wait longer for a response, making visible acknowledgement especially useful.

This guide covers deterministic and indeterminate progress, XML views, Kotlin updates, error states and accessibility, while tying every displayed value to real work.

Showing progress that matches the task

A ProgressBar should communicate whether the app is working and, where possible, how much remains. Brief actions can use a small spinner, while longer operations benefit from a horizontal bar, status text and a cancellation option.

Match the component to the task and its duration. Adding an item to a Coles or Woolworths basket may need only a short inline indicator, while a ride-hailing request, parcel delivery or bank transfer requires clearer staged feedback.

Sensors also have calibration periods. For a practical example, a related magnetometer compass walkthrough demonstrates how an app can provide useful feedback while hardware readings settle.

Choosing determinate and indeterminate modes

A determinate ProgressBar has a measurable range, commonly from zero to 100. Use it when the app can count completed stages or receive a genuine percentage from the server.

An indeterminate ProgressBar moves continuously when the remaining time cannot be estimated. It suits an initial connection attempt or an uncounted database query. Displaying a fixed value such as 50 percent would imply knowledge the app does not have.

Some workflows combine both modes. Start with an indeterminate spinner during connection, switch to determinate progress after receiving item totals, and then replace the bar with the completed state. Animation must never conceal a timeout or failure.

Building the layout and connecting Kotlin

Place the indicator beside a short status label instead of covering unrelated content. This XML defines a horizontal ProgressBar and a TextView that can report the current stage.

<TextView
    android:id="@+id/loadingStatus"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:accessibilityLiveRegion="polite"
    android:text="Loading trip details"
    android:visibility="gone" />

<ProgressBar
    android:id="@+id/loadingProgress"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="100"
    android:progress="0"
    android:visibility="gone" />

In the Activity, obtain references to both views. Keeping the label in the layout lets users and accessibility services receive the same information as the graphic.

class MainActivity : AppCompatActivity() {
    private lateinit var loadingProgress: ProgressBar
    private lateinit var loadingStatus: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        loadingProgress = findViewById(R.id.loadingProgress)
        loadingStatus = findViewById(R.id.loadingStatus)
    }
}

Keep both views hidden until work begins. This prevents a stale loading message from appearing after an operation has finished or the Activity has been recreated.

Progress updates and state transitions

Run slow work in a background dispatcher and update views on the main thread. In a lifecycle-aware Activity, lifecycleScope.launch cancels the coroutine when the screen is destroyed, while withContext(Dispatchers.IO) keeps blocking work away from the interface.

Use an indeterminate bar when the duration is unknown. For measurable stages, set a maximum and update the value only when a stage completes. Methods such as setProgressCompat can animate the change without fabricating intermediate percentages.

A compact set of transitions keeps a typical request understandable:

  • Show the bar and status when the request begins.
  • Disable the action that triggered the request.
  • Update the percentage at genuine stage boundaries.
  • Replace the loading state with the result.

Displayed values should also have clear meanings:

  • Zero means work has started but no measurable stage is complete.
  • A partial value represents the completed portion of the known total.
  • One hundred is reserved for fully successful completion.
  • Errors replace progress rather than appearing as completion.

Handling delays, errors and retries

Give very short operations a brief minimum display time. Otherwise, a request that finishes in 20 milliseconds may create a distracting flash. Never keep an indicator visible solely to make the animation appear balanced.

Set timeouts and provide a clear recovery path. A failed trip lookup should hide the ProgressBar, preserve the entered route and offer a retry button. Repeated attempts can use backoff, but the interface should explain whether it is reconnecting or waiting for the server.

Keep request state outside the Activity when it must survive rotation. A ViewModel can retain the operation result and allow the replacement Activity to render the same stage, which is useful during long commutes through regional areas.

Adding accessible status messages

A bar alone does not explain what is happening. Pair it with text such as “Loading available trips” and update that text as the state changes. The live region allows compatible accessibility services to announce meaningful updates.

Do not announce every one-percent increase. Frequent announcements interrupt TalkBack users and make progress harder to follow. Announce major milestones such as connection, halfway completion and success, while the visual bar communicates finer changes.

Check colour contrast, large-font layouts and reduced-motion settings. Bright Queensland sunlight and reflective train windows can make a faint track difficult to see, so use a strong tint and sufficient contrast between the filled and unfilled portions.

Testing the loading experience

Test instant, slow, empty, failed and retried responses. Use Android Studio’s layout inspector to confirm that the bar is constrained correctly, then throttle the network to observe delayed states. Rotation, backgrounding and process recreation also need coverage.

Exercise conditions encountered by Australian users, including a weak signal in regional WA, a crowded Sydney station and an intermittent connection aboard a Brisbane ferry. Each scenario should leave the interface readable and the next action clear.

Verify that the bar disappears on every terminal path, including cancellation and exceptions. A reliable indicator reports real work, communicates its current state and never leaves the interface waiting forever.