Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 10 Theory – Listening for UI Notifications; Views; User Preferences; Persisting Data; Sharing Data

Week 10 – UI Events, Views, Preferences and Data Storage · 95 min read · 32 MCQs to check yourself

Coding in Flow – Save variables in SharedPreferences

Android Coding with Harsha – RecyclerView in Android Studio (Java)

1. Listening for UI notifications (UI events)

When the user interacts with a view, Android delivers an event. Apps "listen" by registering event listeners – interfaces with callback methods.

Event listeners

Listener Callback Fires when
View.OnClickListener onClick(v) View tapped
View.OnLongClickListener onLongClick(v) → Boolean View pressed and held
View.OnTouchListener onTouch(v, event) Any touch: ACTION_DOWN, ACTION_MOVE, ACTION_UP
View.OnFocusChangeListener onFocusChange(v, hasFocus) Field gains/loses focus
View.OnKeyListener onKey(v, keyCode, event) Hardware key pressed while focused
TextWatcher beforeTextChanged, onTextChanged, afterTextChanged Text in an EditText changes
CompoundButton.OnCheckedChangeListener onCheckedChanged CheckBox/Switch toggled
RadioGroup.OnCheckedChangeListener onCheckedChanged(group, id) Radio selection changes
AdapterView.OnItemSelectedListener onItemSelected Spinner item chosen
SeekBar.OnSeekBarChangeListener onProgressChanged Slider moved
TextView.OnEditorActionListener onEditorAction Keyboard "Done/Search" pressed

Ways to attach a listener

// 1. Lambda (shortest, Java 8+)
btnSave.setOnClickListener(v -> save());

// 2. Anonymous inner class (the classic Java way)
btnCancel.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

// 3. Activity implements the interface (one handler for many views)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnSave) save();
        else if (v.getId() == R.id.btnCancel) finish();
    }
}
// btnSave.setOnClickListener(this);

// 4. Text changes – TextWatcher
etSearch.addTextChangedListener(new TextWatcher() {
    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { filter(s.toString()); }
});

Event handlers vs listeners

Gestures

GestureDetector recognises fling, double tap, long press, scroll; ScaleGestureDetector recognises pinch zoom.

2. Views – more widgets and lists

View Use
Spinner Drop-down; filled with an ArrayAdapter
AutoCompleteTextView Suggestions while typing
Switch / SwitchMaterial On/off setting
SeekBar / Slider Choose a value
RatingBar Star rating
ProgressBar Loading indicator (indeterminate) or progress (determinate)
DatePicker / TimePicker (dialogs) Choose date/time
WebView Web content
CardView Rounded container with elevation

Adapters and lists

An Adapter is a bridge between a data source (list/array/database) and a list view; it creates a view for each item.

// Course.java – the data (model) class
public class Course {
    public final String code, title;
    public Course(String code, String title) { this.code = code; this.title = title; }
}

// CourseAdapter.java
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.VH> {
    private final List<Course> items;
    public CourseAdapter(List<Course> items) { this.items = items; }

    static class VH extends RecyclerView.ViewHolder {
        TextView tvCode, tvTitle;
        VH(View view) {
            super(view);
            tvCode = view.findViewById(R.id.tvCode);
            tvTitle = view.findViewById(R.id.tvTitle);
        }
    }

    @NonNull @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_course, parent, false);
        return new VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH h, int position) {
        Course c = items.get(position);
        h.tvCode.setText(c.code);
        h.tvTitle.setText(c.title);
        h.itemView.setOnClickListener(v ->
                Toast.makeText(v.getContext(), c.title, Toast.LENGTH_SHORT).show());
    }

    @Override
    public int getItemCount() { return items.size(); }
}

// in the activity:
RecyclerView recycler = findViewById(R.id.recycler);
recycler.setLayoutManager(new LinearLayoutManager(this));
List<Course> list = new ArrayList<>();
list.add(new Course("CDE-315", "Mobile Application Development"));
list.add(new Course("CS-301", "Artificial Intelligence"));
recycler.setAdapter(new CourseAdapter(list));

