鸿蒙初学 使用DataAbility操作数据库

参考资源:
华为Harmony鸿蒙开发笔记五:DataAbility操作数据库
元数据绑定框架

1. 创建实体类

@Entity(tableName = "user")
public class User extends OrmObject {
    
    
    @PrimaryKey(autoGenerate = true)
    private Integer id;
    private String name;
    private String introduction;
    
    getter...
    setter...

    /**
     * convert values bucket to user
     *
     * @param valuesBucket values bucket
     * @return user
     */
    public User fromValues(ValuesBucket valuesBucket) {
    
    
        name = valuesBucket.getString("name");
        introduction = valuesBucket.getString("introduction");
        return this;
    }
}

2. 创建UserOrmDatabase

@Database(entities = {
    
    User.class, Note.class}, version = 1)
public abstract class UserOrmDatabase extends OrmDatabase {
    
    
    /**
     * Configuring this Database's name.
     */
    public static final String DATABASE_NAME = "User.db";

    /**
     * Configuring this Database's alias.
     */
    public static final String DATABASE_NAME_ALIAS = "User";
}

3. 创建UserDataAbility并重写其中插入和查询的方法

public class UserDataAbility extends Ability {
    
    
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "TAG");
    public final static String URI = "dataability:///work.wxmx.metadatabindingstudy.UserDataAbility";
    private static final int ERR_CODE = -1;
    private static final String ROW_ID = "id";

    private OrmContext ormContext = null;

    @Override
    public void onStart(Intent intent) {
    
    
        super.onStart(intent);
        HiLog.info(LABEL_LOG, "UserDataAbility onStart");
        DatabaseHelper manager = new DatabaseHelper(this);
        ormContext = manager.getOrmContext(
                UserOrmDatabase.DATABASE_NAME_ALIAS,
                UserOrmDatabase.DATABASE_NAME,
                UserOrmDatabase.class);
    }

    @Override
    public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates) {
    
    
        //查询数据库
        OrmPredicates ormPredicates = DataAbilityUtils.createOrmPredicates(predicates, User.class);
        ResultSet resultSet = ormContext.query(ormPredicates, columns);
        if (resultSet == null) {
    
    
            HiLog.info(LABEL_LOG, "resultSet is null");
        }
        return resultSet;
    }

    @Override
    public int insert(Uri uri, ValuesBucket value) {
    
    
        HiLog.info(LABEL_LOG, "insert...", "");
        User user = new User();
        if (ormContext.insert(user.fromValues(value))) {
    
    
            ormContext.flush();
            DataAbilityHelper.creator(this, uri).notifyChange(uri);
            return (int) user.getRowId();
        }
        return ERR_CODE;
    }
    // ... 其他方法略
}

4. 创建布局

<?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">

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal">

        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text="name: "
            ohos:text_size="40fp"
            ohos:visibility="visible"/>

        <TextField
            ohos:id="$+id:name_text_field"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:align_parent_right="true"
            ohos:hint="name"
            ohos:multiple_lines="false"
            ohos:right_margin="15vp"
            ohos:text_size="40fp"/>
    </DirectionalLayout>

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal">

        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text="intro: "
            ohos:text_size="40fp"
            ohos:visibility="visible"/>

        <TextField
            ohos:id="$+id:introduction_text_field"
            ohos:height="match_content"

            ohos:width="match_content"
            ohos:align_parent_right="true"
            ohos:hint="introduction"
            ohos:max_text_lines="10"
            ohos:multiple_lines="false"
            ohos:right_margin="15vp"
            ohos:text_size="40fp"/>
    </DirectionalLayout>

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal">

        <Button
            ohos:id="$+id:insert_btn"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:background_element="gray"
            ohos:text="insert"
            ohos:text_size="40fp"/>

        <Button
            ohos:left_margin="20vp"
            ohos:id="$+id:query_btn"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:background_element="gray"
            ohos:text="query"
            ohos:text_size="40fp"/>
    </DirectionalLayout>
    <Text
        ohos:text="AAA"
        ohos:text_size="20fp"
        ohos:id="$+id:result_text"
        ohos:multiple_lines="true"
        ohos:height="match_content"
        ohos:width="match_content"/>
</DirectionalLayout>

效果图如下:
在这里插入图片描述

5. 在MainAbilitySlice中添加处理事件的逻辑

public class MainAbilitySlice extends AbilitySlice {
    
    
    DataAbilityHelper mHelper;
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "TAG");

    @Override
    public void onStart(Intent intent) {
    
    
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mHelper = DataAbilityHelper.creator(this);
        Button insertBtn = (Button) findComponentById(ResourceTable.Id_insert_btn);
        Button queryBtn = (Button) findComponentById(ResourceTable.Id_query_btn);
        Text nameText = (Text) findComponentById(ResourceTable.Id_name_text_field);
        Text resultText = (Text) findComponentById(ResourceTable.Id_result_text);
        Text introductionText = (Text) findComponentById(ResourceTable.Id_introduction_text_field);
        insertBtn.setClickedListener(new Component.ClickedListener() {
    
    
            @Override
            public void onClick(Component component) {
    
    
                ValuesBucket bucket = new ValuesBucket();
                bucket.putString("name", nameText.getText());
                bucket.putString("introduction", introductionText.getText());
                try {
    
    
                    mHelper.insert(Uri.parse(UserDataAbility.URI), bucket);
                } catch (DataAbilityRemoteException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
        queryBtn.setClickedListener(new Component.ClickedListener() {
    
    
            @Override
            public void onClick(Component component) {
    
    
                HiLog.info(LABEL_LOG, "queryData Ability start");
                // 构造查询条件
                DataAbilityPredicates predicates = new DataAbilityPredicates();
                predicates.like("name", "%" + nameText.getText() + "%");
                // 进行查询
                String[] columns = new String[]{
    
    "id", "name", "introduction"};
                Uri uri = Uri.parse(UserDataAbility.URI);
                ResultSet resultSet = null;
                try {
    
    
                    resultSet = mHelper.query(uri, columns, predicates);
                } catch (DataAbilityRemoteException e) {
    
    
                    e.printStackTrace();
                }
                // 处理结果
                resultSet.goToFirstRow();
                StringBuilder builder = new StringBuilder();
                while (resultSet.goToNextRow()) {
    
    
                    // 在此处理ResultSet中的记录;
                    String name = resultSet.getString(1);
                    String introduction = resultSet.getString(2);
                    HiLog.info(LABEL_LOG, "name=" + name);
                    HiLog.info(LABEL_LOG, "introduction=" + introduction);
                    builder.append(name + ": " + introduction + "\n");
                }
                resultText.setText(builder.toString());
            }
        });

    }

    @Override
    public void onActive() {
    
    
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
    
    
        super.onForeground(intent);
    }
}

效果图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41359651/article/details/119532056
今日推荐