Lesson 13 – Store Data Using the SharedPreferences Class

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

The Android platform gives us several facilities for permanent data storage (i.e they are not deleted when the application is shut down or closed)

Depending on the type of needs we will use one of these methods:

  1. Using the SharedPreferences class.
  2. Using Text files.
  3. In a database with access to SQL.

It will not be unusual for an application to use more than one of these methods for data storage.

When we have to store a limited amount of data it is appropriate to use the SharedPreferences class. For example application settings such as display colors, the current level in a game, initial data of input controls etc.

Problem 1:

Make a program that requests the entry of a person’s email. Save the email entered using the SharedPreferences class. Each time the application is started, store the last entered email in the EditText control. Provide a button to store the entered mail and end the program.

We will create a new project called project013.

The visual interface to implement is:

 

Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class -

We have the components:

 
We have an EditText (ID = "et1", hint = "Enter email")
We have a Button (ID = "button1", text = "save")

The code Kotlin is:

package com.coding180.project013


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText

class MainActivity: AppCompatActivity () {

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

        val et1 = findViewById (R.id.et1) as EditText
        val preferences = getSharedPreferences ("data", Context.MODE_PRIVATE)
        et1.setText (preferences.getString ("mail", ""))
        val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
            val editor = preferences.edit ()
            editor.putString ("mail", et1.text.toString ())
            editor.commit ()
            finish()
        }
    }
}

We get the reference of the EditText:

        Val et1 = findViewById (R.id.et1) as EditText

We obtain a reference from an object of the SharedPreferences class through the inherited getSharedPreferences method of the AppCompatActivity class. The first parameter is the name of the preferences file and the second is the way the file is created (MODE_PRIVATE indicates that only this application can query the XML file that is created)

        Val preferences = getSharedPreferences ("data", Context.MODE_PRIVATE)

To extract the data from the preferences file we must indicate the name to extract and a return value if the name does not exist in the preferences file (in our example the first time that our program is executed logically there is no preferences file Which makes Android believe it, if we try to extract the value of mail will return the second parameter ie the String with an empty string:

        Et1.setText (preferences.getString ("mail", ""))

When you press the “confirm” button, what we do is to save the contents of the EditText in a variable called “mail” in the preferences file:

        Button1.setOnClickListener {
            Val editor = preferences.edit ()
            Editor.putString ("mail", et1.text.toString ())
            Editor.commit ()
            Finish ()
        }

We must create an object of the class Editor and obtain the object reference of the class SharedPreferences that we just created. Using the putString method, we store in mail the value of the String loaded in the EditText. Then we must call the commit method of the Editor class so that the data is stored permanently in the preferences file. This causes that when we restart the application recovers the last email entered.

Recall that the finish method of the AppCompatActivity class ends the current activity (as we have an application with a single activity will completely end our program)

When we save data in the preferences file we can store different types of data according to the method we call at the time of recording:

            Editor.putInt ("age", 3)
            Editor.putBoolean ("active", true)
            Editor.putFloat ("height", 2.3f)

When we retrieve them we must also indicate what kind of data we extract:

            Val e = preferences.getInt ("age", 0)
            Val acti = preferences.getBoolean ("active", false)
            Val alt = preferences.getFloat ("height", 0f)

Problem 2:

Make a program that allows managing a personal agenda. Our key will be the name of the person.

We will create a new project called project014.

The visual interface to implement will be similar to this:

 

Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class -

  EditText of type Plain Text (ID = et1, hint = "Name of the person", text = "")
  EditText of type Multiline Text (ID = et2, hint = "data")
  Button (ID = "boton1", text = "RECORD")
  Button (ID = "boton2", text = "RECOVER")

The source code in Kotlin is:

package com.coding180.project001


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

class MainActivity: AppCompatActivity () {

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

        val et1 = findViewById (R.id.et1) as EditText
        val et2 = findViewById (R.id.et2) as EditText
        val preferences = getSharedPreferences ("schedule", Context.MODE_PRIVATE)
        val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
            val editor = preferences.edit ()
            editor.putString (et1.text.toString (), et2.text.toString ())
            editor.commit ()
            Toast.makeText (this, "Recorded Data", Toast.LENGTH_LONG) .show ()
            et1.setText ("")
            et2.setText ("")
        }
        var button2 = findViewById (R.id.button2) as Button
        button2.setOnClickListener {
            val data = preferences.getString (et1.text.toString (), "")
            if (data.length == 0)
                Toast.makeText (this, "There is no such name in the directory", Toast.LENGTH_LONG) .show ()
            else
                et2.setText (data)

        }
    }
}

We get the reference of the two EditText:

        Val et1 = findViewById (R.id.et1) as EditText
        Val et2 = findViewById (R.id.et2) as EditText

We get the reference of the preferences file called “agenda”:

        Val preferences = getSharedPreferences ("schedule", Context.MODE_PRIVATE)

When you press the record button we create an object of the class Editor by calling the edit method of the object preferences:

        Boton1.setOnClickListener {
            Val editor = preferences.edit ()

We record in the file of preferences as key the name of the person stored in et1 and as value the data stored in the et2:

            Editor.putString (et1.text.toString (), et2.text.toString ())

Finally we confirm the recording in the preferences file by calling the commit method:

            Editor.commit ()

We show the program operator a message indicating that the data was stored and delete the contents of the two EditText:

            Toast.makeText (this, "Recorded Data", Toast.LENGTH_LONG) .show ()
            Et1.setText ("")
            Et2.setText ("")

When you press the recover button we look in the preferences file if there is any key with the name loaded in the et1:

        Boton2.setOnClickListener {
            Val data = preferences.getString (et1.text.toString (), "")

If in the variable data has zero characters then we can show the operator that there is no person with the name entered:

            If (data.length == 0)
                Toast.makeText (this, "There is no such name in the directory", Toast.LENGTH_LONG) .show ()

Otherwise we show the data retrieved in et2:

             Else
                Et2.setText (data)
        }

In the emulator we can see how we enter and retrieve data from the agenda:

 

Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class - Lesson 13 - Store Data Using the SharedPreferences Class -

About The Author

Related posts

Leave a Reply