本地如何存储Array<T>

以下是我的自定义类:

export class GlobalContext{ 
  private constructor() { } 
  private static instance: GlobalContext; 
  private _objects = new Map<string, Object>(); 
 
  public static getContext():GlobalContext{ 
    if (!GlobalContext.instance) { 
      GlobalContext.instance = new GlobalContext(); 
    } 
    return GlobalContext.instance; 
  } 
 
  getObject(value: string): Object | undefined { 
    return this._objects.get(value); 
  } 
 
  setObject(key: string, objectClass: Object): void { 
    this._objects.set(key, objectClass); 
  } 
} 
export class WearUserList { 
  address?: string 
  areaId?: number 
  birthday?: string 
  cityId?: number 
  coreId: number = 0 
  country?: number 
  createTime?: string 
  defaultVersion?: number 
}

我在登录成功后通过以下方法存储了一个。

Array<WearUserList> 
GlobalContext.getContext().setObject('wearUserList',reslut.data?.wearUserList)

登录成功后在主页面通过以下方法可以获取到具体的数值。

@State private  mLocalRoleList:Array<WearUserList> = [] 
aboutToAppear(){ 
this.mLocalRoleList= GlobalContext.getContext().getObject('wearUserList') as Array<WearUserList>; 
}

​应用进入后台onBackground()应用进入前台onForeground()都正常,可以正常获取Array<WearUserList>

问题:当在首页面右滑后,系统调用了onWindowStageDestroy()onDestroy()当再次启动应用后,存储在本地的Array<WearUserList>数据丢失了,获致不到了。如保解决此问题?或者有没有更好的方法存储Array<WearUserList>,在用户操作退出登录时清空Array<WearUserList>​。

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

​提供一个demo供参考:

请注意下面是一个ts文件,不是ets文件,RDBUtilDemo这个工具类新建文件的时候请新建成ts文件​。

import { relationalStore, ValuesBucket } from '@kit.ArkData'; 
 
export class RDBUtilDemo{ 
  private static rdbStore:relationalStore.RdbStore 
  static setStore(store:relationalStore.RdbStore){ 
    RDBUtilDemo.rdbStore = store 
  } 
  static getStore():relationalStore.RdbStore{ 
    return RDBUtilDemo.rdbStore 
  } 
 
  static executeSql(sql:string):Promise<void>{ 
    return RDBUtilDemo.getStore().executeSql(sql) 
  } 
 
  static insert(tableName:string,data:any):Promise<number>{ 
    return RDBUtilDemo.getStore().insert(tableName,data) 
  } 
 
  static queryAll():Promise<Array<WearUserList>>{ 
    let predicates = new relationalStore.RdbPredicates("WearUserList") 
    return new Promise<Array<WearUserList>>((resolve,reject) =>{ 
      RDBUtilDemo.getStore().query(predicates).then((result) =>{ 
        let employees = new Array<WearUserList>() 
        while (result.goToNextRow()) { 
          let employee = new WearUserList( 
            result.getString(1), 
            result.getLong(0), 
            result.getString(2) === '1' ? true : false 
          ); 
          employees.push(employee) 
        } 
        resolve(employees) 
      }).catch((error:string) =>{ 
        reject(error) 
      }) 
    }) 
  } 
 
  static deleteById(id:number) { 
    let predicates = new relationalStore.RdbPredicates('WearUserList') 
    predicates.equalTo('AREAID',id) 
    return RDBUtilDemo.getStore().delete(predicates) 
  } 
 
  static updateById(id:number,data:any){ 
    let predicates = new relationalStore.RdbPredicates('WearUserList') 
    predicates.equalTo('AREAID',id) 
    return RDBUtilDemo.getStore().update(data,predicates) 
  } 
 
} 
export class WearUserList{ 
  address: string='' 
  areaId: number=0 
  status: boolean=false 
  constructor(address: string, areaId: number, status: boolean) { 
    this.address = address; 
    this.areaId = areaId; 
    this.status = status; 
  } 
 
}

这是一个普通的ets页面,可以看一下效果:

import { RDBUtilDemo, WearUserList } from '../util/RDBUtilDemo'; 
import { ValuesBucket } from '@kit.ArkData'; 
 
@Entry 
@Component 
struct RDBStoreDemo { 
  @State message: string = 'Hello World'; 
  @State em: WearUserList[] = []; 
 
