Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 10 Lab 10 – Store and Retrieve a Username Using SharedPreferences
Week 10 – UI Events, Views, Preferences and Data Storage · 120 min read · 8 MCQs to check yourself
Coding in Flow – How to save variables in SharedPreferences
Objective
Save the student's username with SharedPreferences, read it back when the app opens again ("Welcome back, Ali!"), count app launches, and remove the data on Logout – then find the saved XML file on the device. CLOs: CLO-2 (develop apps that store data), CLO-3 (choose a suitable storage option).
What you will build in CampusMate
A LoginActivity that remembers the user:
| First launch | Next launches (Remember me ticked) |
|---|---|
| Empty username box, "Welcome to CampusMate" | Username filled in, "Welcome back, Ali!", launch count |
SharedPreferences = a small key–value file private to the app – perfect for usernames, settings and flags (not for big data or passwords).
Workflow
| Step | What you do | File |
|---|---|---|
| 1 | Create LoginActivity and make it the launcher | New → Activity, manifest |
| 2 | Design the login screen | activity_login.xml |
| 3 | Open the preferences file | LoginActivity.java |
| 4 | Save the username (Login button) | saveUser() |
| 5 | Read it on start + launch counter | loadUser() |
| 6 | Remove it (Logout / Forget me) | forgetUser() |
| 7 | Find the XML file in Device Explorer | Android Studio |
| 8 | Run and test | Emulator |
Step 1 – Create LoginActivity
New → Activity → Empty Views Activity → LoginActivity, tick Launcher Activity (so the app now starts here). If it is not ticked, move the <intent-filter> with MAIN/LAUNCHER from MainActivity to LoginActivity in the manifest.
Step 2 – Layout (activity_login.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/tvGreeting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to CampusMate"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvLaunches"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/etUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Username"
android:inputType="text" />
<CheckBox
android:id="@+id/cbRemember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember me" />
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />
<Button
android:id="@+id/btnForget"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Forget me" />
</LinearLayout>
Step 3 – Open the preferences file (LoginActivity.java)
package com.example.campusmate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
// Keys: use constants so a typing mistake cannot create a different key
private static final String PREFS = "user_prefs";
private static final String KEY_USERNAME = "username";
private static final String KEY_REMEMBER = "remember";
private static final String KEY_LAUNCHES = "launches";
private SharedPreferences prefs;
private EditText etUsername;
private CheckBox cbRemember;
private TextView tvGreeting, tvLaunches;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
prefs = getSharedPreferences(PREFS, MODE_PRIVATE); // file: user_prefs.xml
etUsername = findViewById(R.id.etUsername);
cbRemember = findViewById(R.id.cbRemember);
tvGreeting = findViewById(R.id.tvGreeting);
tvLaunches = findViewById(R.id.tvLaunches);
findViewById(R.id.btnLogin).setOnClickListener(v -> saveUser());
findViewById(R.id.btnForget).setOnClickListener(v -> forgetUser());
loadUser(); // Step 5
}
// Steps 4–6 below
}
MODE_PRIVATE = only CampusMate can read this file.
Step 4 – Save the username
private void saveUser() {
String name = etUsername.getText().toString().trim();
if (name.isEmpty()) {
etUsername.setError("Enter a username");
return;
}
prefs.edit() // 1. get an Editor
.putString(KEY_USERNAME, name) // 2. put values
.putBoolean(KEY_REMEMBER, cbRemember.isChecked())
.apply(); // 3. save in the background
Toast.makeText(this, "Saved. Logging in…", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, HomeActivity.class); // the dashboard from Lab 5
i.putExtra("NAME", name);
startActivity(i);
}
apply() saves asynchronously (no UI freeze); commit() saves immediately and returns true/false – use apply() normally.
Step 5 – Read it back and count launches
private void loadUser() {
// Launch counter: read old value, add 1, write back
int launches = prefs.getInt(KEY_LAUNCHES, 0) + 1;
prefs.edit().putInt(KEY_LAUNCHES, launches).apply();
tvLaunches.setText("App opened " + launches + " time(s)");
String saved = prefs.getString(KEY_USERNAME, null); // null if never saved
boolean remember = prefs.getBoolean(KEY_REMEMBER, false);
if (saved != null && remember) {
etUsername.setText(saved);
cbRemember.setChecked(true);
tvGreeting.setText("Welcome back, " + saved + "!");
}
}
The second parameter of every get…() is the default value returned when the key does not exist yet.
Step 6 – Remove the data (Forget me / Logout)
private void forgetUser() {
prefs.edit()
.remove(KEY_USERNAME) // delete one key
.remove(KEY_REMEMBER)
.apply();
// prefs.edit().clear().apply(); // would delete ALL keys, including the counter
etUsername.setText("");
cbRemember.setChecked(false);
tvGreeting.setText("Welcome to CampusMate");
Toast.makeText(this, "Username removed", Toast.LENGTH_SHORT).show();
}
Connect to Lab 8: the Logout menu item in HomeActivity can call the same code: getSharedPreferences("user_prefs", MODE_PRIVATE).edit().remove("username").apply(); before finish().
Step 7 – See the file on the device
Run the app on an emulator → View → Tool Windows → Device Explorer → data/data/com.example.campusmate/shared_prefs/user_prefs.xml → double-click:
<map>
<string name="username">Ali</string>
<boolean name="remember" value="true" />
<int name="launches" value="3" />
</map>
It is plain XML – so never store passwords in SharedPreferences.
Run and test
| Test | Expected result |
|---|---|
| First launch | "Welcome to CampusMate", "App opened 1 time(s)" |
| Enter Ali, tick Remember, Login | Dashboard opens |
| Close the app (swipe away) and reopen | "Welcome back, Ali!", count increases |
| Login without Remember, reopen | Field empty (remember = false) |
| Forget me, reopen | No greeting; count still increases |
| Device Explorer | user_prefs.xml shows your values |
Common errors and fixes
| Problem | Fix |
|---|---|
| Value never saved | You forgot .apply() (or .commit()) at the end |
| Value always default | Key spelled differently when saving and reading – use constants |
| ClassCastException | Saved with putInt, read with getString – use the same type |
| Old data after reinstall testing | Uninstall the app or Settings → Apps → CampusMate → Clear storage |
Short and long questions
1. (Viva) How did your app greet the user automatically on the next launch?
Model answer
In onCreate it read prefs.getString("username", null) and getBoolean("remember", false); if a username existed and remember was true, it set the welcome TextView to "Welcome back, name!".
2. (Viva) Why should passwords not be stored in SharedPreferences?
Model answer
The XML file is plain text; on rooted devices or through backups it could be read. Sensitive data must be encrypted using the Android Keystore or not stored on the device at all.
3. (Viva) Where is SharedPreferences data stored and when is it deleted?
Model answer
In an XML file in /data/data/package/shared_prefs/ in the app's private storage. It is deleted when the app is uninstalled, when the user clears app data, or when the app calls remove()/clear().
4. (Viva) Write the code you used to save the username.
Model answer
getSharedPreferences("user_prefs", MODE_PRIVATE).edit().putString("username", name).putBoolean("remember", cbRemember.isChecked()).apply();
This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 10 Theory – Listening for UI Notifications; Views; User Preferences; Persisting Data; Sharing Data · Next: Week 11 Theory – Sending SMS Messages; Getting Feedback; Sending E-mail
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester