free web tracker
Course Content
Java Programming Basics for Android
Learn the basics of Java programming for Android app development using Android Studio. This guide covers key concepts like variables, loops, and classes to help you start building your first Android apps with confidence. Perfect for beginners!
0/10
User Interaction and App Logic
Learn how to make your app respond to users! This section covers handling clicks, getting input, showing messages, switching screens, and saving simple data. A perfect start to build interactive Android apps with real logic.
0/10
Advanced Layouts and Components
Learn to build modern Android UIs using advanced layouts like RecyclerView, CardView, TabLayout, and more. This section helps beginners create beautiful, interactive, and user-friendly app interfaces step by step.
0/10
Media and Resources
Learn how to manage media and resources in Android Studio. This section covers adding audio, images, video, using drawables, custom fonts, and handling runtime permissions—essential for building rich, engaging Android applications.
0/4
Mastering Java Android Development – Beginner

1. What is SharedPreferences?

SharedPreferences is a key-value pair storage method in Android. It is best used for saving small pieces of data like user settings, login states, or preferences.

2. Create or Access SharedPreferences

SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);

    • "MyPrefs" is the name of the preference file.
    • MODE_PRIVATE means the file is accessible only by your app.

3. Save Data to SharedPreferences

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.putInt("userAge", 25);
editor.putBoolean("isLoggedIn", true);
editor.apply(); // or editor.commit();

    • apply() saves changes asynchronously.
    • commit() saves changes synchronously and returns a success boolean.

4. Retrieve Data from SharedPreferences

String username = sharedPreferences.getString("username", "defaultUser");
int age = sharedPreferences.getInt("userAge", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

Use default values in case the key doesn’t exist.

5. Remove or Clear SharedPreferences Data

// Remove specific data
editor.remove("username");
editor.apply();

// Clear all data
editor.clear();
editor.apply();

Use Case Example: Login State Check

if(sharedPreferences.getBoolean("isLoggedIn", false)) {
    // Navigate to MainActivity
} else {
    // Navigate to LoginActivity
}

Best Practices

    • Use meaningful key names.
    • Don’t use SharedPreferences to store large or complex objects.
    • Use apply() unless you need confirmation that the data was saved.