保存数据方面的翻译

Saving Data

保存数据


Dependencies and prerequisites

依赖关系和先决条件(也就是安卓开发所需要的必要的条件)

  • Android 1.6 (API Level 4) or higher
  • 安卓1.6(API甚至4级版本)或者更高的版本
  • Familiarity with Map key-value collections
  • 相似于Map键值集合
  • Familiarity with the Java file I/O API
  • 类似于Java文件中的输入输出API
  • Familiarity with SQL databases
  • 相似于SQL数据库

You should also read


  你应该阅读

Most Android apps need to save data, even if only to save information about the app state duringonPause() so the 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:

绝大多数的apps需要保存数据,运用onPause方法来仅仅保存用户的数据,用户的进程都在继续,它之前的数据还是被保存下来。最简单的用户程序也需要保存用户设置,并且有些应用程序必须要处理很多的文件信息或者是数据库信息,这节课将带你掌握安卓中最基本的数据存储选择方法,包括:

  • Saving key-value pairs of simple data types in a shared preferences file
  • 在共享文件中保持简单数据的键值对
  • Saving arbitrary files in Android's file system
  • 将任意文件保存在Android的文件系统
  • Using databases managed by SQLite
  • 利用SQLite来管理数据库

Saving Key-Value Sets

保持键值设置            

      

You should also read

If you have a relatively small collection of key-values that you'd like to save, you should use theSharedPreferences APIs. ASharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. EachSharedPreferences file is managed by the framework and can be private or shared.

This class shows you how to use the SharedPreferences APIs to store and retrieve simple values.

如果你想保存相对较小的键值对集合,你应该利用这个SharedPreferences的APIs,一个SharedPreferences对象指向一个文件包含键值对并且提供简单的方法来读写文件,任何一个SharedPreferences文件

Note: The SharedPreferences APIs are only for reading and writing key-value pairs and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they useSharedPreferences as their implementation to save the app settings). For information about using thePreference APIs, see theSettings guide.

笔记:SharedPreferences api键值仅供阅读和写作,你不应该混淆他们与Preference的api,帮助您构建一个用户界面应用程序设置(尽管他们使用SharedPreferences作为实现保存应用程序设置)。使用preference的api的信息,请参见设置指南。

Get a Handle to a SharedPreferences

SharedPreferences处理


You can create a new shared preference file or access an existing one by calling one of two methods:

你可以创建新的共享preference的文件或者访问一个现有的通过调用两种方法之一

  • getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
  • getSharedPreferences()-利用这个方法你可以通过命名的文件可以从众多的共享文件中找出这个文件来,这个方法你可以分析第一份参数,你可以从任何上下文调用这个应用程序。
  • getPreferences() — Use this from anActivity if you need to 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.
  • getPreferences()-如果你需要为这个Activity中只需要一个共享的preference文件。因而调用这种方法,因为这个检索一个默认的共享文件,属于活动的preference,你不需要提供一个名称。
  • For example, the following code is executed inside a Fragment. It accesses the shared preferences file that's identified by the resource string R.string.preference_file_key and opens it using the private mode so the file is accessible by only your app.
  • 例如,接下来的编码就是在Fragment中进行执行,它可以接触到共享文件并且可以可以被资源字符串R.string.preference_file_key 进行标示,同时你可以通过设置它的模式是私有的模式,这样只有你的app可以接触到这个文件了
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

When naming your shared preference files, you should use a name that's uniquely identifiable to your app, such as"com.example.myapp.PREFERENCE_FILE_KEY"

Alternatively, if you need just one shared preference file for your activity, you can use thegetPreferences() method:

当你命名你的共享文件,你应该使用一个名称(这种不同的名称)来标示你的文件名,例如"com.example.myapp.PREFERENCE_FILE_KEY"可供选择对的,如果你仅仅一个共享文件给你的Activity,你可以使用getPreferences()方法

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Caution: If you create a shared preferences file withMODE_WORLD_READABLE orMODE_WORLD_WRITEABLE, then any other apps that know the file identifier can access your data.

提醒:如果你创建一个共享文件伴有MODE_WORLD_READABLE 或者MODE_WORLD_WRITEABLE, 那么任何其他的apps将知道这个文件的标示符可以获取你的数据

Write to Shared Preferences

写入共享文件


To write to a shared preferences file, create a SharedPreferences.Editor by callingedit() on yourSharedPreferences.

为了写入数据进入你的共享文件,利用你的共享文件中的叫edit()的方法来创建一个SharedPreferences.Editor

