您的位置:首页 > 移动开发 > Android开发

笔记:Android存储数据

2016-04-26 10:05 441 查看

Saving Data //存储数据

Most Android apps need to save data, even if only to save information about the app state during 
onPause()
 sothe user's progress is not lost. Most non-trivial apps also need to save user settings, and some apps must manage large amounts of information in files and databases. This class introduces you to the principal(主要的) data storage options in Android, including:Saving key-value pairs of simple data types in a shared preferences file  //sharepreference形式Saving arbitrary files in Android's file system//文件形式Using databases managed by SQLite //SQLite数据库形式sharepreference形式-------(可以设置能被其他应用程序读写)Learnto use a shared preferences file for storingsmall amounts ofinformation in key-value pairs.Ifyou have arelatively small collection of key-valuesthat you'd like to save, you should use the 
SharedPreferences
 APIs.Each 
SharedPreferences
 fileis managed by the framework and can be private or shared.getSharedPreferences() — Use this ifyou need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any 
Context
 inyour app.  //可能需要多个SharePreference时需要为SharePreference分配名字
getPreferences()
 —Use this from an 
Activity
 if you needto use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.//只需要一个SharePreference时直接通过getPreferences()获取
Context context = getActivity();    //可能需要多个SharePreference时
SharedPreferences sharedPref = context.getSharedPreferences(“名字”, Context.MODE_PRIVATE);//如果要共享的话,名字最好与包名相关
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); //只需要一个SharePreference时
To write to a shared preferences file, create a 
SharedPreferences.Editor
 bycalling 
edit()
 onyour
SharedPreferences
.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); //存储数据
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
editor.commit();
To retrieve values from a shared preferences file, call methods such as 
getInt()
 and 
getString()
,providing the key for the value you want, and optionally a default value to return if the key isn't present
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);  //读取数据
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);  //如果没有这个数据则返回的数据
long highScore = sharedPref.getInt(“key”, defaultValue);

Saving Files---------------------

File
 objectis suited to reading or writing large amounts of datain start-to-finish order without skipping around. For example, it's good for image files or anything exchangedover a network.AllAndroid 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 storage 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 isr emovable or not. The following lists summarize the facts about each storage space.Internal storage:It's always available.Files saved here are accessible by only your app by default.When the user uninstalls your app, the system removes all your app's files from internal storage.Internal storage is best when you want to be sure that neither the user nor other apps can access your files.External storage:It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.It's world-readable, so files saved here may be read outside of your control.When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from 
getExternalFilesDir()
.External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer. Althoughapps are installed onto the internal storage by default, you can specify the
android:installLocation
 attributein your manifest so your app may be installed on external storage. Users appreciate this option when the APKsize is very large and they have an external storage space that's larger than the internal storage. // app默认被安装在内部存储空间中,不过可以在manifest文件中通过
android:installLocation属性指定app被安装在外部存储空间中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
, if your app uses the 
WRITE_EXTERNAL_STORAGE
 permission,then it implicitly has permission to read the external storage as well.
使用WRITE_EXTERNAL_STORAGE
 权限除了表示能够写入外部存储空间外还隐式地表示app有读取外部存储空间的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 If your app needs to read the external storage (but not write to it), then you will need to declare the 
READ_EXTERNAL_STORAGE
 permission.
如果想要只能读取外部存储空间不能写入外部存储空间的话,则使用 
READ_EXTERNAL_STORAGE权限
Youdon’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory. //app在读取写入内部存储空间时不需要权限
总结:读写外部存储空间需要权限,读写内部存储空间不需要权限

Save a File on Internal Storage(文件可以设置为能被其他应用程序读写,内部存储空间存储的文件理论上可以被其他app访问到,但其他app需要知道你的app的包名和文件名才可以访问而且你必须设置文件为readableor writable)

When saving a file to internal storage, you can acquire the appropriate directory as a 
File
 bycalling one of two methods:
getFilesDir()
Returns a 
File
 representingan internal directory for your app.
getCacheDir()
Returns a 
File
 representingan internal directory for your app's temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage,it may delete your cache files without warning.To create a new file in one of these directories, you can use the 
File()
 constructor,passing the 
File
 provided by one of the abovemethods that specifies your internal storage directory. For example:
File file = new File(context.getFilesDir(), filename); //根据获取的内部存储空间路径创建文件
Alternatively, you can call 
openFileOutput()
 toget a 
FileOutputStream
 that writesto a file in your internal directory. For example, here's how to write some text to a file:
String filename = "myfile";String string = "Hello world!";FileOutputStream outputStream;try {  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);    //打开内部存储空间文件并写入  outputStream.write(string.getBytes());  outputStream.close();} catch (Exception e) {  e.printStackTrace();}
Or, if you need to cache some files, you should instead use 
createTempFile()
.For example, the following method extracts the file name from a 
URL
 andcreates a file with that name in your app's internal cache directory:
