Essential HarmonyOS Utilities for Data Persistence and Media Selection

Data Persistence Management

To handle lightweight data storage efficiently, we can encapsulate the dataPreferences API into a reusable utility class. This abstraction simplifies the process of reading and writing key-value pairs, such as user settings or session tokens.

import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';

const STORAGE_NAME = 'AppLocalStore';

export class AppStorageManager {
  private store: preferences.Preferences | null = null;

  constructor(context: common.UIAbilityContext) {
    const options: preferences.Options = { name: STORAGE_NAME };
    try {
      this.store = preferences.getPreferencesSync(context, options);
    } catch (err) {
      const error = err as BusinessError;
      console.error(`Storage init failed: ${error.code}, ${error.message}`);
    }
  }

  /**
   * Persists a string value to the local storage.
   */
  public storeValue(key: string, value: string): void {
    if (!this.store) return;
    try {
      this.store.putSync(key, value);
      this.store.flush();
    } catch (err) {
      const error = err as BusinessError;
      console.error(`Write failed: ${error.code}, ${error.message}`);
    }
  }

  /**
   * Retrieves a string value from the local storage.
   */
  public retrieveValue(key: string): string | null {
    if (!this.store) return null;
    try {
      return this.store.getSync(key, null) as string;
    } catch (err) {
      const error = err as BusinessError;
      console.error(`Read failed: ${error.code}, ${error.message}`);
      return null;
    }
  }
}

Implementation Example

The following component demonstrates how to utilize the storage manager to save and retrieve text input dynamically.

import common from '@ohos.app.ability.common';
import { AppStorageManager } from './AppStorageManager';

@Entry
@Component
struct StorageDemoPage {
  @State displayText: string = 'No Data';
  private context = getContext(this) as common.UIAbilityContext;
  private storage = new AppStorageManager(this.context);

  aboutToAppear(): void {
    const cached = this.storage.retrieveValue('user_note');
    if (cached) {
      this.displayText = cached;
    }
  }

  build() {
    Row() {
      Column({ space: 20 }) {
        Text(this.displayText).fontSize(24)

        Button('Save Current Time').onClick(() => {
          const timeStr = new Date().toISOString();
          this.storage.storeValue('user_note', timeStr);
          this.displayText = timeStr;
        })

        Button('Clear Data').onClick(() => {
          this.storage.storeValue('user_note', '');
          this.displayText = 'Cleared';
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

Image Selection Helper

Interacting with the system photo gallery is a common requirement. The following utility leverages the PhotoViewPicker to provide a clean, promise-based interface for selecting images, avoiding callback nesting complexity.

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

/**
 * Opens the system gallery to select a single image.
 * @returns The URI of the selected image.
 */
export async function selectImageFromGallery(): Promise<string> {
  try {
    const selectOptions = new picker.PhotoSelectOptions();
    selectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    selectOptions.maxSelectNumber = 1;

    const photoPicker = new picker.PhotoViewPicker();
    const result = await photoPicker.select(selectOptions);
    
    if (result.photoUris && result.photoUris.length > 0) {
      return result.photoUris[0];
    }
    return '';
  } catch (err) {
    const error = err as BusinessError;
    console.error(`Image selection failed: ${error.code}, ${error.message}`);
    return '';
  }
}

Integration Example

This component uses the helper function to update an Image component with the user's selection.

import { selectImageFromGallery } from './ImageSelector';

@Entry
@Component
struct GalleryDemoPage {
  @State selectedImageUri: string = '';

  build() {
    Column() {
      Button('Open Gallery')
        .margin({ top: 50, bottom: 20 })
        .onClick(async () => {
          this.selectedImageUri = await selectImageFromGallery();
        })

      Image(this.selectedImageUri)
        .width(200)
        .height(200)
        .objectFit(ImageFit.Cover)
        .border({ width: 1, color: Color.Gray })
        .alt($r('app.media.icon'))
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Center)
  }
}

Tags: HarmonyOS ArkTS data persistence PhotoPicker Mobile Development

Posted on Mon, 18 May 2026 12:29:23 +0000 by PastorHank