Pass the keys and values you want to write with methods such as putInt() andputString(). Then callcommit() to save the changes. For example:

你可以使用这些方法例如putInt()和putString()传递键和值,然后利用commit()的方法来保持修改的数据。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

Read from Shared Preferences

读取共享文件:


To retrieve values from a shared preferences file, call methods such as getInt() andgetString(), providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:

从共享首选项文件中检索值,调用方法如getInt()和getString(),提供你想要的值的键,选择返回默认值,如果不存在的关键。例如:


SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

Saving Files

保存文件

Android uses a file system that's similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

安卓利用文件系统也就是类似于基于不同平台的磁盘文件系统,这节课键描述怎样利用文件的APIs来读写文件

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it's good for image files or anything exchanged over a network.

一个文件对象是适合阅读或写作大量的数据提供从头到尾的顺序没有跳过。例如,有利于图像文件或任何通过网络交换。

Choose Internal or External Storage

选用内部或者外部进行存储


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 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 is removable or not. The following lists summarize the facts about each storage space.

所有安卓设备都含有两个文件存储区:就是内部存储和外部存储的两个部分,这些名称起源于安卓早些时候,当大多数设备提供了内置的非易失性存储器(内存)加上可以移除的存储设备例如微型的SD卡(外部存储)。有些的设备分为长久的存储区分为两内存和外存两个部分,因此,尽管没有移动的中间存储设备,总有两种存储空间和API行为是相同的外部存储器是否可移动。以下列表总结关于每个存储空间的事实。

Internal storage:

内部存储

  • It's always available.
  • 这总是可用的
  • Files saved here are accessible by only your app by default.
  • 文件将保存在你的默认app中
  • When the user uninstalls your app, the system removes all your app's files from internal storage.
  • 如果用户卸载你的app,那么系统将移除掉你app内存中所有的文件

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

内部存储无论是用户或者是其他的apps都不能接触你的文件

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.
  • 这个总是不可用的,因为用户可以安装外部存储器USB存储和在某些情况下删除它从设备。
  • 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().
  • 当用户卸载你的app,系统将移除你利用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.

外部存储文件是最好的地方,不需要访问限制,你想与其他应用程序共享的文件或允许用户访问计算机。

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that's larger than the internal storage. For more information, see App Install Location.

提示:尽管应用程序安装到内部存储在默认情况下,您可以指定android:installLocation属性在你的清单,这样你的应用程序可以安装在外部存储器。用户欣赏这个选项当APK文件大小是非常大的,他们有一个外部比内部存储的存储空间。有关更多信息,请参见应用安装位置

Obtain Permissions for External Storage

获取外部存储权限


To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

当一个文件保存到内部存储,您可以获得适当的目录作为一个文件通过调用两种方法之一:

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

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. 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. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

注意:目前,所有应用程序可以读取外部存储没有特别许可。然而,这将改变在将来发布的版本中。如果你的应用程序需要读取外部存储器(但不写),那么您将需要申报READ_EXTERNAL_STORAGE许可。确保应用程序继续正常工作,你现在应该宣布这个许可,在更改生效。

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

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’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.

然而,如果您的应用程序使用WRITE_EXTERNAL_STORAGE许可,那么它隐式权限读取外部存储器。

Save a File on Internal Storage

在内部存储中保存文件


When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

当你保存文件在内部存储中,你可以获得适当的目录作为一个文件通过调用两种方法之一:

getFilesDir()
Returns a File representing an internal directory for your app.
返回一个代表一个内部文件为您的应用程序目录。
getCacheDir()
Returns a File representing an 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, i t may delete your cache files without warning.
返回一个代表一个内部文件目录应用程序的临时缓存文件。一定要删除每个文件一旦不再需要和实现一个合理的大小限制为您使用的内存数量在任何给定的时间,比如1 mb。如果系统开始运行低存储,它可能毫无预警地删除缓存文件。

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

其中的一个目录中创建一个新文件,您可以使用File()构造函数,通过上述方法之一提供的文件,指定您的内部存储目录。例如:

File file = new File(context.getFilesDir(), filename);

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:

或者,你可以叫openFileOutput()获得FileOutputStream写入一个文件在你的内部目录中。例如,下面是如何编写一些文本文件:

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 and creates a file with that name in your app's internal cache directory:

或者,如果您需要缓存一些文件,您应该使用createTempFile()。例如,下面的方法提取文件的名字从一个URL并创建一个文件,这个名字在你的应用程序的内部缓存目录:

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 directories and 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 for your files on the internal storage, they are never accessible to other apps.

