未验证 提交 d845ed78 编写于 作者: O openharmony_ci 提交者: Gitee

!8978 [翻译完成】#I5LFI4

Merge pull request !8978 from Annie_wang/PR7901
......@@ -2,45 +2,48 @@
> **NOTE**
>
> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs.
Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files.
## Available APIs
Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can call the **Preferences** APIs to manage data.
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md).
## Available APIs
### Creating a Preferences Instance
The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance.
The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
**Table 1** API for creating a **Preferences** instance
For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md).
| Package | API | Description |
| ----------------- | ------------------------------------------- | ------------------------------------------- |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
### Obtaining a **Preferences** Instance
### Writing Data
Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance.
Call the **put()** method to add or modify data in a **Preferences** instance.
**Table 1** API for obtaining a **Preferences** instance
**Table 2** API for writing data
| Package | API | Description |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
| Class | API | Description |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Accessing Data
### Reading Data
Call the **put()** method to add or modify data in a **Preferences** instance.
Call the **get()** method to read data from a **Preferences** instance.
**Table 3** API for reading data
Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.
**Table 2** APIs for accessing **Preferences** data
| Class | API | Description |
| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | getAll(): Promise<Object> | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. |
| Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Storing Data Persistently
......@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p
**Table 4** API for data persistence
| Class | API | Description |
| ------- | ----------------------- | --------------------------------------- |
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.|
| Class | API | Description |
| ----------- | ----------------------- | ------------------------------------------- |
| Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
### Observing Data Changes
You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data.
You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data.
**Table 5** APIs for observing **Preferences** changes
| Class | API | Description |
| ------- | ------------------------------------------------------------ | -------------- |
| Class | API | Description |
| ----------- | ------------------------------------------------------------ | -------------- |
| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. |
......@@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file.
**Table 6** APIs for deleting **Preferences**
| Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
| Package | API | Description |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void> | Deletes a **Preferences** instance from the memory and its files from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory. |
## How to Develop
1. Import @ohos.data.preferences and related modules to the development environment.
```js
import data_preferences from '@ohos.data.preferences'
import data_preferences from '@ohos.data.preferences';
```
2. Create a **Preferences** instance.
2. Obtain a **Preferences** instance.
Read the specified file and load its data to the **Preferences** instance for data operations.
```js
let promise = data_preferences.getPreferences(this.context, 'mystore')
let promise = data_preferences.getPreferences(this.context, 'mystore');
```
3. Write data.
Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance.
Use the **preferences.put()** method to write data to the **Preferences** instance.
```js
promise.then((preferences) => {
let putPromise = preferences.put('startup', 'auto')
let putPromise = preferences.put('startup', 'auto');
putPromise.then(() => {
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
}).catch((err) => {
console.info("Failed to put the value of startup with err: " + err)
console.info("Failed to put the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get the preferences")
console.info("Failed to get the preferences.");
})
```
4. Read data.
Use the **get()** method of the **Preferences** class to read data.
Use the **preferences.get()** method to read data.
```js
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default')
let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of startup is " + value)
console.info("The value of 'startup' is " + value);
}).catch((err) => {
console.info("Failed to get the value of startup with err: " + err)
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get the preferences")})
console.info("Failed to get the preferences.")
});
```
5. Store data persistently.
......@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file.
6. Observe data changes.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data.
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key" + key + " changed.");
}
preferences.on('change', observer)
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup with err: " + err)
return
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file with err: " + err)
return
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed to file successfully.") // Observer will be called.
console.info("Flushed data successfully."); // The observer will be called.
})
})
```
7. Delete the specified file.
Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js
let proDelete = data_preferences.deletePreferences(context, 'mystore')
let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => {
console.info("Data deleted successfully.")
console.info("Deleted data successfully.");
}).catch((err) => {
console.info("Failed to delete data with err: " + err)
console.info("Failed to delete data. Cause: " + err);
})
```
# Preferences Overview
Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
Preferences are used to implement quick access and persistence of the data in the `key-value` structure.
After an application obtains a **Preferences** instance, the data in the instance will be cached in the memory for faster access.
The cached data can also be written to a text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing files.
You do not need to worry about the implementation of the database lock mechanism.
## Basic Concepts
- **Key-value data structure**
- **Key-value structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
A type of data structure. The `Key` is the unique identifier for a piece of data, and the `Value` is the specific data being identified.
- **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent.
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. The database that organizes data in the `key-value` structure is a non-relational database.
## Working Principles
When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file.
When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method.
1. An application can load data from a **Preferences** persistent file to a **Preferences** instance. The system stores the **Preferences** instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** persistent file.
2. When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the `Preferences` instance can be flushed to its **Preferences** persistent file by calling the **flush()** method.
**Figure 1** How **Preferences** work
**Figure 1** Working mechanism
![](figures/preferences.png)
## Constraints
- **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
- The `Key` in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
# Preferences
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, the keys are of the string type, and the values can be of the number, string, Boolean, Array\<number>, Array\<string>, or Array\<boolean> type.
The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
> **NOTE**<br/>
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
```js
import data_preferences from '@ohos.data.preferences';
```
......@@ -17,36 +20,39 @@ import data_preferences from '@ohos.data.preferences';
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.|
| Name | Type| Readable| Writable| Description |
| ---------------- | -------- | ---- | ---- | --------------------------------------- |
| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. The key must be less than 80 bytes. |
| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. The value must be less than 8192 bytes.|
## data_preferences.getPreferences
getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void
Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses an asynchronous callback to return the result.
Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes| Callback used to return the result.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance. |
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
**Example**
```ts
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
```js
var preferences = null;
data_preferences.getPreferences(this.context, 'mystore', function (err, object) {
if (err) {
console.info("Failed to get the preferences")
console.info("Failed to get the preferences. Cause: " + err);
return;
}
console.info("Got preferences successfully.")
preferences = object;
console.info("Got the preferences successfully.");
})
```
......@@ -55,28 +61,31 @@ data_preferences.getPreferences(this.context, 'mystore', function (err, preferen
getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses a promise to return the result.
Obtains a **Preferences** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | -------------------------- |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the result.|
| Type | Description |
| ------------------------------------------ | ---------------------------------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.|
**Example**
```ts
```js
var preferences = null;
let promise = data_preferences.getPreferences(this.context, 'mystore')
promise.then((preferences) => {
console.info("Got preferences successfully.")
promise.then((object) => {
preferences = object;
console.info("Got the preferences successfully.");
}).catch((err) => {
console.info("Failed to get the preferences")
console.info("Failed to get the preferences. Cause: " + err);
})
```
......@@ -85,26 +94,29 @@ promise.then((preferences) => {
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory.
Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result.
Deletes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result.
If the **Preferences** instance has a persistent file, this API also deletes the persistent file.
The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
**Example**
```ts
```js
data_preferences.deletePreferences(this.context, 'mystore', function (err) {
if (err) {
console.info("Failed to delete data, err: " + err)
console.info("Failed to delete the preferences. Cause: " + err);
return
}
console.info("Deleted preferences successfully.")
console.info("Deleted the preferences successfully." );
})
```
......@@ -113,29 +125,32 @@ data_preferences.deletePreferences(this.context, 'mystore', function (err) {
deletePreferences(context: Context, name: string): Promise&lt;void&gt;
Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory.
Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the result.
Deletes a **Preferences** instance from the memory. This API uses a promise to return the result.
If the **Preferences** instance has a persistent file, this API also deletes the persistent file.
The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | -------------------------- |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
```js
let promise = data_preferences.deletePreferences(this.context, 'mystore')
promise.then(() => {
console.info("Deleted preferences successfully.")
console.info("Deleted the preferences successfully.");
}).catch((err) => {
console.info("Failed to delete preferences, err: " + err)
console.info("Failed to delete the preferences. Cause: " + err);
})
```
......@@ -144,27 +159,27 @@ promise.then(() => {
removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Removes a **Preferences** singleton instance from the memory.
Removes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result.
When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result.
The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
**Example**
```ts
```js
data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
if (err) {
console.info("Failed to remove preferences from cache, err: " + err)
return
console.info("Failed to remove the preferences. Cause: " + err);
return;
}
console.info("Removed preferences from cache successfully.")
console.info("Removed the preferences successfully.");
})
```
......@@ -173,62 +188,65 @@ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (e
removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
Removes a **Preferences** singleton instance from the memory.
Removes a **Preferences** instance from the memory. This API uses a promise to return the result.
When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the execution result.
The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | -------------------------- |
| context | [Context](js-apis-ability-context.md) | Yes | Application context. |
| name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
```js
let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore')
promise.then(() => {
console.info("Removed preferences from cache successfully.")
console.info("Removed the preferences successfully.");
}).catch((err) => {
console.info("Failed to remove preferences from cache, err: " + err)
console.info("Failed to remove the preferences. Cause: " + err);
})
```
## Preferences
Provides APIs for obtaining and modifying storage data.
Provides methods for obtaining and modifying data.
Before calling any method of **Preferences**, you must obtain a **Preferences** instance by using [data_preferences.getPreferences](#data_preferencesgetpreferences).
### get
get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void
Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses an asynchronous callback to return the result.
Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not the type of the default value, the default value is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.
| callback | AsyncCallback&lt;ValueType&gt; | Yes| Callback used to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to obtain. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| callback | AsyncCallback&lt;[ValueType](#valuetype)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is** undefined** and **data** is the value obtained. Otherwise, **err** is an error code.|
**Example**
```ts
preferences.get('startup', 'default', function(err, value) {
```js
preferences.get('startup', 'default', function(err, data) {
if (err) {
console.info("Failed to get the value of startup, err: " + err)
return
console.info("Failed to get the value of 'startup'. Cause: " + err);
return;
}
console.info("The value of startup is " + value)
console.info("Got the value of 'startup'. Data: " + data);
})
```
......@@ -237,28 +255,29 @@ preferences.get('startup', 'default', function(err, value) {
get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses a promise to return the result.
Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not the type of the default value, the default value is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to obtain. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise used to return the result.|
| Type | Description |
| ----------------------------------- | ----------------------------- |
| Promise<[ValueType](#valuetype)&gt; | Promise used to return the value obtained.|
**Example**
```ts
let promise = preferences.get('startup', 'default')
promise.then((value) => {
console.info("The value of startup is " + value)
```js
let promise = preferences.get('startup', 'default');
promise.then((data) => {
console.info("Got the value of 'startup'. Data: " + data);
}).catch((err) => {
console.info("Failed to get the value of startup, err: " + err)
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
```
......@@ -266,25 +285,26 @@ promise.then((value) => {
getAll(callback: AsyncCallback&lt;Object&gt;): void;
Obtains the **Object** instance that contains all KV pairs.
Obtains an **Object** instance that contains all KV pairs. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback used to return the **Object** instance obtained.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;Object&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.|
**Example**
```ts
```js
preferences.getAll(function (err, value) {
if (err) {
console.info("getAll failed, err: " + err)
return
console.info("Failed to get all KV pairs. Cause: " + err);
return;
}
let keys = Object.keys(value)
console.info('getAll keys = ' + keys)
console.info("getAll object = " + JSON.stringify(value))
let allKeys = Object.keys(value);
console.info("getAll keys = " + allKeys);
console.info("getAll object = " + JSON.stringify(value));
});
```
......@@ -293,24 +313,24 @@ preferences.getAll(function (err, value) {
getAll(): Promise&lt;Object&gt;
Obtains the **Object** instance that contains all KV pairs.
Obtains an **Object** instance that contains all KV pairs. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Object&gt; | Promise used to return the **Object** instance obtained.|
| Type | Description |
| --------------------- | ------------------------------------------- |
| Promise&lt;Object&gt; | Promise used to return the **Object** instance obtained.|
**Example**
```ts
let promise = preferences.getAll()
```js
let promise = preferences.getAll();
promise.then((value) => {
let keys = Object.keys(value)
console.info('getAll keys = ' + keys)
console.info("getAll object = " + JSON.stringify(value))
let allKeys = Object.keys(value);
console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value));
}).catch((err) => {
console.info("getAll failed, err: " + err)
console.info("Failed to get all KV pairs. Cause: " + err);
})
```
......@@ -318,25 +338,25 @@ promise.then((value) => {
put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
Puts a new value to this **Preferences** instance and its persistence file. This API uses an asynchronous callback to return the result.
Writes data to this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. |
**Example**
```ts
```js
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup, err: " + err)
return
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
})
```
......@@ -345,28 +365,28 @@ preferences.put('startup', 'auto', function (err) {
put(key: string, value: ValueType): Promise&lt;void&gt;
Puts a new value to this **Preferences** instance and its persistence file. This API uses a promise to return the result.
Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.|
| Name| Type | Mandatory| Description |
| ------ | ----------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
let promise = preferences.put('startup', 'auto')
```js
let promise = preferences.put('startup', 'auto');
promise.then(() => {
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
}).catch((err) => {
console.info("Failed to put the value of startup, err: " + err)
console.info("Failed to put the value of 'startup'. Cause: " + err);
})
```
......@@ -375,27 +395,27 @@ promise.then(() => {
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result.
Checks whether this **Preferences** instance contains a KV pair of the given key. This API uses an asynchronous callback to return the result..
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.|
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to check. It cannot be empty. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.|
**Example**
```ts
```js
preferences.has('startup', function (err, isExist) {
if (err) {
console.info("Failed to check the key of startup, err: " + err)
return
console.info("Failed to check the key 'startup'. Cause: " + err);
return;
}
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key 'startup' is contained.");
} else {
console.info("The key of startup is not contained.")
console.info("The key 'startup' is not contained.");
}
})
```
......@@ -405,31 +425,32 @@ preferences.has('startup', function (err, isExist) {
has(key: string): Promise&lt;boolean&gt;
Checks whether this **Preferences** instance contains data with a given key. This API uses a promise to return the result.
Checks whether this **Preferences** instance contains data with the given key. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------- |
| key | string | Yes | Key of the data to check. It cannot be empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.|
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.|
**Example**
```ts
let promise = preferences.has('startup')
```js
let promise = preferences.has('startup');
promise.then((isExist) => {
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key 'startup' is contained.");
} else {
console.info("The key of startup is not contained.")
console.info("The key 'startup' is not contained.");
}
}).catch((err) => {
console.info("Failed to check the key of startup, err: " + err)
console.info("Failed to check the key 'startup'. Cause: " + err);
})
```
......@@ -438,24 +459,24 @@ promise.then((isExist) => {
delete(key: string, callback: AsyncCallback&lt;void&gt;): void
Deletes a KV pair of the specified key from this **Preferences** instance. This API uses an asynchronous callback to return the result.
Deletes a KV pair from this **Preferences** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| key | string | Yes | Key of the KV pair to delete. It cannot be empty. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
**Example**
```ts
```js
preferences.delete('startup', function (err) {
if (err) {
console.info("Failed to delete startup key, err: " + err)
return
console.info("Failed to delete the key 'startup'. Cause: " + err);
return;
}
console.info("Deleted startup key successfully.")
console.info("Deleted the key 'startup'.");
})
```
......@@ -464,27 +485,27 @@ preferences.delete('startup', function (err) {
delete(key: string): Promise&lt;void&gt;
Deletes a KV pair of the specified key from this **Preferences** instance. This API uses a promise to return the result.
Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------- |
| key | string | Yes | Key of the KV pair to delete. It cannot be empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
let promise = preferences.delete('startup')
```js
let promise = preferences.delete('startup');
promise.then(() => {
console.info("Deleted startup key successfully.")
console.info("Deleted the key 'startup'.");
}).catch((err) => {
console.info("Failed to delete startup key, err: " + err)
console.info("Failed to delete the key 'startup'. Cause: " + err);
})
```
......@@ -493,23 +514,23 @@ promise.then(() => {
flush(callback: AsyncCallback&lt;void&gt;): void
Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses an asynchronous callback to return the result.
Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
**Example**
```ts
```js
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file, err: " + err)
return
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed data to file successfully.")
console.info("Flushed data successfully.");
})
```
......@@ -518,22 +539,22 @@ preferences.flush(function (err) {
flush(): Promise&lt;void&gt;
Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses a promise to return the result.
Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
let promise = preferences.flush()
```js
let promise = preferences.flush();
promise.then(() => {
console.info("Flushed data to file successfully.")
}).catch((err) => {
console.info("Failed to flush data to file, err: " + err)
console.info("Failed to flush data. Cause: " + err);
})
```
......@@ -542,23 +563,23 @@ promise.then(() => {
clear(callback: AsyncCallback&lt;void&gt;): void
Clears data of this **Preferences** instance. This API uses an asynchronous callback to return the result.
Clears this **Preferences** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
**Example**
```ts
```js
preferences.clear(function (err) {
if (err) {
console.info("Failed to clear data, err: " + err)
return
console.info("Failed to clear data. Cause: " + err);
return;
}
console.info("Cleared to file successfully.")
console.info("Cleared data successfully.");
})
```
......@@ -567,22 +588,22 @@ preferences.clear(function (err) {
clear(): Promise&lt;void&gt;
Clears data of this **Preferences** instance. This API uses a promise to return the result.
Clears this **Preferences** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
```js
let promise = preferences.clear()
promise.then(() => {
console.info("Cleared to file successfully.")
console.info("Cleared data successfully.");
}).catch((err) => {
console.info("Failed to clear data, err: " + err)
console.info("Failed to clear data. Cause: " + err);
})
```
......@@ -591,40 +612,40 @@ promise.then(() => {
on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
Subscribes to data changes. When the value of the subscribed key changes, a callback will be invoked after **flush()** is executed.
Subscribes to data changes. A callback will be triggered to return the new value if the value of the subscribed key is changed and [flushed](#flush).
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Yes| Callback used to return data changes.|
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Yes | Callback invoked to return data changes. |
**Example**
```ts
```js
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
console.info("Failed to get preferences.")
console.info("Failed to get the preferences.");
return;
}
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key " + key + " changed.");
}
preferences.on('change', observer)
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup, err: " + err)
return
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file, err: " + err)
return
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed data to file successfully.") // The observer will be called.
console.info("Flushed data successfully."); // The observer will be called.
})
})
})
......@@ -640,37 +661,37 @@ Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.|
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.|
**Example**
```ts
```js
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
console.info("Failed to get preferences.")
console.info("Failed to get preferences.");
return;
}
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key " + key + " changed.");
}
preferences.on('change', observer)
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup, err: " + err)
return
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file, err: " + err)
return
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed data to file successfully.") // The observer will be called.
console.info("Flushed data successfully."); // The observer will be called.
})
preferences.off('change', observer)
preferences.off('change', observer);
})
})
```
......@@ -681,11 +702,11 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Type | Description |
| -------------- | ------------------------------ |
| number | The value is a number. |
| string | The value is a string. |
| boolean | The value is of Boolean type. |
| Type | Description |
| --------------- | ------------------------------ |
| number | The value is a number. |
| string | The value is a string. |
| boolean | The value is of Boolean type. |
| Array\<number> | The value is an array of numbers. |
| Array\<boolean> | The value is a Boolean array. |
| Array\<string> | The value is an array of the strings.|
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册