public File getTempFile(Context context, String url) {    File file;    try {        String fileName = Uri.parse(url).getLastPathSegment();        file = File.createTempFile(fileName, null, context.getCacheDir());  //根据获取的内部存储空间缓存路径创建文件    catch (IOException e) {        // Error while creating file    }    return file;}
Note: Your app's internal storage directory is specified by your app's package name in a special location of the Android file system.Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directoriesand do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use 
MODE_PRIVATE
 foryour files on the internal storage, they are never accessible to other apps.

Save a File on External Storage

Because the external storage may be unavailable—such as when the user has mounted the storageto a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling 
getExternalStorageState()
.If the returned state is equal to 
MEDIA_MOUNTED
,then you can read and write your files. For example, the following methods are useful to determine the storage availability://在使用外部存储空间前,要先判断是否存在外部存储空间
/* 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;}
-----------------------------------Although the external storage is modifiable(可修改的) by the user and other apps, there are two categories of files you might save here:Public files(可以被其他app访问,在app被卸载时应保留)Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.For example, photos captured by your app or other downloaded files.Private files(理论上可以被其他app访问,在app被卸载时被删除)Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, theyare files that realistically don't provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app's external private directory.For example, additional resources downloaded by your app or temporary media files.------------------------------------If you want to save public files on the external storage, use the 
getExternalStoragePublicDirectory()
 methodto get a 
File
 representingthe appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as 
DIRECTORY_MUSIC
 or 
DIRECTORY_PICTURES
.For example:
public File getAlbumStorageDir(String albumName) {      (可以被其他app访问,在app被卸载时应保留)    // 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;}
-------------------------------------If you want to save files that are private to your app, you can acquire the appropriate directory by calling
getExternalFilesDir()
 andpassing it a name indicating the type of directory you'd like. Each directory created this way is added to a parent directory that encapsulates all your app's external storage files, which the system deletes when the user uninstalls your app.For example, here's a method you can use to create a directory for an individual photo album:
public File getAlbumStorageDir(Context context, String albumName) {  (理论上可以被其他app访问,在app被卸载时被删除)    // Get the directory for the app's private pictures directory.    File file = new File(context.getExternalFilesDir(            Environment.DIRECTORY_PICTURES), albumName);    if (!file.mkdirs()) {        Log.e(LOG_TAG, "Directory not created");    }    return file;}
If none of the pre-defined sub-directory names suit your files, you can instead call 
getExternalFilesDir()
 andpass 
null
. This returns the root directory for your app's private directory on the external storage.Remember that 
getExternalFilesDir()
 createsa directory inside a directory that is deleted when the user uninstalls your app. If the files you're saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should insteaduse
getExternalStoragePublicDirectory()
.---------------------------------------------Regardless of whether you use 
getExternalStoragePublicDirectory()
 forfiles that are shared or
getExternalFilesDir()
 forfiles that are private to your app, it's important that you use directory names provided by API constants like 
DIRECTORY_PICTURES
.These directory names ensure that the files are treated properly by the system. For instance, files saved in 
DIRECTORY_RINGTONES
 arecategorized by the system media scanner as ringtones instead of music.---------------------------------------------

Query Free Space(查询空余的空间和捕捉空间不足错误)

If you know ahead of time how much data you're saving, you can find out whether sufficientspace is available without causing an 
IOException
 bycalling 
getFreeSpace()
 or 
getTotalSpace()
.These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.You aren't required to check the amount of available space before you save your file.You can instead try writing the file right away, then catch an 
IOException
 ifone occurs. You may need to do this if you don't know exactly how much space you need.For example, if you change the file's encoding before you save it by converting a PNG image to JPEG, you won'tknow the file's size beforehand.

Delete a File

1.You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call 
delete()
 onitself.(打开文件后删除)
myFile.delete();
2.If the file is saved on internal storage(内部存储空间), you can also ask the 
Context
 tolocate and delete a file by calling
deleteFile()
:
myContext.deleteFile(fileName);
-------------------------------------------------------------------------------------------------Note: When the user uninstalls your app, the Android system deletes the following:All files you saved on internal storageAll files you saved on external storage using 
getExternalFilesDir()
.However, you should manually delete all cached files created with 
getCacheDir()
 ona regular basis and also regularly delete other files you no longer need.在app被卸载时,系统自动删除被存储在内部空间的文件,以及被存储在外部空间由getExternalFilesDir()获取的外部空间路径创建的私人文件。-----------------------------------------------------------------------------------

Saving Data in SQL Databases

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: