• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.preferences (Preferences)
2
3The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
4
5The 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.
6
7
8> **NOTE**
9>
10> 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.
11
12
13## Modules to Import
14
15```js
16import data_preferences from '@ohos.data.preferences';
17```
18
19## Constants
20
21**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
22
23| Name            | Type| Readable| Writable| Description                                   |
24| ---------------- | -------- | ---- | ---- | --------------------------------------- |
25| MAX_KEY_LENGTH   | number   | Yes  | No  | Maximum length of a key, which is 80 bytes.    |
26| MAX_VALUE_LENGTH | number   | Yes  | No  | Maximum length of a value, which is 8192 bytes.|
27
28
29## data_preferences.getPreferences
30
31getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void
32
33Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result.
34
35**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
36
37**Parameters**
38
39| Name  | Type                                            | Mandatory| Description                                                        |
40| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
41| context  | Context            | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).                                                |
42| name     | string                                           | Yes  | Name of the **Preferences** instance.                                     |
43| 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.|
44
45**Example**
46
47FA model:
48
49```js
50// Obtain the context.
51import featureAbility from '@ohos.ability.featureAbility';
52let context = featureAbility.getContext();
53let preferences = null;
54
55try {
56    data_preferences.getPreferences(context, 'mystore', function (err, val) {
57        if (err) {
58	        console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
59	        return;
60	    }
61	    preferences = val;
62	    console.info("Obtained the preferences successfully.");
63	})
64} catch (err) {
65    console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
66}
67```
68
69Stage model:
70
71```ts
72import UIAbility from '@ohos.app.ability.UIAbility';
73
74let preferences = null;
75
76class EntryAbility extends UIAbility {
77    onWindowStageCreate(windowStage) {
78        try {
79            data_preferences.getPreferences(this.context, 'mystore', function (err, val) {
80                if (err) {
81                    console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
82                    return;
83                }
84                preferences = val;
85                console.info("Obtained the preferences successfully.");
86            })
87        } catch (err) {
88            console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
89        }
90    }
91}
92```
93
94## data_preferences.getPreferences
95
96getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
97
98Obtains a **Preferences** instance. This API uses a promise to return the result.
99
100**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
101
102**Parameters**
103
104| Name | Type                                 | Mandatory| Description                   |
105| ------- | ------------------------------------- | ---- | ----------------------- |
106| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).           |
107| name    | string                                | Yes  | Name of the **Preferences** instance.|
108
109**Return value**
110
111| Type                                      | Description                              |
112| ------------------------------------------ | ---------------------------------- |
113| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.|
114
115**Example**
116
117FA model:
118
119```js
120// Obtain the context.
121import featureAbility from '@ohos.ability.featureAbility';
122let context = featureAbility.getContext();
123
124let preferences = null;
125try {
126    let promise = data_preferences.getPreferences(context, 'mystore');
127    promise.then((object) => {
128        preferences = object;
129        console.info("Obtained the preferences successfully.");
130    }).catch((err) => {
131        console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
132    })
133} catch(err) {
134    console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
135}
136```
137
138Stage model:
139
140```ts
141import UIAbility from '@ohos.app.ability.UIAbility';
142
143let preferences = null;
144
145class EntryAbility extends UIAbility {
146    onWindowStageCreate(windowStage) {
147        try {
148            let promise = data_preferences.getPreferences(this.context, 'mystore');
149            promise.then((object) => {
150                preferences = object;
151                console.info("Obtained the preferences successfully.");
152            }).catch((err) => {
153                console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
154            })
155        } catch(err) {
156            console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
157        }
158    }
159}
160```
161
162## data_preferences.deletePreferences
163
164deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
165
166Deletes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result.
167
168If the **Preferences** instance has a persistent file, this API also deletes the persistent file.
169
170The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
171
172**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
173
174**Parameters**
175
176| Name  | Type                                 | Mandatory| Description                                                |
177| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
178| context  | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).                                        |
179| name     | string                                | Yes  | Name of the **Preferences** instance to delete.                          |
180| 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.|
181
182**Error codes**
183
184For details about the following error codes, see [Preference Error Codes](../errorcodes/errorcode-preferences.md).
185
186| ID| Error Message                      |
187| -------- | ------------------------------|
188| 15500010 | Failed to delete the preferences. |
189
190**Example**
191
192FA model:
193
194```js
195// Obtain the context.
196import featureAbility from '@ohos.ability.featureAbility';
197let context = featureAbility.getContext();
198
199try {
200    data_preferences.deletePreferences(context, 'mystore', function (err, val) {
201        if (err) {
202            console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
203            return;
204        }
205        console.info("Deleted the preferences successfully." );
206    })
207} catch (err) {
208    console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
209}
210```
211
212Stage model:
213
214```ts
215import UIAbility from '@ohos.app.ability.UIAbility';
216class EntryAbility extends UIAbility {
217    onWindowStageCreate(windowStage) {
218        try {
219            data_preferences.deletePreferences(this.context, 'mystore', function (err, val) {
220                if (err) {
221                    console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
222                    return;
223                }
224                console.info("Deleted the preferences successfully." );
225            })
226        } catch (err) {
227            console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
228        }
229    }
230}
231```
232
233## data_preferences.deletePreferences
234
235deletePreferences(context: Context, name: string): Promise&lt;void&gt;
236
237Deletes a **Preferences** instance from the memory. This API uses a promise to return the result.
238
239If the **Preferences** instance has a persistent file, this API also deletes the persistent file.
240
241The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
242
243**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
244
245**Parameters**
246
247| Name | Type                                 | Mandatory| Description                   |
248| ------- | ------------------------------------- | ---- | ----------------------- |
249| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).           |
250| name    | string                                | Yes  | Name of the **Preferences** instance to delete.|
251
252**Return value**
253
254| Type               | Description                     |
255| ------------------- | ------------------------- |
256| Promise&lt;void&gt; | Promise that returns no value.|
257
258**Error codes**
259
260For details about the following error codes, see [Preference Error Codes](../errorcodes/errorcode-preferences.md).
261
262| ID| Error Message                      |
263| -------- | ------------------------------|
264| 15500010 | Failed to delete the preferences. |
265
266**Example**
267
268FA model:
269
270```js
271// Obtain the context.
272import featureAbility from '@ohos.ability.featureAbility';
273let context = featureAbility.getContext();
274
275try {
276    let promise = data_preferences.deletePreferences(context, 'mystore');
277    promise.then(() => {
278        console.info("Deleted the preferences successfully.");
279    }).catch((err) => {
280        console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
281    })
282} catch(err) {
283    console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
284}
285```
286
287Stage model:
288
289```ts
290import UIAbility from '@ohos.app.ability.UIAbility';
291class EntryAbility extends UIAbility {
292    onWindowStageCreate(windowStage) {
293        try{
294            let promise = data_preferences.deletePreferences(this.context, 'mystore');
295            promise.then(() => {
296                console.info("Deleted the preferences successfully.");
297            }).catch((err) => {
298                console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
299            })
300        } catch(err) {
301            console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
302        }
303    }
304}
305```
306
307## data_preferences.removePreferencesFromCache
308
309removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
310
311Removes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result.
312
313The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
314
315**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
316
317**Parameters**
318
319| Name  | Type                                 | Mandatory| Description                                                |
320| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
321| context  | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).                                        |
322| name     | string                                | Yes  | Name of the **Preferences** instance to remove.                          |
323| 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.|
324
325**Example**
326
327FA model:
328
329```js
330// Obtain the context.
331import featureAbility from '@ohos.ability.featureAbility';
332let context = featureAbility.getContext();
333
334try {
335    data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
336        if (err) {
337            console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
338            return;
339        }
340        console.info("Removed the preferences successfully.");
341    })
342} catch (err) {
343    console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
344}
345```
346
347Stage model:
348
349```ts
350import UIAbility from '@ohos.app.ability.UIAbility';
351class EntryAbility extends UIAbility {
352    onWindowStageCreate(windowStage) {
353        try {
354            data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err, val) {
355                if (err) {
356                    console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
357                    return;
358                }
359                console.info("Removed the preferences successfully.");
360            })
361        } catch (err) {
362            console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
363        }
364    }
365}
366
367```
368
369## data_preferences.removePreferencesFromCache
370
371removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
372
373Removes a **Preferences** instance from the memory. This API uses a promise to return the result.
374
375The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
376
377**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
378
379**Parameters**
380
381| Name | Type                                 | Mandatory| Description                   |
382| ------- | ------------------------------------- | ---- | ----------------------- |
383| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).           |
384| name    | string                                | Yes  | Name of the **Preferences** instance to remove.|
385
386**Return value**
387
388| Type               | Description                     |
389| ------------------- | ------------------------- |
390| Promise&lt;void&gt; | Promise that returns no value.|
391
392**Example**
393
394FA model:
395
396```js
397// Obtain the context.
398import featureAbility from '@ohos.ability.featureAbility';
399let context = featureAbility.getContext();
400
401try {
402    let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
403	promise.then(() => {
404    	console.info("Removed the preferences successfully.");
405    }).catch((err) => {
406        console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
407    })
408} catch(err) {
409    console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
410}
411```
412
413Stage model:
414
415```ts
416import UIAbility from '@ohos.app.ability.UIAbility';
417
418class EntryAbility extends UIAbility {
419    onWindowStageCreate(windowStage) {
420        try {
421            let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore');
422            promise.then(() => {
423                console.info("Removed the preferences successfully.");
424            }).catch((err) => {
425                console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
426            })
427        } catch(err) {
428            console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
429        }
430    }
431}
432```
433
434## Preferences
435
436Provides methods for obtaining and modifying data.
437
438Before calling any method of **Preferences**, you must obtain a **Preferences** instance by using [data_preferences.getPreferences](#data_preferencesgetpreferences).
439
440
441### get
442
443get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void
444
445Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not of the default value type, **defValue** is returned.
446
447**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
448
449**Parameters**
450
451| Name  | Type                                        | Mandatory| Description                                                        |
452| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
453| key      | string                                       | Yes  | Key of the data to obtain. It cannot be empty.                             |
454| 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.|
455| 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.|
456
457**Example**
458
459```js
460try {
461    preferences.get('startup', 'default', function (err, val) {
462        if (err) {
463            console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
464            return;
465        }
466        console.info("Obtained the value of 'startup' successfully. val: " + val);
467    })
468} catch (err) {
469    console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
470}
471```
472
473
474### get
475
476get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
477
478Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not of the default value type, **defValue** is returned.
479
480**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
481
482 **Parameters**
483
484| Name  | Type                   | Mandatory| Description                                                        |
485| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
486| key      | string                  | Yes  | Key of the data to obtain. It cannot be empty.                             |
487| 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.|
488
489**Return value**
490
491| Type                               | Description                         |
492| ----------------------------------- | ----------------------------- |
493| Promise<[ValueType](#valuetype)&gt; | Promise used to return the value obtained.|
494
495**Example**
496
497```js
498try {
499    let promise = preferences.get('startup', 'default');
500    promise.then((data) => {
501        console.info("Got the value of 'startup'. Data: " + data);
502    }).catch((err) => {
503        console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
504    })
505} catch(err) {
506    console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
507}
508```
509
510### getAll
511
512getAll(callback: AsyncCallback&lt;Object&gt;): void;
513
514Obtains an **Object** instance that contains all KV pairs. This API uses an asynchronous callback to return the result.
515
516**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
517
518**Parameters**
519
520| Name  | Type                       | Mandatory| Description                                                        |
521| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
522| 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.|
523
524**Example**
525
526```js
527try {
528    preferences.getAll(function (err, value) {
529        if (err) {
530            console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message);
531            return;
532        }
533    let allKeys = Object.keys(value);
534    console.info("getAll keys = " + allKeys);
535    console.info("getAll object = " + JSON.stringify(value));
536    })
537} catch (err) {
538    console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message);
539}
540```
541
542
543### getAll
544
545getAll(): Promise&lt;Object&gt;
546
547Obtains an **Object** instance that contains all KV pairs. This API uses a promise to return the result.
548
549**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
550
551**Return value**
552
553| Type                 | Description                                       |
554| --------------------- | ------------------------------------------- |
555| Promise&lt;Object&gt; | Promise used to return the **Object** instance obtained.|
556
557**Example**
558
559```js
560try {
561    let promise = preferences.getAll();
562    promise.then((value) => {
563        let allKeys = Object.keys(value);
564        console.info('getAll keys = ' + allKeys);
565        console.info("getAll object = " + JSON.stringify(value));
566    }).catch((err) => {
567        console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message);
568    })
569} catch (err) {
570    console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message);
571}
572```
573
574### put
575
576put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
577
578Writes 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.
579
580**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
581
582**Parameters**
583
584| Name  | Type                     | Mandatory| Description                                                        |
585| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
586| key      | string                    | Yes  | Key of the data. It cannot be empty.                               |
587| 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.|
588| 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.    |
589
590**Example**
591
592```js
593try {
594    preferences.put('startup', 'auto', function (err) {
595        if (err) {
596            console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
597            return;
598        }
599        console.info("Put the value of 'startup' successfully.");
600    })
601} catch (err) {
602    console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
603}
604```
605
606
607### put
608
609put(key: string, value: ValueType): Promise&lt;void&gt;
610
611Writes 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.
612
613**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
614
615**Parameters**
616
617| Name| Type                   | Mandatory| Description                                                        |
618| ------ | ----------------------- | ---- | ------------------------------------------------------------ |
619| key    | string                  | Yes  | Key of the data. It cannot be empty.                               |
620| 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.|
621
622**Return value**
623
624| Type               | Description                     |
625| ------------------- | ------------------------- |
626| Promise&lt;void&gt; | Promise that returns no value.|
627
628**Example**
629
630```js
631try {
632    let promise = preferences.put('startup', 'auto');
633    promise.then(() => {
634        console.info("Put the value of 'startup' successfully.");
635    }).catch((err) => {
636        console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
637    })
638} catch(err) {
639    console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
640}
641```
642
643
644### has
645
646has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
647
648Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.
649
650**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
651
652**Parameters**
653
654| Name  | Type                        | Mandatory| Description                                                        |
655| -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
656| key      | string                       | Yes  | Key of the data to check. It cannot be empty.                             |
657| 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.|
658
659**Example**
660
661```js
662try {
663    preferences.has('startup', function (err, val) {
664        if (err) {
665            console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
666            return;
667        }
668        if (val) {
669            console.info("The key 'startup' is contained.");
670        } else {
671            console.info("The key 'startup' is not contained.");
672        }
673  })
674} catch (err) {
675    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
676}
677```
678
679
680### has
681
682has(key: string): Promise&lt;boolean&gt;
683
684Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.
685
686**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
687
688**Parameters**
689
690| Name| Type  | Mandatory| Description                           |
691| ------ | ------ | ---- | ------------------------------- |
692| key    | string | Yes  | Key of the data to check. It cannot be empty.|
693
694**Return value**
695
696| Type                  | Description                                                        |
697| ---------------------- | ------------------------------------------------------------ |
698| 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.|
699
700**Example**
701
702```js
703try {
704    let promise = preferences.has('startup');
705    promise.then((val) => {
706        if (val) {
707            console.info("The key 'startup' is contained.");
708        } else {
709            console.info("The key 'startup' is not contained.");
710        }
711    }).catch((err) => {
712        console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
713  })
714} catch(err) {
715    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
716}
717```
718
719
720### delete
721
722delete(key: string, callback: AsyncCallback&lt;void&gt;): void
723
724Deletes a KV pair from this **Preferences** instance based on the specified key. This API uses an asynchronous callback to return the result.
725
726**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
727
728**Parameters**
729
730| Name  | Type                     | Mandatory| Description                                                |
731| -------- | ------------------------- | ---- | ---------------------------------------------------- |
732| key      | string                    | Yes  | Key of the KV pair to delete. It cannot be empty.                     |
733| 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.|
734
735**Example**
736
737```js
738try {
739    preferences.delete('startup', function (err) {
740        if (err) {
741            console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
742            return;
743        }
744        console.info("Deleted the key 'startup'.");
745    })
746} catch (err) {
747    console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
748}
749```
750
751
752### delete
753
754delete(key: string): Promise&lt;void&gt;
755
756Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result.
757
758**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
759
760**Parameters**
761
762| Name| Type  | Mandatory| Description                           |
763| ------ | ------ | ---- | ------------------------------- |
764| key    | string | Yes  | Key of the KV pair to delete. It cannot be empty.|
765
766**Return value**
767
768| Type               | Description                     |
769| ------------------- | ------------------------- |
770| Promise&lt;void&gt; | Promise that returns no value.|
771
772**Example**
773
774```js
775try {
776    let promise = preferences.delete('startup');
777	promise.then(() => {
778        console.info("Deleted the key 'startup'.");
779    }).catch((err) => {
780        console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
781    })
782} catch(err) {
783    console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
784}
785```
786
787
788### flush
789
790flush(callback: AsyncCallback&lt;void&gt;): void
791
792Saves the data of this **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result.
793
794**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
795
796**Parameters**
797
798| Name  | Type                     | Mandatory| Description                                                |
799| -------- | ------------------------- | ---- | ---------------------------------------------------- |
800| 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.|
801
802**Example**
803
804```js
805try {
806    preferences.flush(function (err) {
807        if (err) {
808            console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
809            return;
810        }
811        console.info("Flushed data successfully.");
812    })
813} catch (err) {
814    console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
815}
816```
817
818
819### flush
820
821flush(): Promise&lt;void&gt;
822
823Saves the data of this **Preferences** instance to a file asynchronously. This API uses a promise to return the result.
824
825**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
826
827**Return value**
828
829| Type               | Description                     |
830| ------------------- | ------------------------- |
831| Promise&lt;void&gt; | Promise that returns no value.|
832
833**Example**
834
835```js
836try {
837    let promise = preferences.flush();
838    promise.then(() => {
839        console.info("Flushed data successfully.");
840    }).catch((err) => {
841        console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
842    })
843} catch (err) {
844    console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
845}
846```
847
848
849### clear
850
851clear(callback: AsyncCallback&lt;void&gt;): void
852
853Clears this **Preferences** instance. This API uses an asynchronous callback to return the result.
854
855**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
856
857**Parameters**
858
859| Name  | Type                     | Mandatory| Description                                                |
860| -------- | ------------------------- | ---- | ---------------------------------------------------- |
861| 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.|
862
863**Example**
864
865```js
866try {
867	preferences.clear(function (err) {
868        if (err) {
869            console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
870            return;
871        }
872        console.info("Cleared data successfully.");
873    })
874} catch (err) {
875    console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
876}
877```
878
879
880### clear
881
882clear(): Promise&lt;void&gt;
883
884Clears this **Preferences** instance. This API uses a promise to return the result.
885
886**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
887
888**Return value**
889
890| Type               | Description                     |
891| ------------------- | ------------------------- |
892| Promise&lt;void&gt; | Promise that returns no value.|
893
894**Example**
895
896```js
897try {
898    let promise = preferences.clear();
899	promise.then(() => {
900    	console.info("Cleared data successfully.");
901    }).catch((err) => {
902        console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
903    })
904} catch(err) {
905    console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
906}
907```
908
909
910### on('change')
911
912on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
913
914Subscribes 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).
915
916**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
917
918**Parameters**
919
920| Name  | Type                            | Mandatory| Description                                    |
921| -------- | -------------------------------- | ---- | ---------------------------------------- |
922| type     | string                           | Yes  | Event type to subscribe to. The value **change** indicates data change events.|
923| callback | Callback&lt;{ key : string }&gt; | Yes  | Callback invoked to return data changes.                          |
924
925**Example**
926
927```js
928try {
929	data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
930		if (err) {
931			console.info("Failed to obtain the preferences.");
932			return;
933		}
934		let observer = function (key) {
935			console.info("The key " + key + " changed.");
936		}
937		preferences.on('change', observer);
938		preferences.put('startup', 'manual', function (err) {
939			if (err) {
940				console.info("Failed to put the value of 'startup'. Cause: " + err);
941				return;
942			}
943			console.info("Put the value of 'startup' successfully.");
944
945			preferences.flush(function (err) {
946				if (err) {
947					console.info("Failed to flush data. Cause: " + err);
948					return;
949				}
950				console.info("Flushed data successfully.");
951			})
952		})
953	})
954} catch (err) {
955	console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
956}
957```
958
959
960### off('change')
961
962off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void
963
964Unsubscribes from data changes.
965
966**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
967
968**Parameters**
969
970| Name  | Type                            | Mandatory| Description                                      |
971| -------- | -------------------------------- | ---- | ------------------------------------------ |
972| type     | string                           | Yes  | Event type to unsubscribe from. The value **change** indicates data change events.  |
973| callback | Callback&lt;{ key : string }&gt; | No  | Callback to unregister. If this parameter is left blank, the callbacks for all data changes will be unregistered.|
974
975**Example**
976
977```js
978try {
979    data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
980        if (err) {
981            console.info("Failed to obtain the preferences.");
982            return;
983        }
984        let observer = function (key) {
985            console.info("The key " + key + " changed.");
986        }
987        preferences.on('change', observer);
988        preferences.put('startup', 'auto', function (err) {
989            if (err) {
990                console.info("Failed to put the value of 'startup'. Cause: " + err);
991                return;
992            }
993            console.info("Put the value of 'startup' successfully.");
994
995            preferences.flush(function (err) {
996                if (err) {
997                    console.info("Failed to flush data. Cause: " + err);
998                    return;
999                }
1000                console.info("Flushed data successfully.");
1001            })
1002            preferences.off('change', observer);
1003        })
1004    })
1005} catch (err) {
1006    console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
1007}
1008```
1009
1010## ValueType
1011
1012Enumerates the value types.
1013
1014**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1015
1016| Type           | Description                          |
1017| --------------- | ------------------------------ |
1018| number          | The value is a number.            |
1019| string          | The value is a string.          |
1020| boolean         | The value is of Boolean type.          |
1021| Array\<number>  | The value is an array of numbers.  |
1022| Array\<boolean> | The value is a Boolean array.  |
1023| Array\<string>  | The value is an array of the strings.|
1024