  async aboutToAppear() { 
    let result = await RDBUtilDemo.queryAll() 
    console.log(JSON.stringify(result)) 
  } 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
        Button('创建数据表') 
          .onClick(() =>{ 
            const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS WearUserList (AREAID INTEGER PRIMARY KEY AUTOINCREMENT,ADDRESS TEXT, STATUS BOOLEAN)' 
            RDBUtilDemo.executeSql(SQL_CREATE_TABLE) 
              .then(() =>{ 
                openDialog('创建成功') 
              }).catch((e:string) =>{ 
              openDialog(e) 
            }) 
          }) 
 
        List(){ 
          ForEach(this.em,(item:WearUserList,index:number) =>{ 
            ListItem(){ 
              Row() { 
                Text(`${item.address}`).fontSize(20) 
                Text(`${item.areaId}`).fontSize(20) 
                Text(`${item.status}`).fontSize(20) 
              } 
            } 
          }) 
        } 
 
        Button('插入数据') 
          .onClick(() =>{ 
            const valueBucket1: ValuesBucket = { 
              'AREAID': 1, 
              'ADDRESS': 'TESTADDRESS1', 
              'STATUS': true 
            }; 
            RDBUtilDemo.insert('WearUserList', valueBucket1) 
              .then((updateNumber) =>{ 
                openDialog("已插入数据:"+updateNumber) 
              }).catch((error:string) =>{ 
              openDialog('error:'+JSON.stringify(error)) 
            }) 
          }) 
 
        Button('查询数据') 
          .onClick(() =>{ 
            RDBUtilDemo.queryAll().then((WearUserLists: Array<WearUserList>) =>{ 
              openDialog('WearUserLists:'+JSON.stringify(WearUserLists)) 
              for (let index = 0; index < WearUserLists.length; index++) { 
                this.em.push(WearUserLists[index]) 
              } 
            }).catch((err:string) =>{ 
              openDialog('err:'+err) 
              console.log('error:'+JSON.stringify(err)) 
            }) 
          }) 
 
        Button('删除') 
          .onClick(() =>{ 
            RDBUtilDemo.deleteById(1).then((updateName) =>{ 
              openDialog('删除数据:'+updateName.toString()) 
            }).catch((err:string) =>{ 
              openDialog(err) 
              console.log('error:'+JSON.stringify(err)) 
            }) 
          }) 
 
        Button('修改').onClick(() =>{ 
          const valueBucket1: ValuesBucket = { 
            'ADDRESS': 'TESTADDRESS22', 
            'STATUS': false 
          }; 
          RDBUtilDemo.updateById(1,valueBucket1) 
            .then((updateName) =>{ 
              openDialog('已更新数据'+updateName) 
            }).catch((err:string) =>{ 
            openDialog(err) 
            console.log('error:'+JSON.stringify(err)) 
          }) 
        }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
 
function openDialog(text:string){ 
  AlertDialog.show({ 
    title:'title', 
    message:text, 
    autoCancel:true, 
    alignment:DialogAlignment.Bottom, 
    offset:{dx:0,dy:-20} 
  }) 
}

还有最后一步,需要再EntryAbility的。

onWindowStageCreate方法里边去初始化数据库: 
const STORE_CONFIG: relationalStore.StoreConfig={ 
  name:'rdb.db', 
  securityLevel: 
  relationalStore.SecurityLevel.S1 
} 
relationalStore.getRdbStore(this.context,STORE_CONFIG,(err,store) =>{ 
  if (err) { 
    console.info("获取失败") 
    return 
  } 
  console.info("获取成功") 
  RDBUtilDemo.setStore(store) 
})
分享
微博
QQ
微信
回复
7天前
相关问题
HarmonyOS array 如何转 arraylist ?
70浏览 • 1回复 待解决
hb build -T单独编译,应如何编译
3497浏览 • 1回复 待解决
Uint8Array如何转成ArrayBuffer
1378浏览 • 1回复 待解决
如何全局存储WebController
714浏览 • 1回复 待解决
Array快速的转成ArrayList
873浏览 • 1回复 待解决
Uint8Array 如何直接转为String or Json
2448浏览 • 1回复 待解决
如何将Uint8Array转ArrayBuffer?
310浏览 • 1回复 待解决
本地service与本地应用间如何传递消息
5432浏览 • 1回复 待解决
数据存储方案如何选择
219浏览 • 1回复 待解决
使用imageSource如何存储图片
318浏览 • 1回复 待解决