Android SharedPreferences Tutorial and Example

Build a simple Android drawing app with Canvas

A compact drawing tool is an excellent Android project because it combines a familiar interface with touch handling, graphics rendering and file export. The version described here uses Kotlin, a custom View and Android's Canvas drawing API, keeping the code small enough to understand while leaving room for useful features.

The app displays an empty drawing surface, brush controls and actions for undoing, clearing and saving. Users draw with a finger or stylus, choose a colour, then export the result as an image. Every gesture maps to a small number of events, so the project remains approachable for beginners.

A practical scope matters because bitmap handling, storage permissions and sharing rules can otherwise make a small app complicated. Start with local artwork and no account system. The finished tool should work offline, feel responsive on common phone sizes and avoid sending sketches to a server.

For Australian users, the app should remain useful during a Sydney bus trip or Melbourne train journey, when connectivity can vary and a quick offline sketch may be more practical than a cloud workflow. It must also suit the Australian Google Play market, where free downloads and compact utilities are common, while respecting the Privacy Act 1988 and the Australian Consumer Law.

Set up the Android project

Create an empty Activity project in Android Studio, select Kotlin and choose a minimum SDK that covers the devices you want to support. Add Material components for the toolbar and buttons, then create a layout containing the drawing View above a row of colour, undo, clear and save controls.

Give each control a stable resource ID and a meaningful content description. A palette swatch should announce its colour, while icon-only buttons need labels such as “Undo stroke”. Use a ConstraintLayout so the surface can grow vertically without pushing the controls off a smaller screen.

Handle button clicks in the Activity or ViewModel and forward those actions to the drawing View. For a future created-date field, this date picker example demonstrates how an EditText click listener opens a dialog. That pattern is separate from the brush surface but can guide later metadata controls.

Draw paths on a custom canvas

Add a DrawingView class that extends View. Give it a Paint object configured with Paint.Style.STROKE, rounded caps and joins, plus anti-aliasing for smoother edges. Override onDraw, iterate through the completed strokes and active path, and render each with canvas.drawPath(path, paint).

Keep a list of completed paths and a current path for the stroke in progress. On ACTION_DOWN, begin with moveTo; on ACTION_MOVE, append coordinates with lineTo and call invalidate() so the screen updates. Add the completed path to the list on ACTION_UP.

private var activePath: Path? = null
private val strokes = mutableListOf<Path>()

override fun onTouchEvent(event: MotionEvent): Boolean {
    when (event.actionMasked) {
        MotionEvent.ACTION_DOWN -> {
            activePath = Path().apply { moveTo(event.x, event.y) }
            invalidate()
        }
        MotionEvent.ACTION_MOVE -> {
            activePath?.lineTo(event.x, event.y)
            invalidate()
        }
        MotionEvent.ACTION_UP -> {
            activePath?.let { strokes.add(it) }
            activePath = null
            invalidate()
        }
        MotionEvent.ACTION_CANCEL -> {
            activePath = null
            invalidate()
        }
    }
    return true
}

Store raw touch coordinates in the View's pixel space, but convert brush widths from density-independent pixels with resources.displayMetrics.density. With a stylus, pressure can select from two or three predefined widths; continuous pressure-based width requires rendering individual segments rather than one path.

Capture touch input and colour

Read the colour and brush size before each new stroke rather than changing the shared Paint midway through one. A palette can use a small grid of ImageButton views, while a seek bar or slider adjusts width. Keep the selected state visible so users can predict the next mark.

Use MotionEvent coordinates directly for simple drawing, but reject touches outside the canvas bounds. Palm rejection is optional; basic support for MotionEvent.TOOL_TYPE_STYLUS is useful when a user draws with a compatible Samsung device.

Three storage approaches suit different stages of development, with clear differences in editing flexibility and memory demands.

Approach Undo model Memory behaviour Best fit
Saved paths Remove one completed stroke Depends on the number of path points Basic freehand drawing
Bitmap layer Requires pixel-level history High at large resolutions Textures and raster effects
Command log Replays recorded brush actions Grows with the action count Advanced brushes and replay

For this project, saved Path objects provide the cleanest undo model. Each undo removes the last completed path and triggers another redraw, while a bitmap layer is better when adding raster textures or pixel-based effects.

Save, reopen and share artwork

To export, create a bitmap with the View's dimensions, fill it with white, and redraw the stored paths onto its Canvas. This avoids capturing surrounding controls and produces a clean PNG. Generate a descriptive file name and remember that device orientation can change the final width and height.

On Android 10 and later, insert the image into MediaStore under Environment.DIRECTORY_PICTURES, then clear the pending flag after writing. For older releases, request the appropriate external-storage permission and use a public pictures directory. If the app only saves its own images, it does not need broad media access.

Sharing needs a temporary PNG in the cache directory and a FileProvider configured with a paths XML resource. Pass the content URI through an Intent with ACTION_SEND, set the MIME type to image/png and grant temporary read permission to the receiving app.

Keep the first release local-only. If analytics or cloud storage are added, explain what is collected and obtain consent where required under the Privacy Act 1988. Any paid upgrade must also make prices and consumer guarantees clear under the Australian Consumer Law.

Test and publish for Australian users

Test on several Android versions, screen densities and screen sizes, including a narrow phone and a large display. Draw continuous curves, lift the finger between strokes, undo repeatedly and rotate the device before saving. Check that the exported image matches the visible canvas.

Run an accessibility pass with TalkBack, large display sizes and high-contrast colour choices. The Australian app market includes established drawing and note tools, so a polished first release should open quickly, explain destructive actions and avoid accidental data loss.

  • Offer an obvious reset action with an undo path so a mis-tap does not erase all work.
  • Use visible labels and TalkBack descriptions for every brush control.
  • Cap bitmap dimensions or sample large canvases to control memory usage.
  • Save into a dedicated pictures folder and use Australian date and time conventions in exported names.
  • Test offline launches and sharing on popular Android phones sold in Australia.
  • Provide a plain-language privacy policy that confirms whether drawings leave the device.

This creates a stable first release with a clear boundary between canvas behaviour, Android storage and user controls.