什么是輕量級數(shù)據(jù)庫
輕量級數(shù)據(jù)庫是一種以鍵值對形式保存數(shù)據(jù)的存儲(chǔ)方式.每條數(shù)據(jù)都需要指定一個(gè)唯一鍵名來進(jìn)行區(qū)分.可以存儲(chǔ)布爾型师抄、整型琅捏、字符串等基礎(chǔ)數(shù)據(jù)類型.其特點(diǎn)為簡單驱敲、輕量,適合保存少量簡單類型的數(shù)據(jù),不適合保存大批量或復(fù)雜類型的數(shù)據(jù).
基礎(chǔ)樣例
1. 寫入和讀取數(shù)據(jù)
- java代碼
public class MainAbilitySlice extends AbilitySlice {
private Preferences preferences;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
String filename = "pdb";
preferences = databaseHelper.getPreferences(filename);
findComponentById(ResourceTable.Id_writeText).setClickedListener(component -> write());
findComponentById(ResourceTable.Id_readText).setClickedListener(component -> read());
findComponentById(ResourceTable.Id_modifyText).setClickedListener(component -> modify());
findComponentById(ResourceTable.Id_delText).setClickedListener(component -> del());
}
private void write() {
preferences.putString("name", "花生皮編程");
preferences.flush();
}
private void read() {
String name = preferences.getString("name", "數(shù)據(jù)不存在");
new ToastDialog(getContext()).setText(name).show();
}
private void modify() {
preferences.putString("name", "花生皮編程2");
preferences.flush();
}
private void del() {
preferences.delete("name");
}
}
- 對應(yīng)頁面布局文件:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$+id:writeText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="寫數(shù)據(jù)"
ohos:text_size="20fp"/>
<Text
ohos:id="$+id:readText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="讀數(shù)據(jù)"
ohos:text_size="20fp"/>
<Text
ohos:id="$+id:modifyText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="修改數(shù)據(jù)"
ohos:text_size="20fp"/>
<Text
ohos:id="$+id:delText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="刪除數(shù)據(jù)"
ohos:text_size="20fp"/>
</DirectionalLayout>
常用函數(shù)說明
函數(shù)名 | 用途 |
---|---|
putString | 存儲(chǔ)字符串類型數(shù)據(jù) |
putInt | 存儲(chǔ)整型數(shù)據(jù) |
putLong | 存儲(chǔ)長整型數(shù)據(jù) |
putFloat | 存儲(chǔ)浮點(diǎn)型數(shù)據(jù) |
putBoolean | 存儲(chǔ)布爾值,true或false |
putStringSet | 存儲(chǔ)字符串集合 |
delete | 刪除指定鍵名對應(yīng)的數(shù)據(jù)記錄 |
clear | 清空所有存儲(chǔ)的數(shù)據(jù) |
apply | 修改數(shù)據(jù)后,提交保存到文件中 |
getString | 以字符串類型讀取出數(shù)據(jù) |
getInt | 以整型讀取出數(shù)據(jù) |
getLong | 以長整型讀取出數(shù)據(jù) |
getFloat | 以浮點(diǎn)型讀取出數(shù)據(jù) |
getBoolean | 以布爾值讀取出數(shù)據(jù) |
完整源代碼
https://gitee.com/hspbc/harmonyos_demos/tree/master/preferenceDemo
關(guān)于我
廈門大學(xué)計(jì)算機(jī)專業(yè) | 前華為工程師
分享編程技術(shù)热凹,沒啥深度,但看得懂排吴,適合初學(xué)者秆乳。
Java | 安卓 | 前端 | 小程序 | 鴻蒙