3. User preferences

Preferences store small amounts of simple data as key–value pairs – settings (dark mode, language), the logged-in username, "first launch" flags, high scores.

SharedPreferences

SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);

// write
prefs.edit()
        .putString("username", "ali_raza")
        .putBoolean("dark_mode", true)
        .apply();                 // asynchronous (commit() is synchronous and returns a boolean)

// read (with default values)
String user = prefs.getString("username", "Guest");
boolean dark = prefs.getBoolean("dark_mode", false);

// remove / clear
prefs.edit().remove("username").apply();
prefs.edit().clear().apply();
apply() commit()
Writes to memory immediately, to disk in the background Writes synchronously on the calling thread
Returns nothing Returns true/false
Preferred on the UI thread Use only when you need the result

Preference screens (settings UI)

AndroidX Preference library builds a standard settings screen from XML (SwitchPreferenceCompat, ListPreference, EditTextPreference) shown in a PreferenceFragmentCompat; values save automatically to the default SharedPreferences.

Jetpack DataStore (modern replacement)

Security

SharedPreferences are plain text – do not store passwords or tokens unencrypted; use the Android Keystore-backed encryption (the old EncryptedSharedPreferences library is deprecated – use Keystore or DataStore with encryption).

4. Persisting data

Option Data type Where Example
SharedPreferences / DataStore Small key–value Private XML/file Settings, username
Internal storage files Any file, private filesDir, cacheDir Notes, JSON cache
External / shared storage Media and documents for the user MediaStore, Storage Access Framework Photos, PDFs
SQLite database Structured, relational Private .db file Students, products
Room (Jetpack) SQLite with objects Private Recommended local DB
Cloud / server Shared, synced Firebase Firestore, Supabase, REST API Multi-device data

Internal storage files

// write
try (FileOutputStream out = openFileOutput("notes.txt", MODE_PRIVATE)) {
    out.write("Buy books".getBytes());
} catch (IOException e) { e.printStackTrace(); }

// read
StringBuilder text = new StringBuilder();
try (BufferedReader r = new BufferedReader(new InputStreamReader(openFileInput("notes.txt")))) {
    String line;
    while ((line = r.readLine()) != null) text.append(line).append("\n");
} catch (IOException e) { e.printStackTrace(); }

Files in filesDir are private, need no permission and are deleted on uninstall. cacheDir is for temporary data the system may clear.

External/shared storage

Since scoped storage (Android 10/11), apps write to their own app-specific external folder freely, and use MediaStore (images, video, audio) or the Storage Access Framework (user picks a file/folder) for shared files. The old READ/WRITE_EXTERNAL_STORAGE permissions no longer give broad access; Android 13+ uses READ_MEDIA_IMAGES/VIDEO/AUDIO and the Photo Picker.

SQLite

A lightweight, file-based relational database built into Android (public domain, by D. Richard Hipp). Classic approach: extend SQLiteOpenHelper (onCreate creates tables, onUpgrade migrates), then use insert, query (returns a Cursor), update, delete or raw SQL.

public class DbHelper extends SQLiteOpenHelper {
    public DbHelper(Context ctx) { super(ctx, "campus.db", null, 1); }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, roll TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        db.execSQL("DROP TABLE IF EXISTS student");
        onCreate(db);
    }
}

// usage in an activity
SQLiteDatabase db = new DbHelper(this).getWritableDatabase();
ContentValues row = new ContentValues();
row.put("name", "Sara");
row.put("roll", "23-027");
db.insert("student", null, row);

Room (recommended)

Room is an abstraction layer over SQLite with compile-time SQL checking:

