Beginner: Using Lightweight Preference Database in Harmony OS

RChancha
Huawei Developers
Published in
2 min readApr 19, 2021

--

Introduction

Harmony OS is a future-proof distributed operating system open to you as part of the initiatives for all-scenario strategy, adaptable to mobile office, fitness and health, social communication, and media entertainment, to name a few. Unlike a legacy operating system that runs on a standalone device, Harmony OS is built on a distributed architecture designed based on a set of system capabilities. It can run on a wide range of device forms, including smartphones, tablets, wearables, smart TVs and head units.

A lightweight preference database is used to store simple key-value pairs and provides simple method to read and write them.

In this article, we will create a simple login page for smartwatch to store user’s credential into lightweight preference database.

Requirements

  1. DevEco IDE

2. Smartwatch wearable simulator

Development

In order to save and load user’s credential, we need to obtain Preferences instance.

First time when user launches the app, user needs to register. User will enter username and password and click on register to store credential into preference database using put() method.

flushSync() is used to write preference in file synchronously. To write synchronously, we can use flush().

When user enters credential and click on login button, app will fetch or query the credential from lightweight preference using get() method and compare it with entered credential to validate.

If validation fails, error message will be shown

Code snippet of MainAblitySlice.java

ability_main.xml contains UI design

We will use background_ability_main.xml to define background color and shape of DependentLayout in ability_main.xml

background_text_field.xml is used to define shape and background color of textfield.

We have defined style for text field to display error in background_text_field_error.xml.

Tips and Tricks

1. flush() and flushsync() is used to write data asynchronously and synchronously respectively.

2. To obtain the targetContext and srcContext in the preceding code, call the getApplicationContext() method in the AbilitySlice or Ability class.

Conclusion

This article is focused on Harmony OS lightweight preferences database which is very helpful for storing light weight data. This article explains the integration of preferences into simple login app for smartwatch to store user’s credential.

If you found this tutorial helpful, then help us by SHARING this post. Thank You!

Reference

Harmony Official document

--

--