鸿蒙生态系统开发实例:鸿蒙记事本开发全攻略

以下是基于鸿蒙生态系统(HarmonyOS)的文本记事本应用开发实例,包含数据库存储、时间戳管理及日历提醒功能的完整实现代码和说明。


数据库设计

使用轻量级数据库存储记事本内容,建表语句如下:

// DatabaseHelper.java
public class DatabaseHelper extends OrmContext {
    private static final String DATABASE_NAME = "notes.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, DATABASE_VERSION);
    }

    @Override
    public void onCreate(DatabaseHelper helper) {
        helper.executeSql("CREATE TABLE IF NOT EXISTS notes (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "title TEXT," +
                "content TEXT," +
                "timestamp INTEGER," +
                "reminder_time INTEGER)");
    }
}


数据模型类

定义记事本数据实体类:

// Note.java
@Entity(tableName = "notes")
public class Note {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @Column(name = "title")
    private String title;
    @Column(name = "content")
    private String content;
    @Column(name = "timestamp")
    private long timestamp;
    @Column(name = "reminder_time")
    private long reminderTime;

    // Getter/Setter方法省略...
}


核心功能实现

添加/更新记事
// NoteDao.java
public class NoteDao {
    public static boolean saveNote(Note note, OrmContext context) {
        if (note.getId() == 0) {
            note.setTimestamp(System.currentTimeMillis());
            return context.insert(note) > 0;
        } else {
            return context.update(note) > 0;
        }
    }
}

查询记事列表(按时间倒序)
public static List<Note> getAllNotes(OrmContext context) {
    WhereClause where = new WhereClause("1=1");
    OrderAttribute order = new OrderAttribute("timestamp", false);
    return context.query(where, order);
}

删除记事
public static boolean deleteNote(Note note, OrmContext context) {
    return context.delete(note) > 0;
}


日历提醒功能

集成系统日历服务设置提醒:

// ReminderUtil.java
public class ReminderUtil {
    public static void setCalendarReminder(Context context, Note note) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
                .setData(CalendarContract.Events.CONTENT_URI)
                .putExtra(CalendarContract.Events.TITLE, note.getTitle())
                .putExtra(CalendarContract.Events.DESCRIPTION, note.getContent())
                .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, note.getReminderTime())
                .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, note.getReminderTime() + 3600000);
        context.startAbility(intent);
    }
}


UI界面实现(部分关键代码)

主页面列表
<!-- resources/base/layout/note_list.xml -->
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent">
    <ListContainer
        ohos:id="$+id:note_list"
        ohos:width="match_parent"
        ohos:height="match_parent"/>
</DirectionalLayout>

列表项数据绑定
// NoteListSlice.java
private void bindListData() {
    List<Note> notes = NoteDao.getAllNotes(getOrmContext());
    ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_note_list);
    SampleItemProvider provider = new SampleItemProvider(notes, this);
    listContainer.setItemProvider(provider);
}


注意事项

  1. 需在config.json中添加数据库和日历权限:
"reqPermissions": [
    {
        "name": "ohos.permission.WRITE_CALENDAR"
    },
    {
        "name": "ohos.permission.READ_CALENDAR"
    }
]

  1. 时间戳处理建议使用java.time包(API 8+)或java.util.Calendar

  2. 数据库操作需在主线程外执行,建议使用TaskDispatcher分发异步任务

完整项目需包含以下扩展功能:

  • 数据分页加载
  • 内容搜索功能
  • 提醒通知处理
  • 数据备份/恢复机制

以下是一个基于开源数据库PostgreSQL的详细代码实现示例,涵盖数据库连接、表操作和基本CRUD功能:

环境准备

安装PostgreSQL数据库及Python驱动:

sudo apt-get install postgresql postgresql-contrib
pip install psycopg2-binary

数据库连接配置

import psycopg2

def get_db_connection():
    conn = psycopg2.connect(
        host="localhost",
        database="mydatabase",
        user="postgres",
        password="yourpassword",
        port="5432"
    )
    return conn

创建数据表

def create_tables():
    commands = (
        """
        CREATE TABLE IF NOT EXISTS users (
            user_id SERIAL PRIMARY KEY,
            username VARCHAR(255) NOT NULL,
            email VARCHAR(255) UNIQUE NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        """,
        """
        CREATE TABLE IF NOT EXISTS products (
            product_id SERIAL PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            price DECIMAL(10,2) NOT NULL,
            stock INTEGER DEFAULT 0
        )
        """
    )
    
    conn = None
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        for command in commands:
            cur.execute(command)
        cur.close()
        conn.commit()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()

插入数据

def insert_user(username, email):
    sql = """INSERT INTO users(username, email)
             VALUES(%s, %s) RETURNING user_id"""
    conn = None
    user_id = None
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute(sql, (username, email))
        user_id = cur.fetchone()[0]
        conn.commit()
        cur.close()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()
    return user_id

查询数据

def get_users():
    conn = None
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("SELECT user_id, username, email FROM users ORDER BY username")
        rows = cur.fetchall()
        cur.close()
        return rows
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()

更新数据

def update_user_email(user_id, new_email):
    conn = None
    updated_rows = 0
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("UPDATE users SET email = %s WHERE user_id = %s",
                    (new_email, user_id))
        updated_rows = cur.rowcount
        conn.commit()
        cur.close()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()
    return updated_rows

删除数据

def delete_user(user_id):
    conn = None
    rows_deleted = 0
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("DELETE FROM users WHERE user_id = %s", (user_id,))
        rows_deleted = cur.rowcount
        conn.commit()
        cur.close()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()
    return rows_deleted

事务处理示例

def transfer_funds(from_id, to_id, amount):
    conn = None
    try:
        conn = get_db_connection()
        conn.autocommit = False
        cur = conn.cursor()
        
        # 检查余额
        cur.execute("SELECT balance FROM accounts WHERE id = %s", (from_id,))
        balance = cur.fetchone()[0]
        if balance < amount:
            raise ValueError("Insufficient funds")
            
        # 执行转账
        cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s",
                   (amount, from_id))
        cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s",
                   (amount, to_id))
        
        conn.commit()
        cur.close()
    except Exception as e:
        if conn:
            conn.rollback()
        print(f"Transaction failed: {e}")
    finally:
        if conn is not None:
            conn.close()

索引创建

def create_indexes():
    conn = None
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("CREATE INDEX IF NOT EXISTS idx_user_email ON users(email)")
        cur.execute("CREATE INDEX IF NOT EXISTS idx_product_price ON products(price)")
        conn.commit()
        cur.close()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if conn is not None:
            conn.close()

以上代码实现包含数据库基本操作和高级功能,可根据实际需求进行扩展。使用时需确保PostgreSQL服务已启动,并修改连接参数匹配实际环境。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值