HarmonyOs~用户首选项

看了官网的例子  对于我这种小白来说太过于繁琐  下边 咱们就简单来实现下用户首选项吧~

首先看下目录结构  用到了三个文件

上代码:

首先是B2_builder.ets

import PreferenceModel from '../model/PreferenceModel';
import Fruit from '../viewModel/Fruit';
@Entry
@Component
struct B2_builder {
  @State fruit: Fruit = new Fruit();
  build() {
    Column(){
      Text('用户首选项练习')
        .fontSize(30)
        .margin({top:40,bottom:40})
        .fontWeight(FontWeight.Bolder)

      Row(){
        Text('水果')
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .margin({right:40})
        TextInput({
          placeholder:'apple',
          text:this.fruit.fruitName

        }).onChange((_e:string)=>{
          console.log(_e,'ee')
          this.fruit.fruitName=_e
        })
          .width(200)
      }

      .margin({bottom:20})
      Row(){
        Text('数量 ')
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .margin({right:40})
        TextInput({
          placeholder:'20',
            text:this.fruit.fruitNum
        }).onChange((_e:string)=>{
          console.log(_e,'ee')
          this.fruit.fruitNum=_e
        })
          .width(200)
      }

      Button('写入用户首选项').onClick((event: ClickEvent) => {
        console.log( this.fruit.fruitName,' this.fruit.fruitName')
        console.log( this.fruit.fruitNum,' this.fruit.fruitNum')
        PreferenceModel.writeData(this.fruit);


      })
        .margin({top:40,bottom:40})
      Button('读取用户首选项').onClick((event: ClickEvent) => {
        PreferenceModel.getFruitData().then((resultData: Fruit) => {
          if (resultData) {
            console.log(resultData.fruitNum,'resultData')

            this.fruit = resultData;

          }
        });

      })
        .margin({bottom:40})
      Button('删除用户首选项').onClick((event: ClickEvent) => {

        PreferenceModel.deletePreferences();
        // After a database file is deleted, the corresponding data is left blank.
        this.fruit.fruitName = '';
        this.fruit.fruitNum = ''
      })
        .margin({bottom:40})



    }
    .height('100%')
    .width('100%')
  }
}

Fruit.ets


export default class Fruit {
 
    fruitName: string = '';

 
    fruitNum: string = '';
}

PreferenceModel.ets

/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { promptAction } from '@kit.ArkUI';
import { preferences } from '@kit.ArkData';
import Fruit from '../viewModel/Fruit';

class CommonConstant {
  DURATION: number = 3000;

  FRUIT_FLAG: number = 0;

  NUMBER_FLAG: number = 1;

  TAG = '[PreferenceModel]';

  KEY_NAME = 'fruit';

  PREFERENCES_NAME = 'fruit.db';
}
let CommonConstants=new CommonConstant()



let context = getContext(this);
let preference: preferences.Preferences;
let preferenceTemp: preferences.Preferences;

/**
 * Preference model.
 *
 * @param fruitData Fruit data.
 */
class PreferenceModel {
  private fruitData: Fruit = new Fruit();

  /**
   * Read the specified Preferences persistence file and load the data into the Preferences instance.
   */
  async getPreferencesFromStorage() {
    try {
      preference = await preferences.getPreferences(context, CommonConstants.PREFERENCES_NAME);
    } catch (err) {

      console.error(CommonConstants.TAG, `Failed to get preferences, Cause: ${err}`)
    }
  }

  /**
   * Deletes the specified Preferences persistence file from memory and removes the Preferences instance.
   */
  async deletePreferences() {
    try {
      await preferences.deletePreferences(context, CommonConstants.PREFERENCES_NAME);
    } catch(err) {

      console.error(CommonConstants.TAG, `Failed to delete preferences, Cause: ${err}`)
    };
    preference = preferenceTemp;
    this.showToastMessage('Delete database successfully!');
  }

  /**
   * Save the data to the Preferences.
   *
   * @param fruit Fruit data.
   */
  async putPreference(fruit: Fruit) {

    if (!preference) {
      await this.getPreferencesFromStorage();
    }
    // The fruit name and fruit quantity data entered by the user are saved to the cached Preference instance.
    try {
      await preference.put(CommonConstants.KEY_NAME, JSON.stringify(fruit));
    } catch (err) {

      console.error(CommonConstants.TAG, `Failed to put value, Cause: ${err}`)
    }
    // Store the Preference instance in the preference persistence file
    await preference.flush();
  }

  /**
   * Get preference data.
   */
  async getPreference() {
    let fruit = '';
    if (!preference) {
      await this.getPreferencesFromStorage();
    }
    try {
      // fruit = <string> await preference.get(CommonConstants.KEY_NAME, '');
      fruit = (await preference.get(CommonConstants.KEY_NAME, '')).toString();
    } catch (err) {
      console.error(CommonConstants.TAG, `Failed to get value, Cause: ${err}`)
    }
    // If the data is empty, a message is displayed indicating that data needs to be written.
    if (fruit === '') {
      this.showToastMessage('是空的先写入数据');
      return;
    }
    this.showToastMessage('读取成功');
    return JSON.parse(fruit);
  }

  /**
   * Process the data obtained from the database.
   * 读取用户首选项
   */
  async getFruitData() {
    this.fruitData = await this.getPreference();
    return this.fruitData;
  }

  /**
   * Verifies that the data entered is not empty.
   *
   * @param fruit Fruit data.
   */
  checkFruitData(fruit: Fruit) {
    if (fruit.fruitName === '' || fruit.fruitNum === '') {
      this.showToastMessage('Fruit name or fruit num is empty, please write data first!');
      return true;
    }
    return false;
  }

  /**
   * write data.
   * 写入文件
   * @param fruit  Fruit data.
   */
  writeData(fruit: Fruit) {

    let isDataNull = this.checkFruitData(fruit);
    if (isDataNull) {
      return;
    }
    // The data is inserted into the preferences database if it is not empty.
    this.putPreference(fruit);
    this.showToastMessage('写入成功');
  }

  /**
   * Popup window prompt message.
   *
   * @param message Prompt message.
   */
  showToastMessage(message: string) {
    promptAction.showToast({
      message: message,
      duration: CommonConstants.DURATION
    });
  };
}

export default new PreferenceModel();

B2_builder.ets是负责ui界面的  PreferenceModel.ets是负责写入读取以及删除逻辑的   然后我们看下效果图是这样的

点击不同的按钮执行不同的操作 

代码没有进行封装 是非常容易看懂的  慢慢摸索吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值