Java Android App Development Course, Save to Shared Preferences

When developing on Android, there are often cases where you need to store certain settings or user information of the application.
What is used at this time is SharedPreferences.
SharedPreferences is useful for saving data using simple key-value pairs and is suitable for storing small amounts of data.
In this tutorial, we will cover how to save and retrieve user information using SharedPreferences.

1. What is SharedPreferences?

SharedPreferences is a lightweight data storage mechanism in Android that makes it easy to save and recover application settings, user information, etc.
It is suitable for storing small data sets, and the data is stored in the XML file format in the app’s data directory.

2. Reasons to Use SharedPreferences

  • Simple data storage: It allows you to easily save simple information such as user settings and login information.
  • Shareable: You can easily access shared values across multiple activities.
  • Lightweight: It is useful when using a complex database is unnecessary.

3. Basic Usage of SharedPreferences

The process of using SharedPreferences can be broadly divided into three steps:
Creation, Data Saving, Data Retrieval.

3.1 Creating SharedPreferences

The method for creating SharedPreferences is as follows. The code below is an example of creating SharedPreferences in the `MainActivity` class.

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

3.2 Data Saving

When saving data to SharedPreferences, you need to use the `Editor`. Below is an example of saving a username and age.


SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "John Doe");
editor.putInt("age", 25);
editor.apply();

3.3 Data Retrieval

To retrieve the saved data, use the `getString` or `getInt` method. The code below is an example of retrieving saved user information.


String username = sharedPreferences.getString("username", "default");
int age = sharedPreferences.getInt("age", 0);

4. Practical Example

Below is the example code utilizing SharedPreferences overall. We will create an app that saves information entered by the user and displays the saved information on the screen.

4.1 Layout File (activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username"/>

    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="number"/>

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"/>

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    </LinearLayout>

4.2 Main Activity (MainActivity.java)

import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

        private SharedPreferences sharedPreferences;
        private EditText editTextUsername, editTextAge;
        private TextView textViewResult;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            editTextUsername = findViewById(R.id.editTextUsername);
            editTextAge = findViewById(R.id.editTextAge);
            textViewResult = findViewById(R.id.textViewResult);
            Button buttonSave = findViewById(R.id.buttonSave);

            sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
            loadStoredData();

            buttonSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String username = editTextUsername.getText().toString();
                    int age = Integer.parseInt(editTextAge.getText().toString());
                    saveData(username, age);
                }
            });
        }

        private void saveData(String username, int age) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username", username);
            editor.putInt("age", age);
            editor.apply();
            loadStoredData();
        }

        private void loadStoredData() {
            String username = sharedPreferences.getString("username", "default");
            int age = sharedPreferences.getInt("age", 0);
            textViewResult.setText("Username: " + username + "\nAge: " + age);
        }
    }

5. Precautions

SharedPreferences is suitable for storing small amounts of data.
If you need to store large amounts of data or complex data structures, it is recommended to use an SQLite database or the Room library.

6. Conclusion

In this tutorial, we learned how to save and retrieve simple user information using SharedPreferences.
By utilizing these features, you can develop various applications that enhance the user experience.
In the future, we will also cover how to use the Room library to efficiently manage more data.