Android Development 7: simple data storage (using SharedPreferences) and file operations,

Source: Internet
Author: User

Android Development 7: simple data storage (using SharedPreferences) and file operations,
Preface

La la ~ Hello, everyone. Meet again ~

This blog post describes how to complete a memorandum for registration and logon, learn basic usage of SharedPreferences, learn common file operations in Android, and review programming on the Android interface.

Go to the topic ~

 

Basic knowledge 1. Use of SharedPreferences

You can use SharedPreferences to store the user name and password. SharedPreferences directly processes xml files without the need to separate strings. The storage efficiency is higher than that of internal storage and the user name and password of external storage.

  (1) read SharedPreferences

In Android, The getSharedPreferences (String, int) function is used to obtain SharedPreferences. Meanings of the two parameters:

String: Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor.

Int: Operating mode. Use 0 or MODE_PRIVATE for the default operation.

For SharedPreferencesReadThe operation is completed by using the SharedPreferences object method returned by the getSharedPreferences (String, int) function. You can see that SharedPreferences supports the following methods to read the previously stored data:

      • Abstract Map <String,?> GetAll ()
      • Abstract boolean getBoolean (String key, boolean defValue)
      • Abstract float getFloat (String key, float defValue)
      • Abstract int getInt (String key, int defValue)
      • Abstract long getLong (String key, long defValue)
      • Abstract String getString (String key, String defValue)
      • Abstract Set <String> getStringSet (String key, Set <String> defValues)

A defValue parameter is required for all methods. If the specified key does not exist, SharedPreferences will directly return this default value.

(2) Write SharedPreferences

All write operations on SharedPreferences must be completed through the Editor object returned by the SharedPreferences. edit () function.

Example:

Context context = getActivity();SharedPreferences sharedPref = context.getSharedPreferences("MY_PREFERENCE", Context.MODE_PRIVATE);// Alternatively, if you need just one shared preference file for your activity, you can use the getPreferences() method://    SharedPreferences sharedPref =getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("KEY_SCORE", newHighScore); editor.commit();

After using SharedPreferences to save the user name and password locally, you can find an info. xml file under the \ data \ + package name + \ shared_prefs directory.

 

2. Android File Operations in

There are two types of Storage space in Android: Internal Storage and External Storage.

(1) Internal Storage

By default, files stored in Internal Storage are only visible to applications. Other applications and users cannot access these files in their own regions.

The sample code for writing files to Internal Storage is as follows:

try (FileOutputStream fileOutputStream = openFileOutput(FILE_NAME, MODE_PRIVATE)) { String str = "Hello, World!"; fileOutputStream.write(str.getBytes()); Log.i("TAG", "Successfully saved file.");} catch (IOException ex) { Log.e("TAG", "Fail to save file.");}

If the corresponding file does not exist, the openFileOutput (String, int) function will directly create a new file. Note that the input file name parameter cannot contain path separators (I .e. '/'). This function returns a FileOutputStream object and can call the write () method to write the content.

Correspondingly, you can use openFileInput (String) to read files. This function returns a FileInput-Stream and calls the read () method to read the content.

try (FileInputStream fileInputStream =openFileInput(FILE_NAME)) { byte[] contents = new byte[fileInputStream.available()];     fileInputStream.read(contents);} catch (IOException ex) { Log.e("TAG", "Fail to read file.");}

 

(2) External Storage

Android supports reading and writing files using Java file APIs, but the key point is to have a proper path. If you want to store some public, large files (such as media files), External Storage is a suitable place. As stated in the document:

All Android devices have two file storage areas: "internal" and "external" storage. these names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage ), plus a removable stor-age medium such as a micro SD card (external storage ). some devices divide the permanent storage space into "internal" and "external" partitions,So even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not.

Whether or not the external SD card is supported, all Android devices divide the storage space into two parts: internal and external.

To write files to External Storage, you must declare the permission in the AndroidManifest. xml file:

    • <manifest ...><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />...</manifest>

Call getExternalFilesDir (String type) or Environment. getExternalStoragePublicDirectory () to obtain the SD card path. The difference between the two is that the directory pointed to by the former will be deleted when the application is uninstalled, while the latter will not.

 

The above two functions return a File object, representing a directory path. Using this File object, combined with the File name, you can create FileInputStream or FileOutputStream to read and write the swap File.

