Android API Guides --- Data Storage

Source: Internet
Author: User
Tags sqlite query

Android API Guides --- Data Storage
Data Storage
Store application data in databases, files, or preferences, internal or removable storage. You can also add a data backup service to enable users to store and recover application and system data.
Storage Options
Training
Synchronize to cloud

This course covers different policies for the application of cloud computing functions. It covers synchronizing data and using the cloud's own back-end Web applications, and using the cloud, so that users can restore their data backup data when installing applications on a new device.

Storage Options

Android provides several options to save persistent application data. The solution you select depends on your specific needs, such as whether the data should be private applications or access other applications (and users), and how much space your data needs.


Your data storage options are as follows:


Shared Preferences
Stored in basic data of Private Key-value pairs.
Internal Storage
Private data stored in the device memory.
External Storage
Public data is stored in shared external storage.
SQLite Databases
Store structured data in a dedicated database.
Network Connection
Use your network server to store data on the network.
Android provides a way for you to expose your private data to other apps-and content providers. The content provider is an optional component that publicly reads data/writes to your applications and is subject to any restrictions imposed. For more information about using content providers, see the content provider documentation.


Use Shared Preferences


This SharedPreferences class provides an overall framework that allows you to save and retrieve persistent key-value pairs of the original data type. You can use SharedPreferences to save any basic data: Boolean, floating point, integer, long and string. The data will be persistent in the user session (even if your application is killed ).


User preferences


Sharing preferences are not strictly used to save "user preferences", for example, the user selects a ringtone. If you are interested in creating user preferences for the application and viewing PreferenceActivity, it provides a framework activity to create user preferences for you, which will be automatically persistent (using sharing preferences ).
To obtain the SharedPreferences object for your application, use either of the following methods:


GetSharedPreferences ()-If you need to identify multiple preferences by name, your first parameter specifies to use this.
GetPreferences ()-If you only need to use this in your activity preferences file. Because this will be the only option to submit your activity, You do not provide a name.
Write value:


Call edit () to get a SharedPreferences. Editor.
And methods, such as putBoolean () and putString add value ().
Submit and submit new values ()
To read the value, use methods such as SharedPreferences getBoolean () and GetString ().


Here is an example of the preference that is saved in the mute mode of a calculator key:

 

