Android SharedPreferences Tutorial and Example

Creating a Calculator with Scientific Functions for Android

Scientific calculators are familiar in Australian classrooms, labs and engineering work, but Android gives them a portable, touch-friendly form. Creating a Calculator with Scientific Functions is a strong tutorial project because it joins interface design, numerical logic and persistent settings. The finished app can support revision, fieldwork and quick estimates without sending every equation to a server.

A useful first version handles addition, subtraction, multiplication, division, parentheses and percentages. Extend the expression language with sine, cosine, tangent, logarithms, roots, powers, factorials, and constants such as π and e. A clearly labelled degree/radian switch prevents a common source of incorrect answers.

Use Kotlin with Android Views and XML layouts to keep the project approachable for readers learning Android. Separate the buttons, display and calculation engine, then connect them through a ViewModel. Parse expressions with a dedicated parser instead of evaluating strings as code; this provides predictable precedence and avoids unsafe execution.

Australian use cases add practical requirements. Display Australian dollars and offer a 10% GST option, use Celsius and kilometres for local measurements, and make controls comfortable for commuters in Sydney or Melbourne. Google Play is the main Android storefront here, and privacy expectations are influenced by the Australian Privacy Act 1988. Store only what the calculator genuinely needs.

Choose the feature set and project structure

Create an Android Studio project with an empty Views Activity, Kotlin and a minimum SDK that covers your intended devices. Give the calculation package three responsibilities: Tokenizer, Parser and Evaluator. The tokenizer identifies numbers, operators and functions; the parser applies precedence; the evaluator performs each operation. Keep the current expression and result in a ViewModel so rotation does not erase them.

Capability Basic mode Scientific mode Implementation note
Arithmetic Four operations Four operations Tokenizer and evaluator
Scientific functions None Trigonometry, logs and roots Named function dispatcher
Angle handling Not required Degrees or radians SharedPreferences setting
Number formatting Decimal values Decimal or scientific notation BigDecimal for money, Double for science
History Optional Optional Local SQLite or Room storage

Keep each component independently testable. For example, percentage handling can be a separate formatter, while sine and cosine use the same parser pipeline. This arrangement also lets you expose a simple keypad and an advanced keypad without duplicating calculation logic.

Build an accessible calculator layout

Place a read-only result display and editable expression field above the keypad. Use a ConstraintLayout as the root and GridLayout for the number keys, with a horizontally scrollable row for scientific functions. This remains usable on narrow phones and expands cleanly on tablets in landscape.

Give every key a visible label, an accessible name and a minimum touch target of 48 dp. Do not rely on colour alone to show the active angle unit or selected operator. For an everyday estimate at Coles or Woolworths, show the running value in AUD and state clearly whether GST is included.

Use an input type designed for decimal entry, but accept the multiplication sign, division sign and pasted expressions from a physical keyboard. Confirm the active mode in text such as “DEG” or “RAD”. Recalculate after each completed command while leaving an unfinished expression visible for correction.

Implement the scientific expression engine

Build a recursive-descent parser or a shunting-yard parser that produces tokens without running arbitrary code. Give multiplication and division higher precedence than addition and subtraction, and treat a leading minus as unary negation. Parentheses should change evaluation order, while percentage can be implemented as either a postfix operation or division by 100, provided the behaviour is documented.

Map recognised names to Kotlin functions such as sin, cos, tan, ln and log10. Convert angles to radians before applying trigonometric functions, then return the original unit in the display. Support positive and negative exponents, square roots and factorials; limit factorial input to a safe range rather than allowing an overflowing result.

A Kotlin dispatcher can keep angle conversion in one place:

fun trig(name: String, value: Double, useDegrees: Boolean): Double {
    val angle = if (useDegrees) Math.toRadians(value) else value
    return when (name) {
        "sin" -> kotlin.math.sin(angle)
        "cos" -> kotlin.math.cos(angle)
        "tan" -> kotlin.math.tan(angle)
        else -> error("Unknown function")
    }
}

Use Double for general scientific work and BigDecimal when the interface offers a dedicated money calculation. Guard every operation: division by zero should display an undefined result, a logarithm of a negative number should be rejected, and overflow should produce a clear message. Unit-test precedence, unit conversion, invalid input and boundary values before connecting the engine to the buttons.

Save settings without collecting unnecessary data

Use SharedPreferences for the selected angle unit, GST preference, theme and most recent expression. Keep history optional and store it locally; SQLite or Room can hold timestamped calculations when search, deletion and a configurable history limit are required. Avoid retaining an expression if it might contain sensitive household or study information.

If the app later adds analytics, account records or cloud history, reassess the Australian Privacy Act 1988, Google Play data-safety disclosures and the need for a privacy policy. A small help page can point users to consumer security advice without transmitting their calculations, provided the link is clearly marked as external.

Keep the main calculator entirely offline by removing unnecessary network and location permissions. Let users clear history from the settings screen and explain what remains on the device. This makes the data story clear to Australian users and gives the Play Store listing a simple privacy position.

Test and publish with practical recommendations

Write unit tests for the tokenizer, parser and evaluator, then add instrumented tests for keypad actions, rotation, accessibility labels and different screen sizes. Check rapid repeated presses, very long expressions, locale decimal input and devices with limited memory. A release candidate should also survive opening and closing the app while an expression is incomplete.

Build a signed Android App Bundle, set a current target API and a sensible minimum SDK, then complete the Google Play data-safety and content-rating forms. Test the listing in the Australian market, include an Australian support contact, and review the app against the Australian Consumer Law before promising refunds or paid features. A crash-free, private and accessible calculator is easier to support than one packed with rarely used options.

  • Ship basic arithmetic first while keeping scientific controls discoverable on a dedicated panel.
  • Default to degrees for general use, label the setting prominently, and provide radians for mathematics and engineering.
  • Keep GST and money formatting outside the scientific engine so decimal precision remains predictable.
  • Publish a privacy policy, support address and clear history controls before adding analytics or cloud sync.