Part Role
@Entity A class = a table
@Dao Interface with @Insert, @Update, @Delete, @Query("SELECT ...")
@Database Abstract class that lists entities and provides DAOs
@Entity
public class Student {
    @PrimaryKey(autoGenerate = true) public int id;
    public String name;
    public String roll;
}

@Dao
public interface StudentDao {
    @Insert void add(Student s);
    @Query("SELECT * FROM Student ORDER BY name") LiveData<List<Student>> all();
}

@Database(entities = {Student.class}, version = 1)
public abstract class AppDb extends RoomDatabase {
    public abstract StudentDao studentDao();
}
// Room does not allow database work on the main thread – run add() in an ExecutorService.

Database work must run off the main thread (e.g. with an ExecutorService), otherwise Room throws an exception.

5. Sharing data between apps

Each app is sandboxed: other apps cannot read its private files or databases. Android offers controlled ways to share:

Mechanism How
Share intent (ACTION_SEND) Send text, links or files to another app chosen by the user
Content Provider A component exposing structured data through a content URI (content://authority/path) with query/insert/update/delete; used by Contacts, Calendar, MediaStore
ContentResolver The client object apps use to talk to any provider
FileProvider Shares a private file securely through a temporary content:// URI with read permission (never share file:// URIs – blocked since Android 7)
Intent extras / results Pass data between activities (lab 4)
Clipboard ClipboardManager copy/paste
Cloud backend Firestore/REST API to share data across users and devices
// Reading contacts through the Contacts content provider (needs READ_CONTACTS permission)
Cursor cursor = getContentResolver().query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}, null, null, null);
if (cursor != null) {
    while (cursor.moveToNext()) Log.d("C", cursor.getString(0));
    cursor.close();
}

Content URI parts: content:// (scheme) + authority (e.g. com.android.contacts) + path (table) + optional ID.

Short and long questions

1. Differentiate between event listeners and event handlers.

Model answer

Event listeners are interfaces registered on a view from outside (setOnClickListener) to respond to user events. Event handlers are callback methods such as onTouchEvent() or onKeyDown() that are overridden inside a custom View class to handle its own events.

2. What is an event listener? Name five listeners with their callbacks.

Model answer

An event listener is an interface with callback methods that Android calls when the user interacts with a view. Examples: OnClickListener – onClick(); OnLongClickListener – onLongClick(); OnTouchListener – onTouch(); OnFocusChangeListener – onFocusChange(); TextWatcher – afterTextChanged() (also OnCheckedChangeListener – onCheckedChanged()).

3. What is RecyclerView? Name its main components.

Model answer

RecyclerView is a flexible, efficient widget for displaying large scrollable lists and grids by recycling row views that leave the screen. Components: LayoutManager (Linear/Grid/Staggered), Adapter (onCreateViewHolder, onBindViewHolder, getItemCount) and ViewHolder (holds references to row views).

4. Differentiate between apply() and commit().

Model answer

apply() commits changes to memory immediately and writes to disk asynchronously, returning nothing – preferred on the UI thread. commit() writes synchronously and returns true or false indicating success.

5. What are SharedPreferences? Write code to save and read a username.

Model answer

SharedPreferences store small amounts of primitive data as key–value pairs in a private XML file that persists until uninstall. Save: getSharedPreferences("user_prefs", MODE_PRIVATE).edit().putString("username", name).apply(); read: getSharedPreferences("user_prefs", MODE_PRIVATE).getString("username", "Guest").

6. What is Room? Name its three main components.

Model answer

Room is a Jetpack persistence library providing an object-mapping layer over SQLite with compile-time SQL verification. Components: Entity (table), DAO (data access methods with @Insert, @Query etc.) and Database (abstract RoomDatabase class providing DAOs).

7. List the data storage options in Android.

Model answer

SharedPreferences/DataStore (key–value), internal storage files (private), external/shared storage via MediaStore and Storage Access Framework, SQLite databases (directly or through Room), and network/cloud storage (Firebase, REST APIs).

