@ohos.data.preferences (User Preferences)

The Preferences module provides APIs for processing data in the form of key-value (KV) pairs, including querying, modifying, and persisting KV pairs.

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

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

import dataPreferences from '@ohos.data.preferences';

Constants

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Name Type Readable Writable Description
MAX_KEY_LENGTH number Yes No Maximum length of a key, which is 80 bytes.
MAX_VALUE_LENGTH number Yes No Maximum length of a value, which is 8192 bytes.

dataPreferences.getPreferences

getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void

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 Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.
callback AsyncCallback<Preferences> Yes Callback invoked to return the result. If the operation is successful, err is undefined and the Preferences instance obtained is returned. Otherwise, err is an error object.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    dataPreferences.getPreferences(context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => {
                if (err) {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                return;
                }
                preferences = val;
                console.info("Succeeded in getting preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.getPreferences

getPreferences(context: Context, name: string): Promise<Preferences>

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 Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.

Return value

Type Description
Promise<Preferences> Promise used to return the Preferences instance obtained.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

let preferences: dataPreferences.Preferences | null = null;
try {
    let promise = dataPreferences.getPreferences(context, 'myStore');
    promise.then((object: dataPreferences.Preferences) => {
        preferences = object;
        console.info("Succeeded in getting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let promise = dataPreferences.getPreferences(this.context, 'myStore');
            promise.then((object: dataPreferences.Preferences) => {
                preferences = object;
                console.info("Succeeded in getting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.getPreferences10+

getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void

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 Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.
callback AsyncCallback<Preferences> Yes Callback invoked to return the result. If the operation is successful, err is undefined and the Preferences instance obtained is returned. Otherwise, err is an error object.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.getPreferences(context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
                if (err) {
                    console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                preferences = val;
                console.info("Succeeded in getting preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.getPreferences10+

getPreferences(context: Context, options: Options): Promise<Preferences>

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 Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.

Return value

Type Description
Promise<Preferences> Promise used to return the Preferences instance obtained.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();

let preferences: dataPreferences.Preferences | null = null;
try {
    let options: dataPreferences.Options =  { name: 'myStore' };
    let promise = dataPreferences.getPreferences(context, options);
    promise.then((object: dataPreferences.Preferences) => {
        preferences = object;
        console.info("Succeeded in getting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options =  { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.getPreferences(this.context, options);
            promise.then((object: dataPreferences.Preferences) => {
                preferences = object;
                console.info("Succeeded in getting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.getPreferencesSync10+

getPreferencesSync(context: Context, options: Options): Preferences

Obtains a Preferences instance. This API returns the result synchronously.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.

Return value

Type Description
Preferences Preferences instance obtained.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    let options: dataPreferences.Options =  { name: 'myStore' };
    preferences = dataPreferences.getPreferencesSync(context, options);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            preferences = dataPreferences.getPreferencesSync(this.context, options);
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.deletePreferences

deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void

Deletes a Preferences instance from the cache. If the Preferences instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.

After the Preferences instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted Preferences instance to null. The system will reclaim the deleted Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15500010 Failed to delete preferences file.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    dataPreferences.deletePreferences(context, 'myStore', (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in deleting preferences." );
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
                if (err) {
                    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in deleting preferences." );
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.deletePreferences

deletePreferences(context: Context, name: string): Promise<void>

Deletes a Preferences instance from the cache. If the Preferences instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.

After the Preferences instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted Preferences instance to null. The system will reclaim the deleted Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15500010 Failed to delete preferences file.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let promise = dataPreferences.deletePreferences(context, 'myStore');
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try{
            let promise = dataPreferences.deletePreferences(this.context, 'myStore');
            promise.then(() => {
                console.info("Succeeded in deleting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.deletePreferences10+

deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void

Deletes a Preferences instance from the cache. If the Preferences instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.

After the Preferences instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted Preferences instance to null. The system will reclaim the deleted Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15500010 Failed to delete preferences file.
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.deletePreferences(context, options, (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in deleting preferences." );
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.deletePreferences(this.context, options, (err: BusinessError) => {
                if (err) {
                    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in deleting preferences." );
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.deletePreferences10+

deletePreferences(context: Context, options: Options): Promise<void>

Deletes a Preferences instance from the cache. If the Preferences instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.

After the Preferences instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted Preferences instance to null. The system will reclaim the deleted Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15500010 Failed to delete preferences file.
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    let promise = dataPreferences.deletePreferences(context, options);
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try{
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.deletePreferences(this.context, options);
            promise.then(() => {
                console.info("Succeeded in deleting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCache

removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void

Removes a Preferences instance from the cache. This API uses an asynchronous callback to return the result.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
try {
    dataPreferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => {
        if (err) {
            console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in removing preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => {
                if (err) {
                    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in removing preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCache

removePreferencesFromCache(context: Context, name: string): Promise<void>

Removes a Preferences instance from the cache. This API uses a promise to return the result.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.

Return value

Type Description
Promise<void> Promise that returns no value.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
try {
    let promise = dataPreferences.removePreferencesFromCache(context, 'myStore');
    promise.then(() => {
        console.info("Succeeded in removing preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let promise = dataPreferences.removePreferencesFromCache(this.context, 'myStore');
            promise.then(() => {
                console.info("Succeeded in removing preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCacheSync10+

removePreferencesFromCacheSync(context: Context, name: string): void

Removes a Preferences instance from the cache. This API returns the result synchronously.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
name string Yes Name of the Preferences instance.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    dataPreferences.removePreferencesFromCacheSync(context, 'myStore');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.removePreferencesFromCacheSync(this.context, 'myStore');
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCache10+

removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void

Removes a Preferences instance from the cache. This API uses an asynchronous callback to return the result.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.removePreferencesFromCache(context, options, (err: BusinessError) => {
        if (err) {
            console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in removing preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
                if (err) {
                    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in removing preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCache10+

removePreferencesFromCache(context: Context, options: Options): Promise<void>

Removes a Preferences instance from the cache. This API uses a promise to return the result.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    let promise = dataPreferences.removePreferencesFromCache(context, options);
    promise.then(() => {
        console.info("Succeeded in removing preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.removePreferencesFromCache(this.context, options);
            promise.then(() => {
                console.info("Succeeded in removing preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

dataPreferences.removePreferencesFromCacheSync10+

removePreferencesFromCacheSync(context: Context, options: Options):void

Removes a Preferences instance from the cache. This API returns the result synchronously.

After an application calls getPreferences for the first time to obtain a Preferences instance, the obtained Preferences instance is cached. When the application calls getPreferences again, the Preferences instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling getPreferences again will read data from the persistent file and create a new Preferences instance.

After the Preferences instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed Preferences instance to null. The system will reclaim the removed Preferences instances in a unified manner.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
context Context Yes Application context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
options Options Yes Configuration options of the Preferences instance.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15501001 Only supported in stage mode.
15501002 The data group id is not valid.

Example

FA model:

// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.removePreferencesFromCacheSync(context, options);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.removePreferencesFromCacheSync(this.context, options);
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}

Options10+

Represents the configuration options of a Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Name Type Mandatory Description
name string Yes Name of the Preferences instance.
dataGroupId string No Application group ID, which needs to be obtained from the AppGallery.
Model restriction: This attribute can be used only in the stage model.
This parameter is supported since API version 10. It specifies the Preferences instance created in the sandbox directory corresponding to the dataGroupId. If this parameter is not specified, the Preferences instance is created in the sandbox directory of the application.

Preferences

Provides APIs for obtaining and modifying the stored data.

Before calling any API of Preferences, you must obtain a Preferences instance by using dataPreferences.getPreferences.

get

get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void

Obtains the value of a key from this Preferences instance. 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.

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 Yes Default value to be returned. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.
callback AsyncCallback<ValueType> 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 object.

Example

import {BusinessError} from '@ohos.base';

try {
    preferences.get('startup', 'default', (err: BusinessError, val: dataPreferences.ValueType) => {
        if (err) {
            console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Obtained the value of 'startup' successfully. val: " + val);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}

get

get(key: string, defValue: ValueType): Promise<ValueType>

Obtains the value of a key from this Preferences instance. 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.

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 Yes Default value to be returned. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.

Return value

Type Description
Promise<ValueType> Promise used to return the value obtained.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.get('startup', 'default');
    promise.then((data: dataPreferences.ValueType) => {
        console.info("Got the value of 'startup'. Data: " + data);
    }).catch((err: BusinessError) => {
        console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}

getSync10+

getSync(key: string, defValue: ValueType): ValueType

Obtains the value of a key from this Preferences instance. This API returns the result synchronously. If the value is null or is not of the default value type, defValue 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 Yes Default value to be returned. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.

Return value

Type Description
ValueType Returns the value obtained.

Example

try {
    let value: dataPreferences.ValueType = preferences.getSync('startup', 'default');
    console.info("Succeeded in getting value of 'startup'. Data: " + value);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}

getAll

getAll(callback: AsyncCallback<Object>): void;

Obtains all KV pairs 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
callback AsyncCallback<Object> Yes Callback invoked to return the result. If the operation is successful, err is undefined and value provides all KV pairs obtained. Otherwise, err is an error object.

Example

import {BusinessError} from '@ohos.base';

// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    preferences.getAll((err: BusinessError, value: Object) => {
        if (err) {
            console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
            return;
        }
        let allKeys = getObjKeys(value);
        console.info("getAll keys = " + allKeys);
        console.info("getAll object = " + JSON.stringify(value));
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}

getAll

getAll(): Promise<Object>

Obtains all KV pairs from this Preferences instance. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Return value

Type Description
Promise<Object> Promise used to return the KV pairs obtained.

Example

import {BusinessError} from '@ohos.base';

// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    let promise = preferences.getAll();
    promise.then((value: Object) => {
        let allKeys = getObjKeys(value);
        console.info('getAll keys = ' + allKeys);
        console.info("getAll object = " + JSON.stringify(value));
    }).catch((err: BusinessError) => {
        console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}

getAllSync10+

getAllSync(): Object

Obtains all KV pairs from this Preferences instance. This API returns the result synchronously.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Return value

Type Description
Object Returns all KV pairs obtained.

Example

// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    let value = preferences.getAllSync();
    let allKeys = getObjKeys(value);
    console.info('getAll keys = ' + allKeys);
    console.info("getAll object = " + JSON.stringify(value));
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}

put

put(key: string, value: ValueType, callback: AsyncCallback<void>): void

Writes data to this Preferences instance. This API uses an asynchronous callback to return the result. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
key string Yes Key of the data. It cannot be empty.
value ValueType Yes Value to write. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.
callback AsyncCallback<void> Yes Callback invoked to return the result. If data is written successfully, err is undefined. Otherwise, err is an error object.

Example

import {BusinessError} from '@ohos.base';

try {
    preferences.put('startup', 'auto', (err: BusinessError) => {
        if (err) {
            console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Successfully put the value of 'startup'.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message);
}

put

put(key: string, value: ValueType): Promise<void>

Writes data to this Preferences instance. This API uses a promise to return the result. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
key string Yes Key of the data. It cannot be empty.
value ValueType Yes Value to write. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.

Return value

Type Description
Promise<void> Promise that returns no value.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.put('startup', 'auto');
    promise.then(() => {
        console.info("Successfully put the value of 'startup'.");
    }).catch((err: BusinessError) => {
        console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code +", message =" + message);
}

putSync10+

putSync(key: string, value: ValueType): void

Writes data to this Preferences instance. This API returns the result synchronously. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
key string Yes Key of the data. It cannot be empty.
value ValueType Yes Value to write. The value supports the following types: number, string, boolean, Array<number>, Array<string>, and Array<boolean>.

Example

try {
    preferences.putSync('startup', 'auto');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code +", message =" + message);
}

has

has(key: string, callback: AsyncCallback<boolean>): void

Checks whether this Preferences instance contains the 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<boolean> 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

import {BusinessError} from '@ohos.base';

try {
    preferences.has('startup', (err: BusinessError, val: boolean) => {
        if (err) {
            console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        if (val) {
            console.info("The key 'startup' is contained.");
        } else {
            console.info("The key 'startup' is not contained.");
        }
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}

has

has(key: string): Promise<boolean>

Checks whether this Preferences instance contains the KV pair of 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.

Return value

Type Description
Promise<boolean> Promise used to return the result. If the Preferences instance contains the KV pair, true will be returned. Otherwise, false will be returned.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.has('startup');
    promise.then((val: boolean) => {
        if (val) {
            console.info("The key 'startup' is contained.");
        } else {
            console.info("The key 'startup' is not contained.");
        }
    }).catch((err: BusinessError) => {
        console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}

hasSync10+

hasSync(key: string): boolean

Checks whether this Preferences instance contains the KV pair of the given key. This API returns the result synchronously.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
key string Yes Key of the data to check. It cannot be empty.

Return value

Type Description
boolean If the Preferences instance contains the KV pair, true will be returned. Otherwise, false will be returned.

Example

try {
    let isExist: boolean = preferences.hasSync('startup');
    if (isExist) {
        console.info("The key 'startup' is contained.");
    } else {
        console.info("The key 'startup' is not contained.");
    }
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}

delete

delete(key: string, callback: AsyncCallback<void>): void

Deletes a KV pair from this Preferences instance. This API uses an asynchronous callback to return the result. You can use flush to persist the Preferences instance.

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<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Example

import {BusinessError} from '@ohos.base';

try {
    preferences.delete('startup', (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Deleted the key 'startup'.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message);
}

delete

delete(key: string): Promise<void>

Deletes a KV pair from this Preferences instance. This API uses a promise to return the result. You can use flush to persist the Preferences instance.

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.

Return value

Type Description
Promise<void> Promise that returns no value.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.delete('startup');
    promise.then(() => {
        console.info("Deleted the key 'startup'.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message);
}

deleteSync10+

deleteSync(key: string): void

Deletes a KV pair from this Preferences instance. This API returns the result synchronously. You can use flush to persist the Preferences instance.

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.

Example

try {
    preferences.deleteSync('startup');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message);
}

flush

flush(callback: AsyncCallback<void>): void

Flushes the data in this Preferences instance to the persistent file. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Example

import {BusinessError} from '@ohos.base';

try {
    preferences.flush((err: BusinessError) => {
        if (err) {
            console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Successfully flushed data.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}

flush

flush(): Promise<void>

Flushes the data in this Preferences instance to the persistent file. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Return value

Type Description
Promise<void> Promise that returns no value.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.flush();
    promise.then(() => {
        console.info("Successfully flushed data.");
    }).catch((err: BusinessError) => {
        console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}

clear

clear(callback: AsyncCallback<void>): void

Clears this Preferences instance. This API uses an asynchronous callback to return the result. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback invoked to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Example

import {BusinessError} from '@ohos.base';

try {
    preferences.clear((err: BusinessError) =>{
        if (err) {
            console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Successfully cleared data.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}

clear

clear(): Promise<void>

Clears this Preferences instance. This API uses a promise to return the result. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Return value

Type Description
Promise<void> Promise that returns no value.

Example

import {BusinessError} from '@ohos.base';

try {
    let promise = preferences.clear();
    promise.then(() => {
        console.info("Successfully cleared data.");
    }).catch((err: BusinessError) => {
        console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}

clearSync10+

clearSync(): void

Clears this Preferences instance. This API returns the result synchronously. You can use flush to persist the Preferences instance.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Example

try {
    preferences.clearSync();
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}

on('change')

on(type: 'change', callback: ( key : string ) => void): void

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.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value change indicates data changes.
callback Function Yes Callback invoked to return data changes.
key is the key whose value is changed.

Example

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('change', observer);
preferences.putSync('startup', 'manual');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Successfully flushed data.");
})

on('multiProcessChange')10+

on(type: 'multiProcessChange', callback: ( key : string ) => void): void

Subscribes to inter-process data changes. For the multiple processes holding the same preference file, if the value of the subscribed key changes in any process, the callback in this API will be invoked after flush() is executed.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is multiProcessChange, which indicates data changes between multiple processes.
callback Function Yes Callback invoked to return inter-process data changes.
key is the key whose value is changed.

Error codes

For details about the error codes, see User Preference Error Codes.

ID Error Message
15500019 Failed to obtain subscription service.

Example

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.putSync('startup', 'manual');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Successfully flushed data.");
})

off('change')

off(type: 'change', callback?: ( key : string ) => void): void

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 changes.
callback Function No Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered.
key is the key whose value is changed.

Example

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('change', observer);
preferences.putSync('startup', 'auto');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Successfully flushed data.");
})
preferences.off('change', observer);

off('multiProcessChange')10+

off(type: 'multiProcessChange', callback?: ( key : string ) => void): void

Unsubscribes from inter-process data changes.

System capability: SystemCapability.DistributedDataManager.Preferences.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is multiProcessChange, which indicates data changes between multiple processes.
callback Function No Callback to unregister. If this parameter is left blank, all callbacks for inter-process data changes will be unregistered.
key is the key whose value is changed.

Example

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.putSync('startup', 'auto');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Successfully flushed data.");
})
preferences.off('multiProcessChange', observer);

ValueType

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 true or false.
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 strings.