public class Calc extends Activity {  public static final String PREFS_NAME = "MyPrefsFile";  @Override  protected void onCreate(Bundle state){   super.onCreate(state);   . . .   // Restore preferences   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);   boolean silent = settings.getBoolean("silentMode", false);   setSilent(silent);  }  @Override  protected void onStop(){   super.onStop();   // We need an Editor object to make preference changes.   // All objects are from android.context.Context   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);   SharedPreferences.Editor editor = settings.edit();   editor.putBoolean("silentMode", mSilentMode);   // Commit the edits!   editor.commit();  }}
Use internal storage


You can directly store files in the device's internal storage. By default, private applications and other applications cannot access the stored files stored in the internal storage (which can also be accessed by users ). When you uninstall the application, these files will be deleted.


To create and write a private file to the internal storage:


Call openFileOutput () with the file name and operation mode (). This returns a FileOutputStream.
Write and write files ().
Close to closing stream ().
For example:

 

 

String FILENAME = "hello_file";String string = "hello world!";FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);fos.write(string.getBytes());fos.close();
MODE_PRIVATE will create a file (or replace a file with the same name) and make it dedicated to your application. Other available modes include MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.


Read files stored internally:


Call openFileInput () and use it to read the file name. This returns a FileInputStream.
Read byte () from the file ().
Close the stream ().
Tip: If you want to save the static files in the application during compilation, save the files in the RES/production/directory of your project. You can use openRawResource () to open it and pass R. raw. <File Name> resource ID. This method returns an InputStream that can be used to read the file (but cannot be written to the original file.


Save cache files


If you want to cache some data rather than store it, you should use getCacheDir () to open the internal directory, and the application should save the files of the temporary cache file.


When the device is in a low internal storage space, the Android version may delete these cached files ?? Restore space. However, you should not rely on the system to clear these files for you. You should always keep the cached files, and keep the consumption space within 1 MB. When you uninstall the application, these files will be deleted.


Other useful methods


GetFilesDir ()
Obtain the absolute path where all your internal files are saved in the file system directory.
GETDIR ()
Create (or open existing) directories in the internal bucket.
DeleteFile ()
Delete the files stored in the internal storage.
FileList ()
Returns the array of files currently saved by the application.
Use External Storage


Every Android-compatible device supports sharing "External Storage", which you can use to save files. This can be a removable storage medium (such as an SD card) or an internal (non-removable) storage. Files saved to external memory are world readable and can be modified by users when they enable USB to store large capacity files to computers.


Note: If a user installs external storage on a computer or deletes a media file without security, it becomes unavailable to the external storage to execute the external storage device. All applications can read and write files stored in external storage, and users can delete them.


Obtain access to external storage


To read or write files in external storage, the application must obtain READ_EXTERNAL_STORAG ?? E or WRITE_EXTERNAL_STORAG ?? E. System permissions. For example:

 

 

   
    ...
 
If you need to read and write files at the same time, you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access and.


Note: starting with Android4.4, these permissions are not required if you are reading or writing files that only belong to your application. For more information, see the following section about saving dedicated application files.


Check media availability


When you do any work with external storage, you should always call getExternalStorageState () to check whether the media is available. Media may be installed on a computer, missing, read-only, or in some other status. For example, here you can use it to check the availability of the couple's methods:

 

 

/* Checks if external storage is available for read and write */public boolean isExternalStorageWritable() {  String state = Environment.getExternalStorageState();  if (Environment.MEDIA_MOUNTED.equals(state)) {    return true;  }  return false;}/* Checks if external storage is available to at least read */public boolean isExternalStorageReadable() {  String state = Environment.getExternalStorageState();  if (Environment.MEDIA_MOUNTED.equals(state) ||    Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {    return true;  }  return false;}
This getExternalStorageState () method returns, you may want to check other countries, such as whether the media is shared (connected to a computer), completely lost, deleted seriously, and so on. You can use these to notify users when your application needs to access more media information.


Shared File storage with other applications


Hide a file from a media Scan


Include an empty file named. nomedia under the external file directory (note the dot prefix in the file name ). This prevents media scanners from reading media files and providing them to other applications through the MediaStore content provider. However, if your files are actually dedicated to your applications, you should save them in an application, private directory.
In general, you can get new files from your application and save them to the "public" location on the device. Other applications can access them and users can easily copy them from the device. In this case, you should use shared public directories, such as music/, images/and ringtones.


To get a more appropriate public directory file, call getExternalStoragePublicDirectory () to pass the type of the directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. By saving the file to the appropriate media directory, the system's media scanner can properly classify the files in the system (for example, the phone ringtones appear in the system and are set as ringtones rather than music ).


For example, the following method creates a new album directory in the public image directory:

 

 

public File getAlbumStorageDir(String albumName) {  // Get the directory for the user's public pictures directory.  File file = new File(Environment.getExternalStoragePublicDirectory(      Environment.DIRECTORY_PICTURES), albumName);  if (!file.mkdirs()) {    Log.e(LOG_TAG, "Directory not created");  }  return file;}
Saving is a dedicated application file.
If you are processing files that are not used by other applications (Form textures or use sound effects only in your applications ), you should call getExternalFilesDir to use the external storage dedicated storage directory (). This method also requires a type parameter to specify the type of sub-directories (such as the Directory MOVIES ). If you do not need a specific media directory, pass null to the root directory of the private directory of your application.
The READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission is not required to read or write files in the private directory of the application. Therefore, you can declare that the permission can only be granted by requests with lower minSdkVersion attributes.

 

 

   
    ...
 
Note: When you uninstall the application, this directory and all its contents will be deleted. In addition, system media scanners do not read files in these directories, so they are not accessed from the MediaStore content provider. Therefore, you should not use these directories for media that ultimately belong to users, such as capturing or editing photos with your app, or music users with the app you purchased, these files should be stored in the public directory.


Sometimes, partitions of allocated internal memory are used as external storage devices and an SD card slot can be provided. When such devices run less than Android 4.3, the getExternalFilesDir () method can only access internal partitions, and your application cannot read or write data to the SD card. It starts with Android 4.4. However, you can call getExternalFilesDirs (), which returns an array of files in each location of the entry to access these two locations. The first item in the array is considered as the primary external storage, unless it is all or not available, you should use the location. If you want to access these two possible locations and support Android 4.3 and lower, use the static method that supports the library, ContextCompat. getExternalFilesDirs (). This also returns an array of files, but always includes only one entry in Android 4.3 and lower.


Note: although the directories provided by getExternalFilesDir () and getExternalFilesDirs () are accessed by the MediaStore content provider, are the permissions of other applications READ_EXTERNAL_STORAG ?? E. You can access external storage, including all these files. If you need to completely restrict access to your files, you should write your files to internal storage.


Save cache files


Open the external storage directory. You should save the cached file and call getExternalCacheDir (). If you uninstall the application, these files will be automatically deleted.


Similar to ContextCompat. getExternalFilesDirs (), you can also access the secondary external storage in the cache directory (if available) and call ContextCompat. getExternalCacheDirs ().


Tip: to save the file space and maintain the performance of the application, it is no longer necessary to manage your cache files carefully and delete those that are not in the life cycle of your application.


Use Database


Android provides comprehensive support for SQLite databases. Any database you create will access any class in the application by name, rather than outside the application.


The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate () method. You can execute the SQLite command to create a table in the database. For example

 

 

public class DictionaryOpenHelper extends SQLiteOpenHelper {  private static final int DATABASE_VERSION = 2;  private static final String DICTIONARY_TABLE_NAME = "dictionary";  private static final String DICTIONARY_TABLE_CREATE =        "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +        KEY_WORD + " TEXT, " +        KEY_DEFINITION + " TEXT);";  DictionaryOpenHelper(Context context) {    super(context, DATABASE_NAME, null, DATABASE_VERSION);  }  @Override  public void onCreate(SQLiteDatabase db) {    db.execSQL(DICTIONARY_TABLE_CREATE);  }}
Then, you can use the constructed instance that enables you to implement SQLiteOpenHelper. To write data and read data from the database, call getWritableDatabase () and getReadableDatabase (), respectively. These are returned to indicate the database, and the SQLite operation method SQLiteDatabase object is provided.
Android does not impose any restrictions on the concept of super-standard SQLite. We recommend that you use a unique ID to quickly find the auto-increment key field of the record. This is not necessary private data, but if you implement a content provider, you must include a unique ID that uses the BaseColumns. _ ID constant.
You can run the SQLiteDatabase query () method, which accepts various query parameters, such as Table query, raised, selection, columns, groups, and other SQLite queries. For complex queries, such as those requiring column aliases, you should use SQLiteQueryBuilder, which is a convenient way to create a query.
Each SQLite query returns a cursor pointing to all rows found in the query. The cursor always carries a mechanism that allows you to browse and read rows and columns from a database query result.
Demonstrate how to use the SQLite database sample application in Android to view the notebook and retrieval dictionary application.
Database debugging
The Android SDK contains a sqlite3 database tool that allows you to browse table content, run SQL commands, and execute other useful functions in the SQLite database. See check the sqlite3 database from a remote shell to learn how to run this tool.
Use Network Connection
You can use networks (if any) to store and retrieve data for your own web-based services. The class used in the following package for network services:
Java.net. *
Android.net *.

 

 

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.