Example:

 

    • void createExternalStoragePrivateFile() {// Create a path where we will place our private file on  external// storage.File file = new File(getExternalFilesDir(null), "DemoFile.jpg");try {// Very simple code to copy a picture from the  application's// resource into the external file.    Note that this code does// no error checking, and assumes the picture is small (does // not try to copy it in chunks).    Note that if external storage is // not currently mounted this will silently  fail.InputStream is =getResources().openRawResource(R.drawable.balloons);OutputStream os = new FileOutputStream(file); byte[] data = new byte[is.available()]; is.read(data);os.write(data); is.close();os.close();} catch (IOException e) {// Unable to create file, likely because external storage  is// not currently mounted.Log.w("ExternalStorage", "Error writing " + file, e);}}

 

Lab content

1 2 3 4

 

Figure 1: enter for the first time to display the password creation interface

Figure 2: If the password is not matched, the Toast prompt is displayed.

Figure 3: If the password is blank, the Toast prompt is displayed.

Figure 4: The second time after exiting, the displayed input password interface is displayed.

 

5 6 7 8

 

Figure 5: if the password is incorrect, the Toast prompt is displayed.

Figure 6: file loading failure. The Toast prompt is displayed.

Figure 7: The file is imported successfully. The Toast prompt is displayed.

Figure 8: The file is successfully saved. The Toast prompt is displayed.

1. As shown in Figure 1 example Figure 8, this experiment shows that the application contains two activities. 2. First, enter the password for the Activity:

If the application is started for the first time, two input boxes are displayed, namely the new password input box and the Confirm Password Input box.

There are two buttons below the input box:

-After clicking the OK button:

* If the New Password is empty, a Toast prompt is sent. See Figure 3.

* If the New Password and Confirm Password do not match, a Toast prompt is sent. See Figure 2.

* If the two passwords match, save the password and go to the file editing Activity.

-After clicking the CLEAR button:Clear the content of the two input boxes.

• After the password is created, exit the application and enter the application. Only one password input box is displayed. See Figure 4.

-Click OK. If the entered password does not match the previous one, the Toast prompt is displayed. See Figure 5.

-Click the CLEAR button to CLEAR the content in the password input box.

• For demonstration and learning purposes, we use SharedPreferences to save the password in this experiment. However, in practice, this method is not used to store sensitive information, but a safer mechanism. 3. File editing Activity:

• There are three buttons at the bottom of the interface, which have the same degree of consistency, the top alignment, and the average distribution of the buttons. All space above the three buttons except ActionBar and StatusBar is occupied by one EditText (retain margin ). The text in EditText is vertical to the top and left aligned.

• Enter any content in the editing area and click SAVE to SAVE itSpecified file (random file name). After saving, the Toast prompt is displayed. See Figure 8.

• Click the CLEAR button to CLEAR the content of the editing area.

• Click the LOAD button to import content from the same file and display it in the editing box. If the import is successful, Toast is displayed.

Prompt. See Figure 7. If an exception occurs during file reading (if the file does not exist), the Toast prompt is displayed. See Figure 6.

4. Special requirements: after entering the file editing Activity, if you click the return button, the Home interface will be returned directly without returning the password. Inbound Activity.

 

Reference Implementation 1. How to Make the EditText of the file editing Activity occupy all the space above?

Use the LinearLayout and layout_weight attributes.

 

If there are three text fields and two of them declare a weight of 1, while the other is given no weight, the third text field without weight will not grow and will only occupy the area required by its content.The other two will expand equally to fill the space remaining after all three fields are measured.

2. How to remove an Activity from the activity stack when it is invisible (press the return key to directly return Home ) ?

Set the noHistory attribute in AndroidManifest. xml.

 

Whether or not the activity shocould be removed from the activity stack and finished (its finish () method called) when the user navigates away from it and it's no longer visible on screen-"true" if it shoshould be finished, and "false"

If not. The default value is "false ".

3. How to hide/display specific controls as needed?

Set visibility: You can hide or show views using setVisibility (int ). 

 

4. Refer to the project directory structure

  

 

Experiment Process

This experiment mainly implements a memorandum to implement the data storage function. This experiment mainly involves the use of SharePreferences (reading and writing ).

First, write the XML layout file for the two interfaces (note that the LinearLayout and layout_weigh attributes are used to make the EditText of the file editing Activity occupy all the space above ).

Next, complete the MainActivity. java class. In Android, the interface used to obtain SharedPreferences is the getSharedPreferences (String, int) function. The read operation on SharedPreferences is completed using the SharedPreferences object returned by the getSharedPreferences (String, int) function:

  

 

 

All write operations on SharedPreferences must be completed through the Editor object returned by the SharedPreferences. edit () function:

  

 

Click the OK button in the event. If the New Password is empty, the Toast prompt is sent. If the New Password and the Confirm Password do not match, the Toast prompt is sent. If the New Password and the Confirm Password Match, the file editing page is displayed:

  

 

Obtain the password stored locally. If the password is not blank, a password box is hidden. (After the password is created, exit the application and enter the application, only one password box is displayed ):

  

  

Then, click the clear button to set the tag to control the empty event in the password input column (the tag is initially set to true, on the create password page, Click clear to clear all the content in the two password input boxes. On the login page that enters the password, Click clear to hide the content in the password box, check whether the entered password is correct by comparing it with the Stored Password in the hidden Password box ):

  

 

By setting the noHistory attribute in AndroidManifest. xml, you can remove the Activity from the activity stack when it is invisible (press the return key to return to Home ):

  

 

In the java class for file editing, we write files to Internal Storage.

By default, files stored in Internal Storage are only visible to applications. Other applications and users cannot access these files.

If the corresponding file does not exist, the openFileOutput (String, int) function will directly create a new file. Note that the input file name parameter cannot contain path separators (that is '/'). This function returns a FileOutputStream object. You can call the write () method to write the content (written in the save Click Event ):

 

Correspondingly, you can use openFileInput (String) to read files. This function returns a FileInput-Stream and calls the read () method to read the content (written in the load Click Event ):

  

Implements file storage and file loading in file editing.

 

Complete lab ~

 

Lab

  

  

  

  

 

Other knowledge

1. Android provides five storage methods for applications:

Shared Preferences

Internal Storage

External Storage

SQLite Database

Network Connection

 

2. Differences between Internal Storage and External Storage:

Internal storage: always available. By default, files can only be accessed by their own apps. When you uninstall an app, the system will clear all related files in internal; internal is the best storage area you want to ensure that it is not accessed by users and other apps. Internal storage belongs to the application and is invisible to the File Manager.

External storage: it is not always available, because you can choose to use this part as the USB storage mode, so that you will not be able to access it; it is accessible to everyone, therefore, the files saved here lose the access control permission. When you uninstall your app, the system only deletes the files in the external root directory (getExternalFilesDir; external is the best storage region when you do not require strict access permissions and you want these files to be shared by other apps or allow users to access them through a computer. External storage is visible in the file browser/mnt.

These two concepts are relative to the application, should be understood as a logical concept, should not be understood as physical external SD card and mobile phone or mobile device memory. When an application stores data on external storage, the data becomes common and visible and available to all users. When internal storage exists, only this application can be seen and used. Many devices that do not have SD cards inserted, the system virtualizes some storage space for public storage (mainly media such as music and documents ).

 

3. Usage:

1) create a private file in the internal memory and write data to it. Use the following method:

A. Call the openFileOutput (String fileName, int mode) method,

If the file corresponding to fileName exists, open the file. If it does not exist, create and open the file with the mode permission. This method returns a FileOutputStream pointing to the file corresponding to fileName, use this FileOutputStream to write data to the file.

B. Call the write () method of the FileOutputStream object to write data to the file.

C. Call the close () method of the FileOutputStream object to close the file writing stream.

For example, after a file named "abc.txt" is written to the internal memory, the "abc.txt" file is generated in the/data/<package name>/files/directory of the internal storage.

 

To read data from private files in internal storage, use the following methods:

A. Call the openFileInputStream (String fileName) method to open the file corresponding to fileName in internal storage. If the file exists, this method returns a FileInputStream object pointing to the fileName file.

B. Call the read () method of the FileInputStream object to read the content in the fileName file.

C. Call the close () method of the FileInputStream object to close the file reading stream.

2) When I saved it to Internal, nothing was configured. When I saved it to the external, I needed to configure the read and write permissions. The read permission is READ_EXTERNAL_STORAGE and the write permission is READ_EXTERNAL_STORAGE.

