HarmonyOS 缓存demo验证

HarmonyOS
4h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

参考代码:

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

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

// 对象类
export class ImageModel {
  constructor(id: string, tokenInfo: string, imgInfo: string, urlInfo: string) {
    this.id = id
    this.token = tokenInfo
    this.img = imgInfo
    this.url = urlInfo
  }
  id?: string = '';
  token: string = '';
  img: string = '';
  url: string = ''
}

// 首选项工具类
class PreferenceModel {

  // 初始化
  async getPreferencesFromStorage() {
    try {
      preference = await preferences.getPreferences(context,'ImageUrlData.db');
    } catch (err) {
      console.error('[PreferenceModel]', `Failed to get preferences, Cause: ${err}`);
    }
  }

  // 删除首选项
  async deletePreferences() {
    try {
      await preferences.deletePreferences(context, 'ImageUrlData.db');
    } catch(err) {
      console.error('[PreferenceModel]', `Failed to delete preferences, Cause: ${err}`);
    };
    preference = preferenceTemp;
    this.showToastMessage('删除数据库成功');
  }

  // 插入值
  async putPreference(Image:string, ImageInfo: ImageModel) {
    if (!preference) {
      await this.getPreferencesFromStorage();
    }
    try {
      await preference.put(Image, JSON.stringify(ImageInfo));
    } catch (err) {
      console.error('[PreferenceModel]', `Failed to put value, Cause: ${err}`);
    }
    await preference.flush();
  }

  // 获取值
  async getPreference(Image: string) {
    let ImageInfo = '';
    if (!preference) {
      await this.getPreferencesFromStorage();
    }
    try {
      ImageInfo = (await preference.get(Image, '')).toString();
    } catch (err) {
      console.error('[PreferenceModel]', `Failed to get value, Cause: ${err}`);
    }
    if (ImageInfo === '') {
      this.showToastMessage('数据为空,请先写入数据');
      return;
    }
    this.showToastMessage('写入数据成功');
    return JSON.parse(ImageInfo);
  }

  async getImageData(Image: string) {
    return await this.getPreference(Image);
  }

  // 写入数据
  writeData(Image:string, ImageInfo: ImageModel) {
    this.putPreference(Image, ImageInfo);
    this.showToastMessage('写入数据成功');
  }

  showToastMessage(message: string) {
    promptAction.showToast({
      message: message,
      duration: 3000
    });
  };
}

/**
 * 操作首选项
 */
export class LocalDataManager {
  preferenceModel = new PreferenceModel()
  private static localDataManager: LocalDataManager;

  private constructor() {
    this.preferenceModel.getPreferencesFromStorage()
  }

  static instance() {
    if (!LocalDataManager.localDataManager) {
      LocalDataManager.localDataManager = new LocalDataManager();
    }
    return LocalDataManager.localDataManager;
  }

  async queryImageInfo(Image:string) {
    return await this.preferenceModel.getImageData(Image)
  }

  insertImageInfo(Image:string, ImageInfo: ImageModel) {
    this.preferenceModel.writeData(Image, ImageInfo)
    return Image.length
  }

  updateImageInfo(Image:string, ImageInfo: ImageModel) {
    this.preferenceModel.writeData(Image, ImageInfo)
    return Image.length
  }

  deleteImageInfo() {
    this.preferenceModel.deletePreferences()
  }
}

// 使用首选项做缓存
@Entry
@Component
struct NeiMengGuNongJi {
  private localDataManager: LocalDataManager = LocalDataManager.instance();
  @State token_Info: string = ''
  private img: string = 'image00'
  private url: string = 'url000'
  @State num: number = 0
  @State keyInfo: string = ''
  @State imageData: ImageModel = new ImageModel('','','','')

  build() {
    Column() {
      Button('点击存入数据库')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .onClick(()=> {
          for (let i = 1; i <= 10; i++) {
            let tokenInfo  = "token00"+i
            let image = this.img+i
            let urlInfo = this.url+i
            let ImageInfo = new ImageModel("", tokenInfo, image, urlInfo);
            this.localDataManager.insertImageInfo(image, ImageInfo)
          }
        })
      TextInput({placeholder:'输入key值:例如image001'})
        .type(InputType.Normal)
        .onChange((key: string) => {
          this.keyInfo = key
        })
      Button('通过key值:'+this.keyInfo+", 获取value值")
        .fontSize(18)
        .fontWeight(FontWeight.Bold)
        .onClick(async()=> {
          if(this.keyInfo !== ''){
            this.imageData = await this.localDataManager.queryImageInfo(this.keyInfo) as ImageModel
            console.info("imageData="+JSON.stringify(this.imageData))
          }
        })
      Text("key: "+this.keyInfo+", value: " + (this.imageData.token === ''? '' : JSON.stringify(this.imageData))).fontSize(40)
    }
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
2h前
相关问题
HarmonyOS app安装验证的问题?
134浏览 • 0回复 待解决
HarmonyOS音频缓存问题
513浏览 • 1回复 待解决
HarmonyOS 清除Web缓存
747浏览 • 0回复 待解决
HarmonyOS 清除缓存功能
288浏览 • 1回复 待解决
HarmonyOS 图片缓存机制
357浏览 • 1回复 待解决
HarmonyOS 图片缓存策略
415浏览 • 1回复 待解决
HarmonyOS 本地缓存问题?
203浏览 • 0回复 待解决
HarmonyOS 本地缓存问题
135浏览 • 1回复 待解决
HarmonyOS 像素单位的转化和验证
5浏览 • 0回复 待解决
实现验证码登录之前的滑动验证实现
148浏览 • 1回复 待解决
HarmonyOS web清除缓存问题
204浏览 • 1回复 待解决
HarmonyOS 如何清理 web 缓存
36浏览 • 1回复 待解决
HarmonyOS应用更新demo
323浏览 • 1回复 待解决
HarmonyOS 资讯类demo
251浏览 • 1回复 待解决
HarmonyOS 加解密 demo
482浏览 • 1回复 待解决
HarmonyOS viewModal demo问题
394浏览 • 1回复 待解决
HarmonyOS 全局弹窗demo
0浏览 • 0回复 待解决
HarmonyOS 帧动画demo
5浏览 • 1回复 待解决
HarmonyOS如何清除应用缓存
129浏览 • 0回复 待解决
HarmonyOS ArkWeb如何清理缓存
28浏览 • 1回复 待解决