Android SharedPreferences Tutorial and Example

Building a unit converter app

A unit converter app gives Android users a quick way to translate measurements without searching through separate calculators. This project suits beginners who want a visible result from a small, well-structured codebase, while still leaving room for history, preferences and polished validation.

Use Kotlin with Android XML layouts, Material components and View Binding so the interface remains easy to inspect. Keep conversion rules outside the Activity, store transient choices with SharedPreferences, and use Room over SQLite if saved history is included.

Australian defaults should use kilometres and metres for distance, Celsius for weather and litres for fuel. Useful examples include the road distance from Sydney to Melbourne, shop quantities expressed in kilograms and a quick conversion of a 10% GST-inclusive Australian dollar amount.

Develop in small stages: define units, build the screen, implement calculations, add persistence and then test on several Android versions. A sample dataset makes every stage verifiable and prevents interface work from obscuring mathematical mistakes.

Conversion area Starting units Australian default Rule shape
Distance metres, kilometres, miles kilometres for longer routes Multiply by a factor
Temperature Celsius, Fahrenheit, Kelvin Celsius Multiply and offset
Mass grams, kilograms, pounds kilograms Multiply by a factor
Volume millilitres, litres, cups litres Multiply by a factor

Define categories and conversion rules

Start with a deliberately small catalogue: distance, mass, temperature and volume. Give each category an identifier and store its units in a UnitDefinition list, rather than scattering labels and factors throughout the layout. This keeps adding a new category predictable.

Represent ordinary conversions with a multiplier, such as 1 kilometre = 1,000 metres. Handle temperature with the same rule in reverse or with a small strategy object. Keeping the rule in one converter class makes the Activity responsible only for input, output and error messages.

Use BigDecimal for user-facing decimal values and set a sensible scale, such as two decimal places for currency and three for fuel volume. Document the rounding mode in tests, because half-up and half-even results differ at exact boundaries.

Design a beginner-friendly interface

Build the main screen in activity_main.xml with two dropdowns, a numeric input field, a result field and Swap and Clear buttons. Expose category and unit choices with accessible labels, and use a RecyclerView if the catalogue grows beyond a short dropdown.

Default distance to kilometres for longer Australian journeys and metres for construction or exercise; this matches how locals discuss routes between Sydney, Melbourne and Perth. Show Celsius prominently, label fuel volumes as litres, and avoid ambiguous “cups” unless the selected cup size is stated.

Give the result enough contrast, make every control large enough for touch, and connect labels to fields for screen readers. Handle rotation through saved state or ViewModel, and keep the keyboard type numeric with a decimal point accepted.

Implement reliable calculations

Parse the input as BigDecimal only after checking that it is present and valid. Australia normally uses a decimal point, but do not silently discard every comma: it may be a grouping separator. Pass the cleaned value into the converter and return a formatted result for the selected unit.

For a direct temperature conversion, the core can stay compact:

fun celsiusToFahrenheit(value: BigDecimal): BigDecimal =
    value.multiply(BigDecimal("9"))
        .divide(BigDecimal("5"))
        .add(BigDecimal("32"))
        .setScale(2, RoundingMode.HALF_UP)

Trigger recalculation when either unit changes, then keep the field’s numeric value intact when the user taps Swap. Empty input should show a prompt rather than zero, and extreme values should produce a clear range message. Keep these states out of the conversion function.

Store preferences and conversion history

Save the last selected category, unit pair and precision in SharedPreferences. Read them when the Activity starts, but let the ViewModel remain the source of truth during rotation so a transient switch does not unexpectedly reset the screen.

For history, add a Room entity containing the input, source unit, target unit, result and timestamp. Query the latest entries with a RecyclerView adapter and let users delete one item or clear the full log. A repository keeps database calls away from the Activity.

A copy button and Android Sharesheet are useful companions to the core converter. For an optional photo feature that records a tape measure or appliance label, the camera integration guide covers permission handling, image rotation and secure storage.

Test calculations and user journeys

Write unit tests against known pairs, including 100°C = 212°F, one kilometre = 1,000 metres and one litre = 1,000 millilitres. Test zero, negative values where permitted, very large inputs and the chosen rounding boundary. These tests expose bad factors faster than manual tapping.

Use Espresso to enter a value, choose units and verify the displayed result. Android instrumentation tests can also check rotation, accessibility labels and the saved-state path. Run the suite on an emulator and at least one physical device with the app’s minimum supported Android version.

If a companion currency-rate page exists, Thucydides web tests can verify that browser-side flow while Espresso checks the native app. If currency conversion is included, label values as A$, show the rate’s timestamp and state that GST is separate from exchange-rate conversion.

Build milestones for an Australian release

Keep release permissions narrow: request camera access only when the optional photo flow is opened, and explain the purpose before the system prompt. Remove unused libraries, profile the main screen and keep startup responsive on older devices commonly used across the Australian market.

The following checkpoints keep the project focused without turning a small utility into an oversized product. They also cover the local release path for Google Play in Australia, where screenshots, metric examples and A$ pricing should look natural.

Build checkpoints

  • Define the four core categories and their factors.
  • Add input validation, swapping and rounded results.
  • Store preferences and optional Room history.
  • Cover every rule with unit and UI tests.

Release checkpoints

  • Localise labels with Australian English.
  • Verify accessibility, rotation and offline use.
  • Prepare an Android App Bundle and privacy details.
  • Stage the rollout and monitor crash reports.

A staged launch with realistic local examples gives users confidence quickly. The finished app remains simple because its data model, calculations, interface and persistence each have a clear boundary and can be tested independently.