First, you need to determine whether the SD card is available, because external storage may be unavailable. For example, if the SD card is pulled out, you should check whether it is available before access. You can run getExternalStorageState () to query the external storage status. If the returned status is MEDIA_MOUNTED, you can read and write data. The process is the same as that stored on the internal storage device. The path is in the/mnt/sdcard directory. If it is a private file, external access is not allowed. The directory is in the/mnt/sdcard/Android/data/package name directory.

 

4. Other related issues:

If you want to save a file that cannot be modified in the application during compilation, save the file in the/res/raw/directory.

Open this file in the program and call the openRawResource (int id) method. The parameter id in the file indicates R. raw. <file name>,

After this method is enabled, an InputStream is returned, which can be used to read the file. This file cannot be written.

 

If there are cached files that need to be saved and these files do not need to be saved permanently, you can call the getCacheDir () method, after this method is executed, an empty directory named cache/is created (or the cache/directory is opened) in the/data/<package name>/directory of the internal storage ), and return a File object pointing to this (empty) folder. In this cache/directory, you can save cache files. When the internal storage space of the device is insufficient, the system automatically deletes some cached files in the cache/directory, however, to ensure the system running efficiency, You Should manually control the cache/directory size, for example, control it cannot exceed 1 MB. When you uninstall an application, the cache/directory will be deleted together.

For example, call the getCacheDir () method. After this method is executed, an empty directory named cache/will be created in the/data/<package name>/directory of the internal storage.

 

Source code download

Click here to download the source code ~

 

Note

1. experiment environment:

Operating System Windows 10

Experimental software Android Studio 2.2.1

Virtual Device: Nexus_5X

API: 23

2. The code format is not very strict due to the size of the inserted code box during code pasting. Sorry ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.