DEV Community

HarmonyOS
HarmonyOS

Posted on • Edited on

Accessing SharedPreferences data across different modules

Read the original article:Accessing SharedPreferences data across different modules

Context

In modular HarmonyOS applications, it is common to encounter situations where different modules need to exchange data with each other. For instance, a process that records user activity in one module may need to share its results with another module responsible for analytics or progress visualization. This cross-module data sharing ensures consistency and seamless user experiences across the application. HarmonyOS provides developers with different tools for persisting and sharing data locally, such as Preferences and RDB (Relational Database). Among these, Preferences is particularly efficient when working with lightweight, key-value–based storage.

Description

The need to transfer data between modules often arises when modules are designed to operate independently but must still communicate. Preferences provides a convenient solution because it stores data in a local database using simple key-value pairs. This mechanism allows any module to store data and another to retrieve it, as long as they use the same table name and key conventions. A practical example is saving exercise duration data in the Exercise module and then displaying the accumulated results in the ProgressTracking module. By initializing the same preferences storage across modules, developers ensure consistency and accessibility.

Solution / Approach

Exercise Module (Data Saving):

A utility file (ExerciseUtils) initializes preferences storage with a specific table name (exercise_achievements).

Functions such as saveExerciseDuration calculate and store cumulative exercise durations by associating each exercise with a unique key (generated using createSafeKey).

The data is then flushed to ensure persistence.

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

const PREF_NAME = 'exercise_achievements';
let exercisePrefs: preferences.Preferences;

export function createSafeKey(exerciseName: string): string {
  return exerciseName
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '_')
    .replace(/[^a-z0-9_]/g, '');
}

export async function initExercisePrefs() {
  exercisePrefs = await preferences.getPreferences(globalThis.context, PREF_NAME);
}

export async function saveExerciseDuration(exerciseName: string, seconds: number) {

  const key = createSafeKey(exerciseName) + '_total_seconds';
  const current = Number(await exercisePrefs.get(key, 0));
  if (isNaN(current)) {
    console.error('Invalid stored value, resetting to 0');
    await exercisePrefs.put(key, seconds);
  } else {
    await exercisePrefs.put(key, current + seconds);
  }
  await exercisePrefs.flush();
}

export async function getTotalDuration(exerciseName: string): Promise<number> {
  return Number(await exercisePrefs.get(`${createSafeKey(exerciseName)}_total_seconds`, 0)) || 0;
}

Enter fullscreen mode Exit fullscreen mode

ProgressTracking Module (Data Retrieval):

The same preferences storage is initialized using the same table name.

The getTotalDuration function retrieves the stored values and makes them available for display in the UI.

Logs can also be printed for debugging to verify data consistency.

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

const PREF_NAME = 'exercise_achievements';
let exercisePrefs: preferences.Preferences;

export function createSafeKey(exerciseName: string): string {
  return exerciseName
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '_')
    .replace(/[^a-z0-9_]/g, '');
}


export async function getTotalDuration(exerciseName: string): Promise<number> {
  let result = Number(await exercisePrefs.get(`${createSafeKey(exerciseName)}_total_seconds`, 0))
  console.log('GetTotalDuration of '+exerciseName+' '+ result)
  return result;
}

Enter fullscreen mode Exit fullscreen mode

Key Point: Both modules must use the same table name and key structure to ensure data compatibility.

Key Takeaways

Preferences provides a lightweight and efficient way to share data between different modules.

Data is stored as key-value pairs, making it easy to retrieve and update across contexts.

Both the table name and the key must match between modules for proper data access.

Preferences is best suited for simple use cases such as storing cumulative counters, user settings, or lightweight logs. For more complex requirements, RDB might be a better option.

Additional Resources

https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-data-preferences#preferencesgetpreferences

https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-data-relationalstore

Written by Mehmet Algul

Top comments (0)