Android SharedPreferences Tutorial and Example

Building a simple calculator with basic arithmetic operations

A calculator is a practical first Android project because it combines layouts, event listeners, input validation and simple application logic. The finished app can accept two numbers, apply an arithmetic operator and display the result immediately.

This project suits beginners who are learning Android Studio with Kotlin, while also offering useful foundations for larger apps. The same principles apply to forms, shopping tools, unit converters and finance utilities used by people across Australia.

The example below uses a straightforward interface with two number fields, an operation selector and a result area. It keeps the code easy to follow, then adds safeguards for empty input, invalid division and screen sizes commonly found on Android phones.

Choose a small calculator scope

Start with four operations: addition, subtraction, multiplication and division. A basic calculator does not need scientific functions, memory buttons or a long expression parser. Limiting the first version makes it easier to understand how the user interface communicates with Kotlin code.

Create a new Android Studio project using a standard activity and Kotlin. A LinearLayout or ConstraintLayout is enough for this exercise. Give each important view a clear ID, such as firstNumberInput, secondNumberInput, operationSpinner and resultText.

A Spinner works well for selecting an operator because it presents a compact list of choices. You can populate it with +, -, × and ÷. For learners who prefer separate buttons, four operation buttons can call the same calculation function with a different operator value.

Designing the Android screen

Use two EditText controls with inputType="numberDecimal" so Android displays a suitable numeric keyboard. Add descriptive hint text such as “First number” and “Second number”, but keep visible labels as well for accessibility and clarity.

A button labelled “Calculate” should sit below the inputs. The result can be shown in a TextView with a larger text size and sufficient contrast. Padding around each component helps the interface remain comfortable on smaller devices, including budget handsets commonly purchased through Australian retailers.

The layout should also cope with portrait and landscape orientations. Avoid placing controls at fixed pixel positions. Use dp for spacing, allow the result text to wrap, and test the screen on an emulator resembling a Google Pixel as well as a smaller Android phone.

For developers collecting example patterns, Android project ideas can provide additional inspiration for extending a small calculator into a broader practice project.

Writing arithmetic logic safely

The calculation process should follow a predictable sequence: read both fields, convert the text to numbers, identify the selected operator and update the result. Kotlin’s toDoubleOrNull() method is helpful because it returns null instead of crashing when the input cannot be converted.

A simple function might look like this:

private fun calculate(firstText: String, secondText: String, operator: String): String {
    val first = firstText.toDoubleOrNull()
        ?: return "Enter a valid first number"
    val second = secondText.toDoubleOrNull()
        ?: return "Enter a valid second number"

    val answer = when (operator) {
        "+" -> first + second
        "-" -> first - second
        "×" -> first * second
        "÷" -> {
            if (second == 0.0) return "Cannot divide by zero"
            first / second
        }
        else -> return "Choose an operation"
    }

    return answer.toString()
}

Connect the function to the button’s click listener in onCreate(). Read the current text from each EditText, read the Spinner selection, then assign the returned message to the result TextView.

For a cleaner display, format decimal answers before presenting them. A result such as 5.0 may be better shown as 5, while 10 ÷ 3 should retain useful decimal precision. NumberFormat or a carefully configured DecimalFormat can handle this without changing the underlying calculation.

Handling input and user feedback

Validation should be visible and immediate. If either field is empty, call setError() on the relevant input or show a short message in the result area. Avoid allowing the app to fail silently, because beginners and everyday users need to know exactly what needs correction.

Division by zero deserves a separate check. Although a computer can represent special floating-point values, showing “Cannot divide by zero” is clearer for a basic arithmetic tool. It also teaches an important programming habit: validate exceptional cases before performing an operation.

Clear the result when the user edits either number if the previous answer could become confusing. A reset button is another useful addition, especially when the calculator is used repeatedly for household budgeting, schoolwork or comparing prices in Australian dollars.

Do not assume every user has a fast connection or a recent handset. This calculator performs locally, so it should work on a train in Melbourne, at home in regional New South Wales or during a spotty connection in Western Australia. Keeping the app offline also makes its behaviour predictable.

Testing across Australian devices

Test normal calculations, negative values, decimals, blank fields and very large numbers. Confirm that the keyboard does not hide the Calculate button and that rotating the device does not produce an unusable layout. If the app needs to preserve unfinished input after rotation, use a ViewModel or saved instance state.

The following checks cover the main behaviours:

Test case Expected result
12 + 8 20
12 - 8 4
12 × 8 96
12 ÷ 8 1.5
Blank first field Validation message
Text that is not numeric Validation message
Any number divided by zero Division warning
Negative or decimal values Correct arithmetic result

Use TalkBack to check that labels and controls are announced in a logical order. Test light and dark themes, large font settings and both portrait and landscape layouts. These checks are valuable before publishing through Google Play for users in Sydney, Brisbane or anywhere else in the local market.

A calculator does not require internet permissions, account creation or background services. Keeping the permission list empty improves user trust and reduces unnecessary configuration during development.

Practical recommendations for a reliable app

Once the basic version works, improve it in small, testable steps rather than adding every feature at once. The following practices keep the project understandable while making it more useful:

  • Use meaningful view IDs and Kotlin variable names that describe their purpose.
  • Keep arithmetic calculations in a separate function instead of placing everything inside the click listener.
  • Use toDoubleOrNull() and clear validation messages for all user-entered numbers.
  • Check for division by zero before returning a result.
  • Format long decimal values so the result remains readable on narrow screens.
  • Test accessibility settings, screen rotation and older Android devices.
  • Add automated unit tests for each arithmetic operation before introducing percentages or history.

A natural next step is a calculation history stored in a RecyclerView, followed by preferences for themes or decimal formatting. Those additions connect the project to core Android topics such as lists, SharedPreferences and state management without changing the reliable arithmetic foundation.

With a focused layout and defensive input handling, this small application demonstrates the complete path from user input to visible output. It is simple enough for a first Kotlin exercise but structured well enough to support future Android development.