前言:
各位同學(xué)大家好 有段時(shí)間沒(méi)有給大家更新文章了 (因?yàn)橹耙恢痹诿?gòu)房貸款的事情 所以停更 實(shí)在不好意思)今天要講的是鴻蒙里面輕量級(jí)數(shù)據(jù) DatabaseHelper基本用法一些技巧 那么廢話不多說(shuō)我們正式開(kāi)始
效果圖
1介紹
輕量級(jí)偏好數(shù)據(jù)庫(kù)是輕量級(jí)存儲(chǔ)彤守,主要用于保存應(yīng)用的一些常用配置。它是使用鍵值對(duì)的形式來(lái)存儲(chǔ)數(shù)據(jù)的昔脯,保存數(shù)據(jù)時(shí)致份,需要給這條數(shù)據(jù)提供一個(gè)鍵哟冬,讀取數(shù)據(jù)時(shí)再通過(guò)這個(gè)鍵把對(duì)應(yīng)的值取出來(lái)。
說(shuō)明
通過(guò)觀察源碼 輕量級(jí)偏好數(shù)據(jù)庫(kù)值的存儲(chǔ)數(shù)據(jù)類型包括整型、長(zhǎng)整型际插、浮點(diǎn)型哼审、布爾型谐腰、字符串型孕豹、字符串型Set集合。數(shù)據(jù)存儲(chǔ)在本地文件中怔蚌,同時(shí)也加載在內(nèi)存中巩步,不適合需要存儲(chǔ)大量數(shù)據(jù)和頻繁改變數(shù)據(jù)的場(chǎng)景,建議存儲(chǔ)的數(shù)據(jù)不超過(guò)一萬(wàn)條桦踊。
2 創(chuàng)建數(shù)據(jù)庫(kù)
創(chuàng)建數(shù)據(jù)庫(kù)使用數(shù)據(jù)庫(kù)操作的輔助類DatabaseHelper椅野,通過(guò)DatabaseHelper的getPreferences(String name)方法可以獲取到對(duì)應(yīng)文件名的Preferences實(shí)例,再通過(guò)Preferences提供的方法進(jìn)行數(shù)據(jù)庫(kù)的相關(guān)操作籍胯。
DatabaseHelper的構(gòu)造需要傳入context竟闪,Ability和AbilitySlice都實(shí)現(xiàn)了ohos.app.Context接口。因此可以從應(yīng)用中的Ability或AbilitySlice調(diào)用getContext()方法來(lái)獲得context杖狼。
Preferences的數(shù)據(jù)存儲(chǔ)在文件中炼蛤,因此需要指定存儲(chǔ)的文件名,其取值不能為空蝶涩,也不能包含路徑理朋,默認(rèn)存儲(chǔ)目錄可以通過(guò)Context.getPreferencesDir()獲取。
DatabaseHelper databaseHelper = new DatabaseHelper(context);
String filename = "pdb";
Preferences preferences = databaseHelper.getPreferences(filename);
3 寫(xiě)入數(shù)據(jù)
我們這邊在拿到輸入框輸入的數(shù)字和文字 然后在按鈕點(diǎn)擊的是調(diào)用preferences 里面put 方法將數(shù)據(jù)存儲(chǔ)起來(lái)
通過(guò)Preferences的putString(String var1, String var2)和putInt(String var1, int var2)方法可以將數(shù)據(jù)寫(xiě)入Preferences實(shí)例绿聘,通過(guò)flush()或者flushSync()將Preferences實(shí)例持久化嗽上。
flush()會(huì)立即更改內(nèi)存中的Preferences對(duì)象,但會(huì)將更新異步寫(xiě)入磁盤(pán)熄攘。flushSync()更改內(nèi)存中的數(shù)據(jù)的同時(shí)會(huì)將數(shù)據(jù)同步寫(xiě)入磁盤(pán)兽愤。由于flushSync()是同步的,建議不要從主線程調(diào)用它挪圾,以避免界面卡頓浅萧。
/***
* 寫(xiě)入數(shù)據(jù)
*
*
*/
private void btnWrite() {
btnWrite.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String fruit = textFiledFruit.getText();
try {
int number = Integer.parseInt(textFiledNumber.getText());
preferences.putInt("number",number);
preferences.putString("fruit",fruit);
preferences.flush();
new ToastDialog(context).setText("Write to DB file success").show();
} catch (NumberFormatException e) {
new ToastDialog(context).setText("Please input number in Number row").show();
}
}
});
}
4 讀取數(shù)據(jù)
我們通過(guò)調(diào)用 preferences 中的get方法來(lái)獲取存儲(chǔ)在DataBase庫(kù)中的數(shù)據(jù)
通過(guò)Preferences的getString(String var1, String var2)和getInt(String var1, int var2)方法傳入鍵來(lái)獲取對(duì)應(yīng)的值;如果鍵不存在哲思,則返回默認(rèn)值洼畅。
例如獲取上述fruit和number鍵的值,如果fruit和number鍵不存在棚赔,則會(huì)分別返回""和0值土思。通過(guò)默認(rèn)值的設(shè)置,來(lái)避免程序出現(xiàn)異常忆嗜。
/***
*
* 讀取數(shù)據(jù)
*
*/
private void btnRead() {
btnRead.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String string = String.format(Locale.ENGLISH,"Fruit: %s,Number: %d",
preferences.getString("fruit", ""),preferences.getInt("number", 0));
new ToastDialog(context).setText(string).show();
}
});
}
5 刪除數(shù)據(jù)庫(kù)
通過(guò)DatabaseHelper的deletePreferences(String name)方法刪除指定文件己儒。
刪除指定文件時(shí),應(yīng)用不允許再使用該實(shí)例進(jìn)行數(shù)據(jù)操作捆毫,否則會(huì)出現(xiàn)數(shù)據(jù)一致性問(wèn)題闪湾。以刪除上述名稱為"pdb"的文件為例。
/**
* 刪除數(shù)據(jù)
*
*/
private void btnDelete() {
btnDelete.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
if (databaseHelper.deletePreferences(filename)) {
preferences.clear();
new ToastDialog(context).setText("Delete DB file success").show();
} else {
new ToastDialog(context).setText("Delete DB file failed").show();
}
}
});
}
說(shuō)明
輕量級(jí)偏好數(shù)據(jù)庫(kù)支持?jǐn)?shù)據(jù)庫(kù)文件的創(chuàng)建绩卤、移動(dòng)途样,數(shù)據(jù)的查詢江醇、插入、刪除何暇,以及支持注冊(cè)觀察者來(lái)觀察數(shù)據(jù)是否發(fā)生變化陶夜。詳細(xì)信息可參考輕量級(jí)偏好數(shù)據(jù)庫(kù)。
6 緩存list 數(shù)據(jù)
通過(guò)觀察源碼我們發(fā)現(xiàn) DatabaseHelper輕量級(jí)數(shù)據(jù)庫(kù)是沒(méi)有辦法直接存儲(chǔ)我們的list集合 這個(gè)是我們?cè)撛趺崔k 我們通過(guò)將List轉(zhuǎn)成json字符串 然后將json存起來(lái) 我們?cè)谌≈档哪玫絡(luò)son字符串在還原成list就可以實(shí)現(xiàn)了 為了方便演示我們這邊寫(xiě)了一個(gè)工具類
-
1存儲(chǔ)list的方法
/**
* 4.存儲(chǔ)list
*/
public static void putSelectBean(Context context, List<UserBean> phoneList, String key) {
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
Gson gson = new Gson();
String json = gson.toJson(phoneList);
preferences.putString(key, json);
preferences.flush();
}
我們寫(xiě)了一個(gè) putSelectBean 來(lái)存儲(chǔ)我們的list
-
2讀取 list的方法
/**
* 讀取list
*/
public static List<UserBean> getSelectBean(Context context, String key) {
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
Gson gson = new Gson();
String json = preferences.getString(key, null);
Type type = new TypeToken<List<UserBean>>() {
}.getType();
List<UserBean> arrayList = gson.fromJson(json, type);
return arrayList;
}
-
3具體存儲(chǔ)list調(diào)用
/***
*
* 緩存list 集合類型數(shù)據(jù)
*
*/
private void btnSavelist() {
btnsavelist.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
UserBean userBean=new UserBean();
userBean.setUsername("test");
userBean.setPassword("123456");
List<UserBean> datalist=new ArrayList<>();
datalist.add(userBean);
DataBaseUtil.putSelectBean(context,datalist,"datalist");
new ToastDialog(context).setText("寫(xiě)入成功").show();
}
});
}
-
4讀取list類型數(shù)據(jù)調(diào)用
/***
*
* 讀取list 集合類型數(shù)據(jù)
*
*/
private void btnReadList(){
btn_read_list.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
List<UserBean>getData= (List<UserBean>) DataBaseUtil.getSelectBean(context,"datalist");
UserBean userBean= getData.get(0);
new ToastDialog(context).setText(userBean.getUsername()+userBean.getPassword()).show();
}
});
}
7 DatabaseHelper存儲(chǔ)的簡(jiǎn)單封裝
我們?cè)谑褂?DatabaseHelper的時(shí)候每次都要
DatabaseHelper databaseHelper = new DatabaseHelper(context);
String filename = "pdb";
Preferences preferences = databaseHelper.getPreferences(filename);
然后調(diào)用 preferences 的put方法存儲(chǔ) 和get方法讀取 代碼顯得不是很簡(jiǎn)潔 我們做一個(gè)簡(jiǎn)單的工具類封裝即可
-
1存儲(chǔ)方法的封裝
private static String filename = "pdb";
private static Preferences preferences;
private static DatabaseHelper databaseHelper;
/**
* 保存數(shù)據(jù)的方法裆站,我們需要拿到保存數(shù)據(jù)的具體類型条辟,然后根據(jù)類型調(diào)用不同的保存方法
*
* @param context
* @param key
* @param object
* @param :DataBaseUtil.setParam(this, "key", "value");
* key -- userid / accountId obj==
*/
public static void setParam(Context context, String key, Object object) {
String type = "String";
if (object != null) {
type = object.getClass().getSimpleName();
}
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
if ("String".equals(type)) {
preferences.putString(key, (String) object);
} else if ("Integer".equals(type) || "int".equals(type)) {
preferences.putInt(key, (Integer) object);
} else if ("Boolean".equals(type) || "boolean".equals(type)) {
preferences.putBoolean(key, (Boolean) object);
} else if ("Float".equals(type) || "float".equals(type)) {
preferences.putFloat(key, (Float) object);
} else if ("Long".equals(type) || "long".equals(type)) {
preferences.putLong(key, (Long) object);
}
preferences.flush();
}
-
2 讀取方法的簡(jiǎn)單封裝
/**
* 得到保存數(shù)據(jù)的方法,我們根據(jù)默認(rèn)值得到保存的數(shù)據(jù)的具體類型宏胯,然后調(diào)用相對(duì)于的方法獲取值
*
* @param context
* @param key 關(guān)鍵字
* @param defaultObject 若取回空值則返回此默認(rèn)值
* @param :DataBaseUtil.getParam(Activity.this, "key", "defaultValue");
* @return
*/
public static Object getParam(Context context, String key, Object defaultObject) {
String type = "String";
if (defaultObject != null) {
type = defaultObject.getClass().getSimpleName();
}
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
if ("String".equals(type)) {
return preferences.getString(key, (String) defaultObject);
} else if ("Integer".equals(type) || "int".equals(type)) {
return preferences.getInt(key, (Integer) defaultObject);
} else if ("Boolean".equals(type) || "boolean".equals(type)) {
return preferences.getBoolean(key, (Boolean) defaultObject);
} else if ("Float".equals(type) || "float".equals(type)) {
return preferences.getFloat(key, (Float) defaultObject);
} else if ("Long".equals(type) || "long".equals(type)) {
return preferences.getLong(key, (Long) defaultObject);
}
return null;
}
-
具體調(diào)用
/***
*
* 調(diào)用工具類方法存儲(chǔ)
*/
private void btnSavetoutils() {
btnsave_toutils.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String fruit = textFiledFruit.getText();
try {
int number = Integer.parseInt(textFiledNumber.getText());
DataBaseUtil.setParam(context,"number",number);
DataBaseUtil.setParam(context,"fruit",fruit);
new ToastDialog(context).setText("寫(xiě)入成功").show();
} catch (NumberFormatException e) {
new ToastDialog(context).setText("Please input number in Number row").show();
}
}
});
}
完整示例
-
1 xml布局代碼
<?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:orientation="vertical">
<Text
ohos:id="$+id:text_fruit_tag"
ohos:height="35vp"
ohos:width="match_parent"
ohos:background_element="$graphic:text_element"
ohos:layout_alignment="left"
ohos:text="Fruit"
ohos:text_size="85"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
ohos:top_margin="25vp"
ohos:text_color="#000000"
/>
<TextField
ohos:id="$+id:text_fruit"
ohos:height="35vp"
ohos:width="match_parent"
ohos:background_element="$graphic:text_element"
ohos:layout_alignment="left"
ohos:text="Orange"
ohos:text_size="50"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
ohos:text_color="#000000"
ohos:top_margin="25vp"
ohos:basement="#000099"
/>
<Text
ohos:id="$+id:text_number_tag"
ohos:height="35vp"
ohos:width="match_parent"
ohos:background_element="$graphic:text_element"
ohos:layout_alignment="left"
ohos:text="Number"
ohos:text_size="85"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
ohos:text_color="#000000"
ohos:top_margin="25vp"
/>
<TextField
ohos:id="$+id:text_number"
ohos:height="35vp"
ohos:width="match_parent"
ohos:background_element="$graphic:text_element"
ohos:layout_alignment="left"
ohos:text="25"
ohos:text_size="50"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
ohos:text_color="#000000"
ohos:top_margin="25vp"
ohos:basement="#000099"
/>
<Button
ohos:id="$+id:write_btn"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="寫(xiě)入緩存"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
<Button
ohos:id="$+id:read_btn"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="讀取緩存"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
<Button
ohos:id="$+id:delete_btn"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="刪除緩存"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
<Button
ohos:id="$+id:save_list"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="存儲(chǔ)list"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
<Button
ohos:id="$+id:read_list"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="讀取list"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
<Button
ohos:id="$+id:save_toutils"
ohos:width="match_parent"
ohos:height="35vp"
ohos:text="工具類緩存調(diào)用"
ohos:background_element="$graphic:button_element"
ohos:text_size="50"
ohos:text_color="#FFFFFF"
ohos:top_margin="25vp"
ohos:right_margin="20vp"
ohos:left_margin="20vp"
/>
</DirectionalLayout>
-
2 布局效果圖
-
3 java邏輯代碼
package com.example.datademo.slice;
import com.example.datademo.ResourceTable;
import com.example.datademo.bean.UserBean;
import com.example.datademo.utils.DataBaseUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainAbilitySlice extends AbilitySlice {
private Context context;
private Button btnWrite;
private Button btnRead;
private Button btnDelete;
private TextField textFiledFruit;
private TextField textFiledNumber;
private String filename;
private Preferences preferences;
private DatabaseHelper databaseHelper;
private Button btnsavelist;
private Button btnsave_toutils;
private Button btn_read_list;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
context = getContext();
btnWrite = (Button) findComponentById(ResourceTable.Id_write_btn);
btnRead = (Button) findComponentById(ResourceTable.Id_read_btn);
btnDelete = (Button) findComponentById(ResourceTable.Id_delete_btn);
textFiledFruit = (TextField) findComponentById(ResourceTable.Id_text_fruit);
textFiledNumber = (TextField) findComponentById(ResourceTable.Id_text_number);
btnsavelist= (Button) findComponentById(ResourceTable.Id_save_list);
btnsave_toutils= (Button) findComponentById(ResourceTable.Id_save_toutils);
btn_read_list= (Button) findComponentById(ResourceTable.Id_read_list);
databaseHelper = new DatabaseHelper(context);
filename = "pdb";
preferences = databaseHelper.getPreferences(filename);
btnWrite();
btnRead();
btnDelete();
btnSavelist();
btnSavetoutils();
btnReadList();
}
/***
* 寫(xiě)入數(shù)據(jù)
*
*
*/
private void btnWrite() {
btnWrite.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String fruit = textFiledFruit.getText();
try {
int number = Integer.parseInt(textFiledNumber.getText());
preferences.putInt("number",number);
preferences.putString("fruit",fruit);
preferences.flush();
new ToastDialog(context).setText("Write to DB file success").show();
} catch (NumberFormatException e) {
new ToastDialog(context).setText("Please input number in Number row").show();
}
}
});
}
/***
*
* 讀取數(shù)據(jù)
*
*/
private void btnRead() {
btnRead.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String string = String.format(Locale.ENGLISH,"Fruit: %s,Number: %d",
preferences.getString("fruit", ""),preferences.getInt("number", 0));
new ToastDialog(context).setText(string).show();
}
});
}
/**
* 刪除數(shù)據(jù)
*
*/
private void btnDelete() {
btnDelete.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
if (databaseHelper.deletePreferences(filename)) {
preferences.clear();
new ToastDialog(context).setText("Delete DB file success").show();
} else {
new ToastDialog(context).setText("Delete DB file failed").show();
}
}
});
}
/***
*
* 緩存list 集合類型數(shù)據(jù)
*
*/
private void btnSavelist() {
btnsavelist.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
UserBean userBean=new UserBean();
userBean.setUsername("test");
userBean.setPassword("123456");
List<UserBean> datalist=new ArrayList<>();
datalist.add(userBean);
DataBaseUtil.putSelectBean(context,datalist,"datalist");
new ToastDialog(context).setText("寫(xiě)入成功").show();
}
});
}
/***
*
* 調(diào)用工具類方法存儲(chǔ)
*/
private void btnSavetoutils() {
btnsave_toutils.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String fruit = textFiledFruit.getText();
try {
int number = Integer.parseInt(textFiledNumber.getText());
DataBaseUtil.setParam(context,"number",number);
DataBaseUtil.setParam(context,"fruit",fruit);
new ToastDialog(context).setText("寫(xiě)入成功").show();
} catch (NumberFormatException e) {
new ToastDialog(context).setText("Please input number in Number row").show();
}
}
});
}
/***
*
* 讀取list 集合類型數(shù)據(jù)
*
*/
private void btnReadList(){
btn_read_list.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
List<UserBean>getData= (List<UserBean>) DataBaseUtil.getSelectBean(context,"datalist");
UserBean userBean= getData.get(0);
new ToastDialog(context).setText(userBean.getUsername()+userBean.getPassword()).show();
}
});
}
}
-
4 bean 類
package com.example.datademo.bean;
/***
*
* 創(chuàng)建人:xuqing
* 創(chuàng)建時(shí)間:2021年6月20日20:54:28
* 類說(shuō)明:用戶賬號(hào)密碼 bean類
*
*
*/
public class UserBean {
private String username;
private String password;
public UserBean() {
}
public UserBean(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserBean{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
-
4 工具類核心代碼
package com.example.datademo.utils;
import com.example.datademo.bean.UserBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import java.io.*;
import java.lang.reflect.Type;
import java.util.List;
public class DataBaseUtil {
private static String filename = "pdb";
private static Preferences preferences;
private static DatabaseHelper databaseHelper;
/**
* 保存數(shù)據(jù)的方法羽嫡,我們需要拿到保存數(shù)據(jù)的具體類型,然后根據(jù)類型調(diào)用不同的保存方法
*
* @param context
* @param key
* @param object
* @param :DataBaseUtil.setParam(this, "key", "value");
* key -- userid / accountId obj==
*/
public static void setParam(Context context, String key, Object object) {
String type = "String";
if (object != null) {
type = object.getClass().getSimpleName();
}
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
if ("String".equals(type)) {
preferences.putString(key, (String) object);
} else if ("Integer".equals(type) || "int".equals(type)) {
preferences.putInt(key, (Integer) object);
} else if ("Boolean".equals(type) || "boolean".equals(type)) {
preferences.putBoolean(key, (Boolean) object);
} else if ("Float".equals(type) || "float".equals(type)) {
preferences.putFloat(key, (Float) object);
} else if ("Long".equals(type) || "long".equals(type)) {
preferences.putLong(key, (Long) object);
}
preferences.flush();
}
/**
* 得到保存數(shù)據(jù)的方法肩袍,我們根據(jù)默認(rèn)值得到保存的數(shù)據(jù)的具體類型杭棵,然后調(diào)用相對(duì)于的方法獲取值
*
* @param context
* @param key 關(guān)鍵字
* @param defaultObject 若取回空值則返回此默認(rèn)值
* @param :DataBaseUtil.getParam(Activity.this, "key", "defaultValue");
* @return
*/
public static Object getParam(Context context, String key, Object defaultObject) {
String type = "String";
if (defaultObject != null) {
type = defaultObject.getClass().getSimpleName();
}
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
if ("String".equals(type)) {
return preferences.getString(key, (String) defaultObject);
} else if ("Integer".equals(type) || "int".equals(type)) {
return preferences.getInt(key, (Integer) defaultObject);
} else if ("Boolean".equals(type) || "boolean".equals(type)) {
return preferences.getBoolean(key, (Boolean) defaultObject);
} else if ("Float".equals(type) || "float".equals(type)) {
return preferences.getFloat(key, (Float) defaultObject);
} else if ("Long".equals(type) || "long".equals(type)) {
return preferences.getLong(key, (Long) defaultObject);
}
return null;
}
//刪除數(shù)據(jù)
public static void removeParam(Context context, Object defaultObject) {
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
preferences.clear();
}
/**
* 4.存儲(chǔ)list
*/
public static void putSelectBean(Context context, List<UserBean> phoneList, String key) {
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
Gson gson = new Gson();
String json = gson.toJson(phoneList);
preferences.putString(key, json);
preferences.flush();
}
/**
* 讀取list
*/
public static List<UserBean> getSelectBean(Context context, String key) {
databaseHelper = new DatabaseHelper(context);
preferences = databaseHelper.getPreferences(filename);
Gson gson = new Gson();
String json = preferences.getString(key, null);
Type type = new TypeToken<List<UserBean>>() {
}.getType();
List<UserBean> arrayList = gson.fromJson(json, type);
return arrayList;
}
//存數(shù)據(jù)到SD卡里面
public static void storetosd(File file, List<UserBean> data) {
try {
Gson gson = new Gson();
String json = gson.toJson(data);
OutputStream os = new FileOutputStream(file);
os.write(json.getBytes("utf-8"));
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//讀取SD卡里面的數(shù)據(jù)
public static List<UserBean> readbysd(File file) {
List<UserBean> arrayList = null;
Gson gson = new Gson();
try {
InputStream is = new FileInputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
String content = new String(data, "utf-8");
Type type = new TypeToken<List<UserBean>>() {
}.getType();
arrayList = gson.fromJson(content, type);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
}
到此DatabaseHelper基本就講完了 恭喜你看完此文你就會(huì)掌握了鴻蒙輕量級(jí)數(shù)據(jù)庫(kù)DatabaseHelper的用法和使用技巧
最后總結(jié)
鴻蒙的 DatabaseHelper輕量級(jí)數(shù)據(jù)庫(kù)和安卓的 sharepreferences 用法和類似都是默認(rèn)只能存儲(chǔ)基本數(shù)據(jù)類型 但是鴻蒙提供了 flush 和 flushSync 兩個(gè)方法 將Preferences實(shí)例持久化。 flush()會(huì)立即更改內(nèi)存中的Preferences對(duì)象氛赐,但會(huì)將更新異步寫(xiě)入磁盤(pán)魂爪。flushSync()更改內(nèi)存中的數(shù)據(jù)的同時(shí)會(huì)將數(shù)據(jù)同步寫(xiě)入磁盤(pán)。由于flushSync()是同步的艰管,建議不要從主線程調(diào)用它滓侍,以避免界面卡頓。 這里和安卓還是有些許區(qū)別 同學(xué)們要注意蛙婴。使用起來(lái) DatabaseHelper也比較方便和簡(jiǎn)單。以及一些非基本數(shù)據(jù)類型怎么轉(zhuǎn)化來(lái)存儲(chǔ)我也講到了 同學(xué)有興趣可以下載代碼來(lái)看看 最后希望我的文章能幫助到各位解決問(wèn)題 尔破,以后我還會(huì)貢獻(xiàn)更多有用的代碼分享給大家街图。各位同學(xué)如果覺(jué)得文章還不錯(cuò) ,麻煩給關(guān)注和star懒构,小弟在這里謝過(guò)啦!