preface:
Hello, students, I haven't updated the article for you for a while (I'm really sorry to stop because I've been busy with house purchase loans before). Today I want to talk about the basic usage and some skills of lightweight data DatabaseHelper in Hongmeng. So there's no more nonsense. Let's officially start
design sketch
1 Introduction
Lightweight preference database is lightweight storage, which is mainly used to save some common configurations of applications. It stores data in the form of key value pairs. When saving data, you need to provide a key for this data, and then get the corresponding value through this key when reading data.
explain
By observing the source code, the storage data types of lightweight preference database values include integer, long integer, floating point, Boolean, string and string Set. The data is stored in local files and also loaded in memory. It is not suitable for scenes that need to store a large amount of data and frequently change data. It is recommended that the stored data should not exceed 10000.
2 create database
Create a secondary class that uses database operations DatabaseHelper , the corresponding file name can be obtained through the getPreferences(String name) method of DatabaseHelper Preferences Instance, and then operate the database through the methods provided by Preferences.
The construction of DatabaseHelper needs to pass in context, Ability and AbilitySlice It's all done ohos.app.Context Interface. Therefore, you can call the getContext() method from the Ability or AbilitySlice in the application to obtain the context.
The data of Preferences is stored in a file, so you need to specify the file name to be stored. Its value cannot be empty or contain a path. The default storage directory can be through context Getpreferencesdir().
DatabaseHelper databaseHelper = new DatabaseHelper(context); String filename = "pdb"; Preferences preferences = databaseHelper.getPreferences(filename);
3 write data
We get the numbers and words entered in the input box, and then click the button to call the put method in preferences to store the data
You can write data to the Preferences instance through the putString(String var1, String var2) and putInt(String var1, int var2) methods of Preferences, and persist the Preferences instance through flush() or flushSync().
flush() immediately changes the Preferences object in memory, but writes the update asynchronously to disk. flushSync() writes data to disk synchronously while changing data in memory. Since flushsync () is synchronous, it is recommended not to call it from the main thread to avoid interface jamming.
/*** * Write data * * */ 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 read data
We call the get method in preferences to get the data stored in the DataBase library
Pass in the key through getString(String var1, String var2) and getInt(String var1, int var2) methods of Preferences to obtain the corresponding value; If the key does not exist, the default value is returned.
For example, get the values of the above fruit and number keys. If the fruit and number keys do not exist, the values "" and 0 will be returned respectively. By setting the default value, the program can avoid exceptions.
/*** * * Read data * */ 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 delete database
Delete the specified file through the deletePreferences(String name) method of DatabaseHelper.
When deleting the specified file, the application is not allowed to use this instance for data operation, otherwise the data consistency problem will occur. Take deleting the above file named "pdb" as an example.
/** * Delete data * */ 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(); } } }); }
explain
The lightweight preference database supports the creation and movement of database files, the query, insertion and deletion of data, and supports the registration of observers to observe whether the data changes. For details, please refer to Lightweight preference database.
6 cache list data
By observing the source code, we found that the DatabaseHelper lightweight database has no way to directly store our list collection. This is what we should do. We convert the list into json string and then save the json. We can get the json string in the value and restore it to list. For the convenience of demonstration, we have written a tool class here
-
1. Method of storing list
/** * 4.Store 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(); }
We wrote a putSelectBean to store our list
-
2. Method of reading list
/** * Read 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 specific storage list call
/*** * * Cache list collection type data * */ 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("Write successful").show(); } }); }
-
4. Call to read list type data
/*** * * Read list collection type data * */ 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 simple encapsulation of databasehelper storage
We use DatabaseHelper every time
DatabaseHelper databaseHelper = new DatabaseHelper(context); String filename = "pdb"; Preferences preferences = databaseHelper.getPreferences(filename);
Then calling preferences's put method store and get method read code is not very simple, we do a simple tool class encapsulation.
-
1 packaging of storage methods
private static String filename = "pdb"; private static Preferences preferences; private static DatabaseHelper databaseHelper; /** * For the method of saving data, we need to get the specific type of saved data, and then call different saving methods according to the type * * @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 simple encapsulation of reading method
/** * We get the way to save the data. We get the specific type of the data saved according to the default value, and then call the relative method to get the value. * * @param context * @param key keyword * @param defaultObject If a null value is returned, this default value is returned * @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; }
-
Specific call
/*** * * Call tool class method store */ 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("Write successful").show(); } catch (NumberFormatException e) { new ToastDialog(context).setText("Please input number in Number row").show(); } } }); }
Complete example
-
1. XML layout code
<?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="Write cache" 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="Read cache" 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="Delete cache" 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="storage 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="read 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="Tool class cache call" 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 layout renderings
-
3 java logic code
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(); } /*** * Write data * * */ 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(); } } }); } /*** * * Read data * */ 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(); } }); } /** * Delete data * */ 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(); } } }); } /*** * * Cache list collection type data * */ 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("Write successful").show(); } }); } /*** * * Call tool class method store */ 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("Write successful").show(); } catch (NumberFormatException e) { new ToastDialog(context).setText("Please input number in Number row").show(); } } }); } /*** * * Read list collection type data * */ 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 class
package com.example.datademo.bean; /*** * * Created by: xuqing * Creation time: 20:54:28, June 20, 2021 * Class description: user account password bean class * * */ 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. Tool core code
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; /** * For the method of saving data, we need to get the specific type of saved data, and then call different saving methods according to the type * * @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(); } /** * We get the way to save the data. We get the specific type of the data saved according to the default value, and then call the relative method to get the value. * * @param context * @param key keyword * @param defaultObject If a null value is returned, this default value is returned * @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; } //Delete data public static void removeParam(Context context, Object defaultObject) { databaseHelper = new DatabaseHelper(context); preferences = databaseHelper.getPreferences(filename); preferences.clear(); } /** * 4.Store 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(); } /** * Read 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; } //Save data to SD card 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(); } } //Read the data in SD card 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; } }
This is basically the end of the DatabaseHelper. Congratulations. After reading this article, you will master the usage and skills of Hongmeng lightweight DatabaseHelper
Final summary
Hongmeng's DatabaseHelper lightweight database and Android's sharereferences are used and similar. By default, they can only store basic data types. However, Hongmeng provides two methods, flush and flushSync, to persist the Preferences instance. flush() immediately changes the Preferences object in memory, but writes the update asynchronously to disk. flushSync() writes data to disk synchronously while changing data in memory. Since flushSync () is synchronous, it is recommended not to call it from the main thread to avoid interface jamming. There are still some differences between this and Android. Students should pay attention to it. DatabaseHelper is also convenient and simple to use. And how to convert some non basic data types to storage. I also mentioned that students who are interested can download the code to have a look. Finally, I hope my article can help you solve the problem. In the future, I will contribute more useful code to share with you. If you think the article is good, please pay attention and star. Thank you here, You can also add my personal QQ / wechat (1693891473)
Project address:
Code cloud: https://gitee.com/qiuyu123/database