Introduction to SharedPreferences (kotlin/java)

Save items – SharedPreferences (kotlin/java)

Save items – SharedPreferences (kotlin/java)

Under Android, it is common to want to save an element, for example, the name of the connected user, or for example a string list. We have in this case several methods:

  • SharedPreferences
  • Write to a file
  • Save to a database

I will not go into the details of the 3 methods, which each have their advantages and disadvantages. We will focus today on SharedPreferences.

SharedPreferences (java and kotlin)

SharedPreferences are storage spaces specific to each Android application. With a key / value system, you will be able to persist your data easily.

Creation of SharedPreferences (kotlin/java)

SharedPreferences are to be retrieved from a context, with context.getSharedPreferences (NAME, MODE)

1
context.getSharedPreferences("user_prefs",Context.MODE_PRIVATE);

safeguard

In order to save an element, you must open an editor, with sharedPreferences.edit () , you will then have access to all the methods .putString (KEY, VALUE) , .putInt (KEY, VALUE) , etc.

Once your objects are inserted, do not forget to call the .apply () method

sharedPreferences
          .edit()
                    .putInt("integer", 3)
                    .putString("string", "monString")
          .apply();

 

Recovery

The recovery of a persisted element is done with the methods .getString (KEY, DEFAULT_VALUE) , .getInt (KEY, DEFAULT_VALUE) , etc.

You can check the presence of an element with .containsKey (KEY)

1
2
int myInteger = sharedPreferences.getInt("integer", 0);
String myString = sharedPreferences.getString("string", null)

Java example

In this example, I will show how to save an element once and then load it when the application is next started:

public class MainActivity extends AppCompatActivity {

    private static final String PREFS = "PREFS";
    private static final String PREFS_AGE = "PREFS_AGE";
    private static final String PREFS_NAME = "PREFS_NAME";
    SharedPreferences sharedPreferences;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        sharedPreferences = getBaseContext().getSharedPreferences(PREFS, MODE_PRIVATE);
 
     // goal: save only once the name and age of the user
 
        // for that, we start by looking if we already have elements saved
        if (sharedPreferences.contains(PREFS_AGE) && sharedPreferences.contains(PREFS_NAME)) {
 
            int age = sharedPreferences.getInt(PREFS_AGE, 0);
            String name = sharedPreferences.getString(PREFS_NAME, null);
 
            Toast.makeText(this, "Age: " + age + " name: " + name, Toast.LENGTH_SHORT).show();
 
        } else {
           // if no user is saved, add [24, florent]
            sharedPreferences
                    .edit()
                    .putInt(PREFS_AGE, 29)
                    .putString(PREFS_NAME, "Robort Gabriel")
                    .apply();
 
            Toast.makeText(this, "Saved, restart the application to see the result", Toast.LENGTH_SHORT).show();
        }
    }
 
}

Kotlin Example

package com.coding180.com.sharedpreferences

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast


/**
 * Created by xrobot on 1/23/2018.
 */

class MainActivity_Kotlin : AppCompatActivity() {
    internal lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sharedPreferences = baseContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)

        // goal: save only once the name and age of the user

        // for that, we start by looking if we already have elements saved
        if (sharedPreferences.contains(PREFS_AGE) && sharedPreferences.contains(PREFS_NAME)) {

            val age = sharedPreferences.getInt(PREFS_AGE, 0)
            val name = sharedPreferences.getString(PREFS_NAME, null)
            Toast.makeText(this, "Age: $age name: $name", Toast.LENGTH_SHORT).show()

        } else {
            // if no user is saved, add [24, florent]
            sharedPreferences
                    .edit()
                    .putInt(PREFS_AGE, 29)
                    .putString(PREFS_NAME, "Robort Gabriel")
                    .apply()

            Toast.makeText(this, "Saved, restart the application to see the result", Toast.LENGTH_SHORT).show()
        }
    }
    companion object {
        private val PREFS = "PREFS"
        private val PREFS_AGE = "PREFS_AGE"
        private val PREFS_NAME = "PREFS_NAME"
    }

}

SharedPreferences XML file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.coding180.com.sharedpreferences.MainActivityJava">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!