Lesson 33. Data Storage. Preferences.

Lesson 33. Data Storage. Preferences.


In this lesson:

– storing data using Preferences

Enough about Intent and Activity. Let’s talk about data storage. There are several ways to store data on Android:

Preferences – VINI files can be cited as an analogy

SQLite – database, tables

regular files – internal and external (on SD card)

We will start with the simplest – Preferences. Values ​​are saved as a pair: name, value. Just like extras in Intent.

Let’s develop an application. It will have a text box and two buttons – Save and Load. Clicking on Save we will save value from the field after clicking on Load download.

Let’s create a project:

Project name: P0331_SharedPreferences
Build Target: Android 2.3.3
Application name: SharedPreferences
Package name: en.startandroid.develop.p0331sharedpreferences
Create Activity: MainActivity

open main.xml and create the following screen:



        
                
                
        
        
                
                
        

Input box and two buttons.

Now we write code in MainActivity.java:

package ru.startandroid.develop.p0331sharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
  
  EditText etText;
  Button btnSave, btnLoad;
  
  SharedPreferences sPref;
  
  final String SAVED_TEXT = "saved_text";
  
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        etText = (EditText) findViewById(R.id.etText);
        
        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);
        
        btnLoad = (Button) findViewById(R.id.btnLoad);
        btnLoad.setOnClickListener(this);
    }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnSave:
      saveText();
      break;
    case R.id.btnLoad:
      loadText();
      break;
    default:
      break;
    }
  }
  
  void saveText() {
    sPref = getPreferences(MODE_PRIVATE);
    Editor ed = sPref.edit();
    ed.putString(SAVED_TEXT, etText.getText().toString());
    ed.commit();
    Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
  }
  
  void loadText() {
    sPref = getPreferences(MODE_PRIVATE);
    String savedText = sPref.getString(SAVED_TEXT, "");
    etText.setText(savedText);
    Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
  }
}

Identifying screen elements, assigning handlers, and implementing onClick are all clear and simple. we are interested methodsWhich we call in onClick

saveText – data retention. First, we get an object using the getPreferences method sPref class SharedPreferenceswhich allows work with data (read and write). The MODE_PRIVATE constant is used to configure access and means that after saving, the data will only be open this with the app. Next, you need an object to edit the data Editor – we get it from sPref. Specify the putString method name variable is a constant SAVED_TEXT, and value – field content etText. To save the data, commit must be performed. And for clarity we deduce messageThat the data is saved.

loadText – data download. Just like saveText, using the method getPreferences we get the sPref class object SharedPreferences. MODE_PRIVATE again indicated, although only used when recording data. We do not use Editor here because we are only interested in reading data. We read with the method getString – in the parameters we specify a constant – this name, and value default (blank line). Next, write the values ​​in the input field etText and output messageThat the data is read.

We save everything, launch the application.

For starters, let’s make sure that storage is basically needed. Enter some thread in the input field

and without pressing a button Save close the application with a button back.

Now find the app in the general list of emulator apps

and run again.

The input field is empty. What we introduced was missing when the program closed. clicking on Load will also give nothing – we have not stored anything.

Let’s try to save. Re-enter the value and press Save.

The value is saved in the system.

Now close the application (back), Reopen and click Load. The value was considered and reflected.

Let’s make the save and download happen automatically at closing and opening programs, but you didn’t have to push buttons. For this method loadText we will call in onCreate.

public void onCreate(Bundle savedInstanceState) {
  
    ...
  
    btnLoad = (Button) findViewById(R.id.btnLoad);
    btnLoad.setOnClickListener(this);
    
    loadText();
} 

(Only add line 8)

and the saveText method in onDestroy

  @Override
  protected void onDestroy() {
    super.onDestroy();
    saveText();
  }

Let’s save everything, run it. You can now enter data, close the application, reopen it and the data will not be lost. buttons Save and Load also work. When to save it in your application requests is up to you. by press buttons at closing programs, or any other event. The main thing – now you know it.

A few more words on this topic.

Preferences are stored in files and you can view them. To do this, open the menu in Eclipse Window > Show View > Other and select Android > File Explorer. The emulator file system is displayed.
open the folder data / data / ru.startandroid.develop.p0331sharedpreferences / shared_prefs and we see a file there MainActivity.xml. If you download it to your computer and open it, we will see



        abcdefg

That’s right, the name is saved_text and value – abcdefg.

Please note that our package is used in the file path.

Now let’s find out where the file name came from MainActivity.xml. In addition to the method getPreferencesThe one we used is the getSharedPreferences method. It performs exactly the same functions, but allows you to specify a file name to store data. That is, for example, if we were in saveText used the following code to get SharedPreferences:

sPref = getSharedPreferences("MyPref", MODE_PRIVATE);

That data would be stored in a file MyPref.xml, Not in MainActivity.xml.

Now if we look at the output method getPreferences, Then we see the following:

public SharedPreferences getPreferences(int mode) {
  return getSharedPreferences(getLocalClassName(), mode);
}

the method is used getSharedPreferences, And the file name is the class name of the current file Activity. Hence the file name MainActivity.xml.

As a result:

– use getPreferencesIf you are working with data for the current Activity and do not want to invent a file name.

– use getSharedPreferencesIf, for example, you save data that is common to multiple Activity and you choose the file name to save.

By the way, in File Explorer you can see the unicode rwx permissions to the file. Try not to use when saving data MODE_PRIVATE, And MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE and see how the rights change.

full code MainActivity.java:

package ru.startandroid.develop.p0331sharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
  
  EditText etText;
  Button btnSave, btnLoad;
  
  SharedPreferences sPref;
  
  final String SAVED_TEXT = "saved_text";
  
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        etText = (EditText) findViewById(R.id.etText);
        
        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);
        
        btnLoad = (Button) findViewById(R.id.btnLoad);
        btnLoad.setOnClickListener(this);
        
        loadText();
    }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnSave:
      saveText();
      break;
    case R.id.btnLoad:
      loadText();
      break;
    default:
      break;
    }
  }
  
  void saveText() {
    sPref = getPreferences(MODE_PRIVATE);
    Editor ed = sPref.edit();
    ed.putString(SAVED_TEXT, etText.getText().toString());
    ed.commit();
    Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
  }
  
  void loadText() {
    sPref = getPreferences(MODE_PRIVATE);
    String savedText = sPref.getString(SAVED_TEXT, "");
    etText.setText(savedText);
    Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
  }
  
  @Override
  protected void onDestroy() {
    super.onDestroy();
    saveText();
  }

}

In the next lesson:

– data storage with SQLite




Discuss in the forum [202 replies]

Leave a Comment