8. What is a content provider? Give the structure of a content URI.

Model answer

A content provider is an app component that manages access to a structured set of data and shares it with other apps through query, insert, update and delete operations (e.g. Contacts, MediaStore). A content URI has the form content://authority/path/id – scheme content://, the provider's authority, the table path and an optional row ID.

9. Describe the different ways of persisting data in Android – files, SQLite and Room – and explain how apps share data with each other using content providers and FileProvider.

Model answer

1. Internal storage files – openFileOutput("notes.txt", MODE_PRIVATE) to write and openFileInput to read in the private filesDir; no permission; deleted on uninstall. cacheDir holds temporary data.

2. External/shared storage – app-specific external folders need no permission; shared media goes through MediaStore and documents through the Storage Access Framework; Android 13+ uses READ_MEDIA_* permissions and the Photo Picker (scoped storage).

3. SQLite – a built-in relational database stored as a private .db file. Create it by extending SQLiteOpenHelper (onCreate: CREATE TABLE; onUpgrade: migrate), then use insert with ContentValues, query returning a Cursor, update and delete, or execSQL/rawQuery.

4. Room – a Jetpack layer over SQLite: @Entity classes define tables, @Dao interfaces declare @Insert/@Update/@Delete/@Query methods (verified at compile time), and an abstract @Database class provides DAOs. Queries must run off the main thread (e.g. on an ExecutorService) and can return LiveData for automatic UI updates. Room reduces boilerplate and errors and is Google's recommendation.

5. Cloud – Firebase Firestore, Supabase or a REST API for data shared across devices and users.

Sharing data: apps are sandboxed. A Content Provider exposes data through content URIs (content://authority/path/id) and is accessed by other apps with ContentResolver (query, insert, update, delete), protected by permissions – e.g. Contacts (READ_CONTACTS) and MediaStore. FileProvider shares private files through temporary content:// URIs with FLAG_GRANT_READ_URI_PERMISSION (file:// URIs are not allowed since Android 7). Simple data can be shared with ACTION_SEND intents, intent extras or the clipboard.

10. Explain user preferences in Android. Describe SharedPreferences with code for saving, reading, updating and deleting data, compare apply and commit, and mention DataStore and preference screens.

Model answer

User preferences are small pieces of data – settings and simple state such as username, dark mode, language, first-launch flag or high score – stored as key–value pairs that persist across app restarts.

SharedPreferences: obtained with getSharedPreferences("user_prefs", MODE_PRIVATE) (or getPreferences for a single activity). Data is stored in an XML file in /data/data/package/shared_prefs, private to the app, until uninstall or Clear data. Supported types: Boolean, Int, Long, Float, String and Set of String.

  • Save/update: prefs.edit().putString("username", "ali").putBoolean("dark_mode", true).apply()
  • Read: prefs.getString("username", "Guest"), prefs.getBoolean("dark_mode", false) – the second argument is the default.
  • Delete: prefs.edit().remove("username").apply(); clear all: prefs.edit().clear().apply().
  • Listen: registerOnSharedPreferenceChangeListener.

apply vs commit: apply() updates memory immediately and writes to disk asynchronously with no return value; commit() writes synchronously and returns a Boolean – avoid it on the UI thread.

Preference screens: the AndroidX Preference library defines settings in XML (SwitchPreferenceCompat, ListPreference, EditTextPreference) displayed by PreferenceFragmentCompat, saving values automatically.

DataStore: the modern Jetpack replacement (Preferences DataStore and Proto DataStore) that is asynchronous, is transactional and avoids blocking the UI thread.

Security: preferences are plain text; never store passwords or tokens without Keystore-based encryption.

This lesson ends with a quiz of 32 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Mid-Term Revision and Exam Guide (Weeks 1–8) + Lab Mid-Term · Next: Week 10 Lab 10 – Store and Retrieve a Username Using SharedPreferences

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester