> 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
## 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).
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
### 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
| 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>.|
### 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.
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
| 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. |
| 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
### Storing Data Persistently
...
@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p
...
@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.|
| Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
### Observing Data Changes
### 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
**Table 5** APIs for observing **Preferences** changes
| 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 | 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.
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory. |
## How to Develop
## How to Develop
1. Import @ohos.data.preferences and related modules to the development environment.
1. Import @ohos.data.preferences and related modules to the development environment.
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)=>{
}).catch((err)=>{
console.info("Failed to get the preferences")})
console.info("Failed to get the preferences.")
});
```
```
5. Store data persistently.
5. Store data persistently.
...
@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file.
...
@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file.
6. Observe data changes.
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
```js
varobserver=function(key){
varobserver=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){
preferences.put('startup','auto',function(err){
if(err){
if(err){
console.info("Failed to put the value of startup with err: "+err)
console.info("Failed to put the value of 'startup'. Cause: "+err);
return
return;
}
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
preferences.flush(function(err){
preferences.flush(function(err){
if(err){
if(err){
console.info("Failed to flush data to file with err: "+err)
console.info("Failed to flush data. Cause: "+err);
return
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.
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.
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 care about the implementation of the database lock mechanism.
## Basic Concepts
## 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**
-**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
## 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.
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.
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.
**Figure 1**How **Preferences** work
**Figure 1**Working mechanism
![](figures/preferences.png)
![](figures/preferences.png)
## Constraints
## 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.
-**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 `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 `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.