International Islamic UniversityH-10, Islamabad, Pakistan
Mobile Applications Development
Week 05
Using SharedPreferences
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chisht
i
2.
Understand whatSharedPreferences is.
Learn to save and retrieve data.
Build a settings screen using SharedPreferences.
Objective
3.
In Android,SharedPreferences is a simple key–value storage system for saving
small amounts of data that should persist even after the app is closed or the
device is restarted.
Key Points about SharedPreferences
Stores data as key–value pairs.
Useful for user preferences (e.g., theme mode, username, settings, last
opened document page).
Data is stored in a private XML file inside your app’s internal storage.
Data is persisted even after app restarts.
Lightweight: not meant for large or complex data (use a database for that)
What is SharedPreferences ?
4.
Creating SharedPreferencesInstance
val sharedPref = getSharedPreferences("MyAppPrefs",
Context.MODE_PRIVATE)
MyAppPrefs: name of the file.
Context.MODE_PRIVATE: only accessible by this app.
Saving Data
val editor = sharedPref.edit()
editor.putString("username", "Chishti")
editor.putBoolean("isLoggedIn", true)
editor.apply() // or editor.commit()
1. Using SharedPreferences
5.
Retrieving Data
val username = sharedPref.getString("username", "Guest")
val isLoggedIn = sharedPref.getBoolean("isLoggedIn", false)
Removing & Clearing Data
editor.remove("username").apply()
editor.clear().apply() // Clears all data
1. Using SharedPreferences
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v,insets -
>
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom)
insets
}
val usernameEditText: EditText = findViewById(R.id.et_user_name)
val darkModeSwitch: Switch = findViewById(R.id.sw_dark_mode)
val saveButton: Button = findViewById(R.id.btn_save)
val prefs = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
val editor = prefs.edit()
// Load saved data
usernameEditText.setText(prefs.getString("username", ""))
darkModeSwitch.isChecked = prefs.getBoolean("darkMode", false)
1. Using SharedPreferences (MainActivity.kt) (2/3)
10.
saveButton.setOnClickListener {
val username= usernameEditText.text.toString()
val darkMode = darkModeSwitch.isChecked
editor.putString("username", username)
editor.putBoolean("darkMode", darkMode)
editor.apply()
Toast.makeText(this,
"Settings Saved", Toast.LENGTH_SHORT).show()
}
}
}
1. Using SharedPreferences (MainActivity.kt) (3/3)
11.
Best Practices
Use for simple settings or preferences.
Not suitable for large or complex data.
Consider Room DB for complex needs.
Summary
SharedPreferences stores key-value pairs.
Easy way to implement user settings.
Supports saving strings, booleans, ints, etc.
Hands-On Task
Build a settings screen to toggle dark mode.
1. SharedPreferences
12.
In Androiddevelopment, a Menu is a collection of options (commands or
actions) that the user can choose from within an app.
Menus are part of the Android UI (User Interface) framework and provide a
way to offer extra functionality without cluttering the main screen.
Types of Menus in Android
Options Menu: The primary menu for an activity. Appears in the app bar (three-dot
overflow icon). Example: Settings, Search, About.
Context Menu: Opens when the user long-presses on a view. Used for actions that affect
the selected item. Example: Copy, Paste, Delete.
Popup Menu: A small menu that anchors to a view. Shows a dropdown list of actions.
Example: Clicking a button shows quick options.
2. Menu
override fun onSupportNavigateUp():Boolean {
val dialog = AlertDialog.Builder(this)
.setTitle("Warning")
.setMessage("Do you want to close this app ?")
.setPositiveButton("YES") { dialogInterface, i ->
finishAndRemoveTask()
}
.setNeutralButton("NO", null)
.create()
dialog.show()
return true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge(); setContentView(R.layout.activity_main)
2. Using Menu (MainActivity.kt) (3/4)
25.
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v,insets -
>
val systemBars =
insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom)
insets
}
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
// supportActionBar!!.setHomeAsUpIndicator(R.drawable.ic_close)
supportActionBar!!.setBackgroundDrawable(ContextCompat.getColor(this,
R.color.purple_700).toDrawable())
title = "Main Activity"
}
}
2. Using Menu (MainActivity.kt) (4/4)