注意:您的应用程序的内部存储目录指定应用程序的包名称在安卓系统文件系统的一个特殊的位置。从技术上讲,另一个应用程序可以读取你的内部文件如果你设置的文件模式可读。然而,其他应用程序也需要知道应用程序包名和文件名。其他应用程序不能浏览你的内部目录和没有读或写访问,除非你显式地设置文件读取或写入。所以只要你使用MODE_PRIVATE内部存储你的文件,他们永远不会访问其他应用程序。

Save a File on External Storage

保存文件在外部存储中


Because the external storage may be unavailable—such as when the user has mounted the storage to 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:

因为外部存储可能是不可用的-例如当用户已经安装存储到电脑或删除了SD卡,提供外部storage-you应该验证卷可以在访问之前。你可以通过叫getExternalStorageState()的方法来访问外部存储,如果返回值是MEDIA_MOUNTED,那么你可以读写你的文件,例如,一下的方法将决定着你的存储可用

/* 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:

尽管可以通过用户和其他的apps进行修改,这里有两种文件你或许保存在这

Public files 公共文件
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.
这种文件可以被随意访问,当用户卸载你的app,这些文件将保持可用对于你的用户

For example, photos captured by your app or other downloaded files.

例如,照片捕捉到你的应用程序或其他下载的文件。

Private files 私有文件
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, they are 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() method to get a File representing the 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:

如果你想保存公共文件在你的外部存储上,使用getExternalStoragePublicDirectory()方法来呈现在你的外部存储上的正确目录,方法接受一个参数指定类型的文件你想保存,这样就可以在逻辑上与其他公共组织的文件,例如DIRECTORY_MUSIC或者DIRECTORY_PICTURES,例如(下面的方法)

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;
}

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing 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.

如果你想保存对于你的应用程序是私有的文件,你可以利用获得getExternalFilesDir()来传递来表示你用户喜欢的名称来定义这个方法的合适目录,这种方式创建的每个目录添加到父目录,封装了应用程序的所有外部存储文件,系统删除当用户卸载应用程序。

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) {
    // 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() and pass null. This returns the root directory for your app's private directory on the external storage.

如果没有一个预定义的子目录名字适合你的文件,你可以叫getExternalFilesDir()和传递null。这将返回您的应用程序的根目录的私人在外部存储目录。

Remember that getExternalFilesDir() creates a 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 instead use getExternalStoragePublicDirectory().

记住当你卸载你的app的时候,利用getExternalFilesDir()方法创建一个目录在一个上级目录中,如果你卸载以后会保持你的文件可用就像你的app是一个相机,那么用户想保存相片你应该使用该种方法而不是使用getExternalStoragePublicDirectory()这个方法

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files 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 are categorized by the system media scanner as ringtones instead of music.

除非你既不想使用这个getExternalStoragePublicDirectory()这种方法运用在共享文件中又不想利用getExternalFilesDir()方法运用在你的私有文件上,那么重要的是你使用API提供的目录名像DIRECTORY_PICTURES常量。这些目录名确保文件被正确的系统。例如,文件保存在DIRECTORY_RINGTONES由系统分类媒体扫描仪的铃声,而不是音乐。

Query Free Space

查询空闲空间


If you know ahead of time how much data you're saving, you can find out whether sufficient space is available without causing an IOException by calling 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.

如果你想提前知道有多少的数据你在保存

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace(). If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it's probably safe to proceed. Otherwise, you probably shouldn't write to storage.

您可以找到足够的空间是否可用而不会导致一个IOException通过调用getFreeSpace()或getTotalSpace()。这些方法提供当前的可用空间和总空间存储卷,分别。这些信息也是有用的,以避免填充存储体积超过一定阈值。

Note: 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 if one 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't know the file's size beforehand.

注意:您不需要检查的可用空间在你保存你的文件。你可以试着写文件,然后抓住一个IOException如果发生。你可能需要这样做,如果你不知道你需要多少空间。举个例子,如果你改变文件的编码保存之前将PNG图像转换成JPEG,事先你不知道文件的大小。

Delete a File

删除文件


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() on itself.

你应该删除以后你不再用的文件,最直截了当的方式,删除一个文件,打开文件引用调用delete()。

myFile.delete();

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():

myContext.deleteFile(fileName);
如果则会个文件保存在内部存储中,你可以使用Context来放置或者删除一个文件调用deleteFile()方法

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir().

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

然而,您应该手动删除所有缓存文件创建getCacheDir定期()并定期删除你不再需要其他文件。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值