Android SharedPreferences Tutorial and Example

Build an Android Random Quote Generator

A random quote generator is a compact Android project that introduces local data, button handling and state management without needing a backend. Press a control, receive an inspiring line, then share it or keep it among your favourites.

Using Kotlin, XML views and a ViewModel keeps the first version approachable. Quotes remain available offline, which is handy on a Melbourne tram or a regional train, while the ViewModel preserves the selected quote when the screen rotates.

Australian content gives the exercise local character. Ideas include the Bondi to Coogee coastal walk, a delayed Melbourne tram, cricket at the SCG, an arvo coffee break and the friendly reassurance of “no worries”. Use Australian spellings such as “favourite” and “colour” throughout.

The finished app will use Android Studio, accessible controls, a local quote catalogue, sharing and saved favourites. Its structure can later support SQLite or a remote API, but keeping the first version simple makes each Android concept easier to understand.

Set up the Android project

Create a new project in Android Studio with the Empty Views Activity template, Kotlin and a package name such as au.com.example.quotes. Name the launcher activity MainActivity, set the minimum SDK to 24 unless a specific compatibility requirement exists, and keep the generated XML-based interface.

Enable View Binding in the module’s build.gradle.kts, then add the Material Components, lifecycle ViewModel and LiveData dependencies through the Project Structure dialog. View Binding gives MainActivity a typed ActivityMainBinding object, avoiding repeated findViewById calls and making null handling more predictable.

android {
    buildFeatures {
        viewBinding = true
    }
}

Store and organise the quotes

Represent each entry with a Kotlin data class. Keep the author optional so the app can display an anonymous line without leaving an empty label.

data class Quote(
    val text: String,
    val author: String? = null
)

A repository keeps the initial catalogue in one place. These original sample messages avoid presenting invented sayings as quotations from named public figures.

object QuoteRepository {
    val quotes = listOf(
        Quote("A Bondi to Coogee walk is a reliable way to reset."),
        Quote("When the Melbourne tram is late, use the pause to plan the next move."),
        Quote("A flat white and a clear head can turn an arvo around."),
        Quote("Keep your eye on the ball at the SCG and on the goal that matters to you."),
        Quote("No worries—take a breath and try again.")
    )
}

For a larger collection, move these records into SQLite and expose them through a repository that reads from a background dispatcher. For the first build, an immutable list is fast, predictable and easy to test. Store enough variety that repeated use does not quickly exhaust the collection.

Build the quote screen

The screen needs a quote label, an optional author label, a New Quote button and actions for sharing and saving. Give the quote a generous text size, use contrasting colours, and describe each icon-only control through contentDescription so TalkBack users understand it. A vertical LinearLayout inside a ScrollView also handles long quotations and larger text settings.

<Button
    android:id="@+id/newQuoteButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New quote" />

Random selection can use several patterns. Compare the options before choosing the behaviour that suits the app.

Selection pattern Behaviour Best fit
Random index Chooses one position directly A small local catalogue
Shuffled queue Reorders every item before selection Collections where repeats should be avoided
Fixed daily pick Uses the date and time zone One stable quote per day

A random index fits this catalogue because it uses little memory and gives every entry an equal chance. A shuffled queue is better when avoiding repeats matters more than pressing exactly once for a fresh draw. For a fixed daily quote, combine the selection with the Australian time-zone handling described later.

Add state, sharing and favourites

Keep selection in a ViewModel so rotation does not trigger another quote. Expose it with by viewModels(), observe its LiveData in the activity, and update the labels whenever the value changes. The repository should return null for an empty catalogue so the screen can show a clear placeholder rather than fail.

class QuoteViewModel : ViewModel() {
    private val repository = QuoteRepository
    private val _quote = MutableLiveData<Quote>()
    val quote: LiveData<Quote> = _quote

    init {
        nextQuote()
    }

    fun nextQuote() {
        repository.quotes.randomOrNull()?.let {
            _quote.value = it
        }
    }
}

Connect that state to the XML views through the activity binding.

viewModel.quote.observe(this) { quote ->
    binding.quoteText.text = quote.text
    binding.authorText.text = quote.author.orEmpty()
    binding.authorText.isVisible = !quote.author.isNullOrBlank()
}

binding.newQuoteButton.setOnClickListener {
    viewModel.newQuote()
}

Sharing can use Android’s standard ACTION_SEND intent. Include the quote and author in EXTRA_TEXT, then launch a chooser so the user can select Messages, Gmail or another installed app. This sends text only and requires no account or cloud service.

val shareIntent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_TEXT, "\"${quote.text}\"")
}

startActivity(Intent.createChooser(shareIntent, "Share a quote"))

Save favourites with SharedPreferences, storing quote text in a string set. Copy the retrieved set before modifying it, and use a small RecyclerView to display the saved lines. For a daily mode, derive a stable choice from the date and selected Australian time zone. Sydney, Brisbane, Adelaide and Perth do not all change at the same moment, and Western Australia does not use daylight saving. Test the reset near midnight and during daylight-saving transitions.

Test and prepare a release

Test an empty catalogue, a single entry and a collection with many entries. The random selector must never request an invalid index. Rotate the device, reopen the activity and verify that the displayed quote and favourites survive. Check small screens, portrait and landscape layouts, large font sizes and TalkBack labels.

Android is a major consumer platform in Australia, and Google Play is the normal distribution route for a public app. Prepare a release build, sign it with a protected key, set the version code and name, and create a store listing with screenshots taken from the Australian English build.

Review the privacy statement: an offline quote app that collects no personal data should say so clearly. Once the signed package is uploaded to the internal testing track, install that exact build on several devices before promotion. You will then have a practical random quote generator with a clean separation between data, logic and views.