- * 使用PHONE_NUMBERS_EQUAL函数进行号码匹配,支持国际号码格式。
- * 只查询电话号码类型的数据(Phone.CONTENT_ITEM_TYPE)。
- * 使用min_match='+'进行最小匹配,提高查询效率。
- *
- */
- private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
- + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
- + " AND " + Data.RAW_CONTACT_ID + " IN "
- + "(SELECT raw_contact_id "
- + " FROM phone_lookup"
- + " WHERE min_match = '+')";
-
- /**
- * 根据电话号码获取联系人姓名
- *
- * 首先检查缓存中是否已存在该号码对应的联系人姓名,
- * 如果存在则直接返回,否则查询系统联系人数据库。
- * 查询结果会被缓存以提高后续查询效率。
- *
- *
- * @param context 应用上下文,用于访问ContentResolver
- * @param phoneNumber 要查询的电话号码
- * @return 联系人姓名,如果未找到则返回null
- */
- public static String getContact(Context context, String phoneNumber) {
- // 初始化缓存
- if(sContactCache == null) {
- sContactCache = new HashMap();
- }
-
- // 检查缓存中是否已存在
- if(sContactCache.containsKey(phoneNumber)) {
- return sContactCache.get(phoneNumber);
- }
-
- // 构建查询条件,使用toCallerIDMinMatch进行号码最小匹配
- String selection = CALLER_ID_SELECTION.replace("+",
- PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
- Cursor cursor = context.getContentResolver().query(
- Data.CONTENT_URI,
- new String [] { Phone.DISPLAY_NAME },
- selection,
- new String[] { phoneNumber },
- null);
-
- // 处理查询结果
- if (cursor != null && cursor.moveToFirst()) {
- try {
- String name = cursor.getString(0);
- sContactCache.put(phoneNumber, name);
- return name;
- } catch (IndexOutOfBoundsException e) {
- Log.e(TAG, " Cursor get string error " + e.toString());
- return null;
- } finally {
- cursor.close();
- }
- } else {
- Log.d(TAG, "No contact matched with number:" + phoneNumber);
- return null;
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/data/Notes.java b/app/src/main/java/net/micode/notes/data/Notes.java
deleted file mode 100644
index 71f11fa..0000000
--- a/app/src/main/java/net/micode/notes/data/Notes.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-import android.net.Uri;
-/**
- * 笔记数据常量定义类
- *
- * 定义了笔记应用中使用的所有常量、接口和内部类,包括:
- *
- * Content Provider的Authority和URI
- * 笔记类型常量(普通笔记、文件夹、系统文件夹)
- * 系统文件夹ID常量
- * Intent Extra键常量
- * Widget类型常量
- * 笔记数据列接口(NoteColumns、DataColumns)
- * 文本笔记和通话记录笔记内部类
- *
- *
- *
- * 该类主要用于定义数据库表结构和Content Provider的契约,
- * 提供统一的常量访问接口,方便应用各模块使用。
- *
- */
-public class Notes {
- /**
- * Content Provider的Authority
- */
- public static final String AUTHORITY = "micode_notes";
- /**
- * 日志标签
- */
- public static final String TAG = "Notes";
- /**
- * 普通笔记类型
- */
- public static final int TYPE_NOTE = 0;
- /**
- * 文件夹类型
- */
- public static final int TYPE_FOLDER = 1;
- /**
- * 系统类型
- */
- public static final int TYPE_SYSTEM = 2;
-
- /**
- * 以下ID是系统文件夹的标识符
- * {@link Notes#ID_ROOT_FOLDER } 是默认文件夹
- * {@link Notes#ID_TEMPARAY_FOLDER } 用于不属于任何文件夹的笔记
- * {@link Notes#ID_CALL_RECORD_FOLDER} 用于存储通话记录
- */
- public static final int ID_ROOT_FOLDER = 0;
- /**
- * 临时文件夹ID,用于不属于任何文件夹的笔记
- */
- public static final int ID_TEMPARAY_FOLDER = -1;
- /**
- * 通话记录文件夹ID,用于存储通话记录
- */
- public static final int ID_CALL_RECORD_FOLDER = -2;
- /**
- * 回收站文件夹ID,用于存储已删除的笔记
- */
- public static final int ID_TRASH_FOLER = -3;
-
- /**
- * Intent Extra键:提醒日期
- */
- public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
- /**
- * Intent Extra键:背景颜色ID
- */
- public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
- /**
- * Intent Extra键:Widget ID
- */
- public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
- /**
- * Intent Extra键:Widget类型
- */
- public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
- /**
- * Intent Extra键:文件夹ID
- */
- public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
- /**
- * Intent Extra键:通话日期
- */
- public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
-
- /**
- * 无效的Widget类型
- */
- public static final int TYPE_WIDGET_INVALIDE = -1;
- /**
- * 2x2 Widget类型
- */
- public static final int TYPE_WIDGET_2X = 0;
- /**
- * 4x4 Widget类型
- */
- public static final int TYPE_WIDGET_4X = 1;
-
- public static class DataConstants {
- public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
- public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
- }
-
- /**
- * Uri to query all notes and folders
- */
- public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
-
- /**
- * Uri to query data
- */
- public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
-
- public interface NoteColumns {
- /**
- * The unique ID for a row
- * Type: INTEGER (long)
- */
- public static final String ID = "_id";
-
- /**
- * The parent's id for note or folder
- * Type: INTEGER (long)
- */
- public static final String PARENT_ID = "parent_id";
-
- /**
- * Created data for note or folder
- * Type: INTEGER (long)
- */
- public static final String CREATED_DATE = "created_date";
-
- /**
- * Latest modified date
- * Type: INTEGER (long)
- */
- public static final String MODIFIED_DATE = "modified_date";
-
-
- /**
- * Alert date
- * Type: INTEGER (long)
- */
- public static final String ALERTED_DATE = "alert_date";
-
- /**
- * Folder's name or text content of note
- * Type: TEXT
- */
- public static final String SNIPPET = "snippet";
-
- /**
- * Note's widget id
- * Type: INTEGER (long)
- */
- public static final String WIDGET_ID = "widget_id";
-
- /**
- * Note's widget type
- * Type: INTEGER (long)
- */
- public static final String WIDGET_TYPE = "widget_type";
-
- /**
- * Note's background color's id
- * Type: INTEGER (long)
- */
- public static final String BG_COLOR_ID = "bg_color_id";
-
- /**
- * For text note, it doesn't has attachment, for multi-media
- * note, it has at least one attachment
- * Type: INTEGER
- */
- public static final String HAS_ATTACHMENT = "has_attachment";
-
- /**
- * Folder's count of notes
- * Type: INTEGER (long)
- */
- public static final String NOTES_COUNT = "notes_count";
-
- /**
- * The file type: folder or note
- * Type: INTEGER
- */
- public static final String TYPE = "type";
-
- /**
- * The last sync id
- * Type: INTEGER (long)
- */
- public static final String SYNC_ID = "sync_id";
-
- /**
- * Sign to indicate local modified or not
- * Type: INTEGER
- */
- public static final String LOCAL_MODIFIED = "local_modified";
-
- /**
- * Original parent id before moving into temporary folder
- * Type : INTEGER
- */
- public static final String ORIGIN_PARENT_ID = "origin_parent_id";
-
- /**
- * The gtask id
- * Type : TEXT
- */
- public static final String GTASK_ID = "gtask_id";
-
- /**
- * The version code
- * Type : INTEGER (long)
- */
- public static final String VERSION = "version";
-
- /**
- * Sign to indicate the note is pinned to top or not
- * Type : INTEGER
- */
- public static final String TOP = "top";
- }
-
- public interface DataColumns {
- /**
- * The unique ID for a row
- * Type: INTEGER (long)
- */
- public static final String ID = "_id";
-
- /**
- * The MIME type of the item represented by this row.
- * Type: Text
- */
- public static final String MIME_TYPE = "mime_type";
-
- /**
- * The reference id to note that this data belongs to
- * Type: INTEGER (long)
- */
- public static final String NOTE_ID = "note_id";
-
- /**
- * Created data for note or folder
- * Type: INTEGER (long)
- */
- public static final String CREATED_DATE = "created_date";
-
- /**
- * Latest modified date
- * Type: INTEGER (long)
- */
- public static final String MODIFIED_DATE = "modified_date";
-
- /**
- * Data's content
- * Type: TEXT
- */
- public static final String CONTENT = "content";
-
-
- /**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * integer data type
- * Type: INTEGER
- */
- public static final String DATA1 = "data1";
-
- /**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * integer data type
- * Type: INTEGER
- */
- public static final String DATA2 = "data2";
-
- /**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
- */
- public static final String DATA3 = "data3";
-
- /**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
- */
- public static final String DATA4 = "data4";
-
- /**
- * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
- * TEXT data type
- * Type: TEXT
- */
- public static final String DATA5 = "data5";
- }
-
- public static final class TextNote implements DataColumns {
- /**
- * Mode to indicate the text in check list mode or not
- * Type: Integer 1:check list mode 0: normal mode
- */
- public static final String MODE = DATA1;
-
- public static final int MODE_CHECK_LIST = 1;
-
- public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
-
- public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
-
- public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
- }
-
- public static final class CallNote implements DataColumns {
- /**
- * Call date for this record
- * Type: INTEGER (long)
- */
- public static final String CALL_DATE = DATA1;
-
- /**
- * Phone number for this record
- * Type: TEXT
- */
- public static final String PHONE_NUMBER = DATA3;
-
- public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
-
- public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
-
- public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
- }
-}
diff --git a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
deleted file mode 100644
index c862ead..0000000
--- a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
-
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-
-
-/**
- * 笔记数据库帮助类
- *
- * 继承自SQLiteOpenHelper,负责笔记应用SQLite数据库的创建、升级和管理。
- * 管理两个主要数据表:note表(存储笔记和文件夹信息)和data表(存储笔记的详细内容)。
- * 使用数据库触发器自动维护笔记计数、内容同步等关联关系。
- *
- *
- * 主要功能:
- *
- * 创建和升级数据库表结构
- * 创建和管理数据库触发器
- * 维护系统文件夹(通话记录、根文件夹、临时文件夹、回收站)
- * 支持数据库版本升级(当前版本:4)
- * 提供单例模式访问数据库帮助类实例
- *
- *
- *
- * 数据库版本历史:
- *
- * V1: 初始版本
- * V2: 重构表结构
- * V3: 添加GTASK_ID列和回收站文件夹
- * V4: 添加VERSION列
- *
- *
- *
- * @see SQLiteOpenHelper
- * @see Notes
- */
-public class NotesDatabaseHelper extends SQLiteOpenHelper {
- /**
- * 数据库文件名
- */
- private static final String DB_NAME = "note.db";
-
- /**
- * 数据库版本号
- *
- * 当前数据库版本为5,用于跟踪数据库结构变更。
- * 当数据库版本变更时,onUpgrade方法会被调用以执行升级逻辑。
- *
- */
- private static final int DB_VERSION = 5;
-
- /**
- * 数据库表名常量接口
- */
- public interface TABLE {
- /**
- * 笔记表名
- *
- * 存储笔记和文件夹的基本信息,包括ID、父文件夹ID、创建时间、修改时间、
- * 背景颜色、提醒时间、附件状态、笔记数量、摘要、类型、Widget信息、
- * 同步ID、本地修改状态、原始父文件夹ID、GTASK ID、版本等字段。
- *
- */
- public static final String NOTE = "note";
-
- /**
- * 数据表名
- *
- * 存储笔记的详细内容,支持多种MIME类型(文本、图片、附件等)。
- * 每条数据记录关联到一条笔记,包含MIME类型、内容、以及5个通用数据字段。
- *
- */
- public static final String DATA = "data";
- }
-
- /**
- * 日志标签
- */
- private static final String TAG = "NotesDatabaseHelper";
-
- /**
- * 数据库帮助类单例实例
- *
- * 使用单例模式确保全局只有一个数据库帮助类实例,
- * 避免多个实例同时操作数据库导致的数据不一致问题。
- *
- */
- private static NotesDatabaseHelper mInstance;
-
- /**
- * 创建笔记表的SQL语句
- *
- * 创建note表,包含以下字段:
- *
- * ID: 主键,自增
- * PARENT_ID: 父文件夹ID,默认为0
- * ALERTED_DATE: 提醒时间,默认为0
- * BG_COLOR_ID: 背景颜色ID,默认为0
- * CREATED_DATE: 创建时间,默认为当前时间戳
- * HAS_ATTACHMENT: 是否有附件,默认为0
- * MODIFIED_DATE: 修改时间,默认为当前时间戳
- * NOTES_COUNT: 笔记数量,默认为0(仅文件夹有效)
- * SNIPPET: 笔记摘要,默认为空字符串
- * TYPE: 类型(0=普通笔记,1=文件夹,2=系统),默认为0
- * WIDGET_ID: Widget ID,默认为0
- * WIDGET_TYPE: Widget类型,默认为-1
- * SYNC_ID: 同步ID,默认为0
- * LOCAL_MODIFIED: 本地修改标志,默认为0
- * ORIGIN_PARENT_ID: 原始父文件夹ID,默认为0
- * GTASK_ID: Google Tasks ID,默认为空字符串
- * VERSION: 版本号,默认为0
- *
- *
- */
- private static final String CREATE_NOTE_TABLE_SQL =
- "CREATE TABLE " + TABLE.NOTE + "(" +
- NoteColumns.ID + " INTEGER PRIMARY KEY," +
- NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
- NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
- NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
- NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
- NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
- NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
- ")";
-
- /**
- * 创建数据表的SQL语句
- *
- * 创建data表,包含以下字段:
- *
- * ID: 主键,自增
- * MIME_TYPE: MIME类型,不能为空
- * NOTE_ID: 关联的笔记ID,默认为0
- * CREATED_DATE: 创建时间,默认为当前时间戳
- * MODIFIED_DATE: 修改时间,默认为当前时间戳
- * CONTENT: 内容,默认为空字符串
- * DATA1-5: 通用数据字段,用于存储不同类型的数据
- *
- *
- */
- private static final String CREATE_DATA_TABLE_SQL =
- "CREATE TABLE " + TABLE.DATA + "(" +
- DataColumns.ID + " INTEGER PRIMARY KEY," +
- DataColumns.MIME_TYPE + " TEXT NOT NULL," +
- DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
- NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
- NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
- DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
- DataColumns.DATA1 + " INTEGER," +
- DataColumns.DATA2 + " INTEGER," +
- DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
- DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
- DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
- ")";
-
- /**
- * 创建数据表索引的SQL语句
- *
- * 在data表的NOTE_ID字段上创建索引,提高按笔记ID查询数据的效率。
- *
- */
- private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
- "CREATE INDEX IF NOT EXISTS note_id_index ON " +
- TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
-
- /**
- * Increase folder's note count when move note to the folder
- */
- private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
- "CREATE TRIGGER increase_folder_count_on_update "+
- " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
- " BEGIN " +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
- " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
- " END";
-
- /**
- * Decrease folder's note count when move note from folder
- */
- private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
- "CREATE TRIGGER decrease_folder_count_on_update " +
- " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
- " BEGIN " +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
- " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
- " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
- " END";
-
- /**
- * Increase folder's note count when insert new note to the folder
- */
- private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
- "CREATE TRIGGER increase_folder_count_on_insert " +
- " AFTER INSERT ON " + TABLE.NOTE +
- " BEGIN " +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
- " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
- " END";
-
- /**
- * Decrease folder's note count when delete note from the folder
- */
- private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
- "CREATE TRIGGER decrease_folder_count_on_delete " +
- " AFTER DELETE ON " + TABLE.NOTE +
- " BEGIN " +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
- " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
- " AND " + NoteColumns.NOTES_COUNT + ">0;" +
- " END";
-
- /**
- * Update note's content when insert data with type {@link DataConstants#NOTE}
- */
- private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
- "CREATE TRIGGER update_note_content_on_insert " +
- " AFTER INSERT ON " + TABLE.DATA +
- " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
- " BEGIN" +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
- " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
- " END";
-
- /**
- * Update note's content when data with {@link DataConstants#NOTE} type has changed
- */
- private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
- "CREATE TRIGGER update_note_content_on_update " +
- " AFTER UPDATE ON " + TABLE.DATA +
- " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
- " BEGIN" +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
- " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
- " END";
-
- /**
- * Update note's content when data with {@link DataConstants#NOTE} type has deleted
- */
- private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
- "CREATE TRIGGER update_note_content_on_delete " +
- " AFTER delete ON " + TABLE.DATA +
- " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
- " BEGIN" +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.SNIPPET + "=''" +
- " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
- " END";
-
- /**
- * Delete datas belong to note which has been deleted
- */
- private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
- "CREATE TRIGGER delete_data_on_delete " +
- " AFTER DELETE ON " + TABLE.NOTE +
- " BEGIN" +
- " DELETE FROM " + TABLE.DATA +
- " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
- " END";
-
- /**
- * Delete notes belong to folder which has been deleted
- */
- private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
- "CREATE TRIGGER folder_delete_notes_on_delete " +
- " AFTER DELETE ON " + TABLE.NOTE +
- " BEGIN" +
- " DELETE FROM " + TABLE.NOTE +
- " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
- " END";
-
- /**
- * Move notes belong to folder which has been moved to trash folder
- */
- private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
- "CREATE TRIGGER folder_move_notes_on_trash " +
- " AFTER UPDATE ON " + TABLE.NOTE +
- " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
- " BEGIN" +
- " UPDATE " + TABLE.NOTE +
- " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
- " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
- " END";
-
- /**
- * 构造器
- *
- * @param context 应用上下文
- */
- public NotesDatabaseHelper(Context context) {
- super(context, DB_NAME, null, DB_VERSION);
- }
-
- /**
- * 创建笔记表
- *
- * 执行创建note表的SQL语句,创建相关触发器,并初始化系统文件夹。
- *
- *
- * @param db SQLiteDatabase实例
- */
- public void createNoteTable(SQLiteDatabase db) {
- db.execSQL(CREATE_NOTE_TABLE_SQL);
- reCreateNoteTableTriggers(db);
- createSystemFolder(db);
- Log.d(TAG, "note table has been created");
- }
-
- /**
- * 重新创建笔记表触发器
- *
- * 先删除所有已存在的note表相关触发器,然后重新创建所有触发器。
- * 用于在数据库升级时更新触发器逻辑。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void reCreateNoteTableTriggers(SQLiteDatabase db) {
- // 删除所有已存在的触发器
- db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
- db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
- db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
- db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
- db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
- db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
- db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
-
- // 重新创建所有触发器
- db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
- db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
- db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
- db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
- db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
- db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
- db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
- }
-
- /**
- * 创建系统文件夹
- *
- * 在note表中创建四个系统文件夹:
- *
- * 通话记录文件夹(ID_CALL_RECORD_FOLDER)
- * 根文件夹(ID_ROOT_FOLDER)
- * 临时文件夹(ID_TEMPARAY_FOLDER)
- * 回收站文件夹(ID_TRASH_FOLER)
- *
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void createSystemFolder(SQLiteDatabase db) {
- ContentValues values = new ContentValues();
-
- /**
- * call record foler for call notes
- */
- // 创建通话记录文件夹
- values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
-
- /**
- * root folder which is default folder
- */
- // 创建根文件夹(默认文件夹)
- values.clear();
- values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
-
- /**
- * temporary folder which is used for moving note
- */
- // 创建临时文件夹(用于移动笔记)
- values.clear();
- values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
-
- /**
- * create trash folder
- */
- // 创建回收站文件夹
- values.clear();
- values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
- }
-
- /**
- * 创建数据表
- *
- * 执行创建data表的SQL语句,创建相关触发器,并创建索引。
- *
- *
- * @param db SQLiteDatabase实例
- */
- public void createDataTable(SQLiteDatabase db) {
- db.execSQL(CREATE_DATA_TABLE_SQL);
- reCreateDataTableTriggers(db);
- db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
- Log.d(TAG, "data table has been created");
- }
-
- /**
- * 重新创建数据表触发器
- *
- * 先删除所有已存在的data表相关触发器,然后重新创建所有触发器。
- * 用于在数据库升级时更新触发器逻辑。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void reCreateDataTableTriggers(SQLiteDatabase db) {
- // 删除所有已存在的触发器
- db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
- db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
- db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
-
- // 重新创建所有触发器
- db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
- db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
- db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
- }
-
- /**
- * 获取数据库帮助类单例实例
- *
- * 使用双重检查锁定模式确保线程安全的单例实现。
- *
- *
- * @param context 应用上下文
- * @return NotesDatabaseHelper单例实例
- */
- public static synchronized NotesDatabaseHelper getInstance(Context context) {
- if (mInstance == null) {
- mInstance = new NotesDatabaseHelper(context);
- }
- return mInstance;
- }
-
- /**
- * 创建数据库
- *
- * 当数据库文件不存在时调用,创建note表和data表。
- *
- *
- * @param db SQLiteDatabase实例
- */
- @Override
- public void onCreate(SQLiteDatabase db) {
- createNoteTable(db);
- createDataTable(db);
- }
-
- /**
- * 升级数据库
- *
- * 当数据库版本号增加时调用,执行从旧版本到新版本的升级逻辑。
- * 支持增量升级,从当前版本逐步升级到目标版本。
- *
- *
- * @param db SQLiteDatabase实例
- * @param oldVersion 当前数据库版本号
- * @param newVersion 目标数据库版本号
- * @throws IllegalStateException 如果升级失败
- */
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- boolean reCreateTriggers = false;
- boolean skipV2 = false;
-
- // 从V1升级到V2(包括V2到V3)
- if (oldVersion == 1) {
- upgradeToV2(db);
- skipV2 = true; // this upgrade including the upgrade from v2 to v3
- oldVersion++;
- }
-
- // 从V2升级到V3
- if (oldVersion == 2 && !skipV2) {
- upgradeToV3(db);
- reCreateTriggers = true;
- oldVersion++;
- }
-
- // 从V3升级到V4
- if (oldVersion == 3) {
- upgradeToV4(db);
- oldVersion++;
- }
-
- // 如果需要,重新创建触发器
- if (reCreateTriggers) {
- reCreateNoteTableTriggers(db);
- reCreateDataTableTriggers(db);
- }
-
- // 检查升级是否成功
- if (oldVersion != newVersion) {
- throw new IllegalStateException("Upgrade notes database to version " + newVersion
- + "fails");
- }
- }
-
- /**
- * 升级数据库到V2版本
- *
- * 删除旧表并重新创建note表和data表。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void upgradeToV2(SQLiteDatabase db) {
- db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
- db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
- createNoteTable(db);
- createDataTable(db);
- }
-
- /**
- * 升级数据库到V3版本
- *
- * 添加GTASK_ID列到note表,并创建回收站系统文件夹。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void upgradeToV3(SQLiteDatabase db) {
- // drop unused triggers
- // 删除未使用的触发器
- db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
- db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
- db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
- // add a column for gtask id
- // 添加GTASK_ID列
- db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
- + " TEXT NOT NULL DEFAULT ''");
- // add a trash system folder
- // 添加回收站系统文件夹
- ContentValues values = new ContentValues();
- values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
- }
-
- /**
- * 升级数据库到V4版本
- *
- * 添加VERSION列到note表,用于跟踪笔记版本。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void upgradeToV4(SQLiteDatabase db) {
- db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
- + " INTEGER NOT NULL DEFAULT 0");
- }
-
- /**
- * 升级数据库到V5版本
- *
- * 添加TOP列到note表,用于标记笔记是否置顶。
- *
- *
- * @param db SQLiteDatabase实例
- */
- private void upgradeToV5(SQLiteDatabase db) {
- db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.TOP
- + " INTEGER NOT NULL DEFAULT 0");
- }
-}
diff --git a/app/src/main/java/net/micode/notes/data/NotesProvider.java b/app/src/main/java/net/micode/notes/data/NotesProvider.java
deleted file mode 100644
index aa2cf34..0000000
--- a/app/src/main/java/net/micode/notes/data/NotesProvider.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-
-import android.app.SearchManager;
-import android.content.ContentProvider;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Intent;
-import android.content.UriMatcher;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.net.Uri;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.NotesDatabaseHelper.TABLE;
-
-
-/**
- * 笔记Content Provider
- *
- * 继承自ContentProvider,提供对笔记数据的增删改查(CRUD)操作。
- * 管理note表和data表的数据访问,支持URI匹配、数据查询、插入、更新和删除操作。
- * 同时提供搜索建议功能,支持全局搜索笔记内容。
- *
- *
- * 主要功能:
- *
- * URI路由匹配,支持多种URI模式
- * 笔记和数据的查询操作
- * 笔记和数据的插入操作
- * 笔记和数据的更新操作
- * 笔记和数据的删除操作
- * 全局搜索和搜索建议功能
- * 数据变更通知
- * 笔记版本号自动递增
- *
- *
- *
- * 支持的URI模式:
- *
- * content://micode_notes/note - 查询所有笔记
- * content://micode_notes/note/# - 查询指定ID的笔记
- * content://micode_notes/data - 查询所有数据
- * content://micode_notes/data/# - 查询指定ID的数据
- * content://micode_notes/search - 搜索笔记
- * content://micode_notes/search_suggest_query - 搜索建议
- *
- *
- *
- * @see ContentProvider
- * @see NotesDatabaseHelper
- * @see Notes
- */
-public class NotesProvider extends ContentProvider {
- /**
- * URI匹配器
- *
- * 用于匹配不同的URI模式,将请求路由到对应的处理逻辑。
- * 支持笔记、数据、搜索等多种URI模式。
- *
- */
- private static final UriMatcher mMatcher;
-
- /**
- * 数据库帮助类实例
- *
- * 用于获取可读和可写的SQLiteDatabase实例。
- *
- */
- private NotesDatabaseHelper mHelper;
-
- /**
- * 日志标签
- */
- private static final String TAG = "NotesProvider";
-
- /**
- * 笔记URI匹配码
- */
- private static final int URI_NOTE = 1;
- /**
- * 笔记项URI匹配码
- */
- private static final int URI_NOTE_ITEM = 2;
- /**
- * 数据URI匹配码
- */
- private static final int URI_DATA = 3;
- /**
- * 数据项URI匹配码
- */
- private static final int URI_DATA_ITEM = 4;
-
- /**
- * 搜索URI匹配码
- */
- private static final int URI_SEARCH = 5;
- /**
- * 搜索建议URI匹配码
- */
- private static final int URI_SEARCH_SUGGEST = 6;
-
- /**
- * URI匹配器初始化块
- *
- * 初始化UriMatcher,注册所有支持的URI模式。
- *
- */
- static {
- mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
- mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
- mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
- mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
- mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
- mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
- mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
- mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
- }
-
- /**
- * 搜索结果投影
- *
- * 定义搜索建议返回的列,包括笔记ID、文本内容、图标、Intent动作等。
- * 使用TRIM和REPLACE函数去除换行符和空白字符,以便更好地显示搜索结果。
- *
- *
- * x'0A'代表SQLite中的换行符'\n'。对于搜索结果中的标题和内容,
- * 我们会去除换行符和空白字符,以显示更多信息。
- *
- */
- private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
- + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
- + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
- + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
- + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
- + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
- + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
-
- /**
- * 笔记摘要搜索查询SQL语句
- *
- * 搜索note表中SNIPPET字段包含指定关键词的笔记。
- * 排除回收站中的笔记(PARENT_ID不等于ID_TRASH_FOLER)。
- * 只搜索普通笔记(TYPE等于TYPE_NOTE)。
- *
- */
- private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
- + " FROM " + TABLE.NOTE
- + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
- + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
- + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
-
- /**
- * 创建Content Provider
- *
- * 初始化数据库帮助类实例。
- *
- *
- * @return true表示创建成功
- */
- @Override
- public boolean onCreate() {
- mHelper = NotesDatabaseHelper.getInstance(getContext());
- return true;
- }
-
- /**
- * 查询数据
- *
- * 根据URI模式查询对应的数据表,支持笔记、数据、搜索等多种查询模式。
- * 对于搜索模式,使用LIKE模糊匹配查询笔记摘要。
- *
- *
- * @param uri 查询的URI
- * @param projection 要查询的列数组
- * @param selection 查询条件
- * @param selectionArgs 查询条件参数
- * @param sortOrder 排序方式
- * @return 查询结果的Cursor对象
- * @throws IllegalArgumentException 如果URI模式不支持或搜索时指定了不允许的参数
- */
- @Override
- public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
- String sortOrder) {
- Cursor c = null;
- SQLiteDatabase db = mHelper.getReadableDatabase();
- String id = null;
- switch (mMatcher.match(uri)) {
- case URI_NOTE:
- // 查询所有笔记
- c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
- sortOrder);
- break;
- case URI_NOTE_ITEM:
- // 查询指定ID的笔记
- id = uri.getPathSegments().get(1);
- c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
- + parseSelection(selection), selectionArgs, null, null, sortOrder);
- break;
- case URI_DATA:
- // 查询所有数据
- c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
- sortOrder);
- break;
- case URI_DATA_ITEM:
- // 查询指定ID的数据
- id = uri.getPathSegments().get(1);
- c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
- + parseSelection(selection), selectionArgs, null, null, sortOrder);
- break;
- case URI_SEARCH:
- case URI_SEARCH_SUGGEST:
- // 搜索笔记或搜索建议
- if (sortOrder != null || projection != null) {
- throw new IllegalArgumentException(
- "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
- }
-
- String searchString = null;
- if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
- // 从URI路径中获取搜索关键词
- if (uri.getPathSegments().size() > 1) {
- searchString = uri.getPathSegments().get(1);
- }
- } else {
- // 从查询参数中获取搜索关键词
- searchString = uri.getQueryParameter("pattern");
- }
-
- // 搜索关键词为空时返回null
- if (TextUtils.isEmpty(searchString)) {
- return null;
- }
-
- try {
- // 使用模糊匹配搜索笔记摘要
- searchString = String.format("%%%s%%", searchString);
- c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
- new String[] { searchString });
- } catch (IllegalStateException ex) {
- Log.e(TAG, "got exception: " + ex.toString());
- }
- break;
- default:
- throw new IllegalArgumentException("Unknown URI " + uri);
- }
- // 设置通知URI,当数据变更时通知观察者
- if (c != null) {
- c.setNotificationUri(getContext().getContentResolver(), uri);
- }
- return c;
- }
-
- /**
- * 插入数据
- *
- * 根据URI模式向对应的数据表插入数据,支持笔记和数据的插入。
- * 插入成功后通知相关URI的观察者。
- *
- *
- * @param uri 插入数据的URI
- * @param values 要插入的数据值
- * @return 插入数据的URI(包含新增记录的ID)
- * @throws IllegalArgumentException 如果URI模式不支持
- */
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- SQLiteDatabase db = mHelper.getWritableDatabase();
- long dataId = 0, noteId = 0, insertedId = 0;
- switch (mMatcher.match(uri)) {
- case URI_NOTE:
- // 插入笔记
- insertedId = noteId = db.insert(TABLE.NOTE, null, values);
- break;
- case URI_DATA:
- // 插入数据
- if (values.containsKey(DataColumns.NOTE_ID)) {
- noteId = values.getAsLong(DataColumns.NOTE_ID);
- } else {
- Log.d(TAG, "Wrong data format without note id:" + values.toString());
- }
- insertedId = dataId = db.insert(TABLE.DATA, null, values);
- break;
- default:
- throw new IllegalArgumentException("Unknown URI " + uri);
- }
- // Notify the note uri
- // 通知笔记URI的观察者
- if (noteId > 0) {
- getContext().getContentResolver().notifyChange(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
- }
-
- // Notify the data uri
- // 通知数据URI的观察者
- if (dataId > 0) {
- getContext().getContentResolver().notifyChange(
- ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
- }
-
- return ContentUris.withAppendedId(uri, insertedId);
- }
-
- /**
- * 删除数据
- *
- * 根据URI模式删除对应的数据表中的数据,支持笔记和数据的删除。
- * 删除笔记时,不允许删除系统文件夹(ID小于等于0)。
- * 删除成功后通知相关URI的观察者。
- *
- *
- * @param uri 删除数据的URI
- * @param selection 删除条件
- * @param selectionArgs 删除条件参数
- * @return 删除的记录数
- * @throws IllegalArgumentException 如果URI模式不支持
- */
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
- int count = 0;
- String id = null;
- SQLiteDatabase db = mHelper.getWritableDatabase();
- boolean deleteData = false;
- switch (mMatcher.match(uri)) {
- case URI_NOTE:
- // 删除笔记(排除系统文件夹)
- selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
- count = db.delete(TABLE.NOTE, selection, selectionArgs);
- break;
- case URI_NOTE_ITEM:
- // 删除指定ID的笔记
- id = uri.getPathSegments().get(1);
- /**
- * ID that smaller than 0 is system folder which is not allowed to
- * trash
- * ID小于等于0的是系统文件夹,不允许删除
- */
- long noteId = Long.valueOf(id);
- if (noteId <= 0) {
- break;
- }
- count = db.delete(TABLE.NOTE,
- NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
- break;
- case URI_DATA:
- // 删除数据
- count = db.delete(TABLE.DATA, selection, selectionArgs);
- deleteData = true;
- break;
- case URI_DATA_ITEM:
- // 删除指定ID的数据
- id = uri.getPathSegments().get(1);
- count = db.delete(TABLE.DATA,
- DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
- deleteData = true;
- break;
- default:
- throw new IllegalArgumentException("Unknown URI " + uri);
- }
- // 删除成功后通知观察者
- if (count > 0) {
- if (deleteData) {
- // 删除数据时通知笔记URI
- getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
- }
- getContext().getContentResolver().notifyChange(uri, null);
- }
- return count;
- }
-
- /**
- * 更新数据
- *
- * 根据URI模式更新对应的数据表中的数据,支持笔记和数据的更新。
- * 更新笔记时自动递增笔记的版本号。
- * 更新成功后通知相关URI的观察者。
- *
- *
- * @param uri 更新数据的URI
- * @param values 要更新的数据值
- * @param selection 更新条件
- * @param selectionArgs 更新条件参数
- * @return 更新的记录数
- * @throws IllegalArgumentException 如果URI模式不支持
- */
- @Override
- public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
- int count = 0;
- String id = null;
- SQLiteDatabase db = mHelper.getWritableDatabase();
- boolean updateData = false;
- switch (mMatcher.match(uri)) {
- case URI_NOTE:
- // 更新笔记(递增版本号)
- increaseNoteVersion(-1, selection, selectionArgs);
- count = db.update(TABLE.NOTE, values, selection, selectionArgs);
- break;
- case URI_NOTE_ITEM:
- // 更新指定ID的笔记(递增版本号)
- id = uri.getPathSegments().get(1);
- increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
- count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
- + parseSelection(selection), selectionArgs);
- break;
- case URI_DATA:
- // 更新数据
- count = db.update(TABLE.DATA, values, selection, selectionArgs);
- updateData = true;
- break;
- case URI_DATA_ITEM:
- // 更新指定ID的数据
- id = uri.getPathSegments().get(1);
- count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
- + parseSelection(selection), selectionArgs);
- updateData = true;
- break;
- default:
- throw new IllegalArgumentException("Unknown URI " + uri);
- }
-
- // 更新成功后通知观察者
- if (count > 0) {
- if (updateData) {
- // 更新数据时通知笔记URI
- getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
- }
- getContext().getContentResolver().notifyChange(uri, null);
- }
- return count;
- }
-
- /**
- * 解析查询条件
- *
- * 将查询条件与ID条件组合,用于构建完整的SQL WHERE子句。
- *
- *
- * @param selection 原始查询条件
- * @return 组合后的查询条件字符串
- */
- private String parseSelection(String selection) {
- return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
- }
-
- /**
- * 递增笔记版本号
- *
- * 更新指定笔记的VERSION字段,使其值加1。
- * 用于跟踪笔记的修改历史,支持同步功能。
- *
- *
- * @param id 笔记ID,如果小于等于0则使用selection条件
- * @param selection 查询条件
- * @param selectionArgs 查询条件参数
- */
- private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
- StringBuilder sql = new StringBuilder(120);
- sql.append("UPDATE ");
- sql.append(TABLE.NOTE);
- sql.append(" SET ");
- sql.append(NoteColumns.VERSION);
- sql.append("=" + NoteColumns.VERSION + "+1 ");
-
- // 构建WHERE子句
- if (id > 0 || !TextUtils.isEmpty(selection)) {
- sql.append(" WHERE ");
- }
- if (id > 0) {
- sql.append(NoteColumns.ID + "=" + String.valueOf(id));
- }
- if (!TextUtils.isEmpty(selection)) {
- String selectString = id > 0 ? parseSelection(selection) : selection;
- // 替换查询条件中的占位符
- for (String args : selectionArgs) {
- selectString = selectString.replaceFirst("\\?", args);
- }
- sql.append(selectString);
- }
-
- mHelper.getWritableDatabase().execSQL(sql.toString());
- }
-
- /**
- * 获取数据MIME类型
- *
- * 返回指定URI对应的数据MIME类型。
- *
- *
- * @param uri 数据URI
- * @return MIME类型字符串
- */
- @Override
- public String getType(Uri uri) {
- // TODO Auto-generated method stub
- return null;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/data/NotesRepository.java b/app/src/main/java/net/micode/notes/data/NotesRepository.java
deleted file mode 100644
index f100ee3..0000000
--- a/app/src/main/java/net/micode/notes/data/NotesRepository.java
+++ /dev/null
@@ -1,890 +0,0 @@
-/*
- * Copyright (c) 2025, Modern Notes Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-import net.micode.notes.model.Note;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-
-/**
- * 笔记数据仓库
- *
- * 负责数据访问逻辑,统一管理Content Provider和缓存
- * 提供笔记的增删改查、搜索、统计等功能
- *
- *
- * 使用Executor进行后台线程数据访问,避免阻塞UI线程
- *
- *
- * @see Note
- * @see Notes
- */
-public class NotesRepository {
-
- /**
- * 笔记信息类
- *
- * 存储从数据库查询的笔记基本信息
- *
- */
- public static class NoteInfo {
- public long id;
- public String title;
- public String snippet;
- public long parentId;
- public long createdDate;
- public long modifiedDate;
- public int type;
- public int localModified;
- public int bgColorId;
- public boolean isPinned; // 新增置顶字段
-
- public NoteInfo() {}
-
- public long getId() {
- return id;
- }
-
- public long getParentId() {
- return parentId;
- }
-
- public String getNoteDataValue() {
- return snippet;
- }
- }
- private static final String TAG = "NotesRepository";
-
- private final ContentResolver contentResolver;
- private final ExecutorService executor;
-
- // 选择条件常量
- private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + " = ?";
- private static final String ROOT_FOLDER_SELECTION = "(" +
- NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " +
- NoteColumns.PARENT_ID + "=?) OR (" +
- NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " +
- NoteColumns.NOTES_COUNT + ">0)";
-
- /**
- * 数据访问回调接口
- *
- * 统一的数据访问结果回调机制
- *
- *
- * @param 返回数据类型
- */
- public interface Callback {
- /**
- * 成功回调
- *
- * @param result 返回的结果数据
- */
- void onSuccess(T result);
-
- /**
- * 失败回调
- *
- * @param error 异常对象
- */
- void onError(Exception error);
- }
-
- /**
- * 从 Cursor 创建 NoteInfo 对象
- *
- * @param cursor 数据库游标
- * @return NoteInfo 对象
- */
- private NoteInfo noteFromCursor(Cursor cursor) {
- NoteInfo noteInfo = new NoteInfo();
- noteInfo.id = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.ID));
- noteInfo.title = cursor.getString(cursor.getColumnIndexOrThrow(NoteColumns.SNIPPET));
- noteInfo.snippet = cursor.getString(cursor.getColumnIndexOrThrow(NoteColumns.SNIPPET));
- noteInfo.parentId = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.PARENT_ID));
- noteInfo.createdDate = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.CREATED_DATE));
- noteInfo.modifiedDate = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.MODIFIED_DATE));
- noteInfo.type = cursor.getInt(cursor.getColumnIndexOrThrow(NoteColumns.TYPE));
- noteInfo.localModified = cursor.getInt(cursor.getColumnIndexOrThrow(NoteColumns.LOCAL_MODIFIED));
-
- int bgColorIdIndex = cursor.getColumnIndex(NoteColumns.BG_COLOR_ID);
- if (bgColorIdIndex != -1 && !cursor.isNull(bgColorIdIndex)) {
- noteInfo.bgColorId = cursor.getInt(bgColorIdIndex);
- } else {
- noteInfo.bgColorId = 0;
- }
-
- int topIndex = cursor.getColumnIndex(NoteColumns.TOP);
- if (topIndex != -1) {
- noteInfo.isPinned = cursor.getInt(topIndex) > 0;
- }
-
- return noteInfo;
- }
-
- /**
- * 构造函数
- *
- * 初始化ContentResolver和线程池
- *
- *
- * @param contentResolver Content解析器
- */
- public NotesRepository(ContentResolver contentResolver) {
- this.contentResolver = contentResolver;
- // 使用单线程Executor确保数据访问的顺序性
- this.executor = java.util.concurrent.Executors.newSingleThreadExecutor();
- Log.d(TAG, "NotesRepository initialized");
- }
-
- /**
- * 获取指定文件夹的笔记列表
- *
- * 支持根文件夹(显示所有笔记)和子文件夹两种模式
- *
- *
- * @param folderId 文件夹ID,{@link Notes#ID_ROOT_FOLDER} 表示根文件夹
- * @param callback 回调接口
- */
- public void getNotes(long folderId, Callback> callback) {
- executor.execute(() -> {
- try {
- List notes = queryNotes(folderId);
- callback.onSuccess(notes);
- Log.d(TAG, "Successfully loaded notes for folder: " + folderId);
- } catch (Exception e) {
- Log.e(TAG, "Failed to load notes for folder: " + folderId, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 查询笔记列表(内部方法)
- *
- * 同时返回文件夹和便签,文件夹显示在便签之前
- *
- *
- * @param folderId 文件夹ID
- * @return 笔记列表(包含文件夹和便签)
- */
- private List queryNotes(long folderId) {
- List notes = new ArrayList<>();
- List folders = new ArrayList<>();
- List normalNotes = new ArrayList<>();
-
- String selection;
- String[] selectionArgs;
-
- if (folderId == Notes.ID_ROOT_FOLDER) {
- // 根文件夹:显示所有文件夹和便签
- selection = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?) OR (" +
- NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)";
- selectionArgs = new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)};
- } else {
- // 子文件夹:显示该文件夹下的文件夹和便签
- selection = NoteColumns.PARENT_ID + "=? AND " + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM;
- selectionArgs = new String[]{String.valueOf(folderId)};
- }
-
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_NOTE_URI,
- null,
- selection,
- selectionArgs,
- NoteColumns.MODIFIED_DATE + " DESC"
- );
-
- if (cursor != null) {
- try {
- while (cursor.moveToNext()) {
- NoteInfo note = noteFromCursor(cursor);
- if (note.type == Notes.TYPE_FOLDER) {
- // 文件夹单独收集
- folders.add(note);
- } else if (note.type == Notes.TYPE_NOTE) {
- // 便签收集
- normalNotes.add(note);
- } else if (note.type == Notes.TYPE_SYSTEM && note.id == Notes.ID_CALL_RECORD_FOLDER) {
- // 通话记录文件夹
- folders.add(note);
- }
- }
- Log.d(TAG, "Query returned " + folders.size() + " folders and " + normalNotes.size() + " notes");
- } finally {
- cursor.close();
- }
- }
-
- // 文件夹按修改时间倒序排列
- folders.sort((a, b) -> Long.compare(b.modifiedDate, a.modifiedDate));
- // 便签按修改时间倒序排列
- normalNotes.sort((a, b) -> {
- // 首先按置顶状态排序(置顶在前)
- if (a.isPinned != b.isPinned) {
- return a.isPinned ? -1 : 1;
- }
- // 其次按修改时间倒序排列
- return Long.compare(b.modifiedDate, a.modifiedDate);
- });
-
- // 合并:文件夹在前,便签在后
- notes.addAll(folders);
- notes.addAll(normalNotes);
-
- return notes;
- }
-
- /**
- * 查询单个文件夹信息
- *
- * @param folderId 文件夹ID
- * @return 文件夹信息,如果不存在返回null
- */
- public NoteInfo getFolderInfo(long folderId) {
- if (folderId == Notes.ID_ROOT_FOLDER) {
- NoteInfo root = new NoteInfo();
- root.id = Notes.ID_ROOT_FOLDER;
- root.title = "我的便签";
- root.snippet = "我的便签";
- root.type = Notes.TYPE_FOLDER;
- return root;
- }
-
- String selection = NoteColumns.ID + "=?";
- String[] selectionArgs = new String[]{String.valueOf(folderId)};
-
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_NOTE_URI,
- null,
- selection,
- selectionArgs,
- null
- );
-
- if (cursor != null) {
- try {
- if (cursor.moveToFirst()) {
- return noteFromCursor(cursor);
- }
- } finally {
- cursor.close();
- }
- }
- return null;
- }
-
- /**
- * 查询文件夹的父文件夹ID(异步版本)
- *
- * @param folderId 文件夹ID
- * @param callback 回调接口,返回父文件夹ID
- */
- public void getParentFolderId(long folderId, Callback callback) {
- executor.execute(() -> {
- try {
- long parentId = getParentFolderId(folderId);
- callback.onSuccess(parentId);
- } catch (Exception e) {
- callback.onError(e);
- }
- });
- }
-
- /**
- * 查询文件夹的父文件夹ID
- *
- * @param folderId 文件夹ID
- * @return 父文件夹ID,如果不存在返回根文件夹ID
- */
- public long getParentFolderId(long folderId) {
- if (folderId == Notes.ID_ROOT_FOLDER || folderId == Notes.ID_CALL_RECORD_FOLDER) {
- return Notes.ID_ROOT_FOLDER;
- }
-
- NoteInfo folder = getFolderInfo(folderId);
- if (folder != null) {
- return folder.parentId;
- }
- return Notes.ID_ROOT_FOLDER;
- }
-
- /**
- * 获取文件夹路径(从根到当前)
- *
- * @param folderId 当前文件夹ID
- * @return 文件夹路径列表(从根到当前)
- */
- public List getFolderPath(long folderId) {
- List path = new ArrayList<>();
- long currentId = folderId;
-
- while (currentId != Notes.ID_ROOT_FOLDER) {
- NoteInfo folder = getFolderInfo(currentId);
- if (folder == null) {
- break;
- }
- path.add(0, folder); // 添加到列表头部
- currentId = folder.parentId;
- }
-
- // 添加根文件夹
- NoteInfo root = new NoteInfo();
- root.id = Notes.ID_ROOT_FOLDER;
- root.title = "我的便签";
- root.snippet = "我的便签";
- root.type = Notes.TYPE_FOLDER;
- path.add(0, root);
-
- return path;
- }
-
- /**
- * 获取文件夹路径(异步版本)
- *
- * @param folderId 当前文件夹ID
- * @param callback 回调接口,返回文件夹路径列表
- */
- public void getFolderPath(long folderId, Callback> callback) {
- executor.execute(() -> {
- try {
- List path = getFolderPath(folderId);
- callback.onSuccess(path);
- } catch (Exception e) {
- callback.onError(e);
- }
- });
- }
-
- /**
- * 创建新文件夹
- *
- * @param parentId 父文件夹ID
- * @param name 文件夹名称
- * @param callback 回调接口,返回新文件夹的ID
- */
- public void createFolder(long parentId, String name, Callback callback) {
- executor.execute(() -> {
- try {
- ContentValues values = new ContentValues();
- long currentTime = System.currentTimeMillis();
-
- values.put(NoteColumns.PARENT_ID, parentId);
- values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(NoteColumns.SNIPPET, name);
- values.put(NoteColumns.CREATED_DATE, currentTime);
- values.put(NoteColumns.MODIFIED_DATE, currentTime);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- values.put(NoteColumns.NOTES_COUNT, 0);
-
- Uri uri = contentResolver.insert(Notes.CONTENT_NOTE_URI, values);
-
- Long folderId = 0L;
- if (uri != null) {
- try {
- folderId = ContentUris.parseId(uri);
- } catch (Exception e) {
- Log.e(TAG, "Failed to parse folder ID from URI", e);
- }
- }
-
- callback.onSuccess(folderId);
- Log.d(TAG, "Successfully created folder: " + name + " with ID: " + folderId);
- } catch (Exception e) {
- Log.e(TAG, "Failed to create folder: " + name, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 创建新笔记
- *
- * 在指定文件夹下创建一个空笔记
- *
- *
- * @param folderId 父文件夹ID
- * @param callback 回调接口,返回新笔记的ID
- */
- public void createNote(long folderId, Callback callback) {
- executor.execute(() -> {
- try {
- ContentValues values = new ContentValues();
- long currentTime = System.currentTimeMillis();
-
- values.put(NoteColumns.PARENT_ID, folderId);
- values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- values.put(NoteColumns.CREATED_DATE, currentTime);
- values.put(NoteColumns.MODIFIED_DATE, currentTime);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- values.put(NoteColumns.SNIPPET, "");
-
- Uri uri = contentResolver.insert(Notes.CONTENT_NOTE_URI, values);
-
- Long noteId = 0L;
- if (uri != null) {
- try {
- noteId = ContentUris.parseId(uri);
- } catch (Exception e) {
- Log.e(TAG, "Failed to parse note ID from URI", e);
- }
- }
-
- if (noteId > 0) {
- callback.onSuccess(noteId);
- Log.d(TAG, "Successfully created note with ID: " + noteId);
- } else {
- callback.onError(new IllegalStateException("Failed to create note, invalid ID returned"));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to create note", e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 更新笔记内容
- *
- * 更新笔记的标题和内容,自动更新修改时间和本地修改标志
- *
- *
- * @param noteId 笔记ID
- * @param content 笔记内容
- * @param callback 回调接口,返回影响的行数
- */
- public void updateNote(long noteId, String content, Callback callback) {
- executor.execute(() -> {
- try {
- ContentValues values = new ContentValues();
- long currentTime = System.currentTimeMillis();
-
- values.put(NoteColumns.SNIPPET, extractSnippet(content));
- values.put(NoteColumns.MODIFIED_DATE, currentTime);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
-
- Uri uri = ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- int rows = contentResolver.update(uri, values, null, null);
-
- if (rows > 0) {
- // 查询现有的文本数据记录
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_DATA_URI,
- new String[]{DataColumns.ID},
- DataColumns.NOTE_ID + " = ? AND " + DataColumns.MIME_TYPE + " = ?",
- new String[]{String.valueOf(noteId), TextNote.CONTENT_ITEM_TYPE},
- null
- );
-
- long dataId = 0;
- if (cursor != null) {
- try {
- if (cursor.moveToFirst()) {
- dataId = cursor.getLong(cursor.getColumnIndexOrThrow(DataColumns.ID));
- }
- } finally {
- cursor.close();
- }
- }
-
- // 更新或插入文本数据
- ContentValues dataValues = new ContentValues();
- dataValues.put(DataColumns.CONTENT, content);
-
- if (dataId > 0) {
- // 更新现有记录
- Uri dataUri = ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId);
- int dataRows = contentResolver.update(dataUri, dataValues, null, null);
- if (dataRows > 0) {
- callback.onSuccess(rows);
- Log.d(TAG, "Successfully updated note: " + noteId);
- } else {
- callback.onError(new RuntimeException("Failed to update note data"));
- }
- } else {
- // 插入新记录
- dataValues.put(DataColumns.NOTE_ID, noteId);
- dataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
- Uri dataUri = contentResolver.insert(Notes.CONTENT_DATA_URI, dataValues);
- if (dataUri != null) {
- callback.onSuccess(rows);
- Log.d(TAG, "Successfully updated note: " + noteId);
- } else {
- callback.onError(new RuntimeException("Failed to insert note data"));
- }
- }
- } else {
- callback.onError(new RuntimeException("No note found with ID: " + noteId));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to update note: " + noteId, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 删除笔记
- *
- * 将笔记移动到回收站文件夹
- *
- *
- * @param noteId 笔记ID
- * @param callback 回调接口,返回影响的行数
- */
- public void deleteNote(long noteId, Callback callback) {
- executor.execute(() -> {
- try {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
-
- Uri uri = ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- int rows = contentResolver.update(uri, values, null, null);
-
- if (rows > 0) {
- callback.onSuccess(rows);
- Log.d(TAG, "Successfully moved note to trash: " + noteId);
- } else {
- callback.onError(new RuntimeException("No note found with ID: " + noteId));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to delete note: " + noteId, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 批量删除笔记
- *
- * 将多个笔记移动到回收站文件夹
- *
- *
- * @param noteIds 笔记ID列表
- * @param callback 回调接口,返回影响的行数
- */
- public void deleteNotes(List noteIds, Callback callback) {
- executor.execute(() -> {
- try {
- if (noteIds == null || noteIds.isEmpty()) {
- callback.onError(new IllegalArgumentException("Note IDs list is empty"));
- return;
- }
-
- int totalRows = 0;
- for (Long noteId : noteIds) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
-
- Uri uri = ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- int rows = contentResolver.update(uri, values, null, null);
- totalRows += rows;
- }
-
- if (totalRows > 0) {
- callback.onSuccess(totalRows);
- Log.d(TAG, "Successfully moved " + totalRows + " notes to trash");
- } else {
- callback.onError(new RuntimeException("No notes were deleted"));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to batch delete notes", e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 搜索笔记
- *
- * 根据关键字在标题和内容中搜索笔记
- *
- *
- * @param keyword 搜索关键字
- * @param callback 回调接口
- */
- public void searchNotes(String keyword, Callback> callback) {
- executor.execute(() -> {
- try {
- if (keyword == null || keyword.trim().isEmpty()) {
- callback.onSuccess(new ArrayList<>());
- return;
- }
-
- String selection = "(" + NoteColumns.TYPE + " = ?) AND (" +
- NoteColumns.SNIPPET + " LIKE ? OR " +
- NoteColumns.ID + " IN (SELECT " + DataColumns.NOTE_ID +
- " FROM data WHERE " + DataColumns.CONTENT + " LIKE ?))";
-
- String[] selectionArgs = new String[]{
- String.valueOf(Notes.TYPE_NOTE),
- "%" + keyword + "%",
- "%" + keyword + "%"
- };
-
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_NOTE_URI,
- null,
- selection,
- selectionArgs,
- NoteColumns.MODIFIED_DATE + " DESC"
- );
-
- List notes = new ArrayList<>();
- if (cursor != null) {
- try {
- while (cursor.moveToNext()) {
- notes.add(noteFromCursor(cursor));
- }
- Log.d(TAG, "Search returned " + cursor.getCount() + " results for: " + keyword);
- } finally {
- cursor.close();
- }
- }
-
- callback.onSuccess(notes);
- } catch (Exception e) {
- Log.e(TAG, "Failed to search notes: " + keyword, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 获取笔记统计信息
- *
- * 统计指定文件夹下的笔记数量
- *
- *
- * @param folderId 文件夹ID
- * @param callback 回调接口
- */
- public void countNotes(long folderId, Callback callback) {
- executor.execute(() -> {
- try {
- String selection;
- String[] selectionArgs;
-
- if (folderId == Notes.ID_ROOT_FOLDER) {
- selection = NoteColumns.TYPE + " != ?";
- selectionArgs = new String[]{String.valueOf(Notes.TYPE_FOLDER)};
- } else {
- selection = NoteColumns.PARENT_ID + " = ?";
- selectionArgs = new String[]{String.valueOf(folderId)};
- }
-
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_NOTE_URI,
- new String[]{"COUNT(*) AS count"},
- selection,
- selectionArgs,
- null
- );
-
- int count = 0;
- if (cursor != null) {
- try {
- if (cursor.moveToFirst()) {
- count = cursor.getInt(0);
- }
- } finally {
- cursor.close();
- }
- }
-
- callback.onSuccess(count);
- Log.d(TAG, "Counted " + count + " notes in folder: " + folderId);
- } catch (Exception e) {
- Log.e(TAG, "Failed to count notes in folder: " + folderId, e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 获取文件夹列表
- *
- * 查询所有文件夹类型的笔记
- *
- *
- * @param callback 回调接口
- */
- public void getFolders(Callback> callback) {
- executor.execute(() -> {
- try {
- String selection = NoteColumns.TYPE + " = ?";
- String[] selectionArgs = new String[]{
- String.valueOf(Notes.TYPE_FOLDER)
- };
-
- Cursor cursor = contentResolver.query(
- Notes.CONTENT_NOTE_URI,
- null,
- selection,
- selectionArgs,
- NoteColumns.MODIFIED_DATE + " DESC"
- );
-
- List folders = new ArrayList<>();
- if (cursor != null) {
- try {
- while (cursor.moveToNext()) {
- folders.add(noteFromCursor(cursor));
- }
- Log.d(TAG, "Found " + cursor.getCount() + " folders");
- } finally {
- cursor.close();
- }
- }
-
- callback.onSuccess(folders);
- } catch (Exception e) {
- Log.e(TAG, "Failed to load folders", e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 批量移动笔记到指定文件夹
- *
- * 将笔记从当前文件夹移动到目标文件夹
- *
- *
- * @param noteIds 要移动的笔记ID列表
- * @param targetFolderId 目标文件夹ID
- * @param callback 回调接口
- */
- public void moveNotes(List noteIds, long targetFolderId, Callback callback) {
- executor.execute(() -> {
- try {
- if (noteIds == null || noteIds.isEmpty()) {
- callback.onError(new IllegalArgumentException("Note IDs list is empty"));
- return;
- }
-
- int totalRows = 0;
- for (Long noteId : noteIds) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.PARENT_ID, targetFolderId);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
-
- Uri uri = ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- int rows = contentResolver.update(uri, values, null, null);
- totalRows += rows;
- }
-
- if (totalRows > 0) {
- callback.onSuccess(totalRows);
- Log.d(TAG, "Successfully moved " + totalRows + " notes to folder: " + targetFolderId);
- } else {
- callback.onError(new RuntimeException("No notes were moved"));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to move notes", e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 批量更新笔记置顶状态
- *
- * @param noteIds 笔记ID列表
- * @param isPinned 是否置顶
- * @param callback 回调接口
- */
- public void batchTogglePin(List noteIds, boolean isPinned, Callback callback) {
- executor.execute(() -> {
- try {
- if (noteIds == null || noteIds.isEmpty()) {
- callback.onError(new IllegalArgumentException("Note IDs list is empty"));
- return;
- }
-
- int totalRows = 0;
- ContentValues values = new ContentValues();
- values.put(NoteColumns.TOP, isPinned ? 1 : 0);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
-
- for (Long noteId : noteIds) {
- Uri uri = ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- int rows = contentResolver.update(uri, values, null, null);
- totalRows += rows;
- }
-
- if (totalRows > 0) {
- callback.onSuccess(totalRows);
- Log.d(TAG, "Successfully updated pin state for " + totalRows + " notes");
- } else {
- callback.onError(new RuntimeException("No notes were updated"));
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to update pin state", e);
- callback.onError(e);
- }
- });
- }
-
- /**
- * 从内容中提取摘要
- *
- * @param content 笔记内容
- * @return 摘要文本(最多100个字符)
- */
- private String extractSnippet(String content) {
- if (content == null || content.isEmpty()) {
- return "";
- }
- int maxLength = 100;
- return content.length() > maxLength
- ? content.substring(0, maxLength)
- : content;
- }
-
- /**
- * 关闭Executor
- *
- * 在不再需要数据访问时调用,释放线程池资源
- *
- */
- public void shutdown() {
- if (executor != null && !executor.isShutdown()) {
- executor.shutdown();
- Log.d(TAG, "Executor shutdown");
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/app/src/main/java/net/micode/notes/gtask/data/MetaData.java
deleted file mode 100644
index 28f6294..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-import android.util.Log;
-
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-
-/**
- * Google Tasks 元数据类
- *
- * 继承自 Task,用于存储和管理 Google Tasks 同步的元数据信息。
- * 元数据以特殊任务的形式存储在 Google Tasks 中,用于关联本地笔记和远程任务的对应关系。
- * 该类不应通过本地 JSON 或数据库游标进行操作,仅用于远程同步场景。
- *
- */
-public class MetaData extends Task {
- /**
- * 日志标签
- */
- private final static String TAG = MetaData.class.getSimpleName();
-
- /**
- * 关联的 Google Tasks ID
- */
- private String mRelatedGid = null;
-
- /**
- * 设置元数据信息
- *
- * 将 Google Tasks ID 添加到元信息 JSON 对象中,并设置任务名称为元数据专用名称。
- * 元信息以 JSON 字符串形式存储在任务的 notes 字段中。
- *
- *
- * @param gid 关联的 Google Tasks ID
- * @param metaInfo 元信息 JSON 对象
- */
- public void setMeta(String gid, JSONObject metaInfo) {
- try {
- // 将关联的 GID 添加到元信息中
- metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
- } catch (JSONException e) {
- Log.e(TAG, "failed to put related gid");
- }
- // 将元信息转换为字符串并设置为任务备注
- setNotes(metaInfo.toString());
- // 设置为元数据专用名称
- setName(GTaskStringUtils.META_NOTE_NAME);
- }
-
- /**
- * 获取关联的 Google Tasks ID
- *
- * @return 关联的 Google Tasks ID,如果未设置则返回 null
- */
- public String getRelatedGid() {
- return mRelatedGid;
- }
-
- /**
- * 判断是否值得保存
- *
- * 只有当 notes 字段不为空时才值得保存,因为元数据信息存储在 notes 中。
- *
- *
- * @return 如果 notes 不为 null 返回 true,否则返回 false
- */
- @Override
- public boolean isWorthSaving() {
- return getNotes() != null;
- }
-
- /**
- * 根据远程 JSON 设置内容
- *
- * 从远程服务器返回的 JSON 对象中解析元数据信息,提取关联的 Google Tasks ID。
- *
- *
- * @param js 远程服务器返回的 JSON 对象
- */
- @Override
- public void setContentByRemoteJSON(JSONObject js) {
- super.setContentByRemoteJSON(js);
- if (getNotes() != null) {
- try {
- // 从 notes 字段中解析元信息 JSON
- JSONObject metaInfo = new JSONObject(getNotes().trim());
- // 提取关联的 GID
- mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
- } catch (JSONException e) {
- Log.w(TAG, "failed to get related gid");
- mRelatedGid = null;
- }
- }
- }
-
- /**
- * 根据本地 JSON 设置内容
- *
- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。
- *
- *
- * @param js 本地 JSON 对象
- * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法
- */
- @Override
- public void setContentByLocalJSON(JSONObject js) {
- // this function should not be called
- throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
- }
-
- /**
- * 从内容生成本地 JSON 对象
- *
- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。
- *
- *
- * @return 无返回值,总是抛出异常
- * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法
- */
- @Override
- public JSONObject getLocalJSONFromContent() {
- throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
- }
-
- /**
- * 根据数据库游标获取同步动作
- *
- * 此方法不应被调用,因为元数据不通过数据库游标进行操作。
- *
- *
- * @param c 数据库游标
- * @return 无返回值,总是抛出异常
- * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法
- */
- @Override
- public int getSyncAction(Cursor c) {
- throw new IllegalAccessError("MetaData:getSyncAction should not be called");
- }
-
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/Node.java b/app/src/main/java/net/micode/notes/gtask/data/Node.java
deleted file mode 100644
index ad7e431..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/Node.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-
-import org.json.JSONObject;
-
-/**
- * Google Tasks 同步节点抽象基类
- *
- * 定义所有可同步数据模型(Task、TaskList、MetaData)的公共属性和抽象方法。
- * 负责管理同步状态、Google ID、名称、最后修改时间和删除标记等通用属性。
- * 子类需要实现具体的 JSON 转换和同步动作生成逻辑。
- *
- */
-public abstract class Node {
- /**
- * 无需同步操作
- */
- public static final int SYNC_ACTION_NONE = 0;
-
- /**
- * 需要添加到远程服务器
- */
- public static final int SYNC_ACTION_ADD_REMOTE = 1;
-
- /**
- * 需要添加到本地数据库
- */
- public static final int SYNC_ACTION_ADD_LOCAL = 2;
-
- /**
- * 需要从远程服务器删除
- */
- public static final int SYNC_ACTION_DEL_REMOTE = 3;
-
- /**
- * 需要从本地数据库删除
- */
- public static final int SYNC_ACTION_DEL_LOCAL = 4;
-
- /**
- * 需要更新到远程服务器
- */
- public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
-
- /**
- * 需要更新到本地数据库
- */
- public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
-
- /**
- * 同步冲突,需要特殊处理
- */
- public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
-
- /**
- * 同步错误
- */
- public static final int SYNC_ACTION_ERROR = 8;
-
- /**
- * Google Tasks ID,用于唯一标识远程任务
- */
- private String mGid;
-
- /**
- * 节点名称
- */
- private String mName;
-
- /**
- * 最后修改时间(时间戳)
- */
- private long mLastModified;
-
- /**
- * 删除标记,true 表示已删除
- */
- private boolean mDeleted;
-
- /**
- * 构造一个新的节点实例
- *
- * 初始化所有属性为默认值:GID 为 null,名称为空字符串,最后修改时间为 0,删除标记为 false。
- *
- */
- public Node() {
- mGid = null;
- mName = "";
- mLastModified = 0;
- mDeleted = false;
- }
-
- /**
- * 获取创建动作的 JSON 对象
- *
- * 根据指定的动作 ID 生成用于在远程服务器创建节点的 JSON 请求。
- *
- *
- * @param actionId 动作 ID,标识具体的创建操作类型
- * @return 包含创建动作信息的 JSON 对象
- */
- public abstract JSONObject getCreateAction(int actionId);
-
- /**
- * 获取更新动作的 JSON 对象
- *
- * 根据指定的动作 ID 生成用于在远程服务器更新节点的 JSON 请求。
- *
- *
- * @param actionId 动作 ID,标识具体的更新操作类型
- * @return 包含更新动作信息的 JSON 对象
- */
- public abstract JSONObject getUpdateAction(int actionId);
-
- /**
- * 根据远程 JSON 设置节点内容
- *
- * 从远程服务器返回的 JSON 对象中解析并设置节点的属性值。
- *
- *
- * @param js 远程服务器返回的 JSON 对象
- */
- public abstract void setContentByRemoteJSON(JSONObject js);
-
- /**
- * 根据本地 JSON 设置节点内容
- *
- * 从本地数据库存储的 JSON 对象中解析并设置节点的属性值。
- *
- *
- * @param js 本地数据库存储的 JSON 对象
- */
- public abstract void setContentByLocalJSON(JSONObject js);
-
- /**
- * 从节点内容生成本地 JSON 对象
- *
- * 将节点的当前属性值转换为 JSON 对象,用于存储到本地数据库。
- *
- *
- * @return 包含节点内容的 JSON 对象
- */
- public abstract JSONObject getLocalJSONFromContent();
-
- /**
- * 根据数据库游标获取同步动作
- *
- * 比较本地数据库中的数据与当前节点状态,确定需要执行的同步动作类型。
- *
- *
- * @param c 指向本地数据库记录的游标
- * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一
- */
- public abstract int getSyncAction(Cursor c);
-
- /**
- * 设置 Google Tasks ID
- *
- * @param gid Google Tasks ID,用于唯一标识远程任务
- */
- public void setGid(String gid) {
- this.mGid = gid;
- }
-
- /**
- * 设置节点名称
- *
- * @param name 节点名称
- */
- public void setName(String name) {
- this.mName = name;
- }
-
- /**
- * 设置最后修改时间
- *
- * @param lastModified 最后修改时间(时间戳)
- */
- public void setLastModified(long lastModified) {
- this.mLastModified = lastModified;
- }
-
- /**
- * 设置删除标记
- *
- * @param deleted 删除标记,true 表示已删除
- */
- public void setDeleted(boolean deleted) {
- this.mDeleted = deleted;
- }
-
- /**
- * 获取 Google Tasks ID
- *
- * @return Google Tasks ID,如果未设置则返回 null
- */
- public String getGid() {
- return this.mGid;
- }
-
- /**
- * 获取节点名称
- *
- * @return 节点名称
- */
- public String getName() {
- return this.mName;
- }
-
- /**
- * 获取最后修改时间
- *
- * @return 最后修改时间(时间戳)
- */
- public long getLastModified() {
- return this.mLastModified;
- }
-
- /**
- * 获取删除标记
- *
- * @return 删除标记,true 表示已删除
- */
- public boolean getDeleted() {
- return this.mDeleted;
- }
-
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/app/src/main/java/net/micode/notes/gtask/data/SqlData.java
deleted file mode 100644
index 174560e..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.NotesDatabaseHelper.TABLE;
-import net.micode.notes.gtask.exception.ActionFailureException;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-
-/**
- * SQLite 数据内容类
- *
- * 表示笔记的一条数据记录,存储笔记的具体内容信息。
- * 每条数据记录包含 MIME 类型、内容文本和扩展数据字段。
- * 支持从 JSON 对象加载内容或将内容导出为 JSON,用于与 Google Tasks 的数据同步。
- *
- */
-public class SqlData {
- private static final String TAG = SqlData.class.getSimpleName();
-
- /** 无效 ID 标识符 */
- private static final int INVALID_ID = -99999;
-
- /** 数据表查询投影字段数组 */
- public static final String[] PROJECTION_DATA = new String[] {
- DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
- DataColumns.DATA3
- };
-
- /** ID 字段在投影数组中的索引 */
- public static final int DATA_ID_COLUMN = 0;
-
- /** MIME 类型字段在投影数组中的索引 */
- public static final int DATA_MIME_TYPE_COLUMN = 1;
-
- /** 内容字段在投影数组中的索引 */
- public static final int DATA_CONTENT_COLUMN = 2;
-
- /** 扩展数据 1 字段在投影数组中的索引 */
- public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
-
- /** 扩展数据 3 字段在投影数组中的索引 */
- public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
-
- private ContentResolver mContentResolver;
-
- private boolean mIsCreate;
-
- private long mDataId;
-
- private String mDataMimeType;
-
- private String mDataContent;
-
- private long mDataContentData1;
-
- private String mDataContentData3;
-
- private ContentValues mDiffDataValues;
-
- /**
- * 构造一个新建的数据对象
- *
- * 创建一个尚未保存到数据库的新数据记录,初始化所有字段为默认值。
- * 标记为创建状态,后续调用 commit 方法时会执行插入操作。
- *
- *
- * @param context 上下文对象,用于获取 ContentResolver
- */
- public SqlData(Context context) {
- mContentResolver = context.getContentResolver();
- mIsCreate = true;
- mDataId = INVALID_ID;
- mDataMimeType = DataConstants.NOTE;
- mDataContent = "";
- mDataContentData1 = 0;
- mDataContentData3 = "";
- mDiffDataValues = new ContentValues();
- }
-
- /**
- * 从数据库游标构造数据对象
- *
- * 从游标中读取数据记录并初始化对象。
- * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。
- *
- *
- * @param context 上下文对象
- * @param c 指向数据记录的数据库游标
- */
- public SqlData(Context context, Cursor c) {
- mContentResolver = context.getContentResolver();
- mIsCreate = false;
- loadFromCursor(c);
- mDiffDataValues = new ContentValues();
- }
-
- /**
- * 从数据库游标加载数据内容
- *
- * 从游标的当前行读取所有数据字段值并初始化对象的成员变量。
- *
- *
- * @param c 指向数据记录的数据库游标
- */
- private void loadFromCursor(Cursor c) {
- mDataId = c.getLong(DATA_ID_COLUMN);
- mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
- mDataContent = c.getString(DATA_CONTENT_COLUMN);
- mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
- mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
- }
-
- /**
- * 从 JSON 对象设置数据内容
- *
- * 解析 JSON 对象中的数据字段,更新当前对象的成员变量。
- * 比较新旧值,将变更记录到差异值集合中。
- *
- *
- * @param js 包含数据信息的 JSON 对象
- * @throws JSONException 如果 JSON 解析失败
- */
- public void setContent(JSONObject js) throws JSONException {
- long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
- if (mIsCreate || mDataId != dataId) {
- mDiffDataValues.put(DataColumns.ID, dataId);
- }
- mDataId = dataId;
-
- String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
- : DataConstants.NOTE;
- if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
- mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
- }
- mDataMimeType = dataMimeType;
-
- String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
- if (mIsCreate || !mDataContent.equals(dataContent)) {
- mDiffDataValues.put(DataColumns.CONTENT, dataContent);
- }
- mDataContent = dataContent;
-
- long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
- if (mIsCreate || mDataContentData1 != dataContentData1) {
- mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
- }
- mDataContentData1 = dataContentData1;
-
- String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
- if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
- mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
- }
- mDataContentData3 = dataContentData3;
- }
-
- /**
- * 获取数据内容的 JSON 对象
- *
- * 将当前数据的所有字段导出为 JSON 对象格式。
- *
- *
- * @return 包含数据信息的 JSON 对象,如果尚未创建到数据库则返回 null
- * @throws JSONException 如果 JSON 生成失败
- */
- public JSONObject getContent() throws JSONException {
- if (mIsCreate) {
- Log.e(TAG, "it seems that we haven't created this in database yet");
- return null;
- }
- JSONObject js = new JSONObject();
- js.put(DataColumns.ID, mDataId);
- js.put(DataColumns.MIME_TYPE, mDataMimeType);
- js.put(DataColumns.CONTENT, mDataContent);
- js.put(DataColumns.DATA1, mDataContentData1);
- js.put(DataColumns.DATA3, mDataContentData3);
- return js;
- }
-
- /**
- * 提交数据变更到数据库
- *
- * 根据当前状态执行插入或更新操作:
- * - 如果是新建数据,插入新记录并获取生成的 ID
- * - 如果是已存在的数据,更新变更的字段
- *
- *
- * @param noteId 关联的笔记 ID
- * @param validateVersion 是否验证版本号,为 true 时仅更新版本号匹配的记录
- * @param version 笔记的版本号,用于版本验证
- * @throws ActionFailureException 如果创建数据失败
- */
- public void commit(long noteId, boolean validateVersion, long version) {
-
- if (mIsCreate) {
- if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
- mDiffDataValues.remove(DataColumns.ID);
- }
-
- mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
- Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
- try {
- mDataId = Long.valueOf(uri.getPathSegments().get(1));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Get note id error :" + e.toString());
- throw new ActionFailureException("create note failed");
- }
- } else {
- if (mDiffDataValues.size() > 0) {
- int result = 0;
- if (!validateVersion) {
- result = mContentResolver.update(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
- } else {
- // 仅更新笔记版本号匹配的记录,防止并发更新冲突
- result = mContentResolver.update(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
- " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
- + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
- String.valueOf(noteId), String.valueOf(version)
- });
- }
- if (result == 0) {
- Log.w(TAG, "there is no update. maybe user updates note when syncing");
- }
- }
- }
-
- mDiffDataValues.clear();
- mIsCreate = false;
- }
-
- /**
- * 获取数据 ID
- *
- * @return 数据在数据库中的 ID
- */
- public long getId() {
- return mDataId;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java
deleted file mode 100644
index 3355141..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java
+++ /dev/null
@@ -1,668 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.appwidget.AppWidgetManager;
-import android.content.ContentResolver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-import net.micode.notes.tool.ResourceParser;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.ArrayList;
-
-
-/**
- * SQLite 笔记数据类
- *
- * 表示本地数据库中的一条笔记记录,负责笔记数据的增删改查操作。
- * 支持与 Google Tasks 的双向同步,能够从 JSON 对象加载内容或将内容导出为 JSON。
- * 区分普通笔记、文件夹和系统文件夹三种类型,提供版本控制和本地修改标记功能。
- *
- */
-public class SqlNote {
- private static final String TAG = SqlNote.class.getSimpleName();
-
- /** 无效 ID 标识符 */
- private static final int INVALID_ID = -99999;
-
- /** 笔记表查询投影字段数组 */
- public static final String[] PROJECTION_NOTE = new String[] {
- NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
- NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
- NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
- NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
- NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
- NoteColumns.VERSION
- };
-
- /** ID 字段在投影数组中的索引 */
- public static final int ID_COLUMN = 0;
-
- /** 提醒日期字段在投影数组中的索引 */
- public static final int ALERTED_DATE_COLUMN = 1;
-
- /** 背景颜色 ID 字段在投影数组中的索引 */
- public static final int BG_COLOR_ID_COLUMN = 2;
-
- /** 创建日期字段在投影数组中的索引 */
- public static final int CREATED_DATE_COLUMN = 3;
-
- /** 是否有附件字段在投影数组中的索引 */
- public static final int HAS_ATTACHMENT_COLUMN = 4;
-
- /** 修改日期字段在投影数组中的索引 */
- public static final int MODIFIED_DATE_COLUMN = 5;
-
- /** 子笔记数量字段在投影数组中的索引 */
- public static final int NOTES_COUNT_COLUMN = 6;
-
- /** 父文件夹 ID 字段在投影数组中的索引 */
- public static final int PARENT_ID_COLUMN = 7;
-
- /** 摘要文本字段在投影数组中的索引 */
- public static final int SNIPPET_COLUMN = 8;
-
- /** 笔记类型字段在投影数组中的索引 */
- public static final int TYPE_COLUMN = 9;
-
- /** Widget ID 字段在投影数组中的索引 */
- public static final int WIDGET_ID_COLUMN = 10;
-
- /** Widget 类型字段在投影数组中的索引 */
- public static final int WIDGET_TYPE_COLUMN = 11;
-
- /** 同步 ID 字段在投影数组中的索引 */
- public static final int SYNC_ID_COLUMN = 12;
-
- /** 本地修改标记字段在投影数组中的索引 */
- public static final int LOCAL_MODIFIED_COLUMN = 13;
-
- /** 原始父文件夹 ID 字段在投影数组中的索引 */
- public static final int ORIGIN_PARENT_ID_COLUMN = 14;
-
- /** Google Tasks ID 字段在投影数组中的索引 */
- public static final int GTASK_ID_COLUMN = 15;
-
- /** 版本号字段在投影数组中的索引 */
- public static final int VERSION_COLUMN = 16;
-
- private Context mContext;
-
- private ContentResolver mContentResolver;
-
- private boolean mIsCreate;
-
- private long mId;
-
- private long mAlertDate;
-
- private int mBgColorId;
-
- private long mCreatedDate;
-
- private int mHasAttachment;
-
- private long mModifiedDate;
-
- private long mParentId;
-
- private String mSnippet;
-
- private int mType;
-
- private int mWidgetId;
-
- private int mWidgetType;
-
- private long mOriginParent;
-
- private long mVersion;
-
- private ContentValues mDiffNoteValues;
-
- private ArrayList mDataList;
-
- /**
- * 构造一个新建的笔记对象
- *
- * 创建一个尚未保存到数据库的新笔记,初始化所有字段为默认值。
- * 标记为创建状态,后续调用 commit 方法时会执行插入操作。
- *
- *
- * @param context 上下文对象,用于获取 ContentResolver 和默认资源
- */
- public SqlNote(Context context) {
- mContext = context;
- mContentResolver = context.getContentResolver();
- mIsCreate = true;
- mId = INVALID_ID;
- mAlertDate = 0;
- mBgColorId = ResourceParser.getDefaultBgId(context);
- mCreatedDate = System.currentTimeMillis();
- mHasAttachment = 0;
- mModifiedDate = System.currentTimeMillis();
- mParentId = 0;
- mSnippet = "";
- mType = Notes.TYPE_NOTE;
- mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
- mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
- mOriginParent = 0;
- mVersion = 0;
- mDiffNoteValues = new ContentValues();
- mDataList = new ArrayList();
- }
-
- /**
- * 从数据库游标构造笔记对象
- *
- * 从游标中读取笔记数据并初始化对象,如果笔记类型为普通笔记则加载其数据内容。
- * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。
- *
- *
- * @param context 上下文对象
- * @param c 指向笔记记录的数据库游标
- */
- public SqlNote(Context context, Cursor c) {
- mContext = context;
- mContentResolver = context.getContentResolver();
- mIsCreate = false;
- loadFromCursor(c);
- mDataList = new ArrayList();
- if (mType == Notes.TYPE_NOTE)
- loadDataContent();
- mDiffNoteValues = new ContentValues();
- }
-
- /**
- * 从数据库 ID 构造笔记对象
- *
- * 根据笔记 ID 从数据库查询记录并初始化对象,如果笔记类型为普通笔记则加载其数据内容。
- * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。
- *
- *
- * @param context 上下文对象
- * @param id 笔记在数据库中的 ID
- */
- public SqlNote(Context context, long id) {
- mContext = context;
- mContentResolver = context.getContentResolver();
- mIsCreate = false;
- loadFromCursor(id);
- mDataList = new ArrayList();
- if (mType == Notes.TYPE_NOTE)
- loadDataContent();
- mDiffNoteValues = new ContentValues();
-
- }
-
- /**
- * 从数据库 ID 加载笔记数据
- *
- * 根据笔记 ID 查询数据库获取笔记记录,并调用 loadFromCursor(Cursor) 加载数据。
- *
- *
- * @param id 笔记在数据库中的 ID
- */
- private void loadFromCursor(long id) {
- Cursor c = null;
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
- new String[] {
- String.valueOf(id)
- }, null);
- if (c != null) {
- c.moveToNext();
- loadFromCursor(c);
- } else {
- Log.w(TAG, "loadFromCursor: cursor = null");
- }
- } finally {
- if (c != null)
- c.close();
- }
- }
-
- /**
- * 从数据库游标加载笔记数据
- *
- * 从游标的当前行读取所有笔记字段值并初始化对象的成员变量。
- *
- *
- * @param c 指向笔记记录的数据库游标
- */
- private void loadFromCursor(Cursor c) {
- mId = c.getLong(ID_COLUMN);
- mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
- mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
- mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
- mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
- mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
- mParentId = c.getLong(PARENT_ID_COLUMN);
- mSnippet = c.getString(SNIPPET_COLUMN);
- mType = c.getInt(TYPE_COLUMN);
- mWidgetId = c.getInt(WIDGET_ID_COLUMN);
- mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
- mVersion = c.getLong(VERSION_COLUMN);
- }
-
- /**
- * 加载笔记的数据内容
- *
- * 从数据库查询当前笔记的所有数据记录(Data 表),并创建 SqlData 对象列表。
- * 仅对普通笔记类型有效,文件夹类型没有数据内容。
- *
- */
- private void loadDataContent() {
- Cursor c = null;
- mDataList.clear();
- try {
- c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
- "(note_id=?)", new String[] {
- String.valueOf(mId)
- }, null);
- if (c != null) {
- if (c.getCount() == 0) {
- Log.w(TAG, "it seems that the note has not data");
- return;
- }
- while (c.moveToNext()) {
- SqlData data = new SqlData(mContext, c);
- mDataList.add(data);
- }
- } else {
- Log.w(TAG, "loadDataContent: cursor = null");
- }
- } finally {
- if (c != null)
- c.close();
- }
- }
-
- /**
- * 从 JSON 对象设置笔记内容
- *
- * 解析 JSON 对象中的笔记信息和数据,更新当前笔记的字段值。
- * 根据笔记类型(系统文件夹、文件夹、普通笔记)执行不同的更新逻辑。
- * 对于普通笔记,会同时更新其数据内容列表。
- *
- *
- * @param js 包含笔记信息的 JSON 对象
- * @return 如果设置成功返回 true,否则返回 false
- */
- public boolean setContent(JSONObject js) {
- try {
- JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
- Log.w(TAG, "cannot set system folder");
- } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
- // for folder we can only update the snnipet and type
- String snippet = note.has(NoteColumns.SNIPPET) ? note
- .getString(NoteColumns.SNIPPET) : "";
- if (mIsCreate || !mSnippet.equals(snippet)) {
- mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
- }
- mSnippet = snippet;
-
- int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
- : Notes.TYPE_NOTE;
- if (mIsCreate || mType != type) {
- mDiffNoteValues.put(NoteColumns.TYPE, type);
- }
- mType = type;
- } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
- JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
- long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
- if (mIsCreate || mId != id) {
- mDiffNoteValues.put(NoteColumns.ID, id);
- }
- mId = id;
-
- long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
- .getLong(NoteColumns.ALERTED_DATE) : 0;
- if (mIsCreate || mAlertDate != alertDate) {
- mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
- }
- mAlertDate = alertDate;
-
- int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
- .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
- if (mIsCreate || mBgColorId != bgColorId) {
- mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
- }
- mBgColorId = bgColorId;
-
- long createDate = note.has(NoteColumns.CREATED_DATE) ? note
- .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
- if (mIsCreate || mCreatedDate != createDate) {
- mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
- }
- mCreatedDate = createDate;
-
- int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
- .getInt(NoteColumns.HAS_ATTACHMENT) : 0;
- if (mIsCreate || mHasAttachment != hasAttachment) {
- mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
- }
- mHasAttachment = hasAttachment;
-
- long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
- .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
- if (mIsCreate || mModifiedDate != modifiedDate) {
- mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
- }
- mModifiedDate = modifiedDate;
-
- long parentId = note.has(NoteColumns.PARENT_ID) ? note
- .getLong(NoteColumns.PARENT_ID) : 0;
- if (mIsCreate || mParentId != parentId) {
- mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
- }
- mParentId = parentId;
-
- String snippet = note.has(NoteColumns.SNIPPET) ? note
- .getString(NoteColumns.SNIPPET) : "";
- if (mIsCreate || !mSnippet.equals(snippet)) {
- mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
- }
- mSnippet = snippet;
-
- int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
- : Notes.TYPE_NOTE;
- if (mIsCreate || mType != type) {
- mDiffNoteValues.put(NoteColumns.TYPE, type);
- }
- mType = type;
-
- int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
- : AppWidgetManager.INVALID_APPWIDGET_ID;
- if (mIsCreate || mWidgetId != widgetId) {
- mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
- }
- mWidgetId = widgetId;
-
- int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
- .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
- if (mIsCreate || mWidgetType != widgetType) {
- mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
- }
- mWidgetType = widgetType;
-
- long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
- .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
- if (mIsCreate || mOriginParent != originParent) {
- mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
- }
- mOriginParent = originParent;
-
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- SqlData sqlData = null;
- if (data.has(DataColumns.ID)) {
- long dataId = data.getLong(DataColumns.ID);
- for (SqlData temp : mDataList) {
- if (dataId == temp.getId()) {
- sqlData = temp;
- }
- }
- }
-
- if (sqlData == null) {
- sqlData = new SqlData(mContext);
- mDataList.add(sqlData);
- }
-
- sqlData.setContent(data);
- }
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return false;
- }
- return true;
- }
-
- /**
- * 获取笔记内容的 JSON 对象
- *
- * 将当前笔记的所有字段和数据内容导出为 JSON 对象格式。
- * 根据笔记类型生成不同结构的 JSON,普通笔记包含数据数组。
- *
- *
- * @return 包含笔记信息的 JSON 对象,如果尚未创建到数据库则返回 null
- */
- public JSONObject getContent() {
- try {
- JSONObject js = new JSONObject();
-
- if (mIsCreate) {
- Log.e(TAG, "it seems that we haven't created this in database yet");
- return null;
- }
-
- JSONObject note = new JSONObject();
- if (mType == Notes.TYPE_NOTE) {
- note.put(NoteColumns.ID, mId);
- note.put(NoteColumns.ALERTED_DATE, mAlertDate);
- note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
- note.put(NoteColumns.CREATED_DATE, mCreatedDate);
- note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
- note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
- note.put(NoteColumns.PARENT_ID, mParentId);
- note.put(NoteColumns.SNIPPET, mSnippet);
- note.put(NoteColumns.TYPE, mType);
- note.put(NoteColumns.WIDGET_ID, mWidgetId);
- note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
- note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
- js.put(GTaskStringUtils.META_HEAD_NOTE, note);
-
- JSONArray dataArray = new JSONArray();
- for (SqlData sqlData : mDataList) {
- JSONObject data = sqlData.getContent();
- if (data != null) {
- dataArray.put(data);
- }
- }
- js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
- } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
- note.put(NoteColumns.ID, mId);
- note.put(NoteColumns.TYPE, mType);
- note.put(NoteColumns.SNIPPET, mSnippet);
- js.put(GTaskStringUtils.META_HEAD_NOTE, note);
- }
-
- return js;
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * 设置父文件夹 ID
- *
- * 更新笔记的父文件夹 ID,并将变更记录到差异值集合中。
- *
- *
- * @param id 新的父文件夹 ID
- */
- public void setParentId(long id) {
- mParentId = id;
- mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
- }
-
- /**
- * 设置 Google Tasks ID
- *
- * 将 Google Tasks 的任务 ID 关联到当前笔记,用于同步标识。
- *
- *
- * @param gid Google Tasks 任务 ID
- */
- public void setGtaskId(String gid) {
- mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
- }
-
- /**
- * 设置同步 ID
- *
- * 记录最后一次同步的时间戳,用于判断本地和远程数据的同步状态。
- *
- *
- * @param syncId 同步时间戳
- */
- public void setSyncId(long syncId) {
- mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
- }
-
- /**
- * 重置本地修改标记
- *
- * 将本地修改标记设置为 0,表示笔记已同步,无待同步的本地修改。
- *
- */
- public void resetLocalModified() {
- mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
- }
-
- /**
- * 获取笔记 ID
- *
- * @return 笔记在数据库中的 ID,如果尚未创建则返回 INVALID_ID
- */
- public long getId() {
- return mId;
- }
-
- /**
- * 获取父文件夹 ID
- *
- * @return 父文件夹在数据库中的 ID
- */
- public long getParentId() {
- return mParentId;
- }
-
- /**
- * 获取笔记摘要文本
- *
- * @return 笔记的摘要文本
- */
- public String getSnippet() {
- return mSnippet;
- }
-
- /**
- * 判断是否为普通笔记类型
- *
- * @return 如果是普通笔记返回 true,否则返回 false
- */
- public boolean isNoteType() {
- return mType == Notes.TYPE_NOTE;
- }
-
- /**
- * 提交笔记变更到数据库
- *
- * 根据当前状态执行插入或更新操作:
- * - 如果是新建笔记,插入新记录并获取生成的 ID
- * - 如果是已存在的笔记,更新变更的字段
- * - 对于普通笔记,同时提交其数据内容
- *
- *
- * @param validateVersion 是否验证版本号,为 true 时仅更新版本号不大于当前版本的记录
- * @throws ActionFailureException 如果创建笔记失败
- * @throws IllegalStateException 如果尝试更新无效 ID 的笔记
- */
- public void commit(boolean validateVersion) {
- if (mIsCreate) {
- if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
- mDiffNoteValues.remove(NoteColumns.ID);
- }
-
- Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
- try {
- mId = Long.valueOf(uri.getPathSegments().get(1));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Get note id error :" + e.toString());
- throw new ActionFailureException("create note failed");
- }
- if (mId == 0) {
- throw new IllegalStateException("Create thread id failed");
- }
-
- if (mType == Notes.TYPE_NOTE) {
- for (SqlData sqlData : mDataList) {
- sqlData.commit(mId, false, -1);
- }
- }
- } else {
- if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
- Log.e(TAG, "No such note");
- throw new IllegalStateException("Try to update note with invalid id");
- }
- if (mDiffNoteValues.size() > 0) {
- mVersion ++;
- int result = 0;
- if (!validateVersion) {
- result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
- + NoteColumns.ID + "=?)", new String[] {
- String.valueOf(mId)
- });
- } else {
- // 仅更新版本号不大于当前版本的记录,防止并发更新冲突
- result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
- + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
- new String[] {
- String.valueOf(mId), String.valueOf(mVersion)
- });
- }
- if (result == 0) {
- Log.w(TAG, "there is no update. maybe user updates note when syncing");
- }
- }
-
- if (mType == Notes.TYPE_NOTE) {
- for (SqlData sqlData : mDataList) {
- sqlData.commit(mId, validateVersion, mVersion);
- }
- }
- }
-
- // 从数据库重新加载最新数据,确保内存状态与数据库一致
- loadFromCursor(mId);
- if (mType == Notes.TYPE_NOTE)
- loadDataContent();
-
- mDiffNoteValues.clear();
- mIsCreate = false;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/Task.java b/app/src/main/java/net/micode/notes/gtask/data/Task.java
deleted file mode 100644
index f9f0ef3..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/Task.java
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-
-/**
- * Google Tasks 任务类
- *
- * 继承自 Node,表示 Google Tasks 中的一个任务项。
- * 负责管理任务的完成状态、备注信息、元数据、前驱兄弟节点和父任务列表。
- * 支持与本地笔记的双向同步,能够生成创建和更新动作的 JSON 对象。
- *
- */
-public class Task extends Node {
- /**
- * 日志标签
- */
- private static final String TAG = Task.class.getSimpleName();
-
- /**
- * 完成状态标记,true 表示已完成
- */
- private boolean mCompleted;
-
- /**
- * 任务备注信息
- */
- private String mNotes;
-
- /**
- * 元数据 JSON 对象,包含本地笔记的完整信息
- */
- private JSONObject mMetaInfo;
-
- /**
- * 前驱兄弟任务,用于维护任务在列表中的顺序
- */
- private Task mPriorSibling;
-
- /**
- * 父任务列表
- */
- private TaskList mParent;
-
- /**
- * 构造一个新的任务实例
- *
- * 初始化所有属性为默认值:未完成、备注为 null、无前驱兄弟、无父列表、无元数据。
- *
- */
- public Task() {
- super();
- mCompleted = false;
- mNotes = null;
- mPriorSibling = null;
- mParent = null;
- mMetaInfo = null;
- }
-
- /**
- * 获取创建动作的 JSON 对象
- *
- * 生成用于在远程服务器创建任务的 JSON 请求,包含任务名称、备注、父列表 ID 等信息。
- *
- *
- * @param actionId 动作 ID,标识具体的创建操作
- * @return 包含创建动作信息的 JSON 对象
- * @throws ActionFailureException 如果生成 JSON 对象失败
- */
- public JSONObject getCreateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // action_type
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
-
- // action_id
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // index
- js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
-
- // entity_delta
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
- entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
- entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_TASK);
- if (getNotes() != null) {
- entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
- }
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- // parent_id
- js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
-
- // dest_parent_type
- js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
-
- // list_id
- js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
-
- // prior_sibling_id
- if (mPriorSibling != null) {
- js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
- }
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate task-create jsonobject");
- }
-
- return js;
- }
-
- /**
- * 获取更新动作的 JSON 对象
- *
- * 生成用于在远程服务器更新任务的 JSON 请求,包含任务名称、备注、删除状态等信息。
- *
- *
- * @param actionId 动作 ID,标识具体的更新操作
- * @return 包含更新动作信息的 JSON 对象
- * @throws ActionFailureException 如果生成 JSON 对象失败
- */
- public JSONObject getUpdateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // action_type
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
-
- // action_id
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // id
- js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
-
- // entity_delta
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
- if (getNotes() != null) {
- entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
- }
- entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate task-update jsonobject");
- }
-
- return js;
- }
-
- /**
- * 根据远程 JSON 设置内容
- *
- * 从远程服务器返回的 JSON 对象中解析并设置任务的属性值,包括 ID、名称、备注、完成状态等。
- *
- *
- * @param js 远程服务器返回的 JSON 对象
- * @throws ActionFailureException 如果解析 JSON 失败
- */
- public void setContentByRemoteJSON(JSONObject js) {
- if (js != null) {
- try {
- // id
- if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
- setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
- }
-
- // last_modified
- if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
- setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
- }
-
- // name
- if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
- setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
- }
-
- // notes
- if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
- setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
- }
-
- // deleted
- if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
- setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
- }
-
- // completed
- if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
- setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to get task content from jsonobject");
- }
- }
- }
-
- /**
- * 根据本地 JSON 设置内容
- *
- * 从本地数据库存储的 JSON 对象中解析并设置任务的属性值。
- * 从笔记数据中提取内容作为任务名称。
- *
- *
- * @param js 本地数据库存储的 JSON 对象
- */
- public void setContentByLocalJSON(JSONObject js) {
- if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
- || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
- Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
- }
-
- try {
- JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
-
- if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
- Log.e(TAG, "invalid type");
- return;
- }
-
- // 遍历数据数组,查找笔记内容
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
- setName(data.getString(DataColumns.CONTENT));
- break;
- }
- }
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * 从内容生成本地 JSON 对象
- *
- * 将任务的当前属性值转换为 JSON 对象,用于存储到本地数据库。
- * 如果是新建任务,创建新的 JSON 结构;如果是已同步任务,更新现有元数据。
- *
- *
- * @return 包含任务内容的 JSON 对象,如果生成失败则返回 null
- */
- public JSONObject getLocalJSONFromContent() {
- String name = getName();
- try {
- if (mMetaInfo == null) {
- // new task created from web
- if (name == null) {
- Log.w(TAG, "the note seems to be an empty one");
- return null;
- }
-
- JSONObject js = new JSONObject();
- JSONObject note = new JSONObject();
- JSONArray dataArray = new JSONArray();
- JSONObject data = new JSONObject();
- data.put(DataColumns.CONTENT, name);
- dataArray.put(data);
- js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
- note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- js.put(GTaskStringUtils.META_HEAD_NOTE, note);
- return js;
- } else {
- // synced task
- JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
-
- // 更新数据数组中的笔记内容
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
- data.put(DataColumns.CONTENT, getName());
- break;
- }
- }
-
- note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- return mMetaInfo;
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 设置元数据信息
- *
- * 从元数据对象中解析并设置任务的元信息 JSON 对象。
- * 元信息包含本地笔记的完整结构,用于双向同步。
- *
- *
- * @param metaData 元数据对象
- */
- public void setMetaInfo(MetaData metaData) {
- if (metaData != null && metaData.getNotes() != null) {
- try {
- mMetaInfo = new JSONObject(metaData.getNotes());
- } catch (JSONException e) {
- Log.w(TAG, e.toString());
- mMetaInfo = null;
- }
- }
- }
-
- /**
- * 根据数据库游标获取同步动作
- *
- * 比较本地数据库中的数据与当前任务状态,确定需要执行的同步动作类型。
- * 处理各种同步场景:无更新、本地更新、远程更新、冲突、错误等。
- *
- *
- * @param c 指向本地数据库记录的游标
- * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一
- */
- public int getSyncAction(Cursor c) {
- try {
- JSONObject noteInfo = null;
- if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
- noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- }
-
- if (noteInfo == null) {
- Log.w(TAG, "it seems that note meta has been deleted");
- return SYNC_ACTION_UPDATE_REMOTE;
- }
-
- if (!noteInfo.has(NoteColumns.ID)) {
- Log.w(TAG, "remote note id seems to be deleted");
- return SYNC_ACTION_UPDATE_LOCAL;
- }
-
- // validate the note id now
- if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
- Log.w(TAG, "note id doesn't match");
- return SYNC_ACTION_UPDATE_LOCAL;
- }
-
- if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
- // there is no local update
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // no update both side
- return SYNC_ACTION_NONE;
- } else {
- // apply remote to local
- return SYNC_ACTION_UPDATE_LOCAL;
- }
- } else {
- // validate gtask id
- if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
- Log.e(TAG, "gtask id doesn't match");
- return SYNC_ACTION_ERROR;
- }
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // local modification only
- return SYNC_ACTION_UPDATE_REMOTE;
- } else {
- return SYNC_ACTION_UPDATE_CONFLICT;
- }
- }
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
-
- return SYNC_ACTION_ERROR;
- }
-
- /**
- * 判断是否值得保存
- *
- * 只有当任务有元数据、非空名称或非空备注时才值得保存。
- *
- *
- * @return 如果有元数据、非空名称或非空备注返回 true,否则返回 false
- */
- public boolean isWorthSaving() {
- return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
- || (getNotes() != null && getNotes().trim().length() > 0);
- }
-
- /**
- * 设置完成状态
- *
- * @param completed 完成状态,true 表示已完成
- */
- public void setCompleted(boolean completed) {
- this.mCompleted = completed;
- }
-
- /**
- * 设置备注信息
- *
- * @param notes 备注信息
- */
- public void setNotes(String notes) {
- this.mNotes = notes;
- }
-
- /**
- * 设置前驱兄弟任务
- *
- * @param priorSibling 前驱兄弟任务
- */
- public void setPriorSibling(Task priorSibling) {
- this.mPriorSibling = priorSibling;
- }
-
- /**
- * 设置父任务列表
- *
- * @param parent 父任务列表
- */
- public void setParent(TaskList parent) {
- this.mParent = parent;
- }
-
- /**
- * 获取完成状态
- *
- * @return 完成状态,true 表示已完成
- */
- public boolean getCompleted() {
- return this.mCompleted;
- }
-
- /**
- * 获取备注信息
- *
- * @return 备注信息
- */
- public String getNotes() {
- return this.mNotes;
- }
-
- /**
- * 获取前驱兄弟任务
- *
- * @return 前驱兄弟任务
- */
- public Task getPriorSibling() {
- return this.mPriorSibling;
- }
-
- /**
- * 获取父任务列表
- *
- * @return 父任务列表
- */
- public TaskList getParent() {
- return this.mParent;
- }
-
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/data/TaskList.java b/app/src/main/java/net/micode/notes/gtask/data/TaskList.java
deleted file mode 100644
index d454fe7..0000000
--- a/app/src/main/java/net/micode/notes/gtask/data/TaskList.java
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.ArrayList;
-
-
-/**
- * Google Tasks 任务列表类
- *
- * 继承自 Node,表示 Google Tasks 中的一个任务列表(文件夹)。
- * 负责管理任务列表的子任务集合,提供任务的增删改查操作。
- * 支持与本地笔记文件夹的双向同步,能够生成创建和更新动作的 JSON 对象。
- *
- */
-public class TaskList extends Node {
- /**
- * 日志标签
- */
- private static final String TAG = TaskList.class.getSimpleName();
-
- /**
- * 任务列表索引
- */
- private int mIndex;
-
- /**
- * 子任务列表
- */
- private ArrayList mChildren;
-
- /**
- * 构造一个新的任务列表实例
- *
- * 初始化子任务列表为空,索引设置为 1。
- *
- */
- public TaskList() {
- super();
- mChildren = new ArrayList();
- mIndex = 1;
- }
-
- /**
- * 获取创建动作的 JSON 对象
- *
- * 生成用于在远程服务器创建任务列表的 JSON 请求,包含列表名称等信息。
- *
- *
- * @param actionId 动作 ID,标识具体的创建操作
- * @return 包含创建动作信息的 JSON 对象
- * @throws ActionFailureException 如果生成 JSON 对象失败
- */
- public JSONObject getCreateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // action_type
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
-
- // action_id
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // index
- js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
-
- // entity_delta
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
- entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
- entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate tasklist-create jsonobject");
- }
-
- return js;
- }
-
- /**
- * 获取更新动作的 JSON 对象
- *
- * 生成用于在远程服务器更新任务列表的 JSON 请求,包含列表名称、删除状态等信息。
- *
- *
- * @param actionId 动作 ID,标识具体的更新操作
- * @return 包含更新动作信息的 JSON 对象
- * @throws ActionFailureException 如果生成 JSON 对象失败
- */
- public JSONObject getUpdateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // action_type
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
-
- // action_id
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // id
- js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
-
- // entity_delta
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
- entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate tasklist-update jsonobject");
- }
-
- return js;
- }
-
- /**
- * 根据远程 JSON 设置内容
- *
- * 从远程服务器返回的 JSON 对象中解析并设置任务列表的属性值。
- *
- *
- * @param js 远程服务器返回的 JSON 对象
- * @throws ActionFailureException 如果解析 JSON 失败
- */
- public void setContentByRemoteJSON(JSONObject js) {
- if (js != null) {
- try {
- // id
- if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
- setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
- }
-
- // last_modified
- if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
- setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
- }
-
- // name
- if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
- setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
- }
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to get tasklist content from jsonobject");
- }
- }
- }
-
- /**
- * 根据本地 JSON 设置内容
- *
- * 从本地数据库存储的 JSON 对象中解析并设置任务列表的属性值。
- * 根据文件夹类型(普通文件夹或系统文件夹)设置对应的名称。
- *
- *
- * @param js 本地数据库存储的 JSON 对象
- */
- public void setContentByLocalJSON(JSONObject js) {
- if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
- Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
- }
-
- try {
- JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
-
- if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
- // 普通文件夹,使用文件夹名称
- String name = folder.getString(NoteColumns.SNIPPET);
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
- } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
- // 系统文件夹,根据 ID 设置对应的名称
- if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
- else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_CALL_NOTE);
- else
- Log.e(TAG, "invalid system folder");
- } else {
- Log.e(TAG, "error type");
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * 从内容生成本地 JSON 对象
- *
- * 将任务列表的当前属性值转换为 JSON 对象,用于存储到本地数据库。
- * 根据文件夹名称判断是系统文件夹还是普通文件夹。
- *
- *
- * @return 包含任务列表内容的 JSON 对象,如果生成失败则返回 null
- */
- public JSONObject getLocalJSONFromContent() {
- try {
- JSONObject js = new JSONObject();
- JSONObject folder = new JSONObject();
-
- // 去除文件夹名称前缀
- String folderName = getName();
- if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
- folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
- folderName.length());
- folder.put(NoteColumns.SNIPPET, folderName);
- // 根据文件夹名称判断类型
- if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
- || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
- folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- else
- folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
-
- js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
-
- return js;
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 根据数据库游标获取同步动作
- *
- * 比较本地数据库中的数据与当前任务列表状态,确定需要执行的同步动作类型。
- * 对于文件夹冲突,优先应用本地修改。
- *
- *
- * @param c 指向本地数据库记录的游标
- * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一
- */
- public int getSyncAction(Cursor c) {
- try {
- if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
- // there is no local update
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // no update both side
- return SYNC_ACTION_NONE;
- } else {
- // apply remote to local
- return SYNC_ACTION_UPDATE_LOCAL;
- }
- } else {
- // validate gtask id
- if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
- Log.e(TAG, "gtask id doesn't match");
- return SYNC_ACTION_ERROR;
- }
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // local modification only
- return SYNC_ACTION_UPDATE_REMOTE;
- } else {
- // for folder conflicts, just apply local modification
- return SYNC_ACTION_UPDATE_REMOTE;
- }
- }
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
-
- return SYNC_ACTION_ERROR;
- }
-
- /**
- * 获取子任务数量
- *
- * @return 子任务的数量
- */
- public int getChildTaskCount() {
- return mChildren.size();
- }
-
- /**
- * 添加子任务到列表末尾
- *
- * 将任务添加到子任务列表的末尾,并设置其前驱兄弟和父列表。
- *
- *
- * @param task 要添加的子任务
- * @return 如果添加成功返回 true,否则返回 false
- */
- public boolean addChildTask(Task task) {
- boolean ret = false;
- if (task != null && !mChildren.contains(task)) {
- ret = mChildren.add(task);
- if (ret) {
- // need to set prior sibling and parent
- task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
- .get(mChildren.size() - 1));
- task.setParent(this);
- }
- }
- return ret;
- }
-
- /**
- * 在指定位置添加子任务
- *
- * 将任务插入到子任务列表的指定位置,并更新相关任务的前驱兄弟关系。
- *
- *
- * @param task 要添加的子任务
- * @param index 插入位置索引,必须在 0 到子任务数量之间
- * @return 如果添加成功返回 true,否则返回 false
- */
- public boolean addChildTask(Task task, int index) {
- if (index < 0 || index > mChildren.size()) {
- Log.e(TAG, "add child task: invalid index");
- return false;
- }
-
- int pos = mChildren.indexOf(task);
- if (task != null && pos == -1) {
- mChildren.add(index, task);
-
- // update the task list
- Task preTask = null;
- Task afterTask = null;
- if (index != 0)
- preTask = mChildren.get(index - 1);
- if (index != mChildren.size() - 1)
- afterTask = mChildren.get(index + 1);
-
- task.setPriorSibling(preTask);
- if (afterTask != null)
- afterTask.setPriorSibling(task);
- }
-
- return true;
- }
-
- /**
- * 移除子任务
- *
- * 从子任务列表中移除指定任务,并重置其前驱兄弟和父列表关系。
- * 同时更新后续任务的前驱兄弟关系。
- *
- *
- * @param task 要移除的子任务
- * @return 如果移除成功返回 true,否则返回 false
- */
- public boolean removeChildTask(Task task) {
- boolean ret = false;
- int index = mChildren.indexOf(task);
- if (index != -1) {
- ret = mChildren.remove(task);
-
- if (ret) {
- // reset prior sibling and parent
- task.setPriorSibling(null);
- task.setParent(null);
-
- // update the task list
- if (index != mChildren.size()) {
- mChildren.get(index).setPriorSibling(
- index == 0 ? null : mChildren.get(index - 1));
- }
- }
- }
- return ret;
- }
-
- /**
- * 移动子任务到指定位置
- *
- * 将子任务从当前位置移动到目标位置,通过先移除再添加实现。
- *
- *
- * @param task 要移动的子任务
- * @param index 目标位置索引,必须在 0 到子任务数量减 1 之间
- * @return 如果移动成功返回 true,否则返回 false
- */
- public boolean moveChildTask(Task task, int index) {
-
- if (index < 0 || index >= mChildren.size()) {
- Log.e(TAG, "move child task: invalid index");
- return false;
- }
-
- int pos = mChildren.indexOf(task);
- if (pos == -1) {
- Log.e(TAG, "move child task: the task should in the list");
- return false;
- }
-
- if (pos == index)
- return true;
- return (removeChildTask(task) && addChildTask(task, index));
- }
-
- /**
- * 根据 GID 查找子任务
- *
- * @param gid Google Tasks ID
- * @return 找到的子任务,如果未找到则返回 null
- */
- public Task findChildTaskByGid(String gid) {
- for (int i = 0; i < mChildren.size(); i++) {
- Task t = mChildren.get(i);
- if (t.getGid().equals(gid)) {
- return t;
- }
- }
- return null;
- }
-
- /**
- * 获取子任务的索引位置
- *
- * @param task 子任务
- * @return 子任务的索引位置,如果未找到则返回 -1
- */
- public int getChildTaskIndex(Task task) {
- return mChildren.indexOf(task);
- }
-
- /**
- * 根据索引获取子任务
- *
- * @param index 索引位置,必须在 0 到子任务数量减 1 之间
- * @return 对应的子任务,如果索引无效则返回 null
- */
- public Task getChildTaskByIndex(int index) {
- if (index < 0 || index >= mChildren.size()) {
- Log.e(TAG, "getTaskByIndex: invalid index");
- return null;
- }
- return mChildren.get(index);
- }
-
- /**
- * 根据 GID 获取子任务
- *
- * @param gid Google Tasks ID
- * @return 对应的子任务,如果未找到则返回 null
- */
- public Task getChilTaskByGid(String gid) {
- for (Task task : mChildren) {
- if (task.getGid().equals(gid))
- return task;
- }
- return null;
- }
-
- /**
- * 获取子任务列表
- *
- * @return 子任务列表的副本
- */
- public ArrayList getChildTaskList() {
- return this.mChildren;
- }
-
- /**
- * 设置任务列表索引
- *
- * @param index 任务列表索引
- */
- public void setIndex(int index) {
- this.mIndex = index;
- }
-
- /**
- * 获取任务列表索引
- *
- * @return 任务列表索引
- */
- public int getIndex() {
- return this.mIndex;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java
deleted file mode 100644
index 12b3bcd..0000000
--- a/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.exception;
-
-/**
- * 操作失败异常类
- *
- * 用于表示 Google Tasks 同步过程中操作执行失败的情况。
- * 当同步操作(如创建、更新、删除任务或任务列表)失败时抛出此异常。
- * 该异常继承自 RuntimeException,属于非受检异常,调用方可以选择性处理。
- *
- */
-public class ActionFailureException extends RuntimeException {
- private static final long serialVersionUID = 4425249765923293627L;
-
- /**
- * 构造一个无详细信息的操作失败异常
- */
- public ActionFailureException() {
- super();
- }
-
- /**
- * 构造一个带有详细信息的操作失败异常
- *
- * @param paramString 异常的详细信息,描述操作失败的具体原因
- */
- public ActionFailureException(String paramString) {
- super(paramString);
- }
-
- /**
- * 构造一个带有详细信息和原因的操作失败异常
- *
- * @param paramString 异常的详细信息,描述操作失败的具体原因
- * @param paramThrowable 导致此异常的底层异常或错误
- */
- public ActionFailureException(String paramString, Throwable paramThrowable) {
- super(paramString, paramThrowable);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java
deleted file mode 100644
index a7aeedf..0000000
--- a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.exception;
-
-/**
- * 网络异常类
- *
- * 用于表示 Google Tasks 同步过程中发生的网络相关错误。
- * 当网络连接失败、超时或无法访问 Google Tasks 服务时抛出此异常。
- * 该异常继承自 Exception,属于受检异常,调用方必须处理或继续抛出。
- *
- */
-public class NetworkFailureException extends Exception {
- private static final long serialVersionUID = 2107610287180234136L;
-
- /**
- * 构造一个无详细信息的网络异常
- */
- public NetworkFailureException() {
- super();
- }
-
- /**
- * 构造一个带有详细信息的网络异常
- *
- * @param paramString 异常的详细信息,描述网络失败的具体原因
- */
- public NetworkFailureException(String paramString) {
- super(paramString);
- }
-
- /**
- * 构造一个带有详细信息和原因的网络异常
- *
- * @param paramString 异常的详细信息,描述网络失败的具体原因
- * @param paramThrowable 导致此异常的底层异常或错误
- */
- public NetworkFailureException(String paramString, Throwable paramThrowable) {
- super(paramString, paramThrowable);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
deleted file mode 100644
index f8ea190..0000000
--- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
+++ /dev/null
@@ -1,222 +0,0 @@
-
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.AsyncTask;
-
-import net.micode.notes.R;
-import net.micode.notes.ui.NotesListActivity;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-
-/**
- * Google Tasks 同步异步任务
- *
- * 继承自 AsyncTask,用于在后台执行 Google Tasks 同步操作。
- * 支持进度更新、通知显示和同步完成回调。
- *
- */
-public class GTaskASyncTask extends AsyncTask {
-
- /** 同步通知的唯一标识符 */
- private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
-
- /**
- * 同步完成监听器接口
- *
- * 定义同步完成时的回调方法,用于通知调用方同步任务已结束。
- *
- */
- public interface OnCompleteListener {
- /**
- * 同步完成时的回调方法
- */
- void onComplete();
- }
-
- /** 应用上下文 */
- private Context mContext;
-
- /** 通知管理器 */
- private NotificationManager mNotifiManager;
-
- /** Google Tasks 管理器实例 */
- private GTaskManager mTaskManager;
-
- /** 同步完成监听器 */
- private OnCompleteListener mOnCompleteListener;
-
- /**
- * 构造函数
- *
- * 初始化异步任务所需的上下文、监听器、通知管理器和任务管理器。
- *
- *
- * @param context 应用上下文
- * @param listener 同步完成监听器
- */
- public GTaskASyncTask(Context context, OnCompleteListener listener) {
- mContext = context;
- mOnCompleteListener = listener;
- // 获取系统通知服务
- mNotifiManager = (NotificationManager) mContext
- .getSystemService(Context.NOTIFICATION_SERVICE);
- // 获取 GTaskManager 单例
- mTaskManager = GTaskManager.getInstance();
- }
-
- /**
- * 取消同步操作
- *
- * 调用 GTaskManager 的 cancelSync() 方法取消正在进行的同步。
- *
- */
- public void cancelSync() {
- mTaskManager.cancelSync();
- }
-
- /**
- * 发布同步进度
- *
- * 调用 AsyncTask 的 publishProgress() 方法发布进度消息到 UI 线程。
- *
- *
- * @param message 进度消息
- */
- public void publishProgess(String message) {
- publishProgress(new String[] {
- message
- });
- }
-
- /**
- * 显示同步通知
- *
- * 在状态栏显示同步进度或结果通知。
- * 同步成功时跳转到笔记列表,其他情况跳转到设置页面。
- *
- *
- * @param tickerId 通知标题字符串资源 ID
- * @param content 通知内容文本
- */
- private void showNotification(int tickerId, String content) {
- PendingIntent pendingIntent;
- // 根据同步结果选择跳转目标
- if (tickerId != R.string.ticker_success) {
- // 同步失败或取消,跳转到设置页面
- pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
- NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
- } else {
- // 同步成功,跳转到笔记列表
- pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
- NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
- }
- // 构建通知
- Notification.Builder builder = new Notification.Builder(mContext)
- .setAutoCancel(true)
- .setContentTitle(mContext.getString(R.string.app_name))
- .setContentText(content)
- .setContentIntent(pendingIntent)
- .setWhen(System.currentTimeMillis())
- .setOngoing(true);
- Notification notification=builder.getNotification();
- // 显示通知
- mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
- }
-
- /**
- * 后台执行同步操作
- *
- * 在后台线程执行 Google Tasks 同步,发布登录进度并返回同步结果。
- *
- *
- * @param unused 未使用的参数
- * @return 同步状态码(GTaskManager.STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED)
- */
- @Override
- protected Integer doInBackground(Void... unused) {
- // 发布登录进度
- publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
- .getSyncAccountName(mContext)));
- // 执行同步并返回结果
- return mTaskManager.sync(mContext, this);
- }
-
- /**
- * 进度更新回调
- *
- * 在 UI 线程更新同步进度,显示通知并发送广播。
- *
- *
- * @param progress 进度消息数组
- */
- @Override
- protected void onProgressUpdate(String... progress) {
- // 显示进度通知
- showNotification(R.string.ticker_syncing, progress[0]);
- // 如果上下文是 GTaskSyncService,发送广播
- if (mContext instanceof GTaskSyncService) {
- ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
- }
- }
-
- /**
- * 同步完成回调
- *
- * 根据同步结果显示相应的通知,并调用完成监听器。
- * 更新最后同步时间(仅在同步成功时)。
- *
- *
- * @param result 同步结果状态码
- */
- @Override
- protected void onPostExecute(Integer result) {
- // 根据同步结果显示相应通知
- if (result == GTaskManager.STATE_SUCCESS) {
- // 同步成功
- showNotification(R.string.ticker_success, mContext.getString(
- R.string.success_sync_account, mTaskManager.getSyncAccount()));
- // 更新最后同步时间
- NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
- } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
- // 网络错误
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
- } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
- // 内部错误
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
- } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
- // 同步已取消
- showNotification(R.string.ticker_cancel, mContext
- .getString(R.string.error_sync_cancelled));
- }
- // 调用完成监听器
- if (mOnCompleteListener != null) {
- new Thread(new Runnable() {
-
- public void run() {
- mOnCompleteListener.onComplete();
- }
- }).start();
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java
deleted file mode 100644
index 8201fbd..0000000
--- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java
+++ /dev/null
@@ -1,784 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerFuture;
-import android.app.Activity;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.gtask.data.Node;
-import net.micode.notes.gtask.data.Task;
-import net.micode.notes.gtask.data.TaskList;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.gtask.exception.NetworkFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.cookie.Cookie;
-import org.apache.http.impl.client.BasicCookieStore;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.params.HttpProtocolParams;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.Inflater;
-import java.util.zip.InflaterInputStream;
-
-
-/**
- * Google Tasks 客户端类
- *
- * 单例模式实现的 Google Tasks API 客户端,负责与 Google Tasks 服务器的网络通信。
- * 提供登录认证、任务列表和任务的增删改查、批量更新等功能。
- * 使用 HTTP 协议与 Google Tasks API 交互,支持 Cookie 认证和会话管理。
- *
- */
-public class GTaskClient {
- private static final String TAG = GTaskClient.class.getSimpleName();
-
- /** Google Tasks 基础 URL */
- private static final String GTASK_URL = "https://mail.google.com/tasks/";
-
- /** Google Tasks GET 请求 URL */
- private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
-
- /** Google Tasks POST 请求 URL */
- private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
-
- /** 单例实例 */
- private static GTaskClient mInstance = null;
-
- private DefaultHttpClient mHttpClient;
-
- private String mGetUrl;
-
- private String mPostUrl;
-
- private long mClientVersion;
-
- private boolean mLoggedin;
-
- private long mLastLoginTime;
-
- private int mActionId;
-
- private Account mAccount;
-
- private JSONArray mUpdateArray;
-
- /**
- * 私有构造函数
- *
- * 初始化所有成员变量为默认值,防止外部直接实例化。
- *
- */
- private GTaskClient() {
- mHttpClient = null;
- mGetUrl = GTASK_GET_URL;
- mPostUrl = GTASK_POST_URL;
- mClientVersion = -1;
- mLoggedin = false;
- mLastLoginTime = 0;
- mActionId = 1;
- mAccount = null;
- mUpdateArray = null;
- }
-
- /**
- * 获取 GTaskClient 单例实例
- *
- * 使用双重检查锁定确保线程安全的单例实现。
- *
- *
- * @return GTaskClient 单例实例
- */
- public static synchronized GTaskClient getInstance() {
- if (mInstance == null) {
- mInstance = new GTaskClient();
- }
- return mInstance;
- }
-
- /**
- * 登录 Google Tasks
- *
- * 检查登录状态和账户信息,必要时重新登录。
- * Cookie 有效期为 5 分钟,超时后需要重新登录。
- * 支持自定义域名账户和标准 Gmail/Googlemail 账户。
- *
- *
- * @param activity Activity 上下文,用于账户管理
- * @return 如果登录成功返回 true,否则返回 false
- */
- public boolean login(Activity activity) {
- // we suppose that the cookie would expire after 5 minutes
- // then we need to re-login
- final long interval = 1000 * 60 * 5;
- if (mLastLoginTime + interval < System.currentTimeMillis()) {
- mLoggedin = false;
- }
-
- // need to re-login after account switch
- if (mLoggedin
- && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
- .getSyncAccountName(activity))) {
- mLoggedin = false;
- }
-
- if (mLoggedin) {
- Log.d(TAG, "already logged in");
- return true;
- }
-
- mLastLoginTime = System.currentTimeMillis();
- String authToken = loginGoogleAccount(activity, false);
- if (authToken == null) {
- Log.e(TAG, "login google account failed");
- return false;
- }
-
- // login with custom domain if necessary
- if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
- .endsWith("googlemail.com"))) {
- StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
- int index = mAccount.name.indexOf('@') + 1;
- String suffix = mAccount.name.substring(index);
- url.append(suffix + "/");
- mGetUrl = url.toString() + "ig";
- mPostUrl = url.toString() + "r/ig";
-
- if (tryToLoginGtask(activity, authToken)) {
- mLoggedin = true;
- }
- }
-
- // try to login with google official url
- if (!mLoggedin) {
- mGetUrl = GTASK_GET_URL;
- mPostUrl = GTASK_POST_URL;
- if (!tryToLoginGtask(activity, authToken)) {
- return false;
- }
- }
-
- mLoggedin = true;
- return true;
- }
-
-
-
- /**
- * 登录 Google 账户获取认证令牌
- *
- * 从系统账户管理器获取 Google 账户的认证令牌。
- * 如果 invalidateToken 为 true,会先使旧令牌失效再获取新令牌。
- *
- *
- * @param activity Activity 上下文
- * @param invalidateToken 是否使旧令牌失效
- * @return 认证令牌,如果失败则返回 null
- */
- private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
- String authToken;
- AccountManager accountManager = AccountManager.get(activity);
- Account[] accounts = accountManager.getAccountsByType("com.google");
-
- if (accounts.length == 0) {
- Log.e(TAG, "there is no available google account");
- return null;
- }
-
- String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
- Account account = null;
- for (Account a : accounts) {
- if (a.name.equals(accountName)) {
- account = a;
- break;
- }
- }
- if (account != null) {
- mAccount = account;
- } else {
- Log.e(TAG, "unable to get an account with the same name in the settings");
- return null;
- }
-
- // get the token now
- AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,
- "goanna_mobile", null, activity, null, null);
- try {
- Bundle authTokenBundle = accountManagerFuture.getResult();
- authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
- if (invalidateToken) {
- accountManager.invalidateAuthToken("com.google", authToken);
- loginGoogleAccount(activity, false);
- }
- } catch (Exception e) {
- Log.e(TAG, "get auth token failed");
- authToken = null;
- }
-
- return authToken;
- }
-
- /**
- * 尝试登录 Google Tasks
- *
- * 使用认证令牌尝试登录 Google Tasks,如果失败则使令牌失效并重试。
- *
- *
- * @param activity Activity 上下文
- * @param authToken 认证令牌
- * @return 如果登录成功返回 true,否则返回 false
- */
- private boolean tryToLoginGtask(Activity activity, String authToken) {
- if (!loginGtask(authToken)) {
- // maybe the auth token is out of date, now let's invalidate the
- // token and try again
- authToken = loginGoogleAccount(activity, true);
- if (authToken == null) {
- Log.e(TAG, "login google account failed");
- return false;
- }
-
- if (!loginGtask(authToken)) {
- Log.e(TAG, "login gtask failed");
- return false;
- }
- }
- return true;
- }
-
- /**
- * 使用认证令牌登录 Google Tasks
- *
- * 向 Google Tasks 服务器发送 GET 请求进行认证,获取 Cookie 和客户端版本号。
- *
- *
- * @param authToken 认证令牌
- * @return 如果登录成功返回 true,否则返回 false
- */
- private boolean loginGtask(String authToken) {
- int timeoutConnection = 10000;
- int timeoutSocket = 15000;
- HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
- HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
- mHttpClient = new DefaultHttpClient(httpParameters);
- BasicCookieStore localBasicCookieStore = new BasicCookieStore();
- mHttpClient.setCookieStore(localBasicCookieStore);
- HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
-
- // login gtask
- try {
- String loginUrl = mGetUrl + "?auth=" + authToken;
- HttpGet httpGet = new HttpGet(loginUrl);
- HttpResponse response = null;
- response = mHttpClient.execute(httpGet);
-
- // get the cookie now
- List cookies = mHttpClient.getCookieStore().getCookies();
- boolean hasAuthCookie = false;
- for (Cookie cookie : cookies) {
- if (cookie.getName().contains("GTL")) {
- hasAuthCookie = true;
- }
- }
- if (!hasAuthCookie) {
- Log.w(TAG, "it seems that there is no auth cookie");
- }
-
- // get the client version
- String resString = getResponseContent(response.getEntity());
- String jsBegin = "_setup(";
- String jsEnd = ")}";
- int begin = resString.indexOf(jsBegin);
- int end = resString.lastIndexOf(jsEnd);
- String jsString = null;
- if (begin != -1 && end != -1 && begin < end) {
- jsString = resString.substring(begin + jsBegin.length(), end);
- }
- JSONObject js = new JSONObject(jsString);
- mClientVersion = js.getLong("v");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return false;
- } catch (Exception e) {
- // simply catch all exceptions
- Log.e(TAG, "httpget gtask_url failed");
- return false;
- }
-
- return true;
- }
-
- /**
- * 获取下一个动作 ID
- *
- * 每次调用返回递增的动作 ID,用于标识不同的操作请求。
- *
- *
- * @return 动作 ID
- */
- private int getActionId() {
- return mActionId++;
- }
-
- /**
- * 创建 HTTP POST 请求对象
- *
- * 配置请求头,设置内容类型为 application/x-www-form-urlencoded。
- *
- *
- * @return 配置好的 HttpPost 对象
- */
- private HttpPost createHttpPost() {
- HttpPost httpPost = new HttpPost(mPostUrl);
- httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- httpPost.setHeader("AT", "1");
- return httpPost;
- }
-
- /**
- * 获取 HTTP 响应内容
- *
- * 解析 HTTP 实体的内容,支持 gzip 和 deflate 压缩格式。
- *
- *
- * @param entity HTTP 响应实体
- * @return 响应内容的字符串
- * @throws IOException 如果读取响应内容失败
- */
- private String getResponseContent(HttpEntity entity) throws IOException {
- String contentEncoding = null;
- if (entity.getContentEncoding() != null) {
- contentEncoding = entity.getContentEncoding().getValue();
- Log.d(TAG, "encoding: " + contentEncoding);
- }
-
- InputStream input = entity.getContent();
- if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
- input = new GZIPInputStream(entity.getContent());
- } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
- Inflater inflater = new Inflater(true);
- input = new InflaterInputStream(entity.getContent(), inflater);
- }
-
- try {
- InputStreamReader isr = new InputStreamReader(input);
- BufferedReader br = new BufferedReader(isr);
- StringBuilder sb = new StringBuilder();
-
- while (true) {
- String buff = br.readLine();
- if (buff == null) {
- return sb.toString();
- }
- sb = sb.append(buff);
- }
- } finally {
- input.close();
- }
- }
-
- /**
- * 发送 POST 请求到 Google Tasks 服务器
- *
- * 将 JSON 数据封装为 POST 请求发送到服务器,并解析返回的 JSON 响应。
- *
- *
- * @param js 要发送的 JSON 对象
- * @return 服务器返回的 JSON 对象
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果未登录或 JSON 解析失败
- */
- private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
- if (!mLoggedin) {
- Log.e(TAG, "please login first");
- throw new ActionFailureException("not logged in");
- }
-
- HttpPost httpPost = createHttpPost();
- try {
- LinkedList list = new LinkedList();
- list.add(new BasicNameValuePair("r", js.toString()));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
- httpPost.setEntity(entity);
-
- // execute the post
- HttpResponse response = mHttpClient.execute(httpPost);
- String jsString = getResponseContent(response.getEntity());
- return new JSONObject(jsString);
-
- } catch (ClientProtocolException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("postRequest failed");
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("postRequest failed");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("unable to convert response content to jsonobject");
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("error occurs when posting request");
- }
- }
-
- /**
- * 创建新的任务
- *
- * 向 Google Tasks 服务器发送创建任务请求,获取服务器分配的任务 ID。
- *
- *
- * @param task 要创建的任务对象
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public void createTask(Task task) throws NetworkFailureException {
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
-
- // action_list
- actionList.put(task.getCreateAction(getActionId()));
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // post
- JSONObject jsResponse = postRequest(jsPost);
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
- GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
- task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("create task: handing jsonobject failed");
- }
- }
-
- /**
- * 创建新的任务列表
- *
- * 向 Google Tasks 服务器发送创建任务列表请求,获取服务器分配的任务列表 ID。
- *
- *
- * @param tasklist 要创建的任务列表对象
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public void createTaskList(TaskList tasklist) throws NetworkFailureException {
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
-
- // action_list
- actionList.put(tasklist.getCreateAction(getActionId()));
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // post
- JSONObject jsResponse = postRequest(jsPost);
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
- GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
- tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("create tasklist: handing jsonobject failed");
- }
- }
-
- /**
- * 提交批量更新请求
- *
- * 将待更新的节点批量发送到 Google Tasks 服务器。
- * 如果没有待更新的节点,则不执行任何操作。
- *
- *
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public void commitUpdate() throws NetworkFailureException {
- if (mUpdateArray != null) {
- try {
- JSONObject jsPost = new JSONObject();
-
- // action_list
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- postRequest(jsPost);
- mUpdateArray = null;
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("commit update: handing jsonobject failed");
- }
- }
- }
-
- /**
- * 添加待更新节点到批量更新队列
- *
- * 将节点添加到更新队列中,当队列超过 10 个节点时自动提交。
- *
- *
- * @param node 要更新的节点,如果为 null 则不执行任何操作
- * @throws NetworkFailureException 如果提交更新时网络请求失败
- */
- public void addUpdateNode(Node node) throws NetworkFailureException {
- if (node != null) {
- // too many update items may result in an error
- // set max to 10 items
- if (mUpdateArray != null && mUpdateArray.length() > 10) {
- commitUpdate();
- }
-
- if (mUpdateArray == null)
- mUpdateArray = new JSONArray();
- mUpdateArray.put(node.getUpdateAction(getActionId()));
- }
- }
-
- /**
- * 移动任务到新的任务列表或新位置
- *
- * 将任务从一个任务列表移动到另一个任务列表,或在同一任务列表中调整顺序。
- *
- *
- * @param task 要移动的任务
- * @param preParent 任务的原父任务列表
- * @param curParent 任务的新父任务列表
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public void moveTask(Task task, TaskList preParent, TaskList curParent)
- throws NetworkFailureException {
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
- JSONObject action = new JSONObject();
-
- // action_list
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
- action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
- if (preParent == curParent && task.getPriorSibling() != null) {
- // put prioring_sibing_id only if moving within the tasklist and
- // it is not the first one
- action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
- }
- action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
- action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
- if (preParent != curParent) {
- // put the dest_list only if moving between tasklists
- action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
- }
- actionList.put(action);
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- postRequest(jsPost);
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("move task: handing jsonobject failed");
- }
- }
-
- /**
- * 删除节点
- *
- * 向 Google Tasks 服务器发送删除节点请求,将节点标记为已删除。
- *
- *
- * @param node 要删除的节点
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public void deleteNode(Node node) throws NetworkFailureException {
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
-
- // action_list
- node.setDeleted(true);
- actionList.put(node.getUpdateAction(getActionId()));
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- postRequest(jsPost);
- mUpdateArray = null;
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("delete node: handing jsonobject failed");
- }
- }
-
- /**
- * 获取所有任务列表
- *
- * 从 Google Tasks 服务器获取当前账户的所有任务列表。
- *
- *
- * @return 包含所有任务列表信息的 JSON 数组
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果未登录或 JSON 解析失败
- */
- public JSONArray getTaskLists() throws NetworkFailureException {
- if (!mLoggedin) {
- Log.e(TAG, "please login first");
- throw new ActionFailureException("not logged in");
- }
-
- try {
- HttpGet httpGet = new HttpGet(mGetUrl);
- HttpResponse response = null;
- response = mHttpClient.execute(httpGet);
-
- // get the task list
- String resString = getResponseContent(response.getEntity());
- String jsBegin = "_setup(";
- String jsEnd = ")}";
- int begin = resString.indexOf(jsBegin);
- int end = resString.lastIndexOf(jsEnd);
- String jsString = null;
- if (begin != -1 && end != -1 && begin < end) {
- jsString = resString.substring(begin + jsBegin.length(), end);
- }
- JSONObject js = new JSONObject(jsString);
- return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
- } catch (ClientProtocolException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("gettasklists: httpget failed");
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("gettasklists: httpget failed");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("get task lists: handing jasonobject failed");
- }
- }
-
- /**
- * 获取指定任务列表中的所有任务
- *
- * 从 Google Tasks 服务器获取指定任务列表中的所有任务。
- *
- *
- * @param listGid 任务列表的 Google ID
- * @return 包含该任务列表中所有任务信息的 JSON 数组
- * @throws NetworkFailureException 如果网络请求失败
- * @throws ActionFailureException 如果 JSON 处理失败
- */
- public JSONArray getTaskList(String listGid) throws NetworkFailureException {
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
- JSONObject action = new JSONObject();
-
- // action_list
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
- action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
- action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
- actionList.put(action);
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- JSONObject jsResponse = postRequest(jsPost);
- return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("get task list: handing jsonobject failed");
- }
- }
-
- /**
- * 获取同步账户
- *
- * @return 当前登录的 Google 账户
- */
- public Account getSyncAccount() {
- return mAccount;
- }
-
- /**
- * 重置更新数组
- *
- * 清空待更新的节点队列,取消所有未提交的更新操作。
- *
- */
- public void resetUpdateArray() {
- mUpdateArray = null;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java
deleted file mode 100644
index 6beb7a7..0000000
--- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java
+++ /dev/null
@@ -1,857 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.app.Activity;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.util.Log;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.data.MetaData;
-import net.micode.notes.gtask.data.Node;
-import net.micode.notes.gtask.data.SqlNote;
-import net.micode.notes.gtask.data.Task;
-import net.micode.notes.gtask.data.TaskList;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.gtask.exception.NetworkFailureException;
-import net.micode.notes.tool.DataUtils;
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-
-/**
- * Google Tasks 同步管理器
- *
- * 单例模式实现的同步管理器,负责本地笔记与 Google Tasks 之间的数据同步。
- * 提供完整的双向同步功能,包括文件夹、笔记的增删改查操作。
- * 支持同步状态管理、冲突解决和元数据维护。
- *
- */
-public class GTaskManager {
- private static final String TAG = GTaskManager.class.getSimpleName();
-
- /** 同步成功状态码 */
- public static final int STATE_SUCCESS = 0;
-
- /** 网络错误状态码 */
- public static final int STATE_NETWORK_ERROR = 1;
-
- /** 内部错误状态码 */
- public static final int STATE_INTERNAL_ERROR = 2;
-
- /** 同步进行中状态码 */
- public static final int STATE_SYNC_IN_PROGRESS = 3;
-
- /** 同步已取消状态码 */
- public static final int STATE_SYNC_CANCELLED = 4;
-
- private static GTaskManager mInstance = null;
-
- private Activity mActivity;
-
- private Context mContext;
-
- private ContentResolver mContentResolver;
-
- private boolean mSyncing;
-
- private boolean mCancelled;
-
- private HashMap mGTaskListHashMap;
-
- private HashMap mGTaskHashMap;
-
- private HashMap mMetaHashMap;
-
- private TaskList mMetaList;
-
- private HashSet mLocalDeleteIdMap;
-
- private HashMap mGidToNid;
-
- private HashMap mNidToGid;
-
- /**
- * 私有构造函数
- *
- * 初始化所有成员变量,防止外部直接实例化。
- *
- */
- private GTaskManager() {
- mSyncing = false;
- mCancelled = false;
- mGTaskListHashMap = new HashMap();
- mGTaskHashMap = new HashMap();
- mMetaHashMap = new HashMap();
- mMetaList = null;
- mLocalDeleteIdMap = new HashSet();
- mGidToNid = new HashMap();
- mNidToGid = new HashMap();
- }
-
- /**
- * 获取 GTaskManager 单例实例
- *
- * 使用双重检查锁定确保线程安全的单例实现。
- *
- *
- * @return GTaskManager 单例实例
- */
- public static synchronized GTaskManager getInstance() {
- if (mInstance == null) {
- mInstance = new GTaskManager();
- }
- return mInstance;
- }
-
- /**
- * 设置 Activity 上下文
- *
- * 用于获取 Google 账户的认证令牌。
- *
- *
- * @param activity Activity 上下文
- */
- public synchronized void setActivityContext(Activity activity) {
- // used for getting authtoken
- mActivity = activity;
- }
-
- /**
- * 执行同步操作
- *
- * 执行本地笔记与 Google Tasks 之间的双向同步。
- * 包括登录 Google Tasks、初始化任务列表、同步内容等步骤。
- *
- *
- * @param context 应用上下文
- * @param asyncTask 异步任务对象,用于发布进度
- * @return 同步状态码(STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED)
- */
- public int sync(Context context, GTaskASyncTask asyncTask) {
- if (mSyncing) {
- Log.d(TAG, "Sync is in progress");
- return STATE_SYNC_IN_PROGRESS;
- }
- mContext = context;
- mContentResolver = mContext.getContentResolver();
- mSyncing = true;
- mCancelled = false;
- mGTaskListHashMap.clear();
- mGTaskHashMap.clear();
- mMetaHashMap.clear();
- mLocalDeleteIdMap.clear();
- mGidToNid.clear();
- mNidToGid.clear();
-
- try {
- GTaskClient client = GTaskClient.getInstance();
- client.resetUpdateArray();
-
- // login google task
- if (!mCancelled) {
- if (!client.login(mActivity)) {
- throw new NetworkFailureException("login google task failed");
- }
- }
-
- // get the task list from google
- asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
- initGTaskList();
-
- // do content sync work
- asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
- syncContent();
- } catch (NetworkFailureException e) {
- Log.e(TAG, e.toString());
- return STATE_NETWORK_ERROR;
- } catch (ActionFailureException e) {
- Log.e(TAG, e.toString());
- return STATE_INTERNAL_ERROR;
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return STATE_INTERNAL_ERROR;
- } finally {
- mGTaskListHashMap.clear();
- mGTaskHashMap.clear();
- mMetaHashMap.clear();
- mLocalDeleteIdMap.clear();
- mGidToNid.clear();
- mNidToGid.clear();
- mSyncing = false;
- }
-
- return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
- }
-
- private void initGTaskList() throws NetworkFailureException {
- if (mCancelled)
- return;
- GTaskClient client = GTaskClient.getInstance();
- try {
- JSONArray jsTaskLists = client.getTaskLists();
-
- // init meta list first
- mMetaList = null;
- for (int i = 0; i < jsTaskLists.length(); i++) {
- JSONObject object = jsTaskLists.getJSONObject(i);
- String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
-
- if (name
- .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
- mMetaList = new TaskList();
- mMetaList.setContentByRemoteJSON(object);
-
- // load meta data
- JSONArray jsMetas = client.getTaskList(gid);
- for (int j = 0; j < jsMetas.length(); j++) {
- object = (JSONObject) jsMetas.getJSONObject(j);
- MetaData metaData = new MetaData();
- metaData.setContentByRemoteJSON(object);
- if (metaData.isWorthSaving()) {
- mMetaList.addChildTask(metaData);
- if (metaData.getGid() != null) {
- mMetaHashMap.put(metaData.getRelatedGid(), metaData);
- }
- }
- }
- }
- }
-
- // create meta list if not existed
- if (mMetaList == null) {
- mMetaList = new TaskList();
- mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_META);
- GTaskClient.getInstance().createTaskList(mMetaList);
- }
-
- // init task list
- for (int i = 0; i < jsTaskLists.length(); i++) {
- JSONObject object = jsTaskLists.getJSONObject(i);
- String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
-
- if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
- && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_META)) {
- TaskList tasklist = new TaskList();
- tasklist.setContentByRemoteJSON(object);
- mGTaskListHashMap.put(gid, tasklist);
- mGTaskHashMap.put(gid, tasklist);
-
- // load tasks
- JSONArray jsTasks = client.getTaskList(gid);
- for (int j = 0; j < jsTasks.length(); j++) {
- object = (JSONObject) jsTasks.getJSONObject(j);
- gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- Task task = new Task();
- task.setContentByRemoteJSON(object);
- if (task.isWorthSaving()) {
- task.setMetaInfo(mMetaHashMap.get(gid));
- tasklist.addChildTask(task);
- mGTaskHashMap.put(gid, task);
- }
- }
- }
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("initGTaskList: handing JSONObject failed");
- }
- }
-
- private void syncContent() throws NetworkFailureException {
- int syncType;
- Cursor c = null;
- String gid;
- Node node;
-
- mLocalDeleteIdMap.clear();
-
- if (mCancelled) {
- return;
- }
-
- // for local deleted note
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type<>? AND parent_id=?)", new String[] {
- String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
- }, null);
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
- }
-
- mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
- }
- } else {
- Log.w(TAG, "failed to query trash folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // sync folder first
- syncFolder();
-
- // for note existing in database
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type=? AND parent_id<>?)", new String[] {
- String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
- }, NoteColumns.TYPE + " DESC");
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
- mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- syncType = node.getSyncAction(c);
- } else {
- if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // local add
- syncType = Node.SYNC_ACTION_ADD_REMOTE;
- } else {
- // remote delete
- syncType = Node.SYNC_ACTION_DEL_LOCAL;
- }
- }
- doContentSync(syncType, node, c);
- }
- } else {
- Log.w(TAG, "failed to query existing note in database");
- }
-
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // go through remaining items
- Iterator> iter = mGTaskHashMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = iter.next();
- node = entry.getValue();
- doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
- }
-
- // mCancelled can be set by another thread, so we neet to check one by
- // one
- // clear local delete table
- if (!mCancelled) {
- if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
- throw new ActionFailureException("failed to batch-delete local deleted notes");
- }
- }
-
- // refresh local sync id
- if (!mCancelled) {
- GTaskClient.getInstance().commitUpdate();
- refreshLocalSyncId();
- }
-
- }
-
- private void syncFolder() throws NetworkFailureException {
- Cursor c = null;
- String gid;
- Node node;
- int syncType;
-
- if (mCancelled) {
- return;
- }
-
- // for root folder
- try {
- c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
- Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
- if (c != null) {
- c.moveToNext();
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
- mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
- // for system folder, only update remote name if necessary
- if (!node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
- doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
- } else {
- doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
- }
- } else {
- Log.w(TAG, "failed to query root folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // for call-note folder
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
- new String[] {
- String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
- }, null);
- if (c != null) {
- if (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
- mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
- // for system folder, only update remote name if
- // necessary
- if (!node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_CALL_NOTE))
- doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
- } else {
- doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
- }
- }
- } else {
- Log.w(TAG, "failed to query call note folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // for local existing folders
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type=? AND parent_id<>?)", new String[] {
- String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
- }, NoteColumns.TYPE + " DESC");
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
- mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- syncType = node.getSyncAction(c);
- } else {
- if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // local add
- syncType = Node.SYNC_ACTION_ADD_REMOTE;
- } else {
- // remote delete
- syncType = Node.SYNC_ACTION_DEL_LOCAL;
- }
- }
- doContentSync(syncType, node, c);
- }
- } else {
- Log.w(TAG, "failed to query existing folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // for remote add folders
- Iterator> iter = mGTaskListHashMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = iter.next();
- gid = entry.getKey();
- node = entry.getValue();
- if (mGTaskHashMap.containsKey(gid)) {
- mGTaskHashMap.remove(gid);
- doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
- }
- }
-
- if (!mCancelled)
- GTaskClient.getInstance().commitUpdate();
- }
-
- private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- MetaData meta;
- switch (syncType) {
- case Node.SYNC_ACTION_ADD_LOCAL:
- addLocalNode(node);
- break;
- case Node.SYNC_ACTION_ADD_REMOTE:
- addRemoteNode(node, c);
- break;
- case Node.SYNC_ACTION_DEL_LOCAL:
- meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
- if (meta != null) {
- GTaskClient.getInstance().deleteNode(meta);
- }
- mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
- break;
- case Node.SYNC_ACTION_DEL_REMOTE:
- meta = mMetaHashMap.get(node.getGid());
- if (meta != null) {
- GTaskClient.getInstance().deleteNode(meta);
- }
- GTaskClient.getInstance().deleteNode(node);
- break;
- case Node.SYNC_ACTION_UPDATE_LOCAL:
- updateLocalNode(node, c);
- break;
- case Node.SYNC_ACTION_UPDATE_REMOTE:
- updateRemoteNode(node, c);
- break;
- case Node.SYNC_ACTION_UPDATE_CONFLICT:
- // merging both modifications maybe a good idea
- // right now just use local update simply
- updateRemoteNode(node, c);
- break;
- case Node.SYNC_ACTION_NONE:
- break;
- case Node.SYNC_ACTION_ERROR:
- default:
- throw new ActionFailureException("unkown sync action type");
- }
- }
-
- private void addLocalNode(Node node) throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- SqlNote sqlNote;
- if (node instanceof TaskList) {
- if (node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
- sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
- } else if (node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
- sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
- } else {
- sqlNote = new SqlNote(mContext);
- sqlNote.setContent(node.getLocalJSONFromContent());
- sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
- }
- } else {
- sqlNote = new SqlNote(mContext);
- JSONObject js = node.getLocalJSONFromContent();
- try {
- if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
- JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- if (note.has(NoteColumns.ID)) {
- long id = note.getLong(NoteColumns.ID);
- if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
- // the id is not available, have to create a new one
- note.remove(NoteColumns.ID);
- }
- }
- }
-
- if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
- JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- if (data.has(DataColumns.ID)) {
- long dataId = data.getLong(DataColumns.ID);
- if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
- // the data id is not available, have to create
- // a new one
- data.remove(DataColumns.ID);
- }
- }
- }
-
- }
- } catch (JSONException e) {
- Log.w(TAG, e.toString());
- e.printStackTrace();
- }
- sqlNote.setContent(js);
-
- Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
- if (parentId == null) {
- Log.e(TAG, "cannot find task's parent id locally");
- throw new ActionFailureException("cannot add local node");
- }
- sqlNote.setParentId(parentId.longValue());
- }
-
- // create the local node
- sqlNote.setGtaskId(node.getGid());
- sqlNote.commit(false);
-
- // update gid-nid mapping
- mGidToNid.put(node.getGid(), sqlNote.getId());
- mNidToGid.put(sqlNote.getId(), node.getGid());
-
- // update meta
- updateRemoteMeta(node.getGid(), sqlNote);
- }
-
- private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- SqlNote sqlNote;
- // update the note locally
- sqlNote = new SqlNote(mContext, c);
- sqlNote.setContent(node.getLocalJSONFromContent());
-
- Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
- : new Long(Notes.ID_ROOT_FOLDER);
- if (parentId == null) {
- Log.e(TAG, "cannot find task's parent id locally");
- throw new ActionFailureException("cannot update local node");
- }
- sqlNote.setParentId(parentId.longValue());
- sqlNote.commit(true);
-
- // update meta info
- updateRemoteMeta(node.getGid(), sqlNote);
- }
-
- private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- SqlNote sqlNote = new SqlNote(mContext, c);
- Node n;
-
- // update remotely
- if (sqlNote.isNoteType()) {
- Task task = new Task();
- task.setContentByLocalJSON(sqlNote.getContent());
-
- String parentGid = mNidToGid.get(sqlNote.getParentId());
- if (parentGid == null) {
- Log.e(TAG, "cannot find task's parent tasklist");
- throw new ActionFailureException("cannot add remote task");
- }
- mGTaskListHashMap.get(parentGid).addChildTask(task);
-
- GTaskClient.getInstance().createTask(task);
- n = (Node) task;
-
- // add meta
- updateRemoteMeta(task.getGid(), sqlNote);
- } else {
- TaskList tasklist = null;
-
- // we need to skip folder if it has already existed
- String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
- if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
- folderName += GTaskStringUtils.FOLDER_DEFAULT;
- else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
- folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
- else
- folderName += sqlNote.getSnippet();
-
- Iterator> iter = mGTaskListHashMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = iter.next();
- String gid = entry.getKey();
- TaskList list = entry.getValue();
-
- if (list.getName().equals(folderName)) {
- tasklist = list;
- if (mGTaskHashMap.containsKey(gid)) {
- mGTaskHashMap.remove(gid);
- }
- break;
- }
- }
-
- // no match we can add now
- if (tasklist == null) {
- tasklist = new TaskList();
- tasklist.setContentByLocalJSON(sqlNote.getContent());
- GTaskClient.getInstance().createTaskList(tasklist);
- mGTaskListHashMap.put(tasklist.getGid(), tasklist);
- }
- n = (Node) tasklist;
- }
-
- // update local note
- sqlNote.setGtaskId(n.getGid());
- sqlNote.commit(false);
- sqlNote.resetLocalModified();
- sqlNote.commit(true);
-
- // gid-id mapping
- mGidToNid.put(n.getGid(), sqlNote.getId());
- mNidToGid.put(sqlNote.getId(), n.getGid());
- }
-
- private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- SqlNote sqlNote = new SqlNote(mContext, c);
-
- // update remotely
- node.setContentByLocalJSON(sqlNote.getContent());
- GTaskClient.getInstance().addUpdateNode(node);
-
- // update meta
- updateRemoteMeta(node.getGid(), sqlNote);
-
- // move task if necessary
- if (sqlNote.isNoteType()) {
- Task task = (Task) node;
- TaskList preParentList = task.getParent();
-
- String curParentGid = mNidToGid.get(sqlNote.getParentId());
- if (curParentGid == null) {
- Log.e(TAG, "cannot find task's parent tasklist");
- throw new ActionFailureException("cannot update remote task");
- }
- TaskList curParentList = mGTaskListHashMap.get(curParentGid);
-
- if (preParentList != curParentList) {
- preParentList.removeChildTask(task);
- curParentList.addChildTask(task);
- GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
- }
- }
-
- // clear local modified flag
- sqlNote.resetLocalModified();
- sqlNote.commit(true);
- }
-
- private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
- if (sqlNote != null && sqlNote.isNoteType()) {
- MetaData metaData = mMetaHashMap.get(gid);
- if (metaData != null) {
- metaData.setMeta(gid, sqlNote.getContent());
- GTaskClient.getInstance().addUpdateNode(metaData);
- } else {
- metaData = new MetaData();
- metaData.setMeta(gid, sqlNote.getContent());
- mMetaList.addChildTask(metaData);
- mMetaHashMap.put(gid, metaData);
- GTaskClient.getInstance().createTask(metaData);
- }
- }
- }
-
- private void refreshLocalSyncId() throws NetworkFailureException {
- if (mCancelled) {
- return;
- }
-
- // get the latest gtask list
- mGTaskHashMap.clear();
- mGTaskListHashMap.clear();
- mMetaHashMap.clear();
- initGTaskList();
-
- Cursor c = null;
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type<>? AND parent_id<>?)", new String[] {
- String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
- }, NoteColumns.TYPE + " DESC");
- if (c != null) {
- while (c.moveToNext()) {
- String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- Node node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- ContentValues values = new ContentValues();
- values.put(NoteColumns.SYNC_ID, node.getLastModified());
- mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
- c.getLong(SqlNote.ID_COLUMN)), values, null, null);
- } else {
- Log.e(TAG, "something is missed");
- throw new ActionFailureException(
- "some local items don't have gid after sync");
- }
- }
- } else {
- Log.w(TAG, "failed to query local note to refresh sync id");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
- }
-
- /**
- * 获取同步账户名称
- *
- * @return 当前同步的 Google 账户名称
- */
- public String getSyncAccount() {
- return mActivity == null ? null : GTaskClient.getInstance().getSyncAccount().name;
- }
-
- /**
- * 取消同步操作
- *
- * 设置取消标志,停止正在进行的同步操作。
- *
- */
- public void cancelSync() {
- mCancelled = true;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java
deleted file mode 100644
index d207f97..0000000
--- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.app.Activity;
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-
-/**
- * Google Tasks 同步服务
- *
- * 负责管理本地笔记与 Google Tasks 之间的后台同步操作。
- * 通过异步任务执行同步,支持同步状态广播和进度更新。
- *
- */
-public class GTaskSyncService extends Service {
- /** Intent 附加参数名称,用于指定同步操作类型 */
- public final static String ACTION_STRING_NAME = "sync_action_type";
-
- /** 启动同步操作的 Action 值 */
- public final static int ACTION_START_SYNC = 0;
-
- /** 取消同步操作的 Action 值 */
- public final static int ACTION_CANCEL_SYNC = 1;
-
- /** 无效的 Action 值 */
- public final static int ACTION_INVALID = 2;
-
- /** 同步服务广播名称 */
- public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
-
- /** 广播附加参数名称,用于标识是否正在同步 */
- public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
-
- /** 广播附加参数名称,用于传递同步进度消息 */
- public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
-
- /** 同步异步任务实例 */
- private static GTaskASyncTask mSyncTask = null;
-
- /** 同步进度消息 */
- private static String mSyncProgress = "";
-
- /**
- * 启动同步操作
- *
- * 创建并执行 GTaskASyncTask 异步任务,监听同步完成事件。
- * 同步完成后发送广播并停止服务。
- *
- */
- private void startSync() {
- // 检查是否已有同步任务在运行
- if (mSyncTask == null) {
- mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
- public void onComplete() {
- // 清空同步任务引用
- mSyncTask = null;
- // 发送同步完成广播
- sendBroadcast("");
- // 停止服务
- stopSelf();
- }
- });
- // 发送同步开始广播
- sendBroadcast("");
- // 执行异步同步任务
- mSyncTask.execute();
- }
- }
-
- /**
- * 取消同步操作
- *
- * 如果存在正在运行的同步任务,则调用其 cancelSync() 方法取消同步。
- *
- */
- private void cancelSync() {
- if (mSyncTask != null) {
- // 取消异步同步任务
- mSyncTask.cancelSync();
- }
- }
-
- /**
- * 服务创建时的回调
- *
- * 初始化同步任务为 null。
- *
- */
- @Override
- public void onCreate() {
- mSyncTask = null;
- }
-
- /**
- * 服务启动命令的回调
- *
- * 根据 Intent 中的 Action 类型执行相应的同步操作。
- * 支持 ACTION_START_SYNC 和 ACTION_CANCEL_SYNC 两种操作。
- *
- *
- * @param intent 启动服务的 Intent,包含 Action 类型参数
- * @param flags 启动标志
- * @param startId 启动 ID
- * @return START_STICKY 表示服务被杀死后会自动重启
- */
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Bundle bundle = intent.getExtras();
- // 检查 Intent 是否包含 Action 参数
- if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
- // 根据 Action 类型执行相应操作
- switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
- case ACTION_START_SYNC:
- startSync();
- break;
- case ACTION_CANCEL_SYNC:
- cancelSync();
- break;
- default:
- break;
- }
- return START_STICKY;
- }
- return super.onStartCommand(intent, flags, startId);
- }
-
- /**
- * 系统内存不足时的回调
- *
- * 取消正在进行的同步操作以释放资源。
- *
- */
- @Override
- public void onLowMemory() {
- if (mSyncTask != null) {
- // 取消同步任务以释放内存
- mSyncTask.cancelSync();
- }
- }
-
- /**
- * 绑定服务的回调
- *
- * 本服务不支持绑定,返回 null。
- *
- *
- * @param intent 绑定服务的 Intent
- * @return null,表示不支持绑定
- */
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- /**
- * 发送同步状态广播
- *
- * 向应用发送广播,包含当前同步状态和进度消息。
- *
- *
- * @param msg 同步进度消息
- */
- public void sendBroadcast(String msg) {
- // 更新同步进度消息
- mSyncProgress = msg;
- Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
- // 添加是否正在同步的标志
- intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
- // 添加进度消息
- intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
- // 发送广播
- sendBroadcast(intent);
- }
-
- /**
- * 启动同步服务
- *
- * 设置 Activity 上下文到 GTaskManager,然后启动同步服务执行同步操作。
- *
- *
- * @param activity Activity 上下文,用于获取 Google 账户认证信息
- */
- public static void startSync(Activity activity) {
- // 设置 Activity 上下文用于账户认证
- GTaskManager.getInstance().setActivityContext(activity);
- Intent intent = new Intent(activity, GTaskSyncService.class);
- intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
- // 启动同步服务
- activity.startService(intent);
- }
-
- /**
- * 取消同步服务
- *
- * 启动同步服务并发送取消同步的命令。
- *
- *
- * @param context 应用上下文
- */
- public static void cancelSync(Context context) {
- Intent intent = new Intent(context, GTaskSyncService.class);
- intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
- // 启动服务发送取消命令
- context.startService(intent);
- }
-
- /**
- * 检查是否正在同步
- *
- * @return 如果正在同步返回 true,否则返回 false
- */
- public static boolean isSyncing() {
- return mSyncTask != null;
- }
-
- /**
- * 获取同步进度消息
- *
- * @return 当前同步进度消息字符串
- */
- public static String getProgressString() {
- return mSyncProgress;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/model/Note.java b/app/src/main/java/net/micode/notes/model/Note.java
deleted file mode 100644
index 4cbd456..0000000
--- a/app/src/main/java/net/micode/notes/model/Note.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.model;
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.OperationApplicationException;
-import android.net.Uri;
-import android.os.RemoteException;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-
-import java.util.ArrayList;
-
-
-/**
- * 笔记数据模型类
- *
- * 负责管理笔记的基本信息和数据内容,支持笔记的创建、修改和同步操作。
- * 包含笔记元数据(如创建时间、修改时间、父文件夹等)和笔记数据(文本、通话记录等)。
- *
- */
-public class Note {
- /** 笔记差异值,用于记录需要同步的字段变更 */
- private ContentValues mNoteDiffValues;
-
- /** 笔记数据对象,包含文本数据和通话数据 */
- private NoteData mNoteData;
-
- /** 日志标签 */
- private static final String TAG = "Note";
-
- /**
- * 创建新笔记 ID
- *
- * 在数据库中创建一条新笔记记录,并返回其 ID。
- * 初始化笔记的创建时间、修改时间、类型和父文件夹 ID。
- *
- *
- * @param context 应用上下文
- * @param folderId 父文件夹 ID
- * @return 新创建的笔记 ID,失败时返回 0
- */
- public static synchronized long getNewNoteId(Context context, long folderId) {
- // 在数据库中创建新笔记
- ContentValues values = new ContentValues();
- long createdTime = System.currentTimeMillis();
- values.put(NoteColumns.CREATED_DATE, createdTime);
- values.put(NoteColumns.MODIFIED_DATE, createdTime);
- values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- values.put(NoteColumns.PARENT_ID, folderId);
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
-
- long noteId = 0;
- try {
- // 从 URI 中提取笔记 ID
- noteId = Long.valueOf(uri.getPathSegments().get(1));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Get note id error :" + e.toString());
- noteId = 0;
- }
- if (noteId == -1) {
- throw new IllegalStateException("Wrong note id:" + noteId);
- }
- return noteId;
- }
-
- /**
- * 构造函数
- *
- * 初始化笔记差异值和笔记数据对象。
- *
- */
- public Note() {
- mNoteDiffValues = new ContentValues();
- mNoteData = new NoteData();
- }
-
- /**
- * 设置笔记属性值
- *
- * 设置笔记的指定属性值,并标记为本地修改。
- *
- *
- * @param key 属性键名
- * @param value 属性值
- */
- public void setNoteValue(String key, String value) {
- mNoteDiffValues.put(key, value);
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 设置文本数据
- *
- * 设置笔记的文本数据内容。
- *
- *
- * @param key 数据键名
- * @param value 数据值
- */
- public void setTextData(String key, String value) {
- mNoteData.setTextData(key, value);
- }
-
- /**
- * 设置文本数据 ID
- *
- * 设置笔记文本数据的数据库记录 ID。
- *
- *
- * @param id 文本数据 ID
- */
- public void setTextDataId(long id) {
- mNoteData.setTextDataId(id);
- }
-
- /**
- * 获取文本数据 ID
- *
- * @return 文本数据 ID
- */
- public long getTextDataId() {
- return mNoteData.mTextDataId;
- }
-
- /**
- * 设置通话数据 ID
- *
- * 设置笔记通话数据的数据库记录 ID。
- *
- *
- * @param id 通话数据 ID
- */
- public void setCallDataId(long id) {
- mNoteData.setCallDataId(id);
- }
-
- /**
- * 设置通话数据
- *
- * 设置笔记的通话数据内容。
- *
- *
- * @param key 数据键名
- * @param value 数据值
- */
- public void setCallData(String key, String value) {
- mNoteData.setCallData(key, value);
- }
-
- /**
- * 检查是否本地修改
- *
- * 检查笔记是否有本地未同步的修改。
- *
- *
- * @return 如果有本地修改返回 true,否则返回 false
- */
- public boolean isLocalModified() {
- return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
- }
-
- /**
- * 同步笔记到数据库
- *
- * 将笔记的本地修改同步到数据库。
- * 更新笔记元数据和数据内容。
- *
- *
- * @param context 应用上下文
- * @param noteId 笔记 ID
- * @return 如果同步成功返回 true,否则返回 false
- */
- public boolean syncNote(Context context, long noteId) {
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- if (!isLocalModified()) {
- return true;
- }
-
- /**
- * 理论上,数据变更后应更新 {@link NoteColumns#LOCAL_MODIFIED} 和
- * {@link NoteColumns#MODIFIED_DATE}。为数据安全,即使更新失败也更新笔记数据信息
- */
- if (context.getContentResolver().update(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
- null) == 0) {
- Log.e(TAG, "Update note error, should not happen");
- // 不返回,继续执行
- }
- mNoteDiffValues.clear();
-
- if (mNoteData.isLocalModified()
- && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * 笔记数据内部类
- *
- * 管理笔记的文本数据和通话数据。
- * 支持数据的增删改查和批量同步操作。
- *
- */
- private class NoteData {
- /** 文本数据 ID */
- private long mTextDataId;
-
- /** 文本数据值 */
- private ContentValues mTextDataValues;
-
- /** 通话数据 ID */
- private long mCallDataId;
-
- /** 通话数据值 */
- private ContentValues mCallDataValues;
-
- /** 日志标签 */
- private static final String TAG = "NoteData";
-
- /**
- * 构造函数
- *
- * 初始化文本数据和通话数据的 ContentValues 对象。
- *
- */
- public NoteData() {
- mTextDataValues = new ContentValues();
- mCallDataValues = new ContentValues();
- mTextDataId = 0;
- mCallDataId = 0;
- }
-
- /**
- * 检查是否本地修改
- *
- * 检查文本数据或通话数据是否有本地未同步的修改。
- *
- *
- * @return 如果有本地修改返回 true,否则返回 false
- */
- boolean isLocalModified() {
- return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
- }
-
- /**
- * 设置文本数据 ID
- *
- * 设置文本数据的数据库记录 ID。
- *
- *
- * @param id 文本数据 ID,必须大于 0
- */
- void setTextDataId(long id) {
- if(id <= 0) {
- throw new IllegalArgumentException("Text data id should larger than 0");
- }
- mTextDataId = id;
- }
-
- /**
- * 设置通话数据 ID
- *
- * 设置通话数据的数据库记录 ID。
- *
- *
- * @param id 通话数据 ID,必须大于 0
- */
- void setCallDataId(long id) {
- if (id <= 0) {
- throw new IllegalArgumentException("Call data id should larger than 0");
- }
- mCallDataId = id;
- }
-
- /**
- * 设置通话数据
- *
- * 设置笔记的通话数据内容,并标记为本地修改。
- *
- *
- * @param key 数据键名
- * @param value 数据值
- */
- void setCallData(String key, String value) {
- mCallDataValues.put(key, value);
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 设置文本数据
- *
- * 设置笔记的文本数据内容,并标记为本地修改。
- *
- *
- * @param key 数据键名
- * @param value 数据值
- */
- void setTextData(String key, String value) {
- mTextDataValues.put(key, value);
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 将数据推送到 ContentResolver
- *
- * 将文本数据和通话数据的修改同步到数据库。
- * 支持新增和更新操作。
- *
- *
- * @param context 应用上下文
- * @param noteId 笔记 ID
- * @return 笔记 URI,失败时返回 null
- */
- Uri pushIntoContentResolver(Context context, long noteId) {
- /**
- * 安全性检查
- */
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- ArrayList operationList = new ArrayList();
- ContentProviderOperation.Builder builder = null;
-
- // 处理文本数据
- if(mTextDataValues.size() > 0) {
- mTextDataValues.put(DataColumns.NOTE_ID, noteId);
- if (mTextDataId == 0) {
- // 新增文本数据
- mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mTextDataValues);
- try {
- setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Insert new text data fail with noteId" + noteId);
- mTextDataValues.clear();
- return null;
- }
- } else {
- // 更新现有文本数据
- builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mTextDataId));
- builder.withValues(mTextDataValues);
- operationList.add(builder.build());
- }
- mTextDataValues.clear();
- }
-
- // 处理通话数据
- if(mCallDataValues.size() > 0) {
- mCallDataValues.put(DataColumns.NOTE_ID, noteId);
- if (mCallDataId == 0) {
- // 新增通话数据
- mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mCallDataValues);
- try {
- setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Insert new call data fail with noteId" + noteId);
- mCallDataValues.clear();
- return null;
- }
- } else {
- // 更新现有通话数据
- builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mCallDataId));
- builder.withValues(mCallDataValues);
- operationList.add(builder.build());
- }
- mCallDataValues.clear();
- }
-
- // 批量执行更新操作
- if (operationList.size() > 0) {
- try {
- ContentProviderResult[] results = context.getContentResolver().applyBatch(
- Notes.AUTHORITY, operationList);
- return (results == null || results.length == 0 || results[0] == null) ? null
- : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- } catch (RemoteException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- return null;
- } catch (OperationApplicationException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- return null;
- }
- }
- return null;
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/model/WorkingNote.java b/app/src/main/java/net/micode/notes/model/WorkingNote.java
deleted file mode 100644
index 3aa0cd3..0000000
--- a/app/src/main/java/net/micode/notes/model/WorkingNote.java
+++ /dev/null
@@ -1,616 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.model;
-
-import android.appwidget.AppWidgetManager;
-import android.content.ContentUris;
-import android.content.Context;
-import android.database.Cursor;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-import net.micode.notes.tool.ResourceParser.NoteBgResources;
-
-
-/**
- * 工作笔记类
- *
- * 表示正在编辑或查看的笔记对象,提供笔记的加载、保存和修改功能。
- * 支持文本笔记和通话记录笔记两种类型,包含笔记的所有属性和设置监听器。
- *
- */
-public class WorkingNote {
- /** 底层笔记对象 */
- private Note mNote;
-
- /** 笔记 ID */
- private long mNoteId;
-
- /** 笔记内容 */
- private String mContent;
-
- /** 笔记模式 */
- private int mMode;
-
- /** 提醒日期 */
- private long mAlertDate;
-
- /** 修改日期 */
- private long mModifiedDate;
-
- /** 背景颜色 ID */
- private int mBgColorId;
-
- /** Widget ID */
- private int mWidgetId;
-
- /** Widget 类型 */
- private int mWidgetType;
-
- /** 父文件夹 ID */
- private long mFolderId;
-
- /** 应用上下文 */
- private Context mContext;
-
- /** 日志标签 */
- private static final String TAG = "WorkingNote";
-
- /** 是否已删除 */
- private boolean mIsDeleted;
-
- /** 笔记设置变更监听器 */
- private NoteSettingChangedListener mNoteSettingStatusListener;
-
- /** 数据查询投影 - 笔记数据 */
- public static final String[] DATA_PROJECTION = new String[] {
- DataColumns.ID,
- DataColumns.CONTENT,
- DataColumns.MIME_TYPE,
- DataColumns.DATA1,
- DataColumns.DATA2,
- DataColumns.DATA3,
- DataColumns.DATA4,
- };
-
- /** 数据查询投影 - 笔记元数据 */
- public static final String[] NOTE_PROJECTION = new String[] {
- NoteColumns.PARENT_ID,
- NoteColumns.ALERTED_DATE,
- NoteColumns.BG_COLOR_ID,
- NoteColumns.WIDGET_ID,
- NoteColumns.WIDGET_TYPE,
- NoteColumns.MODIFIED_DATE
- };
-
- /** 数据 ID 列索引 */
- private static final int DATA_ID_COLUMN = 0;
-
- /** 数据内容列索引 */
- private static final int DATA_CONTENT_COLUMN = 1;
-
- /** 数据 MIME 类型列索引 */
- private static final int DATA_MIME_TYPE_COLUMN = 2;
-
- /** 数据模式列索引 */
- private static final int DATA_MODE_COLUMN = 3;
-
- /** 笔记父 ID 列索引 */
- private static final int NOTE_PARENT_ID_COLUMN = 0;
-
- /** 笔记提醒日期列索引 */
- private static final int NOTE_ALERTED_DATE_COLUMN = 1;
-
- /** 笔记背景颜色 ID 列索引 */
- private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
-
- /** 笔记 Widget ID 列索引 */
- private static final int NOTE_WIDGET_ID_COLUMN = 3;
-
- /** 笔记 Widget 类型列索引 */
- private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
-
- /** 笔记修改日期列索引 */
- private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
-
- /**
- * 新建笔记构造函数
- *
- * 创建一个新的空笔记对象,初始化所有属性为默认值。
- *
- *
- * @param context 应用上下文
- * @param folderId 父文件夹 ID
- */
- // New note construct
- private WorkingNote(Context context, long folderId) {
- mContext = context;
- mAlertDate = 0;
- mModifiedDate = System.currentTimeMillis();
- mFolderId = folderId;
- mNote = new Note();
- mNoteId = 0;
- mIsDeleted = false;
- mMode = 0;
- mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
- }
-
- /**
- * 已有笔记构造函数
- *
- * 从数据库加载现有笔记数据,初始化笔记对象。
- *
- *
- * @param context 应用上下文
- * @param noteId 笔记 ID
- * @param folderId 父文件夹 ID
- */
- // Existing note construct
- private WorkingNote(Context context, long noteId, long folderId) {
- mContext = context;
- mNoteId = noteId;
- mFolderId = folderId;
- mIsDeleted = false;
- mNote = new Note();
- loadNote();
- }
-
- /**
- * 加载笔记元数据
- *
- * 从数据库加载笔记的基本信息,包括父文件夹、背景颜色、Widget 信息等。
- *
- */
- private void loadNote() {
- Cursor cursor = mContext.getContentResolver().query(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
- null, null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
- mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
- mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
- mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
- mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
- mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
- }
- cursor.close();
- } else {
- Log.e(TAG, "No note with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
- }
- loadNoteData();
- }
-
- /**
- * 加载笔记数据内容
- *
- * 从数据库加载笔记的详细数据,包括文本内容和通话记录。
- *
- */
- private void loadNoteData() {
- Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
- DataColumns.NOTE_ID + "=?", new String[] {
- String.valueOf(mNoteId)
- }, null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- do {
- String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
- if (DataConstants.NOTE.equals(type)) {
- // 加载文本笔记数据
- mContent = cursor.getString(DATA_CONTENT_COLUMN);
- mMode = cursor.getInt(DATA_MODE_COLUMN);
- mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
- } else if (DataConstants.CALL_NOTE.equals(type)) {
- // 加载通话记录数据
- mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
- } else {
- Log.d(TAG, "Wrong note type with type:" + type);
- }
- } while (cursor.moveToNext());
- }
- cursor.close();
- } else {
- Log.e(TAG, "No data with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
- }
- }
-
- /**
- * 创建空笔记
- *
- * 创建一个新的空笔记对象,并设置默认属性。
- *
- *
- * @param context 应用上下文
- * @param folderId 父文件夹 ID
- * @param widgetId Widget ID
- * @param widgetType Widget 类型
- * @param defaultBgColorId 默认背景颜色 ID
- * @return 新创建的 WorkingNote 对象
- */
- public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
- int widgetType, int defaultBgColorId) {
- WorkingNote note = new WorkingNote(context, folderId);
- note.setBgColorId(defaultBgColorId);
- note.setWidgetId(widgetId);
- note.setWidgetType(widgetType);
- return note;
- }
-
- /**
- * 加载已有笔记
- *
- * 从数据库加载指定 ID 的笔记。
- *
- *
- * @param context 应用上下文
- * @param id 笔记 ID
- * @return 加载的 WorkingNote 对象
- */
- public static WorkingNote load(Context context, long id) {
- return new WorkingNote(context, id, 0);
- }
-
- /**
- * 保存笔记
- *
- * 将笔记的修改保存到数据库。
- * 如果笔记不存在则创建新笔记,否则更新现有笔记。
- * 如果有 Widget 则更新 Widget 内容。
- *
- *
- * @return 如果保存成功返回 true,否则返回 false
- */
- public synchronized boolean saveNote() {
- if (isWorthSaving()) {
- if (!existInDatabase()) {
- // 创建新笔记
- if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
- Log.e(TAG, "Create new note fail with id:" + mNoteId);
- return false;
- }
- }
-
- // 同步笔记数据
- mNote.syncNote(mContext, mNoteId);
-
- /**
- * 如果存在该笔记的 Widget,则更新 Widget 内容
- */
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
- && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * 检查笔记是否存在于数据库
- *
- * @return 如果笔记 ID 大于 0 返回 true,否则返回 false
- */
- public boolean existInDatabase() {
- return mNoteId > 0;
- }
-
- /**
- * 检查是否值得保存
- *
- * 判断笔记是否有需要保存的修改。
- *
- *
- * @return 如果值得保存返回 true,否则返回 false
- */
- private boolean isWorthSaving() {
- if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
- || (existInDatabase() && !mNote.isLocalModified())) {
- return false;
- } else {
- return true;
- }
- }
-
- /**
- * 设置笔记设置变更监听器
- *
- * @param l 监听器对象
- */
- public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
- mNoteSettingStatusListener = l;
- }
-
- /**
- * 设置提醒日期
- *
- * 设置笔记的提醒日期,并通知监听器。
- *
- *
- * @param date 提醒日期(毫秒时间戳)
- * @param set 是否设置提醒
- */
- public void setAlertDate(long date, boolean set) {
- if (date != mAlertDate) {
- mAlertDate = date;
- mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
- }
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onClockAlertChanged(date, set);
- }
- }
-
- /**
- * 标记删除
- *
- * 标记笔记为删除状态,并更新 Widget。
- *
- *
- * @param mark 是否标记为删除
- */
- public void markDeleted(boolean mark) {
- mIsDeleted = mark;
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
- }
-
- /**
- * 设置背景颜色 ID
- *
- * 设置笔记的背景颜色,并通知监听器。
- *
- *
- * @param id 背景颜色 ID
- */
- public void setBgColorId(int id) {
- if (id != mBgColorId) {
- mBgColorId = id;
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onBackgroundColorChanged();
- }
- mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
- }
- }
-
- /**
- * 设置清单模式
- *
- * 设置笔记的编辑模式(普通模式或清单模式),并通知监听器。
- *
- *
- * @param mode 模式值
- */
- public void setCheckListMode(int mode) {
- if (mMode != mode) {
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
- }
- mMode = mode;
- mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
- }
- }
-
- /**
- * 设置 Widget 类型
- *
- * @param type Widget 类型
- */
- public void setWidgetType(int type) {
- if (type != mWidgetType) {
- mWidgetType = type;
- mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
- }
- }
-
- /**
- * 设置 Widget ID
- *
- * @param id Widget ID
- */
- public void setWidgetId(int id) {
- if (id != mWidgetId) {
- mWidgetId = id;
- mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
- }
- }
-
- /**
- * 设置工作文本
- *
- * 设置笔记的文本内容。
- *
- *
- * @param text 文本内容
- */
- public void setWorkingText(String text) {
- if (!TextUtils.equals(mContent, text)) {
- mContent = text;
- mNote.setTextData(DataColumns.CONTENT, mContent);
- }
- }
-
- /**
- * 转换为通话记录笔记
- *
- * 将笔记转换为通话记录类型,设置电话号码和通话日期。
- *
- *
- * @param phoneNumber 电话号码
- * @param callDate 通话日期(毫秒时间戳)
- */
- public void convertToCallNote(String phoneNumber, long callDate) {
- mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
- mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
- mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
- }
-
- /**
- * 检查是否有提醒
- *
- * @return 如果有提醒返回 true,否则返回 false
- */
- public boolean hasClockAlert() {
- return (mAlertDate > 0 ? true : false);
- }
-
- /**
- * 获取笔记内容
- *
- * @return 笔记内容字符串
- */
- public String getContent() {
- return mContent;
- }
-
- /**
- * 获取提醒日期
- *
- * @return 提醒日期(毫秒时间戳)
- */
- public long getAlertDate() {
- return mAlertDate;
- }
-
- /**
- * 获取修改日期
- *
- * @return 修改日期(毫秒时间戳)
- */
- public long getModifiedDate() {
- return mModifiedDate;
- }
-
- /**
- * 获取背景颜色资源 ID
- *
- * @return 背景颜色资源 ID
- */
- public int getBgColorResId() {
- return NoteBgResources.getNoteBgResource(mBgColorId);
- }
-
- /**
- * 获取背景颜色 ID
- *
- * @return 背景颜色 ID
- */
- public int getBgColorId() {
- return mBgColorId;
- }
-
- /**
- * 获取标题背景资源 ID
- *
- * @return 标题背景资源 ID
- */
- public int getTitleBgResId() {
- return NoteBgResources.getNoteTitleBgResource(mBgColorId);
- }
-
- /**
- * 获取清单模式
- *
- * @return 清单模式值
- */
- public int getCheckListMode() {
- return mMode;
- }
-
- /**
- * 获取笔记 ID
- *
- * @return 笔记 ID
- */
- public long getNoteId() {
- return mNoteId;
- }
-
- /**
- * 获取父文件夹 ID
- *
- * @return 父文件夹 ID
- */
- public long getFolderId() {
- return mFolderId;
- }
-
- /**
- * 获取 Widget ID
- *
- * @return Widget ID
- */
- public int getWidgetId() {
- return mWidgetId;
- }
-
- /**
- * 获取 Widget 类型
- *
- * @return Widget 类型
- */
- public int getWidgetType() {
- return mWidgetType;
- }
-
- /**
- * 笔记设置变更监听器接口
- *
- * 定义笔记设置变更时的回调方法,用于通知 UI 更新。
- *
- */
- public interface NoteSettingChangedListener {
- /**
- * 当前笔记背景颜色变更时调用
- */
- void onBackgroundColorChanged();
-
- /**
- * 用户设置闹钟时调用
- *
- * @param date 提醒日期
- * @param set 是否设置提醒
- */
- void onClockAlertChanged(long date, boolean set);
-
- /**
- * 用户从 Widget 创建笔记时调用
- */
- void onWidgetChanged();
-
- /**
- * 在清单模式和普通模式之间切换时调用
- *
- * @param oldMode 变更前的模式
- * @param newMode 变更后的模式
- */
- void onCheckListModeChanged(int oldMode, int newMode);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/tool/BackupUtils.java b/app/src/main/java/net/micode/notes/tool/BackupUtils.java
deleted file mode 100644
index 10c3994..0000000
--- a/app/src/main/java/net/micode/notes/tool/BackupUtils.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.os.Environment;
-import android.text.TextUtils;
-import android.text.format.DateFormat;
-import android.util.Log;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-
-
-/**
- * 备份工具类
- *
- * 提供笔记数据导出为文本文件的功能。
- * 支持将笔记、文件夹、通话记录等数据导出到 SD 卡中。
- * 使用单例模式确保全局只有一个实例。
- *
- */
-public class BackupUtils {
- /** 日志标签 */
- private static final String TAG = "BackupUtils";
- // Singleton stuff
- /** 单例实例 */
- private static BackupUtils sInstance;
-
- /**
- * 获取备份工具类的单例实例
- *
- * @param context 应用上下文
- * @return 备份工具类实例
- */
- public static synchronized BackupUtils getInstance(Context context) {
- if (sInstance == null) {
- sInstance = new BackupUtils(context);
- }
- return sInstance;
- }
-
- /**
- * 备份或恢复的状态常量
- *
- * 以下状态常量用于表示备份或恢复操作的状态。
- *
- */
- // Currently, the sdcard is not mounted
- /** SD 卡未挂载 */
- public static final int STATE_SD_CARD_UNMOUONTED = 0;
- // The backup file not exist
- /** 备份文件不存在 */
- public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
- // The data is not well formated, may be changed by other programs
- /** 数据格式损坏,可能被其他程序修改 */
- public static final int STATE_DATA_DESTROIED = 2;
- // Some run-time exception which causes restore or backup fails
- /** 系统错误,运行时异常导致备份或恢复失败 */
- public static final int STATE_SYSTEM_ERROR = 3;
- // Backup or restore success
- /** 备份或恢复成功 */
- public static final int STATE_SUCCESS = 4;
-
- /** 文本导出对象 */
- private TextExport mTextExport;
-
- /**
- * 私有构造函数
- *
- * @param context 应用上下文
- */
- private BackupUtils(Context context) {
- mTextExport = new TextExport(context);
- }
-
- /**
- * 检查外部存储是否可用
- *
- * @return 如果外部存储已挂载且可读写则返回 true,否则返回 false
- */
- private static boolean externalStorageAvailable() {
- return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
- }
-
- /**
- * 导出笔记数据为文本文件
- *
- * @return 导出状态码,可能为 STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR 或 STATE_SUCCESS
- */
- public int exportToText() {
- return mTextExport.exportToText();
- }
-
- /**
- * 获取导出的文本文件名
- *
- * @return 导出的文本文件名
- */
- public String getExportedTextFileName() {
- return mTextExport.mFileName;
- }
-
- /**
- * 获取导出的文本文件目录
- *
- * @return 导出的文本文件目录路径
- */
- public String getExportedTextFileDir() {
- return mTextExport.mFileDirectory;
- }
-
- /**
- * 文本导出内部类
- *
- * 负责将笔记数据导出为可读的文本文件。
- * 支持导出文件夹、笔记和通话记录等不同类型的数据。
- *
- */
- private static class TextExport {
- /** 笔记查询投影字段 */
- private static final String[] NOTE_PROJECTION = {
- NoteColumns.ID,
- NoteColumns.MODIFIED_DATE,
- NoteColumns.SNIPPET,
- NoteColumns.TYPE
- };
-
- /** 笔记 ID 列索引 */
- private static final int NOTE_COLUMN_ID = 0;
-
- /** 笔记修改日期列索引 */
- private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
-
- /** 笔记摘要列索引 */
- private static final int NOTE_COLUMN_SNIPPET = 2;
-
- /** 数据查询投影字段 */
- private static final String[] DATA_PROJECTION = {
- DataColumns.CONTENT,
- DataColumns.MIME_TYPE,
- DataColumns.DATA1,
- DataColumns.DATA2,
- DataColumns.DATA3,
- DataColumns.DATA4,
- };
-
- /** 数据内容列索引 */
- private static final int DATA_COLUMN_CONTENT = 0;
-
- /** 数据 MIME 类型列索引 */
- private static final int DATA_COLUMN_MIME_TYPE = 1;
-
- /** 通话日期列索引 */
- private static final int DATA_COLUMN_CALL_DATE = 2;
-
- /** 电话号码列索引 */
- private static final int DATA_COLUMN_PHONE_NUMBER = 4;
-
- /** 导出文本格式数组 */
- private final String [] TEXT_FORMAT;
- /** 文件夹名称格式索引 */
- private static final int FORMAT_FOLDER_NAME = 0;
- /** 笔记日期格式索引 */
- private static final int FORMAT_NOTE_DATE = 1;
- /** 笔记内容格式索引 */
- private static final int FORMAT_NOTE_CONTENT = 2;
-
- /** 应用上下文 */
- private Context mContext;
- /** 导出文件名 */
- private String mFileName;
- /** 导出文件目录 */
- private String mFileDirectory;
-
- /**
- * 构造函数
- *
- * @param context 应用上下文
- */
- public TextExport(Context context) {
- TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
- mContext = context;
- mFileName = "";
- mFileDirectory = "";
- }
-
- /**
- * 获取指定格式的文本
- *
- * @param id 格式索引
- * @return 格式化字符串
- */
- private String getFormat(int id) {
- return TEXT_FORMAT[id];
- }
-
- /**
- * 导出指定文件夹及其笔记到文本
- *
- * 查询属于该文件夹的所有笔记,并将每个笔记的内容导出到输出流中。
- *
- *
- * @param folderId 文件夹 ID
- * @param ps 输出流
- */
- private void exportFolderToText(String folderId, PrintStream ps) {
- // Query notes belong to this folder
- Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
- NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
- folderId
- }, null);
-
- if (notesCursor != null) {
- if (notesCursor.moveToFirst()) {
- do {
- // Print note's last modified date
- ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
- mContext.getString(R.string.format_datetime_mdhm),
- notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
- // Query data belong to this note
- String noteId = notesCursor.getString(NOTE_COLUMN_ID);
- exportNoteToText(noteId, ps);
- } while (notesCursor.moveToNext());
- }
- notesCursor.close();
- }
- }
-
- /**
- * 导出指定笔记到输出流
- *
- * 查询笔记的所有数据,根据 MIME 类型分别处理通话记录和普通笔记。
- *
- *
- * @param noteId 笔记 ID
- * @param ps 输出流
- */
- private void exportNoteToText(String noteId, PrintStream ps) {
- Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
- DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
- noteId
- }, null);
-
- if (dataCursor != null) {
- if (dataCursor.moveToFirst()) {
- do {
- String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
- if (DataConstants.CALL_NOTE.equals(mimeType)) {
- // Print phone number
- String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
- long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
- String location = dataCursor.getString(DATA_COLUMN_CONTENT);
-
- if (!TextUtils.isEmpty(phoneNumber)) {
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
- phoneNumber));
- }
- // Print call date
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
- .format(mContext.getString(R.string.format_datetime_mdhm),
- callDate)));
- // Print call attachment location
- if (!TextUtils.isEmpty(location)) {
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
- location));
- }
- } else if (DataConstants.NOTE.equals(mimeType)) {
- String content = dataCursor.getString(DATA_COLUMN_CONTENT);
- if (!TextUtils.isEmpty(content)) {
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
- content));
- }
- }
- } while (dataCursor.moveToNext());
- }
- dataCursor.close();
- }
- // print a line separator between note
- try {
- ps.write(new byte[] {
- Character.LINE_SEPARATOR, Character.LETTER_NUMBER
- });
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- }
- }
-
- /**
- * 导出笔记数据为文本文件
- *
- * 将所有笔记、文件夹和通话记录导出为用户可读的文本文件。
- * 首先导出文件夹及其笔记,然后导出根目录下的笔记。
- *
- *
- * @return 导出状态码,可能为 STATE_SD_CARD_UNMOUONTED、STATE_SYSTEM_ERROR 或 STATE_SUCCESS
- */
- public int exportToText() {
- if (!externalStorageAvailable()) {
- Log.d(TAG, "Media was not mounted");
- return STATE_SD_CARD_UNMOUONTED;
- }
-
- PrintStream ps = getExportToTextPrintStream();
- if (ps == null) {
- Log.e(TAG, "get print stream error");
- return STATE_SYSTEM_ERROR;
- }
- // First export folder and its notes
- Cursor folderCursor = mContext.getContentResolver().query(
- Notes.CONTENT_NOTE_URI,
- NOTE_PROJECTION,
- "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
- + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
- + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
-
- if (folderCursor != null) {
- if (folderCursor.moveToFirst()) {
- do {
- // Print folder's name
- String folderName = "";
- if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
- folderName = mContext.getString(R.string.call_record_folder_name);
- } else {
- folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
- }
- if (!TextUtils.isEmpty(folderName)) {
- ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
- }
- String folderId = folderCursor.getString(NOTE_COLUMN_ID);
- exportFolderToText(folderId, ps);
- } while (folderCursor.moveToNext());
- }
- folderCursor.close();
- }
-
- // Export notes in root's folder
- Cursor noteCursor = mContext.getContentResolver().query(
- Notes.CONTENT_NOTE_URI,
- NOTE_PROJECTION,
- NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
- + "=0", null, null);
-
- if (noteCursor != null) {
- if (noteCursor.moveToFirst()) {
- do {
- ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
- mContext.getString(R.string.format_datetime_mdhm),
- noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
- // Query data belong to this note
- String noteId = noteCursor.getString(NOTE_COLUMN_ID);
- exportNoteToText(noteId, ps);
- } while (noteCursor.moveToNext());
- }
- noteCursor.close();
- }
- ps.close();
-
- return STATE_SUCCESS;
- }
-
- /**
- * 获取导出文本文件的输出流
- *
- * 在 SD 卡上创建导出文件,并返回对应的 PrintStream。
- *
- *
- * @return PrintStream 对象,如果创建失败则返回 null
- */
- private PrintStream getExportToTextPrintStream() {
- File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
- R.string.file_name_txt_format);
- if (file == null) {
- Log.e(TAG, "create file to exported failed");
- return null;
- }
- mFileName = file.getName();
- mFileDirectory = mContext.getString(R.string.file_path);
- PrintStream ps = null;
- try {
- FileOutputStream fos = new FileOutputStream(file);
- ps = new PrintStream(fos);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return null;
- } catch (NullPointerException e) {
- e.printStackTrace();
- return null;
- }
- return ps;
- }
- }
-
- /**
- * 在 SD 卡上生成导出文本文件
- *
- * 在指定的路径下创建导出文件,如果目录不存在则创建目录。
- *
- *
- * @param context 应用上下文
- * @param filePathResId 文件路径资源 ID
- * @param fileNameFormatResId 文件名格式资源 ID
- * @return 生成的文件对象,如果创建失败则返回 null
- */
- private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
- StringBuilder sb = new StringBuilder();
- sb.append(Environment.getExternalStorageDirectory());
- sb.append(context.getString(filePathResId));
- File filedir = new File(sb.toString());
- sb.append(context.getString(
- fileNameFormatResId,
- DateFormat.format(context.getString(R.string.format_date_ymd),
- System.currentTimeMillis())));
- File file = new File(sb.toString());
-
- try {
- if (!filedir.exists()) {
- // 创建目录
- filedir.mkdir();
- }
- if (!file.exists()) {
- // 创建文件
- file.createNewFile();
- }
- return file;
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return null;
- }
-}
-
-
diff --git a/app/src/main/java/net/micode/notes/tool/DataUtils.java b/app/src/main/java/net/micode/notes/tool/DataUtils.java
deleted file mode 100644
index d982351..0000000
--- a/app/src/main/java/net/micode/notes/tool/DataUtils.java
+++ /dev/null
@@ -1,439 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.OperationApplicationException;
-import android.database.Cursor;
-import android.os.RemoteException;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-
-/**
- * 数据工具类
- *
- * 提供笔记数据的批量操作、查询和统计功能。
- * 支持批量删除、移动笔记,以及各种数据查询操作。
- *
- */
-public class DataUtils {
- /** 日志标签 */
- public static final String TAG = "DataUtils";
-
- /**
- * 批量删除笔记
- *
- * 从数据库中批量删除指定 ID 的笔记。
- * 跳过系统根文件夹,不允许删除系统文件夹。
- *
- *
- * @param resolver ContentResolver 对象
- * @param ids 要删除的笔记 ID 集合
- * @return 如果删除成功返回 true,否则返回 false
- */
- public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) {
- if (ids == null) {
- Log.d(TAG, "the ids is null");
- return true;
- }
- if (ids.size() == 0) {
- Log.d(TAG, "no id is in the hashset");
- return true;
- }
-
- ArrayList operationList = new ArrayList();
- for (long id : ids) {
- if(id == Notes.ID_ROOT_FOLDER) {
- // 跳过系统根文件夹
- Log.e(TAG, "Don't delete system folder root");
- continue;
- }
- ContentProviderOperation.Builder builder = ContentProviderOperation
- .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
- operationList.add(builder.build());
- }
- try {
- ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
- if (results == null || results.length == 0 || results[0] == null) {
- Log.d(TAG, "delete notes failed, ids:" + ids.toString());
- return false;
- }
- return true;
- } catch (RemoteException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- } catch (OperationApplicationException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- }
- return false;
- }
-
- /**
- * 移动笔记到指定文件夹
- *
- * 将笔记从源文件夹移动到目标文件夹,并记录原始父文件夹 ID。
- *
- *
- * @param resolver ContentResolver 对象
- * @param id 笔记 ID
- * @param srcFolderId 源文件夹 ID
- * @param desFolderId 目标文件夹 ID
- */
- public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.PARENT_ID, desFolderId);
- values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
- }
-
- /**
- * 批量移动笔记到指定文件夹
- *
- * 将多个笔记批量移动到目标文件夹。
- *
- *
- * @param resolver ContentResolver 对象
- * @param ids 要移动的笔记 ID 集合
- * @param folderId 目标文件夹 ID
- * @return 如果移动成功返回 true,否则返回 false
- */
- public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids,
- long folderId) {
- if (ids == null) {
- Log.d(TAG, "the ids is null");
- return true;
- }
-
- ArrayList operationList = new ArrayList();
- for (long id : ids) {
- ContentProviderOperation.Builder builder = ContentProviderOperation
- .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
- builder.withValue(NoteColumns.PARENT_ID, folderId);
- builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
- operationList.add(builder.build());
- }
-
- try {
- ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
- if (results == null || results.length == 0 || results[0] == null) {
- Log.d(TAG, "delete notes failed, ids:" + ids.toString());
- return false;
- }
- return true;
- } catch (RemoteException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- } catch (OperationApplicationException e) {
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- }
- return false;
- }
-
- /**
- * 获取用户文件夹数量
- *
- * 统计除系统文件夹外的所有用户文件夹数量。
- * 排除回收站文件夹。
- *
- *
- * @param resolver ContentResolver 对象
- * @return 用户文件夹数量
- */
- public static int getUserFolderCount(ContentResolver resolver) {
- Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
- new String[] { "COUNT(*)" },
- NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
- new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
- null);
-
- int count = 0;
- if(cursor != null) {
- if(cursor.moveToFirst()) {
- try {
- count = cursor.getInt(0);
- } catch (IndexOutOfBoundsException e) {
- Log.e(TAG, "get folder count failed:" + e.toString());
- } finally {
- cursor.close();
- }
- }
- }
- return count;
- }
-
- /**
- * 检查笔记是否在数据库中可见
- *
- * 检查指定 ID 和类型的笔记是否在数据库中存在且可见(不在回收站)。
- *
- *
- * @param resolver ContentResolver 对象
- * @param noteId 笔记 ID
- * @param type 笔记类型
- * @return 如果笔记可见返回 true,否则返回 false
- */
- public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
- Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
- null,
- NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
- new String [] {String.valueOf(type)},
- null);
-
- boolean exist = false;
- if (cursor != null) {
- if (cursor.getCount() > 0) {
- exist = true;
- }
- cursor.close();
- }
- return exist;
- }
-
- /**
- * 检查笔记是否存在于数据库
- *
- * 检查指定 ID 的笔记是否在数据库中存在。
- *
- *
- * @param resolver ContentResolver 对象
- * @param noteId 笔记 ID
- * @return 如果笔记存在返回 true,否则返回 false
- */
- public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
- Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
- null, null, null, null);
-
- boolean exist = false;
- if (cursor != null) {
- if (cursor.getCount() > 0) {
- exist = true;
- }
- cursor.close();
- }
- return exist;
- }
-
- /**
- * 检查数据是否存在于数据库
- *
- * 检查指定 ID 的笔记数据是否在数据库中存在。
- *
- *
- * @param resolver ContentResolver 对象
- * @param dataId 数据 ID
- * @return 如果数据存在返回 true,否则返回 false
- */
- public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
- Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
- null, null, null, null);
-
- boolean exist = false;
- if (cursor != null) {
- if (cursor.getCount() > 0) {
- exist = true;
- }
- cursor.close();
- }
- return exist;
- }
-
- /**
- * 检查可见文件夹名称是否存在
- *
- * 检查指定名称的文件夹是否在可见区域存在(不在回收站)。
- *
- *
- * @param resolver ContentResolver 对象
- * @param name 文件夹名称
- * @return 如果文件夹名称存在返回 true,否则返回 false
- */
- public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
- Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
- NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
- " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
- " AND " + NoteColumns.SNIPPET + "=?",
- new String[] { name }, null);
- boolean exist = false;
- if(cursor != null) {
- if(cursor.getCount() > 0) {
- exist = true;
- }
- cursor.close();
- }
- return exist;
- }
-
- /**
- * 获取文件夹中的 Widget 信息
- *
- * 获取指定文件夹下所有笔记关联的 Widget 信息。
- *
- *
- * @param resolver ContentResolver 对象
- * @param folderId 文件夹 ID
- * @return Widget 属性集合,如果没有则返回 null
- */
- public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) {
- Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
- new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
- NoteColumns.PARENT_ID + "=?",
- new String[] { String.valueOf(folderId) },
- null);
-
- HashSet set = null;
- if (c != null) {
- if (c.moveToFirst()) {
- set = new HashSet();
- do {
- try {
- AppWidgetAttribute widget = new AppWidgetAttribute();
- widget.widgetId = c.getInt(0);
- widget.widgetType = c.getInt(1);
- set.add(widget);
- } catch (IndexOutOfBoundsException e) {
- Log.e(TAG, e.toString());
- }
- } while (c.moveToNext());
- }
- c.close();
- }
- return set;
- }
-
- /**
- * 根据笔记 ID 获取通话号码
- *
- * 查询指定笔记 ID 关联的通话记录中的电话号码。
- *
- *
- * @param resolver ContentResolver 对象
- * @param noteId 笔记 ID
- * @return 电话号码,如果未找到则返回空字符串
- */
- public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
- Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
- new String [] { CallNote.PHONE_NUMBER },
- CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
- new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
- null);
-
- if (cursor != null && cursor.moveToFirst()) {
- try {
- return cursor.getString(0);
- } catch (IndexOutOfBoundsException e) {
- Log.e(TAG, "Get call number fails " + e.toString());
- } finally {
- cursor.close();
- }
- }
- return "";
- }
-
- /**
- * 根据电话号码和通话日期获取笔记 ID
- *
- * 查询指定电话号码和通话日期对应的笔记 ID。
- *
- *
- * @param resolver ContentResolver 对象
- * @param phoneNumber 电话号码
- * @param callDate 通话日期(毫秒时间戳)
- * @return 笔记 ID,如果未找到则返回 0
- */
- public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
- Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
- new String [] { CallNote.NOTE_ID },
- CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
- + CallNote.PHONE_NUMBER + ",?)",
- new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
- null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- try {
- return cursor.getLong(0);
- } catch (IndexOutOfBoundsException e) {
- Log.e(TAG, "Get call note id fails " + e.toString());
- }
- }
- cursor.close();
- }
- return 0;
- }
-
- /**
- * 根据笔记 ID 获取摘要
- *
- * 查询指定笔记 ID 的摘要内容。
- *
- *
- * @param resolver ContentResolver 对象
- * @param noteId 笔记 ID
- * @return 笔记摘要
- * @throws IllegalArgumentException 如果笔记不存在
- */
- public static String getSnippetById(ContentResolver resolver, long noteId) {
- Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
- new String [] { NoteColumns.SNIPPET },
- NoteColumns.ID + "=?",
- new String [] { String.valueOf(noteId)},
- null);
-
- if (cursor != null) {
- String snippet = "";
- if (cursor.moveToFirst()) {
- snippet = cursor.getString(0);
- }
- cursor.close();
- return snippet;
- }
- throw new IllegalArgumentException("Note is not found with id: " + noteId);
- }
-
- /**
- * 格式化摘要内容
- *
- * 去除摘要首尾空格,并截取到第一个换行符之前的内容。
- *
- *
- * @param snippet 原始摘要内容
- * @return 格式化后的摘要内容
- */
- public static String getFormattedSnippet(String snippet) {
- if (snippet != null) {
- // 去除首尾空格
- snippet = snippet.trim();
- // 截取到第一个换行符之前的内容
- int index = snippet.indexOf('\n');
- if (index != -1) {
- snippet = snippet.substring(0, index);
- }
- }
- return snippet;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java
deleted file mode 100644
index ce9eb54..0000000
--- a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-/**
- * Google Tasks 字符串常量工具类
- *
- * 定义与 Google Tasks 同步相关的所有 JSON 字段名称和常量。
- * 包括操作类型、实体类型、文件夹名称等常量定义。
- *
- */
-public class GTaskStringUtils {
-
- /** 操作 ID */
- public final static String GTASK_JSON_ACTION_ID = "action_id";
-
- /** 操作列表 */
- public final static String GTASK_JSON_ACTION_LIST = "action_list";
-
- /** 操作类型 */
- public final static String GTASK_JSON_ACTION_TYPE = "action_type";
-
- /** 创建操作类型 */
- public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
-
- /** 获取所有操作类型 */
- public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
-
- /** 移动操作类型 */
- public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
-
- /** 更新操作类型 */
- public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
-
- /** 创建者 ID */
- public final static String GTASK_JSON_CREATOR_ID = "creator_id";
-
- /** 子实体 */
- public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
-
- /** 客户端版本 */
- public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
-
- /** 完成状态 */
- public final static String GTASK_JSON_COMPLETED = "completed";
-
- /** 当前列表 ID */
- public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
-
- /** 默认列表 ID */
- public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
-
- /** 删除标记 */
- public final static String GTASK_JSON_DELETED = "deleted";
-
- /** 目标列表 */
- public final static String GTASK_JSON_DEST_LIST = "dest_list";
-
- /** 目标父节点 */
- public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
-
- /** 目标父节点类型 */
- public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
-
- /** 实体增量 */
- public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
-
- /** 实体类型 */
- public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
-
- /** 获取已删除标记 */
- public final static String GTASK_JSON_GET_DELETED = "get_deleted";
-
- /** ID */
- public final static String GTASK_JSON_ID = "id";
-
- /** 索引 */
- public final static String GTASK_JSON_INDEX = "index";
-
- /** 最后修改时间 */
- public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
-
- /** 最新同步点 */
- public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
-
- /** 列表 ID */
- public final static String GTASK_JSON_LIST_ID = "list_id";
-
- /** 列表集合 */
- public final static String GTASK_JSON_LISTS = "lists";
-
- /** 名称 */
- public final static String GTASK_JSON_NAME = "name";
-
- /** 新 ID */
- public final static String GTASK_JSON_NEW_ID = "new_id";
-
- /** 笔记集合 */
- public final static String GTASK_JSON_NOTES = "notes";
-
- /** 父节点 ID */
- public final static String GTASK_JSON_PARENT_ID = "parent_id";
-
- /** 前一个兄弟节点 ID */
- public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
-
- /** 结果集合 */
- public final static String GTASK_JSON_RESULTS = "results";
-
- /** 源列表 */
- public final static String GTASK_JSON_SOURCE_LIST = "source_list";
-
- /** 任务集合 */
- public final static String GTASK_JSON_TASKS = "tasks";
-
- /** 类型 */
- public final static String GTASK_JSON_TYPE = "type";
-
- /** 分组类型 */
- public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
-
- /** 任务类型 */
- public final static String GTASK_JSON_TYPE_TASK = "TASK";
-
- /** 用户信息 */
- public final static String GTASK_JSON_USER = "user";
-
- /** MIUI 文件夹前缀 */
- public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
-
- /** 默认文件夹名称 */
- public final static String FOLDER_DEFAULT = "Default";
-
- /** 通话记录文件夹名称 */
- public final static String FOLDER_CALL_NOTE = "Call_Note";
-
- /** 元数据文件夹名称 */
- public final static String FOLDER_META = "METADATA";
-
- /** 元数据 GTask ID 头 */
- public final static String META_HEAD_GTASK_ID = "meta_gid";
-
- /** 元数据笔记头 */
- public final static String META_HEAD_NOTE = "meta_note";
-
- /** 元数据头 */
- public final static String META_HEAD_DATA = "meta_data";
-
- /** 元数据笔记名称 */
- public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
-}
diff --git a/app/src/main/java/net/micode/notes/tool/ResourceParser.java b/app/src/main/java/net/micode/notes/tool/ResourceParser.java
deleted file mode 100644
index 4677289..0000000
--- a/app/src/main/java/net/micode/notes/tool/ResourceParser.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-import android.content.Context;
-import android.preference.PreferenceManager;
-
-import net.micode.notes.R;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-/**
- * 资源解析工具类
- *
- * 提供笔记背景颜色、字体大小、Widget 样式等资源的解析和获取功能。
- * 支持多种颜色主题和字体大小的配置。
- *
- */
-public class ResourceParser {
-
- /** 黄色背景 */
- public static final int YELLOW = 0;
-
- /** 蓝色背景 */
- public static final int BLUE = 1;
-
- /** 白色背景 */
- public static final int WHITE = 2;
-
- /** 绿色背景 */
- public static final int GREEN = 3;
-
- /** 红色背景 */
- public static final int RED = 4;
-
- /** 默认背景颜色 */
- public static final int BG_DEFAULT_COLOR = YELLOW;
-
- /** 小号字体 */
- public static final int TEXT_SMALL = 0;
-
- /** 中号字体 */
- public static final int TEXT_MEDIUM = 1;
-
- /** 大号字体 */
- public static final int TEXT_LARGE = 2;
-
- /** 超大号字体 */
- public static final int TEXT_SUPER = 3;
-
- /** 默认字体大小 */
- public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
-
- /**
- * 笔记背景资源类
- *
- * 提供笔记编辑页面的背景颜色资源。
- * 包含编辑区域背景和标题栏背景两种资源。
- *
- */
- public static class NoteBgResources {
- /** 编辑区域背景资源数组 */
- private final static int [] BG_EDIT_RESOURCES = new int [] {
- R.drawable.edit_yellow,
- R.drawable.edit_blue,
- R.drawable.edit_white,
- R.drawable.edit_green,
- R.drawable.edit_red
- };
-
- /** 标题栏背景资源数组 */
- private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
- R.drawable.edit_title_yellow,
- R.drawable.edit_title_blue,
- R.drawable.edit_title_white,
- R.drawable.edit_title_green,
- R.drawable.edit_title_red
- };
-
- /**
- * 获取笔记编辑区域背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 背景资源 ID
- */
- public static int getNoteBgResource(int id) {
- return BG_EDIT_RESOURCES[id];
- }
-
- /**
- * 获取笔记标题栏背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 标题栏背景资源 ID
- */
- public static int getNoteTitleBgResource(int id) {
- return BG_EDIT_TITLE_RESOURCES[id];
- }
- }
-
- /**
- * 获取默认背景颜色 ID
- *
- * 根据用户设置返回默认背景颜色。
- * 如果用户启用了随机背景颜色,则随机返回一个颜色 ID。
- *
- *
- * @param context 应用上下文
- * @return 背景颜色 ID(0-4)
- */
- public static int getDefaultBgId(Context context) {
- if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
- NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
- // 随机选择背景颜色
- return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
- } else {
- return BG_DEFAULT_COLOR;
- }
- }
-
- /**
- * 笔记列表项背景资源类
- *
- * 提供笔记列表项的背景颜色资源。
- * 包含首项、中间项、末项和单项四种样式。
- *
- */
- public static class NoteItemBgResources {
- /** 首项背景资源数组 */
- private final static int [] BG_FIRST_RESOURCES = new int [] {
- R.drawable.list_yellow_up,
- R.drawable.list_blue_up,
- R.drawable.list_white_up,
- R.drawable.list_green_up,
- R.drawable.list_red_up
- };
-
- /** 中间项背景资源数组 */
- private final static int [] BG_NORMAL_RESOURCES = new int [] {
- R.drawable.list_yellow_middle,
- R.drawable.list_blue_middle,
- R.drawable.list_white_middle,
- R.drawable.list_green_middle,
- R.drawable.list_red_middle
- };
-
- /** 末项背景资源数组 */
- private final static int [] BG_LAST_RESOURCES = new int [] {
- R.drawable.list_yellow_down,
- R.drawable.list_blue_down,
- R.drawable.list_white_down,
- R.drawable.list_green_down,
- R.drawable.list_red_down,
- };
-
- /** 单项背景资源数组 */
- private final static int [] BG_SINGLE_RESOURCES = new int [] {
- R.drawable.list_yellow_single,
- R.drawable.list_blue_single,
- R.drawable.list_white_single,
- R.drawable.list_green_single,
- R.drawable.list_red_single
- };
-
- /**
- * 获取笔记列表首项背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 首项背景资源 ID
- */
- public static int getNoteBgFirstRes(int id) {
- return BG_FIRST_RESOURCES[id];
- }
-
- /**
- * 获取笔记列表末项背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 末项背景资源 ID
- */
- public static int getNoteBgLastRes(int id) {
- return BG_LAST_RESOURCES[id];
- }
-
- /**
- * 获取笔记列表单项背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 单项背景资源 ID
- */
- public static int getNoteBgSingleRes(int id) {
- return BG_SINGLE_RESOURCES[id];
- }
-
- /**
- * 获取笔记列表中间项背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 中间项背景资源 ID
- */
- public static int getNoteBgNormalRes(int id) {
- return BG_NORMAL_RESOURCES[id];
- }
-
- /**
- * 获取文件夹背景资源 ID
- *
- * @return 文件夹背景资源 ID
- */
- public static int getFolderBgRes() {
- return R.drawable.list_folder;
- }
- }
-
- /**
- * Widget 背景资源类
- *
- * 提供桌面 Widget 的背景颜色资源。
- * 支持 2x2 和 4x4 两种尺寸的 Widget。
- *
- */
- public static class WidgetBgResources {
- /** 2x2 Widget 背景资源数组 */
- private final static int [] BG_2X_RESOURCES = new int [] {
- R.drawable.widget_2x_yellow,
- R.drawable.widget_2x_blue,
- R.drawable.widget_2x_white,
- R.drawable.widget_2x_green,
- R.drawable.widget_2x_red,
- };
-
- /**
- * 获取 2x2 Widget 背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 2x2 Widget 背景资源 ID
- */
- public static int getWidget2xBgResource(int id) {
- return BG_2X_RESOURCES[id];
- }
-
- /** 4x4 Widget 背景资源数组 */
- private final static int [] BG_4X_RESOURCES = new int [] {
- R.drawable.widget_4x_yellow,
- R.drawable.widget_4x_blue,
- R.drawable.widget_4x_white,
- R.drawable.widget_4x_green,
- R.drawable.widget_4x_red
- };
-
- /**
- * 获取 4x4 Widget 背景资源 ID
- *
- * @param id 背景颜色 ID(0-4)
- * @return 4x4 Widget 背景资源 ID
- */
- public static int getWidget4xBgResource(int id) {
- return BG_4X_RESOURCES[id];
- }
- }
-
- /**
- * 文本外观资源类
- *
- * 提供笔记文本的字体样式资源。
- * 支持四种字体大小:小、中、大、超大。
- *
- */
- public static class TextAppearanceResources {
- /** 文本外观样式资源数组 */
- private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
- R.style.TextAppearanceNormal,
- R.style.TextAppearanceMedium,
- R.style.TextAppearanceLarge,
- R.style.TextAppearanceSuper
- };
-
- /**
- * 获取文本外观样式资源 ID
- *
- * 如果 ID 超出范围,则返回默认字体大小。
- *
- *
- * @param id 字体大小 ID(0-3)
- * @return 文本外观样式资源 ID
- */
- public static int getTexAppearanceResource(int id) {
- /**
- * HACKME: 修复在 SharedPreferences 中存储资源 ID 的 bug。
- * ID 可能大于资源数组的长度,在这种情况下,
- * 返回 {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
- */
- if (id >= TEXTAPPEARANCE_RESOURCES.length) {
- return BG_DEFAULT_FONT_SIZE;
- }
- return TEXTAPPEARANCE_RESOURCES[id];
- }
-
- /**
- * 获取文本外观资源数量
- *
- * @return 资源数量
- */
- public static int getResourcesSize() {
- return TEXTAPPEARANCE_RESOURCES.length;
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java
deleted file mode 100644
index 09181bf..0000000
--- a/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
-import android.content.DialogInterface.OnDismissListener;
-import android.content.Intent;
-import android.media.AudioManager;
-import android.media.MediaPlayer;
-import android.media.RingtoneManager;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.PowerManager;
-import android.provider.Settings;
-import android.view.Window;
-import android.view.WindowManager;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.tool.DataUtils;
-
-import java.io.IOException;
-
-/**
- * 闹钟提醒活动
- *
- * 这个类负责显示笔记提醒的闹钟界面,当笔记设置的提醒时间到达时,
- * 由AlarmReceiver启动此活动,显示笔记内容摘要并播放闹钟声音。
- *
- * 主要功能:
- * 1. 在锁屏状态下显示闹钟界面
- * 2. 显示笔记内容摘要
- * 3. 播放系统闹钟声音
- * 4. 提供操作选项(关闭提醒或查看笔记)
- *
- * @see NoteEditActivity
- * @see net.micode.notes.tool.DataUtils
- */
-public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
- // 当前提醒的笔记ID
- private long mNoteId;
- // 笔记内容摘要
- private String mSnippet;
- // 摘要预览最大长度
- private static final int SNIPPET_PREW_MAX_LEN = 60;
- // 媒体播放器,用于播放闹钟声音
- MediaPlayer mPlayer;
-
- /**
- * 活动创建时的初始化方法
- *
- * 设置窗口属性,获取笔记信息,检查笔记是否存在,
- * 如果存在则显示提醒对话框并播放闹钟声音
- *
- * @param savedInstanceState 保存的实例状态
- */
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 请求无标题窗口
- requestWindowFeature(Window.FEATURE_NO_TITLE);
-
- final Window win = getWindow();
- // 添加FLAG_SHOW_WHEN_LOCKED标志,使活动可以在锁屏界面上显示
- win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
-
- // 如果屏幕当前是关闭状态,添加以下标志
- if (!isScreenOn()) {
- // 保持屏幕常亮
- // 打开屏幕
- // 允许在屏幕亮起时锁定
- // 设置窗口布局包含系统装饰区域
- win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
- | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
- | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
- | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
- }
-
- // 获取启动此活动的Intent
- Intent intent = getIntent();
-
- try {
- // 从Intent中解析出笔记ID
- mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
- // 通过笔记ID获取笔记内容摘要
- mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
- // 如果摘要超过最大长度,截取并添加省略号
- mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
- SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
- : mSnippet;
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- return;
- }
-
- // 初始化媒体播放器
- mPlayer = new MediaPlayer();
- // 检查笔记是否在数据库中存在且可见
- if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
- // 显示操作对话框
- showActionDialog();
- // 播放闹钟声音
- playAlarmSound();
- } else {
- // 如果笔记不存在,直接关闭活动
- finish();
- }
- }
-
- /**
- * 检查屏幕是否处于开启状态
- *
- * @return 如果屏幕开启返回true,否则返回false
- */
- private boolean isScreenOn() {
- PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
- return pm.isScreenOn();
- }
-
- /**
- * 播放闹钟声音
- *
- * 获取系统默认的闹钟铃声,设置音频流类型,
- * 并循环播放闹钟声音
- */
- private void playAlarmSound() {
- // 获取系统默认的闹钟铃声URI
- Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
-
- // 获取受静音模式影响的音频流类型
- int silentModeStreams = Settings.System.getInt(getContentResolver(),
- Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
-
- // 如果闹钟音频流受静音模式影响,使用受影响的流类型
- if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
- mPlayer.setAudioStreamType(silentModeStreams);
- } else {
- // 否则使用标准闹钟音频流
- mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
- }
- try {
- // 设置音频源
- mPlayer.setDataSource(this, url);
- // 准备播放
- mPlayer.prepare();
- // 设置循环播放
- mPlayer.setLooping(true);
- // 开始播放
- mPlayer.start();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 显示操作对话框
- *
- * 创建一个AlertDialog,显示笔记摘要和操作按钮
- * 当屏幕开启时,显示"查看笔记"按钮
- */
- private void showActionDialog() {
- // 创建AlertDialog构建器
- AlertDialog.Builder dialog = new AlertDialog.Builder(this);
- // 设置对话框标题为应用名称
- dialog.setTitle(R.string.app_name);
- // 设置对话框内容为笔记摘要
- dialog.setMessage(mSnippet);
- // 添加"确定"按钮,点击事件由当前类处理
- dialog.setPositiveButton(R.string.notealert_ok, this);
- // 如果屏幕是开启状态,添加"查看笔记"按钮
- if (isScreenOn()) {
- dialog.setNegativeButton(R.string.notealert_enter, this);
- }
- // 显示对话框并设置关闭监听器
- dialog.show().setOnDismissListener(this);
- }
-
- /**
- * 对话框按钮点击事件处理
- *
- * 处理用户在提醒对话框中的按钮点击操作,根据点击的按钮执行相应的操作
- *
- * @param dialog 触发点击事件的对话框对象,不能为 null
- * @param which 点击的按钮ID,取值为 DialogInterface.BUTTON_POSITIVE(确定按钮)
- * 或 DialogInterface.BUTTON_NEGATIVE(查看笔记按钮)
- */
- public void onClick(DialogInterface dialog, int which) {
- switch (which) {
- // 如果点击了"查看笔记"按钮(负按钮)
- case DialogInterface.BUTTON_NEGATIVE:
- // 创建跳转到笔记编辑活动的Intent
- Intent intent = new Intent(this, NoteEditActivity.class);
- // 设置动作为查看
- intent.setAction(Intent.ACTION_VIEW);
- // 传递笔记ID
- intent.putExtra(Intent.EXTRA_UID, mNoteId);
- // 启动笔记编辑活动
- startActivity(intent);
- break;
- // 默认情况(点击"确定"按钮)
- default:
- break;
- }
- }
-
- /**
- * 对话框关闭事件处理
- *
- * 当对话框被关闭时(无论是点击按钮还是外部点击),
- * 停止闹钟声音并关闭当前活动
- *
- * @param dialog 被关闭的对话框对象,不能为 null
- */
- public void onDismiss(DialogInterface dialog) {
- // 停止闹钟声音
- stopAlarmSound();
- // 关闭当前活动
- finish();
- }
-
- /**
- * 停止闹钟声音
- *
- * 停止媒体播放器,释放资源并将播放器对象置空
- */
- private void stopAlarmSound() {
- if (mPlayer != null) {
- // 停止播放
- mPlayer.stop();
- // 释放资源
- mPlayer.release();
- // 将播放器对象置空
- mPlayer = null;
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java
deleted file mode 100644
index c00b5c6..0000000
--- a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.AlarmManager; // 系统闹钟管理器,用于设置和管理系统级闹钟
-import android.app.PendingIntent; // 延迟意图,用于在指定时间触发操作
-import android.content.BroadcastReceiver; // 广播接收器基类,用于接收系统广播
-import android.content.ContentUris; // 用于处理内容URI的工具类
-import android.content.Context; // 应用上下文,提供访问应用环境和资源的接口
-import android.content.Intent; // 意图,用于组件间通信
-import android.database.Cursor; // 数据库游标,用于遍历查询结果
-
-import net.micode.notes.data.Notes; // 笔记数据相关类
-import net.micode.notes.data.Notes.NoteColumns; // 笔记表列定义
-
-/**
- * 闹钟初始化接收器
- *
- * 这个类继承自BroadcastReceiver,用于在系统启动或应用需要时重新初始化所有未触发的笔记提醒闹钟。
- * 它会查询数据库中所有设置了提醒时间且未过期的笔记,并为每个笔记设置系统闹钟。
- *
- * 主要触发时机:
- * 1. 系统启动完成时(接收BOOT_COMPLETED广播)
- * 2. 应用安装或更新后可能需要手动触发
- */
-public class AlarmInitReceiver extends BroadcastReceiver {
-
- /**
- * 数据库查询投影,指定需要从笔记表中获取的列
- * 只需要ID和提醒日期两列,用于设置闹钟
- */
- private static final String [] PROJECTION = new String [] {
- NoteColumns.ID, // 笔记ID
- NoteColumns.ALERTED_DATE // 提醒日期
- };
-
- // 列索引常量,用于从查询结果中获取对应列的数据
- private static final int COLUMN_ID = 0; // ID列在结果集中的索引
- private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列在结果集中的索引
-
- /**
- * 接收广播后的处理方法
- *
- * 当接收到广播(通常是系统启动完成广播)时,此方法会被调用。
- * 它会查询所有未过期的笔记提醒,并为每个笔记设置系统闹钟。
- *
- * @param context 应用上下文,用于访问系统服务和资源
- * @param intent 接收到的广播意图
- */
- @Override
- public void onReceive(Context context, Intent intent) {
- // 获取当前系统时间,作为查询条件
- long currentDate = System.currentTimeMillis();
-
- // 查询所有提醒时间晚于当前时间的笔记
- // 查询条件:提醒日期 > 当前时间 AND 笔记类型 = 普通笔记
- Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
- PROJECTION, // 指定查询的列
- NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 查询条件
- new String[] { String.valueOf(currentDate) }, // 查询参数
- null); // 排序方式,null表示默认排序
-
- // 处理查询结果
- if (c != null) {
- // 如果有查询结果,遍历所有符合条件的笔记
- if (c.moveToFirst()) {
- do {
- // 获取笔记的提醒时间
- long alertDate = c.getLong(COLUMN_ALERTED_DATE);
-
- // 创建一个指向AlarmReceiver的Intent,用于在闹钟触发时接收广播
- Intent sender = new Intent(context, AlarmReceiver.class);
- // 将笔记ID作为URI数据附加到Intent中,这样AlarmReceiver就能知道是哪个笔记的闹钟触发了
- sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
-
- // 创建PendingIntent,它封装了上述Intent,可以在指定时间触发
- PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
-
- // 获取系统闹钟服务
- AlarmManager alermManager = (AlarmManager) context
- .getSystemService(Context.ALARM_SERVICE);
-
- // 设置闹钟
- // 使用RTC_WAKEUP模式,即使设备处于睡眠状态也会唤醒设备并触发广播
- alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
- } while (c.moveToNext()); // 移动到下一条记录
- }
- // 关闭游标,释放资源
- c.close();
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java
deleted file mode 100644
index 1ef8a05..0000000
--- a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.BroadcastReceiver; // 广播接收器基类,用于接收系统广播
-import android.content.Context; // 应用上下文,提供访问应用环境和资源的接口
-import android.content.Intent; // 意图,用于组件间通信
-
-/**
- * 闹钟接收器
- *
- * 这个类继承自BroadcastReceiver,用于接收由AlarmManager设置的闹钟触发事件。
- * 当笔记的提醒时间到达时,AlarmManager会发送一个广播,这个接收器会接收该广播
- * 并启动闹钟提醒界面(AlarmAlertActivity)来显示提醒信息。
- *
- * 工作流程:
- * 1. AlarmInitReceiver为每个设置了提醒时间的笔记设置系统闹钟
- * 2. 当提醒时间到达时,系统发送广播
- * 3. AlarmReceiver接收广播并启动AlarmAlertActivity显示提醒
- */
-public class AlarmReceiver extends BroadcastReceiver {
-
- /**
- * 接收闹钟广播后的处理方法
- *
- * 当闹钟时间到达时,系统会发送广播,此方法会被调用。
- * 它会将接收到的Intent重新定向到AlarmAlertActivity,并添加FLAG_ACTIVITY_NEW_TASK标志
- * 确保即使在非UI上下文中也能启动Activity。
- *
- * @param context 应用上下文,用于启动Activity
- * @param intent 接收到的闹钟广播Intent,包含触发闹钟的笔记ID等信息
- */
- @Override
- public void onReceive(Context context, Intent intent) {
- // 将Intent的目标组件设置为AlarmAlertActivity
- // 这样当启动Activity时就会显示闹钟提醒界面
- intent.setClass(context, AlarmAlertActivity.class);
-
- // 添加FLAG_ACTIVITY_NEW_TASK标志
- // 这是必需的,因为从非Activity上下文(如BroadcastReceiver)启动Activity时,
- // 必须指定这个标志,表示启动一个新的任务栈
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-
- // 启动AlarmAlertActivity显示闹钟提醒
- // 原始Intent中包含了触发闹钟的笔记ID等信息,AlarmAlertActivity会使用这些信息
- // 来显示相应的笔记内容和提醒信息
- context.startActivity(intent);
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java b/app/src/main/java/net/micode/notes/ui/DateTimePicker.java
deleted file mode 100644
index 015522e..0000000
--- a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java
+++ /dev/null
@@ -1,651 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import java.text.DateFormatSymbols;
-import java.util.Calendar;
-
-import net.micode.notes.R;
-
-
-import android.content.Context;
-import android.text.format.DateFormat;
-import android.view.View;
-import android.widget.FrameLayout;
-import android.widget.NumberPicker;
-
-/**
- * 日期时间选择器
- *
- * 继承自FrameLayout,提供日期和时间选择的自定义视图组件。
- * 使用NumberPicker组件实现日期、小时、分钟和上午/下午的选择功能。
- * 支持24小时制和12小时制两种显示模式。
- *
- *
- * 主要功能:
- *
- * 显示日期选择器(显示前后3天,共7天)
- * 显示小时选择器(24小时制:0-23,12小时制:1-12)
- * 显示分钟选择器(0-59)
- * 显示上午/下午选择器(仅12小时制)
- * 支持设置日期时间变更监听器
- * 支持启用/禁用状态切换
- *
- *
- *
- * @see NumberPicker
- * @see OnDateTimeChangedListener
- */
-public class DateTimePicker extends FrameLayout {
-
- private static final boolean DEFAULT_ENABLE_STATE = true;
-
- private static final int HOURS_IN_HALF_DAY = 12;
- private static final int HOURS_IN_ALL_DAY = 24;
- private static final int DAYS_IN_ALL_WEEK = 7;
- private static final int DATE_SPINNER_MIN_VAL = 0;
- private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
- private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
- private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
- private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
- private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
- private static final int MINUT_SPINNER_MIN_VAL = 0;
- private static final int MINUT_SPINNER_MAX_VAL = 59;
- private static final int AMPM_SPINNER_MIN_VAL = 0;
- private static final int AMPM_SPINNER_MAX_VAL = 1;
-
- private final NumberPicker mDateSpinner;
- private final NumberPicker mHourSpinner;
- private final NumberPicker mMinuteSpinner;
- private final NumberPicker mAmPmSpinner;
- private Calendar mDate;
-
- private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
-
- private boolean mIsAm;
-
- private boolean mIs24HourView;
-
- private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
-
- private boolean mInitialising;
-
- private OnDateTimeChangedListener mOnDateTimeChangedListener;
-
- /**
- * 日期变更监听器
- *
- * 监听日期选择器的值变化,更新内部日期对象并通知外部监听器。
- *
- */
- private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
- @Override
- public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
- // 根据选择器的变化调整日期
- mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
- updateDateControl();
- onDateTimeChanged();
- }
- };
-
- /**
- * 小时变更监听器
- *
- * 监听小时选择器的值变化,处理跨日情况(如从23点变为0点或从0点变为23点),
- * 在12小时制下处理上午/下午的切换。
- *
- */
- private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
- @Override
- public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
- boolean isDateChanged = false;
- Calendar cal = Calendar.getInstance();
- // 处理12小时制下的跨日情况
- if (!mIs24HourView) {
- // 从下午11点变为12点,日期加1天
- if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
- cal.setTimeInMillis(mDate.getTimeInMillis());
- cal.add(Calendar.DAY_OF_YEAR, 1);
- isDateChanged = true;
- // 从12点变为下午11点,日期减1天
- } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
- cal.setTimeInMillis(mDate.getTimeInMillis());
- cal.add(Calendar.DAY_OF_YEAR, -1);
- isDateChanged = true;
- }
- // 切换上午/下午
- if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
- oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
- mIsAm = !mIsAm;
- updateAmPmControl();
- }
- } else {
- // 处理24小时制下的跨日情况
- if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
- cal.setTimeInMillis(mDate.getTimeInMillis());
- cal.add(Calendar.DAY_OF_YEAR, 1);
- isDateChanged = true;
- } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
- cal.setTimeInMillis(mDate.getTimeInMillis());
- cal.add(Calendar.DAY_OF_YEAR, -1);
- isDateChanged = true;
- }
- }
- // 计算新的小时数
- int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
- mDate.set(Calendar.HOUR_OF_DAY, newHour);
- onDateTimeChanged();
- // 如果日期发生变化,更新年月日
- if (isDateChanged) {
- setCurrentYear(cal.get(Calendar.YEAR));
- setCurrentMonth(cal.get(Calendar.MONTH));
- setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
- }
- }
- };
-
- /**
- * 分钟变更监听器
- *
- * 监听分钟选择器的值变化,处理跨小时情况(如从59分变为0分或从0分变为59分)。
- *
- */
- private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
- @Override
- public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
- int minValue = mMinuteSpinner.getMinValue();
- int maxValue = mMinuteSpinner.getMaxValue();
- int offset = 0;
- // 从最大值变为最小值,小时加1
- if (oldVal == maxValue && newVal == minValue) {
- offset += 1;
- // 从最小值变为最大值,小时减1
- } else if (oldVal == minValue && newVal == maxValue) {
- offset -= 1;
- }
- // 如果跨小时,更新小时和日期
- if (offset != 0) {
- mDate.add(Calendar.HOUR_OF_DAY, offset);
- mHourSpinner.setValue(getCurrentHour());
- updateDateControl();
- // 更新上午/下午状态
- int newHour = getCurrentHourOfDay();
- if (newHour >= HOURS_IN_HALF_DAY) {
- mIsAm = false;
- updateAmPmControl();
- } else {
- mIsAm = true;
- updateAmPmControl();
- }
- }
- mDate.set(Calendar.MINUTE, newVal);
- onDateTimeChanged();
- }
- };
-
- /**
- * 上午/下午变更监听器
- *
- * 监听上午/下午选择器的值变化,切换上午/下午时调整小时数。
- *
- */
- private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
- @Override
- public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
- mIsAm = !mIsAm;
- // 切换上午/下午,调整小时数
- if (mIsAm) {
- mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
- } else {
- mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
- }
- updateAmPmControl();
- onDateTimeChanged();
- }
- };
-
- /**
- * 日期时间变更监听器接口
- *
- * 用于监听日期时间选择器的值变化,当用户修改日期、小时或分钟时回调。
- *
- */
- public interface OnDateTimeChangedListener {
- /**
- * 当日期时间发生变化时调用
- *
- * @param view 日期时间选择器实例
- * @param year 年份
- * @param month 月份(0-11)
- * @param dayOfMonth 日(1-31)
- * @param hourOfDay 小时(0-23)
- * @param minute 分钟(0-59)
- */
- void onDateTimeChanged(DateTimePicker view, int year, int month,
- int dayOfMonth, int hourOfDay, int minute);
- }
-
- /**
- * 构造器
- *
- * 创建日期时间选择器,使用当前系统时间作为初始值。
- * 根据系统设置自动判断是否使用24小时制显示。
- *
- * @param context 应用上下文
- */
- public DateTimePicker(Context context) {
- this(context, System.currentTimeMillis());
- }
-
- /**
- * 构造器
- *
- * 创建日期时间选择器,使用指定的时间作为初始值。
- * 根据系统设置自动判断是否使用24小时制显示。
- *
- * @param context 应用上下文
- * @param date 初始日期时间,以毫秒为单位的时间戳
- */
- public DateTimePicker(Context context, long date) {
- this(context, date, DateFormat.is24HourFormat(context));
- }
-
- /**
- * 构造器
- *
- * 创建日期时间选择器,使用指定的时间和显示模式作为初始值。
- * 初始化所有NumberPicker组件并设置监听器。
- *
- * @param context 应用上下文
- * @param date 初始日期时间,以毫秒为单位的时间戳
- * @param is24HourView 是否使用24小时制显示,true表示24小时制,false表示12小时制
- */
- public DateTimePicker(Context context, long date, boolean is24HourView) {
- super(context);
- mDate = Calendar.getInstance();
- mInitialising = true;
- // 判断当前是否为下午
- mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
- // 加载布局
- inflate(context, R.layout.datetime_picker, this);
-
- // 初始化日期选择器
- mDateSpinner = (NumberPicker) findViewById(R.id.date);
- mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
- mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
- mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
-
- // 初始化小时选择器
- mHourSpinner = (NumberPicker) findViewById(R.id.hour);
- mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
- // 初始化分钟选择器
- mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
- mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
- mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
- mMinuteSpinner.setOnLongPressUpdateInterval(100);
- mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
-
- // 初始化上午/下午选择器
- String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
- mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
- mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
- mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
- mAmPmSpinner.setDisplayedValues(stringsForAmPm);
- mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
-
- // 更新控件到初始状态
- updateDateControl();
- updateHourControl();
- updateAmPmControl();
-
- // 设置24小时制显示模式
- set24HourView(is24HourView);
-
- // 设置当前时间
- setCurrentDate(date);
-
- // 设置启用状态
- setEnabled(isEnabled());
-
- // 设置内容描述
- mInitialising = false;
- }
-
- /**
- * 设置启用状态
- *
- * 设置所有NumberPicker组件的启用状态,控制用户是否可以修改日期时间。
- *
- * @param enabled true表示启用,false表示禁用
- */
- @Override
- public void setEnabled(boolean enabled) {
- if (mIsEnabled == enabled) {
- return;
- }
- super.setEnabled(enabled);
- mDateSpinner.setEnabled(enabled);
- mMinuteSpinner.setEnabled(enabled);
- mHourSpinner.setEnabled(enabled);
- mAmPmSpinner.setEnabled(enabled);
- mIsEnabled = enabled;
- }
-
- /**
- * 获取启用状态
- *
- * @return true表示已启用,false表示已禁用
- */
- @Override
- public boolean isEnabled() {
- return mIsEnabled;
- }
-
- /**
- * 获取当前日期时间(毫秒)
- *
- * @return 当前日期时间,以毫秒为单位的时间戳
- */
- public long getCurrentDateInTimeMillis() {
- return mDate.getTimeInMillis();
- }
-
- /**
- * 设置当前日期时间
- *
- * @param date 要设置的日期时间,以毫秒为单位的时间戳
- */
- public void setCurrentDate(long date) {
- Calendar cal = Calendar.getInstance();
- cal.setTimeInMillis(date);
- setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
- cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
- }
-
- /**
- * 设置当前日期时间
- *
- * @param year 年份
- * @param month 月份(0-11)
- * @param dayOfMonth 日(1-31)
- * @param hourOfDay 小时(0-23)
- * @param minute 分钟(0-59)
- */
- public void setCurrentDate(int year, int month,
- int dayOfMonth, int hourOfDay, int minute) {
- setCurrentYear(year);
- setCurrentMonth(month);
- setCurrentDay(dayOfMonth);
- setCurrentHour(hourOfDay);
- setCurrentMinute(minute);
- }
-
- /**
- * 获取当前年份
- *
- * @return 当前年份
- */
- public int getCurrentYear() {
- return mDate.get(Calendar.YEAR);
- }
-
- /**
- * 设置当前年份
- *
- * @param year 要设置的年份
- */
- public void setCurrentYear(int year) {
- if (!mInitialising && year == getCurrentYear()) {
- return;
- }
- mDate.set(Calendar.YEAR, year);
- updateDateControl();
- onDateTimeChanged();
- }
-
- /**
- * 获取当前月份
- *
- * @return 当前月份(0-11)
- */
- public int getCurrentMonth() {
- return mDate.get(Calendar.MONTH);
- }
-
- /**
- * 设置当前月份
- *
- * @param month 要设置的月份(0-11)
- */
- public void setCurrentMonth(int month) {
- if (!mInitialising && month == getCurrentMonth()) {
- return;
- }
- mDate.set(Calendar.MONTH, month);
- updateDateControl();
- onDateTimeChanged();
- }
-
- /**
- * 获取当前日
- *
- * @return 当前日(1-31)
- */
- public int getCurrentDay() {
- return mDate.get(Calendar.DAY_OF_MONTH);
- }
-
- /**
- * 设置当前日
- *
- * @param dayOfMonth 要设置的日(1-31)
- */
- public void setCurrentDay(int dayOfMonth) {
- if (!mInitialising && dayOfMonth == getCurrentDay()) {
- return;
- }
- mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
- updateDateControl();
- onDateTimeChanged();
- }
-
- /**
- * 获取当前小时(24小时制)
- *
- * @return 当前小时(0-23)
- */
- public int getCurrentHourOfDay() {
- return mDate.get(Calendar.HOUR_OF_DAY);
- }
-
- /**
- * 获取当前小时(根据显示模式)
- *
- * 在24小时制下返回0-23,在12小时制下返回1-12
- *
- * @return 当前小时
- */
- private int getCurrentHour() {
- if (mIs24HourView){
- return getCurrentHourOfDay();
- } else {
- int hour = getCurrentHourOfDay();
- if (hour > HOURS_IN_HALF_DAY) {
- return hour - HOURS_IN_HALF_DAY;
- } else {
- return hour == 0 ? HOURS_IN_HALF_DAY : hour;
- }
- }
- }
-
- /**
- * 设置当前小时(24小时制)
- *
- * @param hourOfDay 要设置的小时(0-23)
- */
- public void setCurrentHour(int hourOfDay) {
- if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
- return;
- }
- mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
- if (!mIs24HourView) {
- // 处理12小时制下的上午/下午状态
- if (hourOfDay >= HOURS_IN_HALF_DAY) {
- mIsAm = false;
- if (hourOfDay > HOURS_IN_HALF_DAY) {
- hourOfDay -= HOURS_IN_HALF_DAY;
- }
- } else {
- mIsAm = true;
- if (hourOfDay == 0) {
- hourOfDay = HOURS_IN_HALF_DAY;
- }
- }
- updateAmPmControl();
- }
- mHourSpinner.setValue(hourOfDay);
- onDateTimeChanged();
- }
-
- /**
- * 获取当前分钟
- *
- * @return 当前分钟(0-59)
- */
- public int getCurrentMinute() {
- return mDate.get(Calendar.MINUTE);
- }
-
- /**
- * 设置当前分钟
- *
- * @param minute 要设置的分钟(0-59)
- */
- public void setCurrentMinute(int minute) {
- if (!mInitialising && minute == getCurrentMinute()) {
- return;
- }
- mMinuteSpinner.setValue(minute);
- mDate.set(Calendar.MINUTE, minute);
- onDateTimeChanged();
- }
-
- /**
- * 判断是否为24小时制显示
- *
- * @return true表示24小时制,false表示12小时制
- */
- public boolean is24HourView () {
- return mIs24HourView;
- }
-
- /**
- * 设置显示模式
- *
- * @param is24HourView true表示使用24小时制,false表示使用12小时制
- */
- public void set24HourView(boolean is24HourView) {
- if (mIs24HourView == is24HourView) {
- return;
- }
- mIs24HourView = is24HourView;
- // 根据显示模式显示或隐藏上午/下午选择器
- mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
- int hour = getCurrentHourOfDay();
- updateHourControl();
- setCurrentHour(hour);
- updateAmPmControl();
- }
-
- /**
- * 更新日期选择器显示
- *
- * 根据当前日期更新日期选择器的显示值,显示前后3天,共7天的日期。
- * 每个日期的格式为"MM.dd EEEE"(月.日 星期)。
- */
- private void updateDateControl() {
- Calendar cal = Calendar.getInstance();
- // 设置为当前日期的前4天
- cal.setTimeInMillis(mDate.getTimeInMillis());
- cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
- mDateSpinner.setDisplayedValues(null);
- // 生成7天的日期显示值
- for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
- cal.add(Calendar.DAY_OF_YEAR, 1);
- mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
- }
- mDateSpinner.setDisplayedValues(mDateDisplayValues);
- // 设置当前选中项为中间项
- mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
- mDateSpinner.invalidate();
- }
-
- /**
- * 更新上午/下午选择器显示
- *
- * 根据当前显示模式和上午/下午状态更新上午/下午选择器的可见性和选中值。
- * 在24小时制下隐藏上午/下午选择器,在12小时制下显示并设置当前选中值。
- */
- private void updateAmPmControl() {
- if (mIs24HourView) {
- // 24小时制下隐藏上午/下午选择器
- mAmPmSpinner.setVisibility(View.GONE);
- } else {
- // 12小时制下显示上午/下午选择器
- int index = mIsAm ? Calendar.AM : Calendar.PM;
- mAmPmSpinner.setValue(index);
- mAmPmSpinner.setVisibility(View.VISIBLE);
- }
- }
-
- /**
- * 更新小时选择器范围
- *
- * 根据当前显示模式更新小时选择器的最小值和最大值。
- * 24小时制:0-23,12小时制:1-12。
- */
- private void updateHourControl() {
- if (mIs24HourView) {
- mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
- mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
- } else {
- mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
- mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
- }
- }
-
- /**
- * 设置日期时间变更监听器
- *
- * @param callback 日期时间变更监听器,如果为null则不执行任何操作
- */
- public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
- mOnDateTimeChangedListener = callback;
- }
-
- /**
- * 触发日期时间变更事件
- *
- * 如果设置了监听器,则通知监听器日期时间已发生变化。
- */
- private void onDateTimeChanged() {
- if (mOnDateTimeChangedListener != null) {
- mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
- getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java
deleted file mode 100644
index a95bc43..0000000
--- a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import java.util.Calendar;
-
-import net.micode.notes.R;
-import net.micode.notes.ui.DateTimePicker;
-import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
-import android.text.format.DateFormat;
-import android.text.format.DateUtils;
-
-/**
- * 日期时间选择对话框
- *
- * 继承自AlertDialog,提供日期和时间选择的对话框界面。
- * 使用DateTimePicker组件作为主视图,支持设置24小时制或12小时制显示。
- *
- *
- * 主要功能:
- *
- * 显示日期和时间选择器
- * 支持设置监听器获取用户选择的时间
- * 动态更新对话框标题显示当前选择的时间
- * 支持24小时制和12小时制切换
- *
- *
- *
- * @see DateTimePicker
- * @see OnDateTimeSetListener
- */
-public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
-
- private Calendar mDate = Calendar.getInstance();
- private boolean mIs24HourView;
- private OnDateTimeSetListener mOnDateTimeSetListener;
- private DateTimePicker mDateTimePicker;
-
- /**
- * 日期时间设置监听器接口
- *
- * 用于监听用户在对话框中点击确定按钮后的回调,获取用户选择的日期和时间。
- *
- */
- public interface OnDateTimeSetListener {
- /**
- * 当用户点击确定按钮时调用
- *
- * @param dialog 日期时间选择对话框实例
- * @param date 用户选择的日期时间,以毫秒为单位的时间戳
- */
- void OnDateTimeSet(AlertDialog dialog, long date);
- }
-
- /**
- * 构造器
- *
- * 创建日期时间选择对话框,初始化DateTimePicker组件并设置默认日期时间。
- * 根据系统设置自动判断是否使用24小时制显示。
- *
- * @param context 应用上下文
- * @param date 初始日期时间,以毫秒为单位的时间戳
- */
- public DateTimePickerDialog(Context context, long date) {
- super(context);
- // 创建日期时间选择器组件
- mDateTimePicker = new DateTimePicker(context);
- setView(mDateTimePicker);
- // 设置日期时间变更监听器
- mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
- public void onDateTimeChanged(DateTimePicker view, int year, int month,
- int dayOfMonth, int hourOfDay, int minute) {
- // 更新内部Calendar对象
- mDate.set(Calendar.YEAR, year);
- mDate.set(Calendar.MONTH, month);
- mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
- mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
- mDate.set(Calendar.MINUTE, minute);
- // 更新对话框标题
- updateTitle(mDate.getTimeInMillis());
- }
- });
- // 设置初始日期时间
- mDate.setTimeInMillis(date);
- // 将秒数清零
- mDate.set(Calendar.SECOND, 0);
- // 设置选择器当前日期
- mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
- // 设置确定按钮
- setButton(context.getString(R.string.datetime_dialog_ok), this);
- // 设置取消按钮
- setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
- // 根据系统设置判断是否使用24小时制
- set24HourView(DateFormat.is24HourFormat(this.getContext()));
- // 更新对话框标题
- updateTitle(mDate.getTimeInMillis());
- }
-
- /**
- * 设置是否使用24小时制显示
- *
- * 根据系统设置或用户偏好,判断是否使用24小时制显示时间。
- * 如果设置为true,将使用24小时制;如果设置为false,将使用12小时制。
- *
- *
- * @param is24HourView true表示使用24小时制,false表示使用12小时制
- */
- public void set24HourView(boolean is24HourView) {
- mIs24HourView = is24HourView;
- }
-
- /**
- * 设置日期时间设置监听器
- *
- * 当用户点击对话框的确定按钮时,调用此监听器的OnDateTimeSet方法,
- * 并传递用户选择的日期时间作为参数。
- *
- *
- * @param callBack 日期时间设置监听器,当用户点击确定按钮时回调
- */
- public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
- mOnDateTimeSetListener = callBack;
- }
-
- /**
- * 更新对话框标题
- *
- * 根据指定的日期时间格式化字符串,并设置为对话框标题。
- * 显示格式包含年、月、日和时间,根据mIs24HourView决定是否使用24小时制。
- *
- * @param date 要显示的日期时间,以毫秒为单位的时间戳
- */
- private void updateTitle(long date) {
- // 设置日期时间格式标志
- int flag =
- DateUtils.FORMAT_SHOW_YEAR |
- DateUtils.FORMAT_SHOW_DATE |
- DateUtils.FORMAT_SHOW_TIME;
- // 根据是否24小时制设置相应的格式标志
- flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
- // 格式化日期时间并设置为对话框标题
- setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
- }
-
- /**
- * 处理对话框按钮点击事件
- *
- * 当用户点击确定按钮时,调用监听器的OnDateTimeSet方法,传递用户选择的日期时间。
- *
- * @param arg0 触发事件的对话框
- * @param arg1 被点击的按钮ID
- */
- public void onClick(DialogInterface arg0, int arg1) {
- // 如果设置了监听器,通知监听器用户选择的日期时间
- if (mOnDateTimeSetListener != null) {
- mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
- }
- }
-
-}
\ No newline at end of file
diff --git a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java
deleted file mode 100644
index 7276081..0000000
--- a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.PopupMenu;
-import android.widget.PopupMenu.OnMenuItemClickListener;
-
-import net.micode.notes.R;
-
-/**
- * 下拉菜单类
- *
- * 封装了PopupMenu和Button,提供下拉菜单功能。
- * 点击按钮时显示弹出菜单,支持设置菜单项点击监听器和标题。
- *
- *
- * 主要功能:
- *
- * 显示下拉菜单
- * 设置菜单项点击监听器
- * 查找菜单项
- * 设置按钮标题
- *
- *
- */
-public class DropdownMenu {
- // 下拉按钮
- private Button mButton;
- // 弹出菜单
- private PopupMenu mPopupMenu;
- // 菜单对象
- private Menu mMenu;
-
- /**
- * 构造器
- *
- * 初始化下拉菜单,设置按钮背景、创建PopupMenu并加载菜单资源
- *
- * @param context 应用上下文
- * @param button 触发下拉菜单的按钮
- * @param menuId 菜单资源ID,用于加载菜单项
- */
- public DropdownMenu(Context context, Button button, int menuId) {
- mButton = button;
- // 设置下拉图标背景
- mButton.setBackgroundResource(R.drawable.dropdown_icon);
- // 创建弹出菜单
- mPopupMenu = new PopupMenu(context, mButton);
- mMenu = mPopupMenu.getMenu();
- // 加载菜单资源
- mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
- // 设置按钮点击监听器,点击时显示弹出菜单
- mButton.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- mPopupMenu.show();
- }
- });
- }
-
- /**
- * 设置菜单项点击监听器
- *
- * @param listener 菜单项点击监听器
- */
- public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
- if (mPopupMenu != null) {
- mPopupMenu.setOnMenuItemClickListener(listener);
- }
- }
-
- /**
- * 查找指定ID的菜单项
- *
- * @param id 菜单项ID
- * @return 找到的菜单项对象,如果未找到则返回null
- */
- public MenuItem findItem(int id) {
- return mMenu.findItem(id);
- }
-
- /**
- * 设置按钮标题
- *
- * @param title 要设置的标题文本
- */
- public void setTitle(CharSequence title) {
- mButton.setText(title);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java
deleted file mode 100644
index 7176cf9..0000000
--- a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CursorAdapter;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-
-/**
- * 文件夹列表适配器
- *
- * 继承自CursorAdapter,用于将数据库中的文件夹数据绑定到ListView中显示。
- * 主要用于笔记移动功能中显示可选择的文件夹列表。
- *
- *
- * 主要功能:
- *
- * 显示所有可用文件夹
- * 处理根文件夹的特殊显示
- * 提供获取文件夹名称的方法
- *
- *
- *
- * @see NotesListActivity
- */
-public class FoldersListAdapter extends CursorAdapter {
- // 数据库查询投影,指定需要从笔记表中获取的列
- public static final String [] PROJECTION = {
- NoteColumns.ID,
- NoteColumns.SNIPPET
- };
-
- // 列索引常量,用于从查询结果中获取对应列的数据
- public static final int ID_COLUMN = 0;
- public static final int NAME_COLUMN = 1;
-
- /**
- * 构造器
- *
- * 初始化文件夹列表适配器
- *
- * @param context 应用上下文
- * @param c 数据库游标,包含文件夹数据
- */
- public FoldersListAdapter(Context context, Cursor c) {
- super(context, c);
- }
-
- /**
- * 创建新的列表项视图
- *
- * 创建一个新的FolderListItem视图对象
- *
- * @param context 应用上下文
- * @param cursor 数据库游标,包含当前项的数据
- * @param parent 父视图
- * @return 新创建的FolderListItem视图对象
- */
- @Override
- public View newView(Context context, Cursor cursor, ViewGroup parent) {
- return new FolderListItem(context);
- }
-
- /**
- * 绑定数据到视图
- *
- * 将数据库游标中的数据绑定到已存在的视图上
- *
- * @param view 需要绑定数据的视图
- * @param context 应用上下文
- * @param cursor 数据库游标,包含当前项的数据
- */
- @Override
- public void bindView(View view, Context context, Cursor cursor) {
- if (view instanceof FolderListItem) {
- // 如果是根文件夹,显示特殊文本;否则显示文件夹名称
- String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
- .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
- ((FolderListItem) view).bind(folderName);
- }
- }
-
- /**
- * 获取指定位置的文件夹名称
- *
- * @param context 应用上下文,用于获取根文件夹的显示文本
- * @param position 列表项位置,从0开始
- * @return 文件夹名称,如果是根文件夹则返回特殊显示文本
- */
- public String getFolderName(Context context, int position) {
- Cursor cursor = (Cursor) getItem(position);
- return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
- .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
- }
-
- /**
- * 文件夹列表项视图
- *
- * 自定义的LinearLayout,用于显示文件夹列表中的单个文件夹项。
- *
- */
- private class FolderListItem extends LinearLayout {
- // 文件夹名称文本视图
- private TextView mName;
-
- /**
- * 构造器
- *
- * 初始化文件夹列表项视图
- *
- * @param context 应用上下文
- */
- public FolderListItem(Context context) {
- super(context);
- // 加载布局文件
- inflate(context, R.layout.folder_list_item, this);
- // 获取文件夹名称文本视图
- mName = (TextView) findViewById(R.id.tv_folder_name);
- }
-
- /**
- * 绑定文件夹名称到视图
- *
- * @param name 要显示的文件夹名称
- */
- public void bind(String name) {
- mName.setText(name);
- }
- }
-
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java
deleted file mode 100644
index d4cecfe..0000000
--- a/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java
+++ /dev/null
@@ -1,1204 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.Activity;
-import android.app.AlarmManager;
-import android.app.AlertDialog;
-import android.app.PendingIntent;
-import android.app.SearchManager;
-import android.appwidget.AppWidgetManager;
-import android.content.ContentUris;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.graphics.Paint;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.text.Spannable;
-import android.text.SpannableString;
-import android.text.TextUtils;
-import android.text.format.DateUtils;
-import android.text.style.BackgroundColorSpan;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.WindowManager;
-import android.widget.CheckBox;
-import android.widget.CompoundButton;
-import android.widget.CompoundButton.OnCheckedChangeListener;
-import android.widget.EditText;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.TextNote;
-import net.micode.notes.model.WorkingNote;
-import net.micode.notes.model.WorkingNote.NoteSettingChangedListener;
-import net.micode.notes.tool.DataUtils;
-import net.micode.notes.tool.ResourceParser;
-import net.micode.notes.tool.ResourceParser.TextAppearanceResources;
-import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;
-import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;
-import net.micode.notes.widget.NoteWidgetProvider_2x;
-import net.micode.notes.widget.NoteWidgetProvider_4x;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import androidx.appcompat.app.AppCompatActivity;
-import com.google.android.material.appbar.MaterialToolbar;
-
-
-public class NoteEditActivity extends AppCompatActivity implements OnClickListener,
- NoteSettingChangedListener, OnTextViewChangeListener {
- /**
- * 笔记头部视图持有者
- *
- * 持有笔记编辑界面头部区域的UI组件引用,包括修改时间、提醒图标、提醒日期和背景颜色设置按钮。
- *
- */
- private class HeadViewHolder {
- public TextView tvModified;
-
- public ImageView ivAlertIcon;
-
- public TextView tvAlertDate;
-
- public ImageView ibSetBgColor;
- }
-
- private static final Map sBgSelectorBtnsMap = new HashMap();
- static {
- sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
- sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);
- sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
- sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);
- sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
- }
-
- private static final Map sBgSelectorSelectionMap = new HashMap();
- static {
- sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
- sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);
- sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
- sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
- sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
- }
-
- private static final Map sFontSizeBtnsMap = new HashMap();
- static {
- sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
- sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);
- sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
- sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
- }
-
- private static final Map sFontSelectorSelectionMap = new HashMap();
- static {
- sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
- sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
- sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
- sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
- }
-
- private static final String TAG = "NoteEditActivity";
-
- private HeadViewHolder mNoteHeaderHolder;
-
- private View mHeadViewPanel;
-
- private View mNoteBgColorSelector;
-
- private View mFontSizeSelector;
-
- private EditText mNoteEditor;
-
- private View mNoteEditorPanel;
-
- private WorkingNote mWorkingNote;
-
- private SharedPreferences mSharedPrefs;
- private int mFontSizeId;
-
- private MaterialToolbar toolbar;
-
- private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
-
- private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
-
- public static final String TAG_CHECKED = String.valueOf('\u221A');
- public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
-
- private LinearLayout mEditTextList;
-
- private String mUserQuery;
- private Pattern mPattern;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.setContentView(R.layout.note_edit);
-
- // 初始化Toolbar(使用MaterialToolbar,与列表页面一致)
- MaterialToolbar toolbar = findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- if (getSupportActionBar() != null) {
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- getSupportActionBar().setDisplayShowHomeEnabled(true);
- }
- toolbar.setNavigationOnClickListener(v -> finish());
-
- if (savedInstanceState == null && !initActivityState(getIntent())) {
- finish();
- return;
- }
- initResources();
- }
-
- /**
- * 恢复活动状态
- *
- * 当系统内存不足导致活动被杀死时,重新加载活动需要恢复之前的状态。
- * 从保存的实例状态中恢复笔记ID,并重新初始化活动状态。
- *
- * @param savedInstanceState 包含之前保存状态的Bundle对象
- */
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID));
- if (!initActivityState(intent)) {
- finish();
- return;
- }
- Log.d(TAG, "Restoring from killed activity");
- }
- }
-
- /**
- * 初始化活动状态
- *
- * 根据传入的Intent初始化活动状态,支持以下操作:
- *
- * ACTION_VIEW: 查看现有笔记,支持从搜索结果打开
- * ACTION_INSERT_OR_EDIT: 创建新笔记或编辑笔记,支持通话记录笔记
- *
- *
- * @param intent 包含操作类型和参数的Intent对象
- * @return 初始化成功返回true,失败返回false
- */
- private boolean initActivityState(Intent intent) {
- /**
- * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
- * then jump to the NotesListActivity
- */
- mWorkingNote = null;
- if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
- long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
- mUserQuery = "";
-
- /**
- * Starting from the searched result
- */
- if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
- noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
- mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
- }
-
- if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
- Intent jump = new Intent(this, NotesListActivity.class);
- startActivity(jump);
- showToast(R.string.error_note_not_exist);
- finish();
- return false;
- } else {
- mWorkingNote = WorkingNote.load(this, noteId);
- if (mWorkingNote == null) {
- Log.e(TAG, "load note failed with note id" + noteId);
- finish();
- return false;
- }
- }
- getWindow().setSoftInputMode(
- WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
- | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
- } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
- // New note
- long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
- int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
- AppWidgetManager.INVALID_APPWIDGET_ID);
- int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE,
- Notes.TYPE_WIDGET_INVALIDE);
- int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
- ResourceParser.getDefaultBgId(this));
-
- // Parse call-record note
- String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
- long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
- if (callDate != 0 && phoneNumber != null) {
- if (TextUtils.isEmpty(phoneNumber)) {
- Log.w(TAG, "The call record number is null");
- }
- long noteId = 0;
- if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),
- phoneNumber, callDate)) > 0) {
- mWorkingNote = WorkingNote.load(this, noteId);
- if (mWorkingNote == null) {
- Log.e(TAG, "load call note failed with note id" + noteId);
- finish();
- return false;
- }
- } else {
- mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
- widgetType, bgResId);
- mWorkingNote.convertToCallNote(phoneNumber, callDate);
- }
- } else {
- mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
- bgResId);
- }
-
- getWindow().setSoftInputMode(
- WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
- | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
- } else {
- Log.e(TAG, "Intent not specified action, should not support");
- finish();
- return false;
- }
- mWorkingNote.setOnSettingStatusChangedListener(this);
- return true;
- }
-
- /**
- * 初始化资源
- *
- * 初始化笔记编辑界面的所有UI组件引用和点击监听器
- *
- */
- private void initResources() {
- mHeadViewPanel = findViewById(R.id.note_title);
- mNoteHeaderHolder = new HeadViewHolder();
- mNoteHeaderHolder.tvModified = findViewById(R.id.tv_modified_date);
- mNoteHeaderHolder.ivAlertIcon = findViewById(R.id.iv_alert_icon);
- mNoteHeaderHolder.tvAlertDate = findViewById(R.id.tv_alert_date);
- mNoteHeaderHolder.ibSetBgColor = findViewById(R.id.btn_set_bg_color);
- mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);
- mNoteEditor = findViewById(R.id.note_edit_view);
- mNoteEditorPanel = findViewById(R.id.sv_note_edit);
- mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
-
- // 设置背景颜色选择器的点击事件
- for (int id : sBgSelectorBtnsMap.keySet()) {
- ImageView iv = findViewById(id);
- iv.setOnClickListener(this);
- }
-
- mFontSizeSelector = findViewById(R.id.font_size_selector);
- for (int id : sFontSizeBtnsMap.keySet()) {
- View view = findViewById(id);
- view.setOnClickListener(this);
- }
-
- mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
- mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
- /**
- * HACKME: Fix bug of store the resource id in shared preference.
- * The id may larger than the length of resources, in this case,
- * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
- */
- if (mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
- mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
- }
- mEditTextList = findViewById(R.id.note_edit_list);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- initNoteScreen();
- }
-
- /**
- * 初始化笔记编辑界面
- *
- * 设置笔记编辑界面的显示内容,包括:
- *
- * 根据字体大小设置文本外观
- * 根据模式(普通/清单)显示笔记内容
- * 设置背景颜色
- * 显示修改时间和提醒信息
- *
- *
- */
- private void initNoteScreen() {
- mNoteEditor.setTextAppearance(this, TextAppearanceResources
- .getTexAppearanceResource(mFontSizeId));
- if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
- switchToListMode(mWorkingNote.getContent());
- } else {
- mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
- mNoteEditor.setSelection(mNoteEditor.getText().length());
- }
- for (Integer id : sBgSelectorSelectionMap.keySet()) {
- findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
- }
- mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
- mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
-
- mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
- mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
- | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
- | DateUtils.FORMAT_SHOW_YEAR));
-
- /**
- * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
- * is not ready
- */
- showAlertHeader();
- }
-
- /**
- * 显示提醒头部信息
- *
- * 根据笔记是否设置了闹钟提醒,显示或隐藏提醒图标和提醒日期。
- * 如果提醒已过期,显示过期提示;否则显示相对时间。
- *
- */
- private void showAlertHeader() {
- if (mWorkingNote.hasClockAlert()) {
- long time = System.currentTimeMillis();
- if (time > mWorkingNote.getAlertDate()) {
- mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);
- } else {
- mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
- mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));
- }
- mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);
- mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);
- } else {
- mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
- mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
- };
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- initActivityState(intent);
- }
-
- /**
- * 保存活动实例状态
- *
- * 在活动被系统销毁前保存当前笔记的ID,以便后续恢复。
- * 如果是新笔记且尚未保存到数据库,会先保存笔记以生成ID。
- *
- * @param outState 用于保存状态的Bundle对象
- */
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- /**
- * For new note without note id, we should firstly save it to
- * generate a id. If the editing note is not worth saving, there
- * is no id which is equivalent to create new note
- */
- if (!mWorkingNote.existInDatabase()) {
- saveNote();
- }
- outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
- Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
- }
-
- /**
- * 分发触摸事件
- *
- * 处理触摸事件,当用户点击背景颜色选择器或字体大小选择器外部区域时,
- * 隐藏相应的选择器面板。
- *
- * @param ev 触摸事件对象
- * @return 如果事件被处理返回true,否则返回false
- */
- @Override
- public boolean dispatchTouchEvent(MotionEvent ev) {
- if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
- && !inRangeOfView(mNoteBgColorSelector, ev)) {
- mNoteBgColorSelector.setVisibility(View.GONE);
- return true;
- }
-
- if (mFontSizeSelector.getVisibility() == View.VISIBLE
- && !inRangeOfView(mFontSizeSelector, ev)) {
- mFontSizeSelector.setVisibility(View.GONE);
- return true;
- }
- return super.dispatchTouchEvent(ev);
- }
-
- /**
- * 检查触摸点是否在视图范围内
- *
- * 判断给定的触摸事件坐标是否位于指定视图的显示区域内。
- *
- * @param view 要检查的视图
- * @param ev 触摸事件对象
- * @return 如果触摸点在视图范围内返回true,否则返回false
- */
- private boolean inRangeOfView(View view, MotionEvent ev) {
- int []location = new int[2];
- view.getLocationOnScreen(location);
- int x = location[0];
- int y = location[1];
- if (ev.getX() < x
- || ev.getX() > (x + view.getWidth())
- || ev.getY() < y
- || ev.getY() > (y + view.getHeight())) {
- return false;
- }
- return true;
- }
-
- /**
- * 活动暂停时保存笔记
- *
- * 在活动暂停时自动保存笔记内容,并清除设置状态(如打开的颜色选择器)。
- *
- */
- @Override
- protected void onPause() {
- super.onPause();
- if(saveNote()) {
- Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
- }
- clearSettingState();
- }
-
- /**
- * 更新桌面小部件
- *
- * 发送广播通知桌面小部件更新,根据笔记的小部件类型(2x或4x)发送相应的更新意图。
- *
- */
- private void updateWidget() {
- Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
- if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
- intent.setClass(this, NoteWidgetProvider_2x.class);
- } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {
- intent.setClass(this, NoteWidgetProvider_4x.class);
- } else {
- Log.e(TAG, "Unspported widget type");
- return;
- }
-
- intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
- mWorkingNote.getWidgetId()
- });
-
- sendBroadcast(intent);
- setResult(RESULT_OK, intent);
- }
-
- /**
- * 处理点击事件
- *
- * 处理各种UI组件的点击事件,包括:
- *
- * 背景颜色设置按钮:显示颜色选择器
- * 背景颜色选项:设置笔记背景颜色
- * 字体大小选项:设置编辑器字体大小
- *
- *
- * @param v 被点击的视图
- */
- public void onClick(View v) {
- int id = v.getId();
- if (id == R.id.btn_set_bg_color) {
- mNoteBgColorSelector.setVisibility(View.VISIBLE);
- findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE);
- } else if (sBgSelectorBtnsMap.containsKey(id)) {
- findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.GONE);
- mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
- mNoteBgColorSelector.setVisibility(View.GONE);
- } else if (sFontSizeBtnsMap.containsKey(id)) {
- findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);
- mFontSizeId = sFontSizeBtnsMap.get(id);
- mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();
- findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
- if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
- getWorkingText();
- switchToListMode(mWorkingNote.getContent());
- } else {
- mNoteEditor.setTextAppearance(this,
- TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
- }
- mFontSizeSelector.setVisibility(View.GONE);
- }
- }
-
- /**
- * 处理返回键按下事件
- *
- * 如果当前有打开的设置面板(颜色选择器或字体选择器),先关闭面板;
- * 否则保存笔记并退出活动。
- *
- */
- @Override
- public void onBackPressed() {
- if(clearSettingState()) {
- return;
- }
-
- saveNote();
- super.onBackPressed();
- }
-
- /**
- * 清除设置状态
- *
- * 检查并关闭所有打开的设置面板(背景颜色选择器和字体大小选择器)。
- *
- * @return 如果关闭了任何面板返回true,否则返回false
- */
- private boolean clearSettingState() {
- if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
- mNoteBgColorSelector.setVisibility(View.GONE);
- return true;
- } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
- mFontSizeSelector.setVisibility(View.GONE);
- return true;
- }
- return false;
- }
-
- /**
- * 背景颜色改变回调
- *
- * 当笔记背景颜色改变时调用,更新UI显示:
- *
- * 显示选中颜色的指示器
- * 更新编辑器面板背景
- * 更新头部面板背景
- *
- *
- */
- public void onBackgroundColorChanged() {
- findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE);
- mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
- mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
- }
-
- /**
- * 准备选项菜单
- *
- * 根据当前笔记的状态动态设置菜单项:
- *
- * 通话记录笔记使用特殊菜单
- * 清单模式下切换菜单项标题
- * 根据是否设置提醒显示/隐藏相应菜单项
- *
- *
- * @param menu 选项菜单对象
- * @return 返回true表示菜单已准备好
- */
- @Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- if (isFinishing()) {
- return true;
- }
- clearSettingState();
- menu.clear();
- if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {
- getMenuInflater().inflate(R.menu.call_note_edit, menu);
- } else {
- getMenuInflater().inflate(R.menu.note_edit, menu);
- }
- if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
- menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
- } else {
- menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
- }
- if (mWorkingNote.hasClockAlert()) {
- menu.findItem(R.id.menu_alert).setVisible(false);
- } else {
- menu.findItem(R.id.menu_delete_remind).setVisible(false);
- }
- return true;
- }
-
- /**
- * 处理选项菜单项选择
- *
- * 处理各种菜单项的点击事件,包括:
- *
- * 新建笔记:创建新笔记
- * 删除笔记:显示确认对话框后删除当前笔记
- * 字体大小:显示字体大小选择器
- * 清单模式:切换普通/清单模式
- * 分享:分享笔记内容到其他应用
- * 发送到桌面:创建桌面小部件
- * 设置提醒:设置闹钟提醒
- * 删除提醒:删除已设置的提醒
- *
- *
- * @param item 被选中的菜单项
- * @return 返回true表示事件已处理
- */
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.menu_new_note:
- createNewNote();
- break;
- case R.id.menu_delete:
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(getString(R.string.alert_title_delete));
- builder.setIcon(android.R.drawable.ic_dialog_alert);
- builder.setMessage(getString(R.string.alert_message_delete_note));
- builder.setPositiveButton(android.R.string.ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- deleteCurrentNote();
- finish();
- }
- });
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- break;
- case R.id.menu_font_size:
- mFontSizeSelector.setVisibility(View.VISIBLE);
- findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
- break;
- case R.id.menu_list_mode:
- mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?
- TextNote.MODE_CHECK_LIST : 0);
- break;
- case R.id.menu_share:
- getWorkingText();
- sendTo(this, mWorkingNote.getContent());
- break;
- case R.id.menu_send_to_desktop:
- sendToDesktop();
- break;
- case R.id.menu_alert:
- setReminder();
- break;
- case R.id.menu_delete_remind:
- mWorkingNote.setAlertDate(0, false);
- break;
- default:
- break;
- }
- return true;
- }
-
- /**
- * 设置提醒
- *
- * 显示日期时间选择对话框,让用户选择提醒时间。
- * 选择完成后设置笔记的提醒日期。
- *
- */
- private void setReminder() {
- DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
- d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
- public void OnDateTimeSet(AlertDialog dialog, long date) {
- mWorkingNote.setAlertDate(date , true);
- }
- });
- d.show();
- }
-
- /**
- * 分享笔记到其他应用
- *
- * 使用ACTION_SEND Intent将笔记内容分享到支持文本分享的应用。
- *
- * @param context 上下文对象
- * @param info 要分享的文本内容
- */
- private void sendTo(Context context, String info) {
- Intent intent = new Intent(Intent.ACTION_SEND);
- intent.putExtra(Intent.EXTRA_TEXT, info);
- intent.setType("text/plain");
- context.startActivity(intent);
- }
-
- /**
- * 创建新笔记
- *
- * 先保存当前编辑的笔记,然后启动新的NoteEditActivity创建新笔记。
- * 新笔记将创建在与当前笔记相同的文件夹中。
- *
- */
- private void createNewNote() {
- // Firstly, save current editing notes
- saveNote();
-
- // For safety, start a new NoteEditActivity
- finish();
- Intent intent = new Intent(this, NoteEditActivity.class);
- intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
- intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());
- startActivity(intent);
- }
-
- /**
- * 删除当前笔记
- *
- * 删除当前编辑的笔记。如果处于同步模式,将笔记移动到垃圾箱;
- * 否则直接从数据库中删除。
- *
- */
- private void deleteCurrentNote() {
- if (mWorkingNote.existInDatabase()) {
- HashSet ids = new HashSet();
- long id = mWorkingNote.getNoteId();
- if (id != Notes.ID_ROOT_FOLDER) {
- ids.add(id);
- } else {
- Log.d(TAG, "Wrong note id, should not happen");
- }
- if (!isSyncMode()) {
- if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
- Log.e(TAG, "Delete Note error");
- }
- } else {
- if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {
- Log.e(TAG, "Move notes to trash folder error, should not happens");
- }
- }
- }
- mWorkingNote.markDeleted(true);
- }
-
- /**
- * 检查是否处于同步模式
- *
- * 检查是否配置了同步账户,如果配置了则处于同步模式。
- *
- * @return 如果配置了同步账户返回true,否则返回false
- */
- private boolean isSyncMode() {
- return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
- }
-
- /**
- * 闹钟提醒改变回调
- *
- * 当笔记的闹钟提醒设置改变时调用。
- * 如果笔记尚未保存到数据库,先保存笔记。
- * 然后使用AlarmManager设置或取消闹钟。
- *
- * @param date 提醒日期时间(毫秒)
- * @param set true表示设置提醒,false表示取消提醒
- */
- public void onClockAlertChanged(long date, boolean set) {
- /**
- * User could set clock to an unsaved note, so before setting the
- * alert clock, we should save the note first
- */
- if (!mWorkingNote.existInDatabase()) {
- saveNote();
- }
- if (mWorkingNote.getNoteId() > 0) {
- Intent intent = new Intent(this, AlarmReceiver.class);
- intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
- PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
- AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
- showAlertHeader();
- if(!set) {
- alarmManager.cancel(pendingIntent);
- } else {
- alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
- }
- } else {
- /**
- * There is the condition that user has input nothing (the note is
- * not worthy saving), we have no note id, remind the user that he
- * should input something
- */
- Log.e(TAG, "Clock alert setting error");
- showToast(R.string.error_note_empty_for_clock);
- }
- }
-
- /**
- * 小部件改变回调
- *
- * 当笔记的小部件设置改变时调用,更新桌面小部件显示。
- *
- */
- public void onWidgetChanged() {
- updateWidget();
- }
-
- /**
- * 编辑文本删除回调
- *
- * 在清单模式下删除某个编辑项时调用。
- * 删除指定位置的编辑项,并更新后续项的索引。
- *
- * @param index 要删除的编辑项索引
- * @param text 编辑项的文本内容
- */
- public void onEditTextDelete(int index, String text) {
- int childCount = mEditTextList.getChildCount();
- if (childCount == 1) {
- return;
- }
-
- for (int i = index + 1; i < childCount; i++) {
- ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
- .setIndex(i - 1);
- }
-
- mEditTextList.removeViewAt(index);
- NoteEditText edit = null;
- if(index == 0) {
- edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
- R.id.et_edit_text);
- } else {
- edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
- R.id.et_edit_text);
- }
- int length = edit.length();
- edit.append(text);
- edit.requestFocus();
- edit.setSelection(length);
- }
-
- /**
- * 编辑文本回车回调
- *
- * 在清单模式下,当用户在某个编辑项中按下回车键时调用。
- * 在指定位置插入新的编辑项,并更新后续项的索引。
- *
- * @param index 回车位置所在的编辑项索引
- * @param text 编辑项的文本内容
- */
- public void onEditTextEnter(int index, String text) {
- /**
- * Should not happen, check for debug
- */
- if(index > mEditTextList.getChildCount()) {
- Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
- }
-
- View view = getListItem(text, index);
- mEditTextList.addView(view, index);
- NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
- edit.requestFocus();
- edit.setSelection(0);
- for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {
- ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
- .setIndex(i);
- }
- }
-
- /**
- * 切换到清单模式
- *
- * 将普通文本编辑器切换到清单模式。
- * 将文本按行分割,每行创建一个清单项,包含复选框和编辑框。
- *
- * @param text 要转换为清单的文本内容
- */
- private void switchToListMode(String text) {
- mEditTextList.removeAllViews();
- String[] items = text.split("\n");
- int index = 0;
- for (String item : items) {
- if(!TextUtils.isEmpty(item)) {
- mEditTextList.addView(getListItem(item, index));
- index++;
- }
- }
- mEditTextList.addView(getListItem("", index));
- mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
-
- mNoteEditor.setVisibility(View.GONE);
- mEditTextList.setVisibility(View.VISIBLE);
- }
-
- /**
- * 高亮显示搜索结果
- *
- * 在文本中高亮显示用户搜索的关键词。
- * 使用背景色标记匹配的文本。
- *
- * @param fullText 完整的文本内容
- * @param userQuery 用户搜索的关键词
- * @return 带有高亮标记的Spannable对象
- */
- private Spannable getHighlightQueryResult(String fullText, String userQuery) {
- SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
- if (!TextUtils.isEmpty(userQuery)) {
- mPattern = Pattern.compile(userQuery);
- Matcher m = mPattern.matcher(fullText);
- int start = 0;
- while (m.find(start)) {
- spannable.setSpan(
- new BackgroundColorSpan(this.getResources().getColor(
- R.color.user_query_highlight)), m.start(), m.end(),
- Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
- start = m.end();
- }
- }
- return spannable;
- }
-
- /**
- * 创建清单列表项视图
- *
- * 创建清单模式下的单个列表项,包含复选框和编辑框。
- * 根据文本内容设置复选框状态和文本样式。
- *
- * @param item 列表项的文本内容
- * @param index 列表项的索引
- * @return 列表项视图
- */
- private View getListItem(String item, int index) {
- View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
- final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
- edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
- CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
- cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (isChecked) {
- edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
- } else {
- edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
- }
- }
- });
-
- if (item.startsWith(TAG_CHECKED)) {
- cb.setChecked(true);
- edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
- item = item.substring(TAG_CHECKED.length(), item.length()).trim();
- } else if (item.startsWith(TAG_UNCHECKED)) {
- cb.setChecked(false);
- edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
- item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
- }
-
- edit.setOnTextViewChangeListener(this);
- edit.setIndex(index);
- edit.setText(getHighlightQueryResult(item, mUserQuery));
- return view;
- }
-
- /**
- * 文本改变回调
- *
- * 在清单模式下,当某个编辑项的文本内容改变时调用。
- * 根据是否有文本内容显示或隐藏复选框。
- *
- * @param index 编辑项的索引
- * @param hasText 是否有文本内容
- */
- public void onTextChange(int index, boolean hasText) {
- if (index >= mEditTextList.getChildCount()) {
- Log.e(TAG, "Wrong index, should not happen");
- return;
- }
- if(hasText) {
- mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
- } else {
- mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
- }
- }
-
- /**
- * 清单模式改变回调
- *
- * 当笔记的清单模式改变时调用。
- * 切换到清单模式时,将文本转换为清单项;
- * 切换到普通模式时,将清单项转换为文本。
- *
- * @param oldMode 旧的模式
- * @param newMode 新的模式
- */
- public void onCheckListModeChanged(int oldMode, int newMode) {
- if (newMode == TextNote.MODE_CHECK_LIST) {
- switchToListMode(mNoteEditor.getText().toString());
- } else {
- if (!getWorkingText()) {
- mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
- ""));
- }
- mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
- mEditTextList.setVisibility(View.GONE);
- mNoteEditor.setVisibility(View.VISIBLE);
- }
- }
-
- /**
- * 获取工作文本
- *
- * 从当前编辑器中获取文本内容并设置到WorkingNote。
- * 如果是清单模式,将所有清单项合并为文本,并标记已选中项。
- *
- * @return 如果有已选中的清单项返回true,否则返回false
- */
- private boolean getWorkingText() {
- boolean hasChecked = false;
- if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < mEditTextList.getChildCount(); i++) {
- View view = mEditTextList.getChildAt(i);
- NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
- if (!TextUtils.isEmpty(edit.getText())) {
- if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
- sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");
- hasChecked = true;
- } else {
- sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");
- }
- }
- }
- mWorkingNote.setWorkingText(sb.toString());
- } else {
- mWorkingNote.setWorkingText(mNoteEditor.getText().toString());
- }
- return hasChecked;
- }
-
- /**
- * 保存笔记
- *
- * 将当前编辑的笔记保存到数据库。
- * 保存成功后设置RESULT_OK结果码,用于标识创建/编辑状态。
- *
- * @return 保存成功返回true,失败返回false
- */
- private boolean saveNote() {
- getWorkingText();
- boolean saved = mWorkingNote.saveNote();
- if (saved) {
- /**
- * There are two modes from List view to edit view, open one note,
- * create/edit a node. Opening node requires to the original
- * position in the list when back from edit view, while creating a
- * new node requires to the top of the list. This code
- * {@link #RESULT_OK} is used to identify the create/edit state
- */
- setResult(RESULT_OK);
- }
- return saved;
- }
-
- /**
- * 发送到桌面
- *
- * 将笔记创建为桌面快捷方式。
- * 如果笔记尚未保存到数据库,先保存笔记。
- * 快捷方式使用笔记内容的前10个字符作为标题。
- *
- */
- private void sendToDesktop() {
- /**
- * Before send message to home, we should make sure that current
- * editing note is exists in databases. So, for new note, firstly
- * save it
- */
- if (!mWorkingNote.existInDatabase()) {
- saveNote();
- }
-
- if (mWorkingNote.getNoteId() > 0) {
- Intent sender = new Intent();
- Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
- shortcutIntent.setAction(Intent.ACTION_VIEW);
- shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId());
- sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
- sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
- makeShortcutIconTitle(mWorkingNote.getContent()));
- sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
- Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app));
- sender.putExtra("duplicate", true);
- sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
- showToast(R.string.info_note_enter_desktop);
- sendBroadcast(sender);
- } else {
- /**
- * There is the condition that user has input nothing (the note is
- * not worthy saving), we have no note id, remind the user that he
- * should input something
- */
- Log.e(TAG, "Send to desktop error");
- showToast(R.string.error_note_empty_for_send_to_desktop);
- }
- }
-
- /**
- * 生成快捷方式图标标题
- *
- * 从笔记内容中提取文本作为快捷方式标题。
- * 移除清单标记,并限制标题长度为10个字符。
- *
- * @param content 笔记内容
- * @return 快捷方式标题
- */
- private String makeShortcutIconTitle(String content) {
- content = content.replace(TAG_CHECKED, "");
- content = content.replace(TAG_UNCHECKED, "");
- return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
- SHORTCUT_ICON_TITLE_MAX_LEN) : content;
- }
-
- /**
- * 显示Toast提示
- *
- * 显示短时Toast提示消息。
- *
- * @param resId 字符串资源ID
- */
- private void showToast(int resId) {
- showToast(resId, Toast.LENGTH_SHORT);
- }
-
- /**
- * 显示Toast提示
- *
- * 显示指定时长的Toast提示消息。
- *
- * @param resId 字符串资源ID
- * @param duration 显示时长(Toast.LENGTH_SHORT或Toast.LENGTH_LONG)
- */
- private void showToast(int resId, int duration) {
- Toast.makeText(this, resId, duration).show();
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NoteEditText.java b/app/src/main/java/net/micode/notes/ui/NoteEditText.java
deleted file mode 100644
index df117b3..0000000
--- a/app/src/main/java/net/micode/notes/ui/NoteEditText.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.graphics.Rect;
-import android.text.Layout;
-import android.text.Selection;
-import android.text.Spanned;
-import android.text.TextUtils;
-import android.text.style.URLSpan;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.ContextMenu;
-import android.view.KeyEvent;
-import android.view.MenuItem;
-import android.view.MenuItem.OnMenuItemClickListener;
-import android.view.MotionEvent;
-import android.widget.EditText;
-
-import net.micode.notes.R;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * 笔记编辑文本框
- *
- * 自定义的EditText,用于笔记编辑界面,支持多行文本编辑、链接识别和上下文菜单。
- * 提供了与NoteEditActivity的交互接口,用于处理删除和回车事件。
- *
- *
- * 主要功能:
- *
- * 支持多行文本编辑,每行是一个独立的EditText
- * 识别并处理URL、电话号码、邮件地址等链接
- * 处理删除和回车事件,通知监听器
- * 支持文本选择和上下文菜单
- *
- *
- *
- * @see NoteEditActivity
- */
-public class NoteEditText extends EditText {
- // 日志标签
- private static final String TAG = "NoteEditText";
- // 当前EditText的索引
- private int mIndex;
- // 删除前的光标位置
- private int mSelectionStartBeforeDelete;
-
- // 电话号码URI方案
- private static final String SCHEME_TEL = "tel:" ;
- // HTTP URI方案
- private static final String SCHEME_HTTP = "http:" ;
- // 邮件URI方案
- private static final String SCHEME_EMAIL = "mailto:" ;
-
- // URI方案与上下文菜单资源ID的映射
- private static final Map sSchemaActionResMap = new HashMap();
- static {
- sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
- sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
- sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
- }
-
- /**
- * 文本视图变更监听器接口
- *
- * 由NoteEditActivity实现,用于处理EditText的删除、回车和文本变更事件。
- *
- *
- * @see NoteEditActivity
- */
- public interface OnTextViewChangeListener {
- /**
- * 当按下删除键且文本为空时调用
- *
- * @param index 当前EditText的索引
- * @param text 当前EditText中的文本内容
- */
- void onEditTextDelete(int index, String text);
-
- /**
- * 当按下回车键时调用
- *
- * @param index 当前EditText的索引
- * @param text 当前EditText中的文本内容
- */
- void onEditTextEnter(int index, String text);
-
- /**
- * 当文本内容变更时调用
- *
- * @param index 当前EditText的索引
- * @param hasText 是否有文本内容
- */
- void onTextChange(int index, boolean hasText);
- }
-
- // 文本视图变更监听器
- private OnTextViewChangeListener mOnTextViewChangeListener;
-
- /**
- * 构造器
- *
- * @param context 应用上下文
- */
- public NoteEditText(Context context) {
- super(context, null);
- mIndex = 0;
- }
-
- /**
- * 设置当前EditText的索引
- *
- * @param index EditText的索引值
- */
- public void setIndex(int index) {
- mIndex = index;
- }
-
- /**
- * 设置文本视图变更监听器
- *
- * @param listener 文本视图变更监听器对象
- */
- public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
- mOnTextViewChangeListener = listener;
- }
-
- /**
- * 构造器
- *
- * @param context 应用上下文
- * @param attrs XML属性集
- */
- public NoteEditText(Context context, AttributeSet attrs) {
- super(context, attrs, android.R.attr.editTextStyle);
- }
-
- /**
- * 构造器
- *
- * @param context 应用上下文
- * @param attrs XML属性集
- * @param defStyle 默认样式
- */
- public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- /**
- * 处理触摸事件
- *
- * 根据触摸位置设置文本选择光标的位置
- *
- * @param event 触摸事件对象
- * @return 如果事件被处理返回true,否则返回false
- */
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- // 获取触摸坐标
- int x = (int) event.getX();
- int y = (int) event.getY();
- // 减去内边距,得到内容区域的坐标
- x -= getTotalPaddingLeft();
- y -= getTotalPaddingTop();
- // 加上滚动偏移量
- x += getScrollX();
- y += getScrollY();
-
- Layout layout = getLayout();
- // 获取触摸点所在的行号
- int line = layout.getLineForVertical(y);
- // 获取触摸点在行中的字符偏移量
- int off = layout.getOffsetForHorizontal(line, x);
- // 设置文本选择光标位置
- Selection.setSelection(getText(), off);
- break;
- }
-
- return super.onTouchEvent(event);
- }
-
- /**
- * 处理按键按下事件
- *
- * 处理删除键和回车键的按下事件
- *
- * @param keyCode 按键代码
- * @param event 按键事件对象
- * @return 如果事件被处理返回true,否则返回false
- */
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- switch (keyCode) {
- case KeyEvent.KEYCODE_ENTER:
- // 如果设置了监听器,返回false让onKeyUp处理
- if (mOnTextViewChangeListener != null) {
- return false;
- }
- break;
- case KeyEvent.KEYCODE_DEL:
- // 记录删除前的光标位置
- mSelectionStartBeforeDelete = getSelectionStart();
- break;
- default:
- break;
- }
- return super.onKeyDown(keyCode, event);
- }
-
- /**
- * 处理按键抬起事件
- *
- * 处理删除键和回车键的抬起事件,通知监听器执行相应操作
- *
- * @param keyCode 按键代码
- * @param event 按键事件对象
- * @return 如果事件被处理返回true,否则返回false
- */
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- switch(keyCode) {
- case KeyEvent.KEYCODE_DEL:
- // 处理删除键
- if (mOnTextViewChangeListener != null) {
- // 如果光标在开头且不是第一个EditText,删除当前EditText
- if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
- mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
- return true;
- }
- } else {
- Log.d(TAG, "OnTextViewChangeListener was not seted");
- }
- break;
- case KeyEvent.KEYCODE_ENTER:
- // 处理回车键
- if (mOnTextViewChangeListener != null) {
- int selectionStart = getSelectionStart();
- // 获取光标后的文本
- String text = getText().subSequence(selectionStart, length()).toString();
- // 保留光标前的文本
- setText(getText().subSequence(0, selectionStart));
- // 通知监听器创建新的EditText
- mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
- } else {
- Log.d(TAG, "OnTextViewChangeListener was not seted");
- }
- break;
- default:
- break;
- }
- return super.onKeyUp(keyCode, event);
- }
-
- /**
- * 焦点变更时的处理
- *
- * 当失去焦点且文本为空时,通知监听器
- *
- * @param focused 是否获得焦点
- * @param direction 焦点移动方向
- * @param previouslyFocusedRect 之前获得焦点的视图矩形
- */
- @Override
- protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
- if (mOnTextViewChangeListener != null) {
- if (!focused && TextUtils.isEmpty(getText())) {
- // 失去焦点且文本为空
- mOnTextViewChangeListener.onTextChange(mIndex, false);
- } else {
- mOnTextViewChangeListener.onTextChange(mIndex, true);
- }
- }
- super.onFocusChanged(focused, direction, previouslyFocusedRect);
- }
-
- /**
- * 创建上下文菜单
- *
- * 如果选中的文本包含URL链接,添加相应的菜单项
- *
- * @param menu 上下文菜单对象
- */
- @Override
- protected void onCreateContextMenu(ContextMenu menu) {
- if (getText() instanceof Spanned) {
- int selStart = getSelectionStart();
- int selEnd = getSelectionEnd();
-
- // 获取选区的起始和结束位置
- int min = Math.min(selStart, selEnd);
- int max = Math.max(selStart, selEnd);
-
- // 获取选区内的所有URLSpan
- final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
- if (urls.length == 1) {
- int defaultResId = 0;
- // 根据URL类型确定菜单项文本
- for(String schema: sSchemaActionResMap.keySet()) {
- if(urls[0].getURL().indexOf(schema) >= 0) {
- defaultResId = sSchemaActionResMap.get(schema);
- break;
- }
- }
-
- if (defaultResId == 0) {
- defaultResId = R.string.note_link_other;
- }
-
- // 添加菜单项
- menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
- new OnMenuItemClickListener() {
- public boolean onMenuItemClick(MenuItem item) {
- // 点击菜单项时打开链接
- urls[0].onClick(NoteEditText.this);
- return true;
- }
- });
- }
- }
- super.onCreateContextMenu(menu);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NoteInfoAdapter.java b/app/src/main/java/net/micode/notes/ui/NoteInfoAdapter.java
deleted file mode 100644
index 6245021..0000000
--- a/app/src/main/java/net/micode/notes/ui/NoteInfoAdapter.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*
- * Copyright (c) 2025, Modern Notes Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.CheckBox;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-import net.micode.notes.R;
-import net.micode.notes.data.NotesRepository;
-import net.micode.notes.tool.ResourceParser;
-import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
-
-import android.util.Log;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * 便签列表适配器
- *
- * 将 List 数据绑定到 ListView
- * 支持便签显示、选中状态、图标显示
- *
- *
- * 现代化实现:使用 ViewHolder 模式优化性能
- *
- */
-public class NoteInfoAdapter extends BaseAdapter {
- private LayoutInflater inflater;
- private List notes;
- private HashSet selectedIds;
- private OnNoteButtonClickListener buttonClickListener;
- private OnNoteItemClickListener itemClickListener;
- private OnNoteItemLongClickListener itemLongClickListener;
-
- /**
- * 便签按钮点击事件回调接口
- */
- public interface OnNoteButtonClickListener {
- /**
- * 编辑按钮点击事件
- *
- * @param position 位置
- * @param noteId 便签 ID
- */
- void onEditButtonClick(int position, long noteId);
- }
-
- /**
- * 便签项点击事件回调接口
- */
- public interface OnNoteItemClickListener {
- void onNoteItemClick(int position, long noteId);
- }
-
- /**
- * 便签项长按事件回调接口
- */
- public interface OnNoteItemLongClickListener {
- void onNoteItemLongClick(int position, long noteId);
- }
-
- /**
- * 构造函数
- *
- * @param context 上下文
- */
- public NoteInfoAdapter(Context context) {
- this.inflater = LayoutInflater.from(context);
- this.notes = new ArrayList<>();
- this.selectedIds = new HashSet<>();
- }
-
- /**
- * 设置便签列表
- *
- * @param notes 便签列表
- */
- public void setNotes(List notes) {
- this.notes = notes != null ? notes : new ArrayList<>();
- notifyDataSetChanged();
- }
-
- /**
- * 设置选中的便签 ID 集合
- *
- * 用于多选模式同步,让 ViewModel 更新 selectedNoteIds 后,
- * Adapter 的 selectedIds 也能同步更新
- *
- *
- * @param selectedIds 选中的便签 ID 集合
- */
- public void setSelectedIds(HashSet selectedIds) {
- if (selectedIds != null && selectedIds != this.selectedIds) {
- this.selectedIds.clear();
- this.selectedIds.addAll(selectedIds);
- notifyDataSetChanged();
- } else if (selectedIds == null) {
- this.selectedIds.clear();
- notifyDataSetChanged();
- }
- }
-
- /**
- * 设置选中的便签 ID 列表
- *
- * 重载方法,接受 List 参数,在内部转换为 HashSet
- *
- *
- * @param selectedIds 选中的便签 ID 列表
- */
- public void setSelectedIds(List selectedIds) {
- if (selectedIds != null && !selectedIds.isEmpty()) {
- this.selectedIds.clear();
- this.selectedIds.addAll(selectedIds);
- notifyDataSetChanged();
- } else {
- this.selectedIds.clear();
- notifyDataSetChanged();
- }
- }
-
- /**
- * 获取选中的便签 ID
- *
- * @return 选中的便签 ID 集合
- */
- public HashSet getSelectedIds() {
- return selectedIds;
- }
-
- /**
- * 切换选中状态
- *
- * @param noteId 便签 ID
- */
- public void toggleSelection(long noteId) {
- if (selectedIds.contains(noteId)) {
- selectedIds.remove(noteId);
- } else {
- selectedIds.add(noteId);
- }
- notifyDataSetChanged();
- }
-
- /**
- * 设置按钮点击监听器
- *
- * @param listener 监听器
- */
- public void setOnNoteButtonClickListener(OnNoteButtonClickListener listener) {
- this.buttonClickListener = listener;
- }
-
- public void setOnNoteItemClickListener(OnNoteItemClickListener listener) {
- this.itemClickListener = listener;
- }
-
- public void setOnNoteItemLongClickListener(OnNoteItemLongClickListener listener) {
- this.itemLongClickListener = listener;
- }
-
- @Override
- public int getCount() {
- return notes.size();
- }
-
- @Override
- public Object getItem(int position) {
- return position >= 0 && position < notes.size() ? notes.get(position) : null;
- }
-
- @Override
- public long getItemId(int position) {
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(position);
- return note != null ? note.getId() : -1;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- Log.d("NoteInfoAdapter", "getView called, position: " + position + ", convertView: " + (convertView != null ? "REUSED" : "NEW"));
- ViewHolder holder;
-
- if (convertView == null) {
- convertView = inflater.inflate(R.layout.note_item, parent, false);
- holder = new ViewHolder();
- holder.title = convertView.findViewById(R.id.tv_title);
- holder.time = convertView.findViewById(R.id.tv_time);
- holder.checkBox = convertView.findViewById(android.R.id.checkbox);
- holder.pinnedIcon = convertView.findViewById(R.id.iv_pinned_icon);
- convertView.setTag(holder);
-
- convertView.setOnClickListener(v -> {
- Log.d("NoteInfoAdapter", "===== onClick TRIGGERED =====");
- ViewHolder currentHolder = (ViewHolder) v.getTag();
- if (currentHolder != null && itemClickListener != null) {
- Log.d("NoteInfoAdapter", "Calling itemClickListener");
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(currentHolder.position);
- if (note != null) {
- itemClickListener.onNoteItemClick(currentHolder.position, note.getId());
- }
- }
- Log.d("NoteInfoAdapter", "===== onClick END =====");
- });
-
- convertView.setOnLongClickListener(v -> {
- Log.d("NoteInfoAdapter", "===== setOnLongClickListener TRIGGERED =====");
- Log.d("NoteInfoAdapter", "Event triggered on view: " + v.getClass().getSimpleName());
- ViewHolder currentHolder = (ViewHolder) v.getTag();
- if (currentHolder != null && itemLongClickListener != null) {
- Log.d("NoteInfoAdapter", "Calling itemLongClickListener");
- itemLongClickListener.onNoteItemLongClick(currentHolder.position, currentHolder.position < notes.size() ? notes.get(currentHolder.position).getId() : -1);
- } else {
- Log.e("NoteInfoAdapter", "itemLongClickListener is NULL!");
- }
- Log.d("NoteInfoAdapter", "===== setOnLongClickListener END =====");
- return true;
- });
- } else {
- holder = (ViewHolder) convertView.getTag();
- }
-
- holder.position = position;
-
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(position);
- if (note != null) {
- String title = note.snippet;
- if (title == null || title.trim().isEmpty()) {
- title = "无标题";
- }
- holder.title.setText(title);
-
- holder.time.setText(formatDate(note.modifiedDate));
-
- int bgResId;
- int totalCount = getCount();
- int bgColorId = note.bgColorId;
-
- if (totalCount == 1) {
- bgResId = NoteItemBgResources.getNoteBgSingleRes(bgColorId);
- } else if (position == 0) {
- bgResId = NoteItemBgResources.getNoteBgFirstRes(bgColorId);
- } else if (position == totalCount - 1) {
- bgResId = NoteItemBgResources.getNoteBgLastRes(bgColorId);
- } else {
- bgResId = NoteItemBgResources.getNoteBgNormalRes(bgColorId);
- }
-
- convertView.setBackgroundResource(bgResId);
-
- if (selectedIds.contains(note.getId())) {
- convertView.setActivated(true);
- } else {
- convertView.setActivated(false);
- }
-
- Log.d("NoteInfoAdapter", "===== Setting checkbox visibility =====");
- Log.d("NoteInfoAdapter", "selectedIds.isEmpty(): " + selectedIds.isEmpty());
- Log.d("NoteInfoAdapter", "selectedIds.size(): " + selectedIds.size());
- Log.d("NoteInfoAdapter", "selectedIds contains note " + note.getId() + ": " + selectedIds.contains(note.getId()));
-
- if (!selectedIds.isEmpty()) {
- Log.d("NoteInfoAdapter", "Setting checkbox VISIBLE");
- holder.checkBox.setVisibility(View.VISIBLE);
- holder.checkBox.setChecked(selectedIds.contains(note.getId()));
- holder.checkBox.setClickable(false);
- } else {
- Log.d("NoteInfoAdapter", "Setting checkbox GONE");
- holder.checkBox.setVisibility(View.GONE);
- }
- Log.d("NoteInfoAdapter", "===== Checkbox visibility set =====");
-
- if (note.isPinned) {
- holder.pinnedIcon.setVisibility(View.VISIBLE);
- } else {
- holder.pinnedIcon.setVisibility(View.GONE);
- }
- }
-
- return convertView;
- }
-
- /**
- * 格式化日期
- *
- * @param timestamp 时间戳
- * @return 格式化后的日期字符串
- */
- private String formatDate(long timestamp) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
- return sdf.format(new Date(timestamp));
- }
-
- /**
- * ViewHolder 模式:优化 ListView 性能
- */
- private static class ViewHolder {
- TextView title;
- TextView time;
- CheckBox checkBox;
- ImageView pinnedIcon;
- int position;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/app/src/main/java/net/micode/notes/ui/NoteItemData.java
deleted file mode 100644
index 46638e9..0000000
--- a/app/src/main/java/net/micode/notes/ui/NoteItemData.java
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.text.TextUtils;
-
-import net.micode.notes.data.Contact;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.tool.DataUtils;
-
-/**
- * 笔记项数据类
- *
- * 用于封装笔记列表项的数据信息,从数据库游标中提取笔记的各项属性,
- * 并提供便捷的访问方法。该类支持普通笔记、文件夹和通话记录笔记等多种类型。
- *
- *
- * 主要功能:
- *
- * 从数据库游标中提取笔记数据
- * 判断笔记在列表中的位置状态(首项、末项、唯一项等)
- * 判断笔记是否跟随文件夹显示
- * 处理通话记录笔记的特殊逻辑
- *
- *
- *
- * @see NotesListItem
- * @see NotesListAdapter
- */
-public class NoteItemData {
- // 数据库查询投影,指定需要从笔记表中获取的列
- static final String [] PROJECTION = new String [] {
- NoteColumns.ID,
- NoteColumns.ALERTED_DATE,
- NoteColumns.BG_COLOR_ID,
- NoteColumns.CREATED_DATE,
- NoteColumns.HAS_ATTACHMENT,
- NoteColumns.MODIFIED_DATE,
- NoteColumns.NOTES_COUNT,
- NoteColumns.PARENT_ID,
- NoteColumns.SNIPPET,
- NoteColumns.TYPE,
- NoteColumns.WIDGET_ID,
- NoteColumns.WIDGET_TYPE,
- NoteColumns.TOP, // 新增TOP字段
- };
-
- // 列索引常量,用于从查询结果中获取对应列的数据
- private static final int ID_COLUMN = 0;
- private static final int ALERTED_DATE_COLUMN = 1;
- private static final int BG_COLOR_ID_COLUMN = 2;
- private static final int CREATED_DATE_COLUMN = 3;
- private static final int HAS_ATTACHMENT_COLUMN = 4;
- private static final int MODIFIED_DATE_COLUMN = 5;
- private static final int NOTES_COUNT_COLUMN = 6;
- private static final int PARENT_ID_COLUMN = 7;
- private static final int SNIPPET_COLUMN = 8;
- private static final int TYPE_COLUMN = 9;
- private static final int WIDGET_ID_COLUMN = 10;
- private static final int WIDGET_TYPE_COLUMN = 11;
- private static final int TOP_COLUMN = 12;
-
- // 笔记ID
- private long mId;
- // 提醒日期
- private long mAlertDate;
- // 背景颜色ID
- private int mBgColorId;
- // 创建日期
- private long mCreatedDate;
- // 是否有附件
- private boolean mHasAttachment;
- // 修改日期
- private long mModifiedDate;
- // 笔记数量(用于文件夹)
- private int mNotesCount;
- // 父文件夹ID
- private long mParentId;
- // 笔记摘要
- private String mSnippet;
- // 笔记类型
- private int mType;
- // 桌面小部件ID
- private int mWidgetId;
- // 桌面小部件类型
- private int mWidgetType;
- // 是否置顶
- private boolean mIsPinned;
- // 联系人名称(用于通话记录)
- private String mName;
- // 电话号码(用于通话记录)
- private String mPhoneNumber;
-
- // 是否为列表最后一项
- private boolean mIsLastItem;
- // 是否为列表第一项
- private boolean mIsFirstItem;
- // 是否为列表唯一一项
- private boolean mIsOnlyOneItem;
- // 是否为文件夹后跟随的单个笔记
- private boolean mIsOneNoteFollowingFolder;
- // 是否为文件夹后跟随的多个笔记之一
- private boolean mIsMultiNotesFollowingFolder;
-
- /**
- * 构造器
- *
- * 从数据库游标中提取笔记数据并初始化各项属性。
- * 对于通话记录笔记,会额外获取联系人信息。
- *
- * @param context 应用上下文,用于访问内容提供者和联系人信息
- * @param cursor 数据库游标,包含笔记数据,游标必须包含PROJECTION中指定的所有列
- */
- public NoteItemData(Context context, Cursor cursor) {
- mId = cursor.getLong(ID_COLUMN);
- mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
- mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
- mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
- mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
- mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
- mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
- mParentId = cursor.getLong(PARENT_ID_COLUMN);
- mSnippet = cursor.getString(SNIPPET_COLUMN);
- // 移除清单项的勾选标记,只保留文本内容
- mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
- NoteEditActivity.TAG_UNCHECKED, "");
- mType = cursor.getInt(TYPE_COLUMN);
- mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
- mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
- // 读取置顶状态
- if (cursor.getColumnCount() > TOP_COLUMN) {
- mIsPinned = cursor.getInt(TOP_COLUMN) > 0;
- } else {
- mIsPinned = false;
- }
-
- mPhoneNumber = "";
- // 如果是通话记录笔记,获取电话号码和联系人名称
- if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
- mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
- if (!TextUtils.isEmpty(mPhoneNumber)) {
- mName = Contact.getContact(context, mPhoneNumber);
- // 如果找不到联系人,使用电话号码作为名称
- if (mName == null) {
- mName = mPhoneNumber;
- }
- }
- }
-
- if (mName == null) {
- mName = "";
- }
- // 检查当前项在列表中的位置状态
- checkPostion(cursor);
- }
-
- /**
- * 检查当前项在列表中的位置状态
- *
- * 判断当前项是否为首项、末项、唯一项,以及是否跟随文件夹显示。
- *
- * @param cursor 数据库游标,用于判断位置状态
- */
- private void checkPostion(Cursor cursor) {
- mIsLastItem = cursor.isLast() ? true : false;
- mIsFirstItem = cursor.isFirst() ? true : false;
- mIsOnlyOneItem = (cursor.getCount() == 1);
- mIsMultiNotesFollowingFolder = false;
- mIsOneNoteFollowingFolder = false;
-
- // 如果是普通笔记且不是第一项,检查前一项是否为文件夹
- if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
- int position = cursor.getPosition();
- if (cursor.moveToPrevious()) {
- // 前一项是文件夹或系统文件夹
- if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
- || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
- // 检查文件夹后是否还有更多笔记
- if (cursor.getCount() > (position + 1)) {
- mIsMultiNotesFollowingFolder = true;
- } else {
- mIsOneNoteFollowingFolder = true;
- }
- }
- // 移动回原位置
- if (!cursor.moveToNext()) {
- throw new IllegalStateException("cursor move to previous but can't move back");
- }
- }
- }
- }
-
- /**
- * 判断是否为文件夹后跟随的单个笔记
- *
- * @return 如果是文件夹后跟随的单个笔记返回true,否则返回false
- */
- public boolean isOneFollowingFolder() {
- return mIsOneNoteFollowingFolder;
- }
-
- /**
- * 判断是否为文件夹后跟随的多个笔记之一
- *
- * @return 如果是文件夹后跟随的多个笔记之一返回true,否则返回false
- */
- public boolean isMultiFollowingFolder() {
- return mIsMultiNotesFollowingFolder;
- }
-
- /**
- * 判断是否为列表最后一项
- *
- * @return 如果是最后一项返回true,否则返回false
- */
- public boolean isLast() {
- return mIsLastItem;
- }
-
- /**
- * 获取通话记录的联系人名称
- *
- * @return 联系人名称,如果不是通话记录或找不到联系人则返回空字符串
- */
- public String getCallName() {
- return mName;
- }
-
- /**
- * 判断是否为列表第一项
- *
- * @return 如果是第一项返回true,否则返回false
- */
- public boolean isFirst() {
- return mIsFirstItem;
- }
-
- /**
- * 判断是否为列表唯一一项
- *
- * @return 如果是唯一一项返回true,否则返回false
- */
- public boolean isSingle() {
- return mIsOnlyOneItem;
- }
-
- /**
- * 获取笔记ID
- *
- * @return 笔记ID
- */
- public long getId() {
- return mId;
- }
-
- /**
- * 获取提醒日期
- *
- * @return 提醒日期(毫秒时间戳),如果没有设置提醒则返回0
- */
- public long getAlertDate() {
- return mAlertDate;
- }
-
- /**
- * 获取创建日期
- *
- * @return 创建日期(毫秒时间戳)
- */
- public long getCreatedDate() {
- return mCreatedDate;
- }
-
- /**
- * 判断笔记是否有附件
- *
- * @return 如果有附件返回true,否则返回false
- */
- public boolean hasAttachment() {
- return mHasAttachment;
- }
-
- /**
- * 获取修改日期
- *
- * @return 修改日期(毫秒时间戳)
- */
- public long getModifiedDate() {
- return mModifiedDate;
- }
-
- /**
- * 获取背景颜色ID
- *
- * @return 背景颜色ID
- */
- public int getBgColorId() {
- return mBgColorId;
- }
-
- /**
- * 获取父文件夹ID
- *
- * @return 父文件夹ID
- */
- public long getParentId() {
- return mParentId;
- }
-
- /**
- * 获取笔记数量
- *
- * @return 笔记数量(主要用于文件夹类型)
- */
- public int getNotesCount() {
- return mNotesCount;
- }
-
- /**
- * 获取文件夹ID
- *
- * @return 文件夹ID(与getParentId相同)
- */
- public long getFolderId () {
- return mParentId;
- }
-
- /**
- * 获取笔记类型
- *
- * @return 笔记类型,取值为Notes.TYPE_NOTE、Notes.TYPE_FOLDER或Notes.TYPE_SYSTEM
- */
- public int getType() {
- return mType;
- }
-
- /**
- * 获取桌面小部件类型
- *
- * @return 桌面小部件类型
- */
- public int getWidgetType() {
- return mWidgetType;
- }
-
- /**
- * 获取桌面小部件ID
- *
- * @return 桌面小部件ID
- */
- public int getWidgetId() {
- return mWidgetId;
- }
-
- /**
- * 获取笔记摘要
- *
- * @return 笔记摘要文本(已移除清单项标记)
- */
- public String getSnippet() {
- return mSnippet;
- }
-
- /**
- * 判断是否设置了提醒
- *
- * @return 如果设置了提醒返回true,否则返回false
- */
- public boolean hasAlert() {
- return (mAlertDate > 0);
- }
-
- /**
- * 判断是否置顶
- * @return 如果置顶返回true
- */
- public boolean isPinned() {
- return mIsPinned;
- }
-
- /**
- * 判断是否为通话记录笔记
- *
- * @return 如果是通话记录笔记且包含电话号码返回true,否则返回false
- */
- public boolean isCallRecord() {
- return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
- }
-
- /**
- * 从游标中获取笔记类型
- *
- * 静态方法,直接从游标中读取类型列的值,无需创建NoteItemData对象
- *
- * @param cursor 数据库游标,必须包含TYPE_COLUMN列
- * @return 笔记类型
- */
- public static int getNoteType(Cursor cursor) {
- return cursor.getInt(TYPE_COLUMN);
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NotesListActivity.java b/app/src/main/java/net/micode/notes/ui/NotesListActivity.java
deleted file mode 100644
index 067fc53..0000000
--- a/app/src/main/java/net/micode/notes/ui/NotesListActivity.java
+++ /dev/null
@@ -1,849 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.AlertDialog;
-import android.appwidget.AppWidgetManager;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Bundle;
-import android.text.InputFilter;
-import android.text.TextUtils;
-import android.util.Log;
-import androidx.appcompat.view.ActionMode;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.WindowInsets;
-import android.view.WindowInsetsController;
-import android.view.WindowManager;
-import android.widget.AdapterView;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.ListView;
-import android.widget.PopupMenu;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import androidx.appcompat.app.AppCompatActivity;
-import androidx.core.graphics.Insets;
-import androidx.core.view.ViewCompat;
-import androidx.core.view.WindowCompat;
-import androidx.core.view.WindowInsetsCompat;
-import androidx.drawerlayout.widget.DrawerLayout;
-import androidx.lifecycle.Observer;
-import androidx.lifecycle.ViewModel;
-import androidx.lifecycle.ViewModelProvider;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.NotesRepository;
-import net.micode.notes.ui.NoteInfoAdapter;
-import net.micode.notes.viewmodel.NotesListViewModel;
-
-import com.google.android.material.floatingactionbutton.FloatingActionButton;
-
-import java.util.List;
-
-/**
- * 笔记列表Activity(重构版)
- *
- * 仅负责UI展示和用户交互,业务逻辑委托给ViewModel
- * 符合MVVM架构模式
- *
- *
- * 相比原版(1305行),重构后代码量减少约70%
- *
- *
- * @see NotesListViewModel
- * @see NotesRepository
- */
-public class NotesListActivity extends AppCompatActivity
- implements NoteInfoAdapter.OnNoteButtonClickListener,
- NoteInfoAdapter.OnNoteItemClickListener,
- NoteInfoAdapter.OnNoteItemLongClickListener,
- SidebarFragment.OnSidebarItemSelectedListener {
- private static final String TAG = "NotesListActivity";
- private static final int REQUEST_CODE_OPEN_NODE = 102;
- private static final int REQUEST_CODE_NEW_NODE = 103;
-
- private NotesListViewModel viewModel;
- private ListView notesListView;
- private androidx.appcompat.widget.Toolbar toolbar;
- private NoteInfoAdapter adapter;
- private DrawerLayout drawerLayout;
- private FloatingActionButton fabNewNote;
- private LinearLayout breadcrumbContainer;
- private LinearLayout breadcrumbItems;
-
- // 多选模式状态
- private boolean isMultiSelectMode = false;
-
- /**
- * 活动创建时的初始化方法
- *
- * 设置布局,初始化ViewModel,设置UI监听器
- *
- *
- * @param savedInstanceState 保存的实例状态
- */
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- // 启用边缘到边缘显示
- WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
-
- setContentView(R.layout.note_list);
-
- // 处理窗口insets(状态栏和导航栏)
- View mainView = findViewById(android.R.id.content);
- ViewCompat.setOnApplyWindowInsetsListener(mainView, (v, windowInsets) -> {
- Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
- // 设置内容区域的padding以避免被状态栏遮挡
- v.setPadding(insets.left, insets.top, insets.right, insets.bottom);
- return WindowInsetsCompat.CONSUMED;
- });
-
- initViewModel();
- initViews();
- observeViewModel();
- }
-
- /**
- * 活动启动时的回调方法
- *
- * 加载笔记列表
- *
- */
- @Override
- protected void onStart() {
- super.onStart();
- viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
- }
-
- /**
- * 初始化ViewModel
- */
- private void initViewModel() {
- NotesRepository repository = new NotesRepository(getContentResolver());
- viewModel = new ViewModelProvider(this,
- new ViewModelProvider.Factory() {
- @Override
- public T create(Class modelClass) {
- if (modelClass.isAssignableFrom(NotesListViewModel.class)) {
- return (T) new NotesListViewModel(repository);
- }
- throw new IllegalArgumentException("Unknown ViewModel class");
- }
- }).get(NotesListViewModel.class);
- Log.d(TAG, "ViewModel initialized");
- }
-
- /**
- * 初始化视图
- */
- private void initViews() {
- notesListView = findViewById(R.id.notes_list);
- toolbar = findViewById(R.id.toolbar);
- drawerLayout = findViewById(R.id.drawer_layout);
-
- // 初始化面包屑导航
- breadcrumbContainer = findViewById(R.id.breadcrumb_container);
- breadcrumbItems = findViewById(R.id.breadcrumb_items);
-
- // 设置适配器
- adapter = new NoteInfoAdapter(this);
- notesListView.setAdapter(adapter);
- adapter.setOnNoteButtonClickListener(this);
- adapter.setOnNoteItemClickListener(this);
- adapter.setOnNoteItemLongClickListener(this);
-
- // 设置点击监听
- notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> parent, View view, int position, long id) {
- Object item = parent.getItemAtPosition(position);
- if (item instanceof NotesRepository.NoteInfo) {
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) item;
- handleItemClick(note, position);
- }
- }
- });
-
- // 初始化 Toolbar
- toolbar = findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- if (getSupportActionBar() != null) {
- getSupportActionBar().setTitle(R.string.app_name);
- }
-
- // 初始化为普通模式
- updateToolbarForNormalMode();
-
- // 设置 Toolbar 的汉堡菜单按钮点击监听器(打开侧栏)
- toolbar.setNavigationOnClickListener(v -> {
- if (drawerLayout != null) {
- drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
- }
- });
-
- // Set FAB click event
- fabNewNote = findViewById(R.id.btn_new_note);
- if (fabNewNote != null) {
- fabNewNote.setOnClickListener(v -> {
- Intent intent = new Intent(NotesListActivity.this, NoteEditActivity.class);
- intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
- intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, viewModel.getCurrentFolderId());
- startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
- });
- }
- }
-
- /**
- * 处理列表项点击
- *
- * 如果是便签,打开编辑器;如果是文件夹,进入该文件夹
- *
- *
- * @param note 项
- * @param position 位置
- */
- private void handleItemClick(NotesRepository.NoteInfo note, int position) {
- if (isMultiSelectMode) {
- // 多选模式:切换选中状态
- boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
- viewModel.toggleNoteSelection(note.getId(), !isSelected);
- if (adapter != null) {
- adapter.setSelectedIds(viewModel.getSelectedNoteIds());
- }
- updateToolbarForMultiSelectMode();
- } else {
- // 普通模式
- if (note.type == Notes.TYPE_FOLDER) {
- // 文件夹:进入该文件夹
- viewModel.enterFolder(note.getId());
- } else {
- // 便签:打开编辑器
- openNoteEditor(note);
- }
- }
- }
-
- /**
- * 观察ViewModel的LiveData
- */
- private void observeViewModel() {
- // 观察笔记列表
- viewModel.getNotesLiveData().observe(this, new Observer>() {
- @Override
- public void onChanged(List notes) {
- updateAdapter(notes);
- }
- });
-
- // 观察加载状态
- viewModel.getIsLoading().observe(this, new Observer() {
- @Override
- public void onChanged(Boolean isLoading) {
- updateLoadingState(isLoading);
- }
- });
-
- // 观察错误消息
- viewModel.getErrorMessage().observe(this, new Observer() {
- @Override
- public void onChanged(String message) {
- if (message != null && !message.isEmpty()) {
- showError(message);
- }
- }
- });
-
- // 观察文件夹路径(用于面包屑导航)
- viewModel.getFolderPathLiveData().observe(this, new Observer>() {
- @Override
- public void onChanged(List path) {
- updateBreadcrumb(path);
- }
- });
-
- // 观察侧栏刷新通知
- viewModel.getSidebarRefreshNeeded().observe(this, new Observer() {
- @Override
- public void onChanged(Boolean refreshNeeded) {
- if (refreshNeeded != null && refreshNeeded) {
- // 通知侧栏刷新
- SidebarFragment sidebarFragment = (SidebarFragment) getSupportFragmentManager()
- .findFragmentById(R.id.sidebar_fragment);
- if (sidebarFragment != null) {
- sidebarFragment.refreshFolderTree();
- }
- // 重置刷新状态
- viewModel.getSidebarRefreshNeeded().setValue(false);
- }
- }
- });
- }
-
- /**
- * 更新面包屑导航
- *
- * @param path 文件夹路径
- */
- private void updateBreadcrumb(List path) {
- if (breadcrumbItems == null || path == null) {
- return;
- }
-
- breadcrumbItems.removeAllViews();
-
- for (int i = 0; i < path.size(); i++) {
- NotesRepository.NoteInfo folder = path.get(i);
-
- // 如果不是第一个,添加分隔符 " > "
- if (i > 0) {
- TextView separator = new TextView(this);
- separator.setText(" > ");
- separator.setTextSize(14);
- separator.setTextColor(android.R.color.darker_gray);
- breadcrumbItems.addView(separator);
- }
-
- // 创建面包屑项
- TextView breadcrumbItem = (TextView) getLayoutInflater()
- .inflate(R.layout.breadcrumb_item, breadcrumbItems, false);
- breadcrumbItem.setText(folder.title);
-
- // 如果是当前文件夹(最后一个),高亮显示且不可点击
- if (i == path.size() - 1) {
- breadcrumbItem.setTextColor(getColor(R.color.primary_color));
- breadcrumbItem.setEnabled(false);
- } else {
- // 其他层级可以点击跳转
- final long targetFolderId = folder.id;
- breadcrumbItem.setOnClickListener(v -> viewModel.enterFolder(targetFolderId));
- }
-
- breadcrumbItems.addView(breadcrumbItem);
- }
- }
-
- /**
- * 更新适配器数据
- */
- private void updateAdapter(List notes) {
- adapter.setNotes(notes);
- Log.d(TAG, "Adapter updated with " + notes.size() + " notes");
- }
-
- /**
- * 更新加载状态
- */
- private void updateLoadingState(boolean isLoading) {
- // TODO: 显示/隐藏进度条
- }
-
- /**
- * 显示错误消息
- */
- private void showError(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 打开笔记编辑器
- */
- private void openNoteEditor(NotesRepository.NoteInfo note) {
- Intent intent = new Intent(this, NoteEditActivity.class);
- intent.setAction(Intent.ACTION_VIEW);
- intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, note.getParentId());
- intent.putExtra(Intent.EXTRA_UID, note.getId());
- startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
- }
-
- /**
- * 编辑按钮点击事件处理
- *
- * @param position 列表位置
- * @param noteId 便签 ID
- */
- @Override
- public void onEditButtonClick(int position, long noteId) {
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
- if (note != null) {
- openNoteEditor(note);
- } else {
- Log.e(TAG, "Edit button clicked but note is null at position: " + position);
- }
- }
-
- @Override
- public void onNoteItemClick(int position, long noteId) {
- Log.d(TAG, "===== onNoteItemClick CALLED =====");
- Log.d(TAG, "position: " + position + ", noteId: " + noteId);
-
- if (isMultiSelectMode) {
- Log.d(TAG, "Multi-select mode active, toggling selection");
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
- if (note != null) {
- boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
- viewModel.toggleNoteSelection(note.getId(), !isSelected);
-
- if (adapter != null) {
- adapter.setSelectedIds(viewModel.getSelectedNoteIds());
- }
- // 更新toolbar标题
- updateToolbarForMultiSelectMode();
- }
- Log.d(TAG, "===== onNoteItemClick END (multi-select mode) =====");
- } else {
- Log.d(TAG, "Normal mode, checking item type");
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
- if (note != null) {
- if (note.type == Notes.TYPE_FOLDER) {
- // 文件夹:进入该文件夹
- Log.d(TAG, "Folder clicked, entering folder: " + note.getId());
- viewModel.enterFolder(note.getId());
- } else {
- // 便签:打开编辑器
- Log.d(TAG, "Note clicked, opening editor");
- openNoteEditor(note);
- }
- }
- Log.d(TAG, "===== onNoteItemClick END =====");
- }
- }
-
- @Override
- public void onNoteItemLongClick(int position, long noteId) {
- Log.d(TAG, "===== onNoteItemLongClick CALLED =====");
- Log.d(TAG, "position: " + position + ", noteId: " + noteId);
-
- if (!isMultiSelectMode) {
- Log.d(TAG, "Entering multi-select mode");
- enterMultiSelectMode();
- viewModel.toggleNoteSelection(noteId, true);
-
- if (adapter != null) {
- adapter.setSelectedIds(viewModel.getSelectedNoteIds());
- }
-
- updateSelectionState(position, true);
-
- Log.d(TAG, "===== onNoteItemLongClick END =====");
- } else {
- Log.d(TAG, "Multi-select mode already active, ignoring long click");
- }
- }
-
- /**
- * 进入多选模式
- */
- private void enterMultiSelectMode() {
- isMultiSelectMode = true;
- // 隐藏FAB按钮
- if (fabNewNote != null) {
- fabNewNote.setVisibility(View.GONE);
- }
- // 更新toolbar为多选模式
- updateToolbarForMultiSelectMode();
- }
-
- /**
- * 退出多选模式
- */
- private void exitMultiSelectMode() {
- isMultiSelectMode = false;
- // 显示FAB按钮
- if (fabNewNote != null) {
- fabNewNote.setVisibility(View.VISIBLE);
- }
- // 清除选中状态
- viewModel.clearSelection();
- if (adapter != null) {
- adapter.setSelectedIds(new java.util.HashSet<>());
- adapter.notifyDataSetChanged();
- }
- // 更新toolbar为普通模式
- updateToolbarForNormalMode();
- }
-
- /**
- * 更新Toolbar为多选模式
- */
- private void updateToolbarForMultiSelectMode() {
- if (toolbar == null) return;
-
- // 设置标题为选中数量
- int selectedCount = viewModel.getSelectedCount();
- String title = getString(R.string.menu_select_title, selectedCount);
- toolbar.setTitle(title);
-
- // 设置导航图标为返回(取消多选)
- toolbar.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material);
- toolbar.setNavigationOnClickListener(v -> exitMultiSelectMode());
-
- // 移除普通模式的菜单(如果有)
- toolbar.getMenu().clear();
-
- // 直接在toolbar上添加操作按钮(不在三点菜单中)
- Menu menu = toolbar.getMenu();
-
- // 删除按钮
- MenuItem deleteItem = menu.add(Menu.NONE, R.id.multi_select_delete, 1, getString(R.string.menu_delete));
- deleteItem.setIcon(android.R.drawable.ic_menu_delete);
- deleteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
-
- // 移动按钮
- MenuItem moveItem = menu.add(Menu.NONE, R.id.multi_select_move, 2, getString(R.string.menu_move));
- moveItem.setIcon(android.R.drawable.ic_menu_sort_by_size);
- moveItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
-
- // 置顶按钮
- boolean allPinned = viewModel.isAllSelectedPinned();
- MenuItem pinItem = menu.add(Menu.NONE, R.id.multi_select_pin, 3, allPinned ? getString(R.string.menu_unpin) : getString(R.string.menu_pin));
- // 使用上传图标代替置顶图标,或者如果有合适的资源可以使用
- pinItem.setIcon(android.R.drawable.ic_menu_upload);
- pinItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
- }
-
- /**
- * 更新Toolbar为普通模式
- */
- private void updateToolbarForNormalMode() {
- if (toolbar == null) return;
-
- // 设置标题为应用名称
- toolbar.setTitle(R.string.app_name);
-
- // 设置导航图标为汉堡菜单
- toolbar.setNavigationIcon(android.R.drawable.ic_menu_sort_by_size);
- toolbar.setNavigationOnClickListener(v -> {
- if (drawerLayout != null) {
- drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
- }
- });
-
- // 清除多选模式菜单
- toolbar.getMenu().clear();
-
- // 添加普通模式菜单(如果需要)
- // getMenuInflater().inflate(R.menu.note_list_options, menu);
- }
-
-
-
- /**
- * 显示删除确认对话框
- */
- private void showDeleteDialog() {
- int selectedCount = viewModel.getSelectedCount();
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(getString(R.string.alert_title_delete));
- builder.setIcon(android.R.drawable.ic_dialog_alert);
- builder.setMessage(getString(R.string.alert_message_delete_notes, selectedCount));
- builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- viewModel.deleteSelectedNotes();
- }
- });
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- }
-
- /**
- * 显示移动菜单
- */
- private void showMoveMenu() {
- // TODO: 实现文件夹选择逻辑
- Toast.makeText(this, "移动功能开发中", Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 活动结果回调方法
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
-
- if (resultCode == RESULT_OK) {
- if (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE) {
- viewModel.refreshNotes();
- }
- }
- }
-
- /**
- * 创建选项菜单
- */
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.note_list, menu);
- return true;
- }
-
- /**
- * 选项菜单项点击事件
- */
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- int itemId = item.getItemId();
-
- switch (itemId) {
- case R.id.menu_search:
- // TODO: 打开搜索对话框
- Toast.makeText(this, "搜索功能开发中", Toast.LENGTH_SHORT).show();
- return true;
- case R.id.menu_new_folder:
- // 创建新文件夹
- showCreateFolderDialog();
- return true;
- case R.id.menu_export_text:
- // TODO: 导出笔记
- Toast.makeText(this, "导出功能开发中", Toast.LENGTH_SHORT).show();
- return true;
- case R.id.menu_sync:
- // TODO: 同步功能
- Toast.makeText(this, "同步功能暂不可用", Toast.LENGTH_SHORT).show();
- return true;
- case R.id.menu_setting:
- // TODO: 设置功能
- Toast.makeText(this, "设置功能开发中", Toast.LENGTH_SHORT).show();
- return true;
- // 多选模式菜单项
- case R.id.multi_select_delete:
- showDeleteDialog();
- return true;
- case R.id.multi_select_move:
- showMoveMenu();
- return true;
- case R.id.multi_select_pin:
- boolean wasPinned = viewModel.isAllSelectedPinned();
- viewModel.toggleSelectedNotesPin();
- String toastMsg = wasPinned ? getString(R.string.menu_unpin) + "成功" : getString(R.string.menu_pin) + "成功";
- Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
- return true;
- default:
- return super.onOptionsItemSelected(item);
- }
- }
-
- /**
- * 上下文菜单创建
- */
- @Override
- public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
- getMenuInflater().inflate(R.menu.sub_folder, menu);
- }
-
- /**
- * 上下文菜单项点击
- */
- @Override
- public boolean onContextItemSelected(MenuItem item) {
- // TODO: 处理文件夹上下文菜单
- return super.onContextItemSelected(item);
- }
-
- /**
- * 活动销毁时的清理
- */
- @Override
- protected void onDestroy() {
- super.onDestroy();
- // 清理资源
- }
-
- private void updateSelectionState(int position, boolean selected) {
- Log.d("NotesListActivity", "===== updateSelectionState called =====");
- Log.d("NotesListActivity", "position: " + position + ", selected: " + selected);
- NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
- if (note != null) {
- Log.d("NotesListActivity", "note ID: " + note.getId());
- Log.d("NotesListActivity", "Current selectedIds size before update: " + adapter.getSelectedIds().size());
- Log.d("NotesListActivity", "Note already in selectedIds: " + adapter.getSelectedIds().contains(note.getId()));
- if (adapter.getSelectedIds().contains(note.getId()) != selected) {
- if (selected) {
- Log.d("NotesListActivity", "Adding note ID to selectedIds");
- adapter.getSelectedIds().add(note.getId());
- } else {
- Log.d("NotesListActivity", "Removing note ID from selectedIds");
- adapter.getSelectedIds().remove(note.getId());
- }
- Log.d("NotesListActivity", "SelectedIds size after update: " + adapter.getSelectedIds().size());
- adapter.notifyDataSetChanged();
- Log.d("NotesListActivity", "notifyDataSetChanged() called");
- } else {
- Log.d("NotesListActivity", "Note selection state unchanged, skipping update");
- }
- } else {
- Log.e("NotesListActivity", "note is NULL at position: " + position);
- }
- Log.d("NotesListActivity", "===== updateSelectionState END =====");
- }
-
- // ==================== SidebarFragment.OnSidebarItemSelectedListener 实现 ====================
-
- @Override
- public void onFolderSelected(long folderId) {
- // 跳转到指定文件夹
- viewModel.enterFolder(folderId);
- // 关闭侧栏
- if (drawerLayout != null) {
- drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
- }
- }
-
- @Override
- public void onTrashSelected() {
- // TODO: 实现跳转到回收站
- Log.d(TAG, "Trash selected");
- // 关闭侧栏
- if (drawerLayout != null) {
- drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
- }
- }
-
- @Override
- public void onSyncSelected() {
- // TODO: 实现同步功能
- Log.d(TAG, "Sync selected");
- Toast.makeText(this, "同步功能待实现", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onLoginSelected() {
- // TODO: 实现登录功能
- Log.d(TAG, "Login selected");
- Toast.makeText(this, "登录功能待实现", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onExportSelected() {
- // TODO: 实现导出功能
- Log.d(TAG, "Export selected");
- Toast.makeText(this, "导出功能待实现", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onSettingsSelected() {
- // TODO: 实现设置功能
- Log.d(TAG, "Settings selected");
- Toast.makeText(this, "设置功能待实现", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onCreateFolder() {
- // 显示创建文件夹对话框
- showCreateFolderDialog();
- }
-
- /**
- * 显示创建文件夹对话框
- */
- private void showCreateFolderDialog() {
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(R.string.dialog_create_folder_title);
-
- final EditText input = new EditText(this);
- input.setHint(R.string.dialog_create_folder_hint);
- input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
-
- builder.setView(input);
-
- builder.setPositiveButton(R.string.menu_create_folder, (dialog, which) -> {
- String folderName = input.getText().toString().trim();
- if (TextUtils.isEmpty(folderName)) {
- Toast.makeText(this, R.string.error_folder_name_empty, Toast.LENGTH_SHORT).show();
- return;
- }
- if (folderName.length() > 50) {
- Toast.makeText(this, R.string.error_folder_name_too_long, Toast.LENGTH_SHORT).show();
- return;
- }
-
- // 创建文件夹
- NotesRepository repository = new NotesRepository(getContentResolver());
- long parentId = viewModel.getCurrentFolderId();
- if (parentId == 0) {
- parentId = Notes.ID_ROOT_FOLDER;
- }
- repository.createFolder(parentId, folderName,
- new NotesRepository.Callback() {
- @Override
- public void onSuccess(Long folderId) {
- runOnUiThread(() -> {
- Toast.makeText(NotesListActivity.this, R.string.create_folder_success, Toast.LENGTH_SHORT).show();
- // 刷新笔记列表
- viewModel.loadNotes(viewModel.getCurrentFolderId());
- });
- }
-
- @Override
- public void onError(Exception error) {
- runOnUiThread(() -> {
- Toast.makeText(NotesListActivity.this, "创建文件夹失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
- });
- }
- });
- });
-
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- }
-
- @Override
- public void onCloseSidebar() {
- // 关闭侧栏
- if (drawerLayout != null) {
- drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
- }
- }
-
- /**
- * 返回键按下事件处理
- *
- * 多选模式:退出多选模式
- * 子文件夹:返回上一级文件夹
- * 根文件夹:最小化应用
- *
- */
- @Override
- public void onBackPressed() {
- if (isMultiSelectMode) {
- // 多选模式:退出多选模式
- exitMultiSelectMode();
- } else if (drawerLayout != null && drawerLayout.isDrawerOpen(findViewById(R.id.sidebar_fragment))) {
- // 侧栏打开:关闭侧栏
- drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
- } else if (viewModel.getCurrentFolderId() != Notes.ID_ROOT_FOLDER &&
- viewModel.getCurrentFolderId() != Notes.ID_CALL_RECORD_FOLDER) {
- // 子文件夹:返回上一级
- if (!viewModel.navigateUp()) {
- // 如果没有导航历史,返回根文件夹
- viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
- }
- } else {
- // 根文件夹:最小化应用
- moveTaskToBack(true);
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java
deleted file mode 100644
index 6085bf0..0000000
--- a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.util.Log;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CursorAdapter;
-
-import net.micode.notes.data.Notes;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-
-
-/**
- * 笔记列表适配器
- *
- * 这个类继承自CursorAdapter,用于将数据库中的笔记数据绑定到ListView中显示。
- * 它支持笔记的选择模式、批量操作以及与桌面小部件的关联。
- *
- * 主要功能:
- * 1. 将笔记数据绑定到NotesListItem视图
- * 2. 支持多选模式和批量选择操作
- * 3. 获取选中的笔记ID和关联的桌面小部件信息
- * 4. 统计笔记数量和选中数量
- *
- * @see NotesListItem
- * @see NoteItemData
- */
-public class NotesListAdapter extends CursorAdapter {
- private static final String TAG = "NotesListAdapter";
- // 应用上下文
- private Context mContext;
- // 记录选中状态的Map,key为位置,value为是否选中
- private HashMap mSelectedIndex;
- // 笔记总数
- private int mNotesCount;
- // 是否处于选择模式
- private boolean mChoiceMode;
-
- /**
- * 桌面小部件属性类
- *
- * 用于存储桌面小部件的ID和类型信息
- */
- public static class AppWidgetAttribute {
- // 桌面小部件ID
- public int widgetId;
- // 桌面小部件类型
- public int widgetType;
- };
-
- /**
- * 构造器
- *
- * 初始化笔记列表适配器,创建选中状态Map和计数器
- *
- * @param context 应用上下文,不能为 null
- */
- public NotesListAdapter(Context context) {
- super(context, null);
- mSelectedIndex = new HashMap();
- mContext = context;
- mNotesCount = 0;
- }
-
- /**
- * 创建新的列表项视图
- *
- * @param context 应用上下文
- * @param cursor 数据库游标,包含当前项的数据
- * @param parent 父视图
- * @return 新创建的NotesListItem视图对象
- */
- @Override
- public View newView(Context context, Cursor cursor, ViewGroup parent) {
- return new NotesListItem(context);
- }
-
- /**
- * 绑定数据到视图
- *
- * 将数据库游标中的数据绑定到已存在的视图上
- *
- * @param view 需要绑定数据的视图
- * @param context 应用上下文
- * @param cursor 数据库游标,包含当前项的数据
- */
- @Override
- public void bindView(View view, Context context, Cursor cursor) {
- if (view instanceof NotesListItem) {
- NoteItemData itemData = new NoteItemData(context, cursor);
- ((NotesListItem) view).bind(context, itemData, mChoiceMode,
- isSelectedItem(cursor.getPosition()));
- }
- }
-
- /**
- * 设置指定位置的选中状态
- *
- * @param position 列表项位置,从0开始
- * @param checked 是否选中
- */
- public void setCheckedItem(final int position, final boolean checked) {
- mSelectedIndex.put(position, checked);
- notifyDataSetChanged();
- }
-
- /**
- * 判断是否处于选择模式
- *
- * @return 如果处于选择模式返回true,否则返回false
- */
- public boolean isInChoiceMode() {
- return mChoiceMode;
- }
-
- /**
- * 设置选择模式
- *
- * @param mode true表示进入选择模式,false表示退出选择模式
- */
- public void setChoiceMode(boolean mode) {
- mSelectedIndex.clear();
- mChoiceMode = mode;
- }
-
- /**
- * 全选或取消全选所有笔记
- *
- * @param checked true表示全选,false表示取消全选
- */
- public void selectAll(boolean checked) {
- Cursor cursor = getCursor();
- for (int i = 0; i < getCount(); i++) {
- if (cursor.moveToPosition(i)) {
- if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
- setCheckedItem(i, checked);
- }
- }
- }
- }
-
- /**
- * 获取所有选中项的笔记ID集合
- *
- * @return 包含所有选中笔记ID的HashSet集合,如果没有选中项则返回空集合
- */
- public HashSet getSelectedItemIds() {
- HashSet itemSet = new HashSet();
- for (Integer position : mSelectedIndex.keySet()) {
- if (mSelectedIndex.get(position) == true) {
- Long id = getItemId(position);
- if (id == Notes.ID_ROOT_FOLDER) {
- Log.d(TAG, "Wrong item id, should not happen");
- } else {
- itemSet.add(id);
- }
- }
- }
-
- return itemSet;
- }
-
- /**
- * 获取所有选中项关联的桌面小部件集合
- *
- * @return 包含所有选中笔记关联的桌面小部件属性的HashSet集合,如果游标无效则返回null
- */
- public HashSet getSelectedWidget() {
- HashSet itemSet = new HashSet();
- for (Integer position : mSelectedIndex.keySet()) {
- if (mSelectedIndex.get(position) == true) {
- Cursor c = (Cursor) getItem(position);
- if (c != null) {
- AppWidgetAttribute widget = new AppWidgetAttribute();
- NoteItemData item = new NoteItemData(mContext, c);
- widget.widgetId = item.getWidgetId();
- widget.widgetType = item.getWidgetType();
- itemSet.add(widget);
- /**
- * Don't close cursor here, only the adapter could close it
- */
- } else {
- Log.e(TAG, "Invalid cursor");
- return null;
- }
- }
- }
- return itemSet;
- }
-
- /**
- * 获取选中项的数量
- *
- * @return 选中项的数量,如果没有选中项则返回0
- */
- public int getSelectedCount() {
- Collection values = mSelectedIndex.values();
- if (null == values) {
- return 0;
- }
- Iterator iter = values.iterator();
- int count = 0;
- while (iter.hasNext()) {
- if (true == iter.next()) {
- count++;
- }
- }
- return count;
- }
-
- /**
- * 判断是否已全选所有笔记
- *
- * @return 如果所有笔记都被选中且至少有一个笔记则返回true,否则返回false
- */
- public boolean isAllSelected() {
- int checkedCount = getSelectedCount();
- return (checkedCount != 0 && checkedCount == mNotesCount);
- }
-
- /**
- * 判断指定位置的项是否被选中
- *
- * @param position 列表项位置,从0开始
- * @return 如果该项被选中返回true,否则返回false
- */
- public boolean isSelectedItem(final int position) {
- if (null == mSelectedIndex.get(position)) {
- return false;
- }
- return mSelectedIndex.get(position);
- }
-
- /**
- * 当内容发生变化时调用
- *
- * 重新计算笔记数量
- */
- @Override
- protected void onContentChanged() {
- super.onContentChanged();
- calcNotesCount();
- }
-
- /**
- * 更换游标
- *
- * @param cursor 新的数据库游标
- */
- @Override
- public void changeCursor(Cursor cursor) {
- super.changeCursor(cursor);
- calcNotesCount();
- }
-
- private void calcNotesCount() {
- mNotesCount = 0;
- for (int i = 0; i < getCount(); i++) {
- Cursor c = (Cursor) getItem(i);
- if (c != null) {
- if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
- mNotesCount++;
- }
- } else {
- Log.e(TAG, "Invalid cursor");
- return;
- }
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NotesListItem.java b/app/src/main/java/net/micode/notes/ui/NotesListItem.java
deleted file mode 100644
index ad89d41..0000000
--- a/app/src/main/java/net/micode/notes/ui/NotesListItem.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.text.format.DateUtils;
-import android.view.View;
-import android.widget.CheckBox;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.tool.DataUtils;
-import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
-
-
-/**
- * 笔记列表项视图
- *
- * 自定义的 LinearLayout,表示笔记列表中的单个笔记项。
- * 该视图显示笔记信息,包括标题、时间、通话名称(针对通话记录)和提醒图标。
- * 支持在多选模式下显示复选框。
- *
- */
-public class NotesListItem extends LinearLayout {
- private ImageView mAlert;
- private TextView mTitle;
- private TextView mTime;
- private TextView mCallName;
- private NoteItemData mItemData;
- private CheckBox mCheckBox;
-
- /**
- * 构造函数
- * @param context 用于加载布局的上下文对象
- */
- public NotesListItem(Context context) {
- super(context);
- inflate(context, R.layout.note_item, this);
- mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
- mTitle = (TextView) findViewById(R.id.tv_title);
- mTime = (TextView) findViewById(R.id.tv_time);
- mCallName = (TextView) findViewById(R.id.tv_name);
- mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
- }
-
- /**
- * 绑定笔记数据到视图项
- * @param context 用于访问资源的上下文对象
- * @param data 包含要显示的笔记信息的 NoteItemData 对象
- * @param choiceMode 列表是否处于多选模式(显示复选框)
- * @param checked 该项是否被选中(仅在多选模式下有意义)
- */
- public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
- if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
- mCheckBox.setVisibility(View.VISIBLE);
- mCheckBox.setChecked(checked);
- } else {
- mCheckBox.setVisibility(View.GONE);
- }
-
- mItemData = data;
- if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
- mCallName.setVisibility(View.GONE);
- mAlert.setVisibility(View.VISIBLE);
- mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
- mTitle.setText(context.getString(R.string.call_record_folder_name)
- + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
- mAlert.setImageResource(R.drawable.call_record);
- } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
- mCallName.setVisibility(View.VISIBLE);
- mCallName.setText(data.getCallName());
- mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
- mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
- if (data.hasAlert()) {
- mAlert.setImageResource(R.drawable.clock);
- mAlert.setVisibility(View.VISIBLE);
- } else {
- mAlert.setVisibility(View.GONE);
- }
- } else {
- mCallName.setVisibility(View.GONE);
- mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
-
- if (data.getType() == Notes.TYPE_FOLDER) {
- mTitle.setText(data.getSnippet()
- + context.getString(R.string.format_folder_files_count,
- data.getNotesCount()));
- mAlert.setVisibility(View.GONE);
- } else {
- mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
- if (data.hasAlert()) {
- mAlert.setImageResource(R.drawable.clock);
- mAlert.setVisibility(View.VISIBLE);
- } else {
- mAlert.setVisibility(View.GONE);
- }
- }
- }
- mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
-
- setBackground(data);
- }
-
- /**
- * 根据笔记项的位置和类型设置合适的背景资源
- * @param data 包含笔记背景颜色和位置信息的 NoteItemData 对象
- */
- private void setBackground(NoteItemData data) {
- int id = data.getBgColorId();
- if (data.getType() == Notes.TYPE_NOTE) {
- if (data.isSingle() || data.isOneFollowingFolder()) {
- setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
- } else if (data.isLast()) {
- setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
- } else if (data.isFirst() || data.isMultiFollowingFolder()) {
- setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
- } else {
- setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
- }
- } else {
- setBackgroundResource(NoteItemBgResources.getFolderBgRes());
- }
- }
-
- /**
- * 获取绑定到该视图项的笔记数据
- * @return 包含该笔记信息的 NoteItemData 对象
- */
- public NoteItemData getItemData() {
- return mItemData;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java
deleted file mode 100644
index fe02819..0000000
--- a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java
+++ /dev/null
@@ -1,587 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.app.ActionBar;
-import android.app.AlertDialog;
-import android.content.BroadcastReceiver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.Preference;
-import android.preference.Preference.OnPreferenceClickListener;
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceCategory;
-import android.text.TextUtils;
-import android.text.format.DateFormat;
-import android.view.LayoutInflater;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.remote.GTaskSyncService;
-
-import android.os.Build; // 用于版本检查
-import android.content.Context; // 用于 RECEIVER_NOT_EXPORTED 常量
-
-
-/**
- * 设置界面Activity
- *
- * 该Activity用于管理应用的各种设置,主要包括:
- *
- * Google Tasks同步账户的设置和管理
- * 同步状态显示和手动同步控制
- * 背景颜色随机显示设置
- *
- *
- *
- * 该类继承自PreferenceActivity,使用SharedPreferences来持久化设置数据。
- * 通过GTaskReceiver接收同步服务的广播,实时更新同步状态。
- *
- */
-public class NotesPreferenceActivity extends PreferenceActivity {
- /**
- * SharedPreferences文件名
- */
- public static final String PREFERENCE_NAME = "notes_preferences";
-
- /**
- * 同步账户名称的SharedPreferences键
- */
- public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
-
- /**
- * 最后同步时间的SharedPreferences键
- */
- public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
-
- /**
- * 背景颜色随机显示设置的SharedPreferences键
- */
- public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
-
- /**
- * 同步账户分类的Preference键
- */
- private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
-
- /**
- * 账户授权过滤器键,用于添加账户Intent
- */
- private static final String AUTHORITIES_FILTER_KEY = "authorities";
-
- /**
- * 同步账户分类的PreferenceCategory
- */
- private PreferenceCategory mAccountCategory;
-
- /**
- * 同步服务广播接收器
- */
- private GTaskReceiver mReceiver;
-
- /**
- * 原始账户数组,用于检测新增账户
- */
- private Account[] mOriAccounts;
-
- /**
- * 是否添加了新账户的标志
- */
- private boolean mHasAddedAccount;
-
- /**
- * 创建Activity
- *
- * 初始化设置界面,包括:
- *
- * 启用ActionBar的返回导航
- * 加载preferences.xml配置文件
- * 初始化账户分类和广播接收器
- * 添加设置界面头部视图
- *
- *
- * @param icicle 保存的实例状态
- */
- @Override
- protected void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- /* using the app icon for navigation */
- getActionBar().setDisplayHomeAsUpEnabled(true);
-
- addPreferencesFromResource(R.xml.preferences);
- mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
- mReceiver = new GTaskReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
- //registerReceiver(mReceiver, filter);
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
- // Android 13 (API 33) 及以上版本需要指定导出标志
- registerReceiver(mReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
- } else {
- // Android 12 及以下版本使用旧方法
- registerReceiver(mReceiver, filter);
- }
- mOriAccounts = null;
- View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
- getListView().addHeaderView(header, null, true);
- }
-
- /**
- * Activity恢复时调用
- *
- * 检查是否有新添加的Google账户,如果有则自动设置为同步账户。
- * 然后刷新UI显示。
- *
- */
- @Override
- protected void onResume() {
- super.onResume();
-
- // need to set sync account automatically if user has added a new
- // account
- if (mHasAddedAccount) {
- Account[] accounts = getGoogleAccounts();
- if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
- for (Account accountNew : accounts) {
- boolean found = false;
- for (Account accountOld : mOriAccounts) {
- if (TextUtils.equals(accountOld.name, accountNew.name)) {
- found = true;
- break;
- }
- }
- if (!found) {
- setSyncAccount(accountNew.name);
- break;
- }
- }
- }
- }
-
- refreshUI();
- }
-
- /**
- * Activity销毁时调用
- *
- * 注销同步服务广播接收器,防止内存泄漏。
- *
- */
- @Override
- protected void onDestroy() {
- if (mReceiver != null) {
- unregisterReceiver(mReceiver);
- }
- super.onDestroy();
- }
-
- /**
- * 加载账户设置选项
- *
- * 创建并添加账户Preference到账户分类中。
- * 点击该Preference时:
- *
- * 如果未设置账户,显示账户选择对话框
- * 如果已设置账户,显示确认更改账户对话框
- * 如果正在同步,显示提示消息
- *
- *
- */
- private void loadAccountPreference() {
- mAccountCategory.removeAll();
-
- Preference accountPref = new Preference(this);
- final String defaultAccount = getSyncAccountName(this);
- accountPref.setTitle(getString(R.string.preferences_account_title));
- accountPref.setSummary(getString(R.string.preferences_account_summary));
- accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
- public boolean onPreferenceClick(Preference preference) {
- if (!GTaskSyncService.isSyncing()) {
- if (TextUtils.isEmpty(defaultAccount)) {
- // the first time to set account
- showSelectAccountAlertDialog();
- } else {
- // if the account has already been set, we need to promp
- // user about the risk
- showChangeAccountConfirmAlertDialog();
- }
- } else {
- Toast.makeText(NotesPreferenceActivity.this,
- R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
- .show();
- }
- return true;
- }
- });
-
- mAccountCategory.addPreference(accountPref);
- }
-
- /**
- * 加载同步按钮和同步状态显示
- *
- * 根据当前同步状态设置按钮文本和点击事件:
- *
- * 正在同步:显示"取消同步"按钮,点击取消同步
- * 未同步:显示"立即同步"按钮,点击开始同步
- *
- * 同时显示最后同步时间或当前同步进度。
- *
- */
- private void loadSyncButton() {
- Button syncButton = (Button) findViewById(R.id.preference_sync_button);
- TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
-
- // set button state
- if (GTaskSyncService.isSyncing()) {
- syncButton.setText(getString(R.string.preferences_button_sync_cancel));
- syncButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
- }
- });
- } else {
- syncButton.setText(getString(R.string.preferences_button_sync_immediately));
- syncButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- GTaskSyncService.startSync(NotesPreferenceActivity.this);
- }
- });
- }
- syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
-
- // set last sync time
- if (GTaskSyncService.isSyncing()) {
- lastSyncTimeView.setText(GTaskSyncService.getProgressString());
- lastSyncTimeView.setVisibility(View.VISIBLE);
- } else {
- long lastSyncTime = getLastSyncTime(this);
- if (lastSyncTime != 0) {
- lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
- DateFormat.format(getString(R.string.preferences_last_sync_time_format),
- lastSyncTime)));
- lastSyncTimeView.setVisibility(View.VISIBLE);
- } else {
- lastSyncTimeView.setVisibility(View.GONE);
- }
- }
- }
-
- /**
- * 刷新UI显示
- *
- * 重新加载账户设置选项和同步按钮状态。
- *
- */
- private void refreshUI() {
- loadAccountPreference();
- loadSyncButton();
- }
-
- /**
- * 显示选择账户对话框
- *
- * 显示一个对话框,列出所有可用的Google账户供用户选择。
- * 同时提供"添加账户"选项,点击后跳转到系统账户添加界面。
- *
- */
- private void showSelectAccountAlertDialog() {
- AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
-
- View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
- TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
- titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
- TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
- subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
-
- dialogBuilder.setCustomTitle(titleView);
- dialogBuilder.setPositiveButton(null, null);
-
- Account[] accounts = getGoogleAccounts();
- String defAccount = getSyncAccountName(this);
-
- mOriAccounts = accounts;
- mHasAddedAccount = false;
-
- if (accounts.length > 0) {
- CharSequence[] items = new CharSequence[accounts.length];
- final CharSequence[] itemMapping = items;
- int checkedItem = -1;
- int index = 0;
- for (Account account : accounts) {
- if (TextUtils.equals(account.name, defAccount)) {
- checkedItem = index;
- }
- items[index++] = account.name;
- }
- dialogBuilder.setSingleChoiceItems(items, checkedItem,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- setSyncAccount(itemMapping[which].toString());
- dialog.dismiss();
- refreshUI();
- }
- });
- }
-
- View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
- dialogBuilder.setView(addAccountView);
-
- final AlertDialog dialog = dialogBuilder.show();
- addAccountView.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- mHasAddedAccount = true;
- Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
- intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
- "gmail-ls"
- });
- startActivityForResult(intent, -1);
- dialog.dismiss();
- }
- });
- }
-
- /**
- * 显示更改账户确认对话框
- *
- * 显示一个对话框,提供三个选项:
- *
- * 更改账户:显示账户选择对话框
- * 移除账户:删除当前同步账户并清理相关数据
- * 取消:关闭对话框
- *
- *
- */
- private void showChangeAccountConfirmAlertDialog() {
- AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
-
- View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
- TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
- titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
- getSyncAccountName(this)));
- TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
- subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
- dialogBuilder.setCustomTitle(titleView);
-
- CharSequence[] menuItemArray = new CharSequence[] {
- getString(R.string.preferences_menu_change_account),
- getString(R.string.preferences_menu_remove_account),
- getString(R.string.preferences_menu_cancel)
- };
- dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- if (which == 0) {
- showSelectAccountAlertDialog();
- } else if (which == 1) {
- removeSyncAccount();
- refreshUI();
- }
- }
- });
- dialogBuilder.show();
- }
-
- /**
- * 获取所有Google账户
- *
- * 从系统AccountManager中获取所有类型为"com.google"的账户。
- *
- * @return Google账户数组
- */
- private Account[] getGoogleAccounts() {
- AccountManager accountManager = AccountManager.get(this);
- return accountManager.getAccountsByType("com.google");
- }
-
- /**
- * 设置同步账户
- *
- * 保存指定的账户名称到SharedPreferences,并清理相关数据:
- *
- * 清除最后同步时间
- * 清除所有笔记的GTASK_ID和SYNC_ID
- *
- *
- * @param account 要设置的账户名称
- */
- private void setSyncAccount(String account) {
- if (!getSyncAccountName(this).equals(account)) {
- SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = settings.edit();
- if (account != null) {
- editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
- } else {
- editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
- }
- editor.commit();
-
- // clean up last sync time
- setLastSyncTime(this, 0);
-
- // clean up local gtask related info
- new Thread(new Runnable() {
- public void run() {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.GTASK_ID, "");
- values.put(NoteColumns.SYNC_ID, 0);
- getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
- }
- }).start();
-
- Toast.makeText(NotesPreferenceActivity.this,
- getString(R.string.preferences_toast_success_set_accout, account),
- Toast.LENGTH_SHORT).show();
- }
- }
-
- /**
- * 移除同步账户
- *
- * 从SharedPreferences中删除同步账户和最后同步时间,
- * 并清理所有笔记的GTASK_ID和SYNC_ID。
- *
- */
- private void removeSyncAccount() {
- SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = settings.edit();
- if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
- editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
- }
- if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
- editor.remove(PREFERENCE_LAST_SYNC_TIME);
- }
- editor.commit();
-
- // clean up local gtask related info
- new Thread(new Runnable() {
- public void run() {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.GTASK_ID, "");
- values.put(NoteColumns.SYNC_ID, 0);
- getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
- }
- }).start();
- }
-
- /**
- * 获取同步账户名称
- *
- * 从SharedPreferences中读取已设置的同步账户名称。
- *
- * @param context 上下文对象
- * @return 同步账户名称,如果未设置则返回空字符串
- */
- public static String getSyncAccountName(Context context) {
- SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
- Context.MODE_PRIVATE);
- return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
- }
-
- /**
- * 设置最后同步时间
- *
- * 将指定的同步时间保存到SharedPreferences。
- *
- * @param context 上下文对象
- * @param time 同步时间戳
- */
- public static void setLastSyncTime(Context context, long time) {
- SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
- Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = settings.edit();
- editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
- editor.commit();
- }
-
- /**
- * 获取最后同步时间
- *
- * 从SharedPreferences中读取最后同步时间。
- *
- * @param context 上下文对象
- * @return 最后同步时间戳,如果未同步过则返回0
- */
- public static long getLastSyncTime(Context context) {
- SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
- Context.MODE_PRIVATE);
- return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
- }
-
- /**
- * 同步服务广播接收器
- *
- * 接收GTaskSyncService发送的广播,实时更新UI显示同步状态和进度。
- *
- */
- private class GTaskReceiver extends BroadcastReceiver {
-
- /**
- * 接收广播
- *
- * 当收到同步服务广播时,刷新UI并更新同步状态显示。
- *
- * @param context 上下文对象
- * @param intent 广播Intent
- */
- @Override
- public void onReceive(Context context, Intent intent) {
- refreshUI();
- if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
- TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
- syncStatus.setText(intent
- .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
- }
-
- }
- }
-
- /**
- * 处理菜单项选择
- *
- * 处理ActionBar上的菜单项点击事件。
- * 当点击返回按钮时,返回到笔记列表界面。
- *
- * @param item 被点击的菜单项
- * @return true表示已处理,false表示未处理
- */
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- Intent intent = new Intent(this, NotesListActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- startActivity(intent);
- return true;
- default:
- return false;
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/ui/SidebarFragment.java b/app/src/main/java/net/micode/notes/ui/SidebarFragment.java
deleted file mode 100644
index 041f68b..0000000
--- a/app/src/main/java/net/micode/notes/ui/SidebarFragment.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.InputFilter;
-import android.text.TextUtils;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.animation.Animation;
-import android.view.animation.TranslateAnimation;
-import android.widget.EditText;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.fragment.app.Fragment;
-import androidx.lifecycle.ViewModelProvider;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.NotesRepository;
-import net.micode.notes.viewmodel.FolderListViewModel;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * 侧栏Fragment
- *
- * 显示文件夹树、菜单项和操作按钮
- * 提供文件夹导航、创建、展开/收起等功能
- *
- */
-public class SidebarFragment extends Fragment {
-
- private static final String TAG = "SidebarFragment";
- private static final int MAX_FOLDER_NAME_LENGTH = 50;
-
- // 视图组件
- private RecyclerView rvFolderTree;
- private TextView tvRootFolder;
- private TextView menuSync;
- private TextView menuLogin;
- private TextView menuExport;
- private TextView menuSettings;
- private TextView menuTrash;
-
- // 适配器和数据
- private FolderTreeAdapter adapter;
- private FolderListViewModel viewModel;
-
- // 单击和双击检测
- private long lastClickTime = 0;
- private View lastClickedView = null;
- private static final long DOUBLE_CLICK_INTERVAL = 300; // 毫秒
-
- // 回调接口
- private OnSidebarItemSelectedListener listener;
-
- /**
- * 侧栏项选择回调接口
- */
- public interface OnSidebarItemSelectedListener {
- /**
- * 跳转到指定文件夹
- * @param folderId 文件夹ID
- */
- void onFolderSelected(long folderId);
-
- /**
- * 打开回收站
- */
- void onTrashSelected();
-
- /**
- * 同步
- */
- void onSyncSelected();
-
- /**
- * 登录
- */
- void onLoginSelected();
-
- /**
- * 导出
- */
- void onExportSelected();
-
- /**
- * 设置
- */
- void onSettingsSelected();
-
- /**
- * 创建文件夹
- */
- void onCreateFolder();
-
- /**
- * 关闭侧栏
- */
- void onCloseSidebar();
- }
-
- @Override
- public void onAttach(@NonNull Context context) {
- super.onAttach(context);
- if (context instanceof OnSidebarItemSelectedListener) {
- listener = (OnSidebarItemSelectedListener) context;
- } else {
- throw new RuntimeException(context.toString() + " must implement OnSidebarItemSelectedListener");
- }
- }
-
- @Override
- public void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- viewModel = new ViewModelProvider(this).get(FolderListViewModel.class);
- }
-
- @Nullable
- @Override
- public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
- @Nullable Bundle savedInstanceState) {
- return inflater.inflate(R.layout.sidebar_layout, container, false);
- }
-
- @Override
- public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
- super.onViewCreated(view, savedInstanceState);
- initViews(view);
- setupListeners();
- observeViewModel();
- }
-
- /**
- * 刷新文件夹树(供外部调用,如删除笔记后)
- */
- public void refreshFolderTree() {
- if (viewModel != null) {
- viewModel.loadFolderTree();
- }
- }
-
- /**
- * 初始化视图
- */
- private void initViews(View view) {
- rvFolderTree = view.findViewById(R.id.rv_folder_tree);
- tvRootFolder = view.findViewById(R.id.tv_root_folder);
- menuSync = view.findViewById(R.id.menu_sync);
- menuLogin = view.findViewById(R.id.menu_login);
- menuExport = view.findViewById(R.id.menu_export);
- menuSettings = view.findViewById(R.id.menu_settings);
- menuTrash = view.findViewById(R.id.menu_trash);
-
- // 设置RecyclerView
- rvFolderTree.setLayoutManager(new LinearLayoutManager(requireContext()));
- adapter = new FolderTreeAdapter(new ArrayList<>(), viewModel);
- adapter.setOnFolderItemClickListener(this::handleFolderItemClick);
- rvFolderTree.setAdapter(adapter);
- }
-
- /**
- * 设置监听器
- */
- private void setupListeners() {
- View view = getView();
- if (view == null) return;
-
- // 根文件夹(单击展开/收起,双击跳转)
- setupFolderClickListener(tvRootFolder, Notes.ID_ROOT_FOLDER);
-
- // 关闭侧栏
- view.findViewById(R.id.btn_close_sidebar).setOnClickListener(v -> {
- if (listener != null) {
- listener.onCloseSidebar();
- }
- });
-
- // 创建文件夹
- view.findViewById(R.id.btn_create_folder).setOnClickListener(v -> showCreateFolderDialog());
-
- // 菜单项
- menuSync.setOnClickListener(v -> {
- if (listener != null) {
- listener.onSyncSelected();
- }
- });
-
- menuLogin.setOnClickListener(v -> {
- if (listener != null) {
- listener.onLoginSelected();
- }
- });
-
- menuExport.setOnClickListener(v -> {
- if (listener != null) {
- listener.onExportSelected();
- }
- });
-
- menuSettings.setOnClickListener(v -> {
- if (listener != null) {
- listener.onSettingsSelected();
- }
- });
-
- menuTrash.setOnClickListener(v -> {
- if (listener != null) {
- listener.onTrashSelected();
- }
- });
- }
-
- /**
- * 设置文件夹的单击/双击监听器
- */
- private void setupFolderClickListener(View view, long folderId) {
- view.setOnClickListener(v -> {
- android.util.Log.d(TAG, "setupFolderClickListener: folderId=" + folderId);
- long currentTime = System.currentTimeMillis();
- if (lastClickedView == view && (currentTime - lastClickTime) < DOUBLE_CLICK_INTERVAL) {
- android.util.Log.d(TAG, "Double click on root folder, jumping to: " + folderId);
- // 这是双击,执行跳转
- if (listener != null) {
- // 根文件夹也可以跳转(回到根)
- listener.onFolderSelected(folderId);
- }
- // 重置双击状态
- lastClickTime = 0;
- lastClickedView = null;
- } else {
- android.util.Log.d(TAG, "Single click on root folder, will toggle expand in " + DOUBLE_CLICK_INTERVAL + "ms");
- // 可能是单击,延迟处理
- lastClickTime = currentTime;
- lastClickedView = view;
- view.postDelayed(() -> {
- // 如果在延迟期间没有发生双击,则执行单击操作(展开/收起)
- if (System.currentTimeMillis() - lastClickTime >= DOUBLE_CLICK_INTERVAL) {
- android.util.Log.d(TAG, "Toggling root folder expand");
- toggleFolderExpand(folderId);
- }
- }, DOUBLE_CLICK_INTERVAL);
- }
- });
- }
-
- /**
- * 观察ViewModel数据变化
- */
- private void observeViewModel() {
- viewModel.getFolderTree().observe(getViewLifecycleOwner(), folderItems -> {
- if (folderItems != null) {
- adapter.setData(folderItems);
- adapter.notifyDataSetChanged();
- }
- });
-
- viewModel.loadFolderTree();
- }
-
- /**
- * 切换文件夹展开/收起状态
- */
- private void toggleFolderExpand(long folderId) {
- android.util.Log.d(TAG, "toggleFolderExpand: folderId=" + folderId);
- viewModel.toggleFolderExpand(folderId);
- }
-
- /**
- * 处理文件夹项点击(单击/双击)
- */
- private void handleFolderItemClick(long folderId) {
- android.util.Log.d(TAG, "handleFolderItemClick: folderId=" + folderId);
- long currentTime = System.currentTimeMillis();
- if (lastClickedFolderId == folderId && (currentTime - lastFolderClickTime) < DOUBLE_CLICK_INTERVAL) {
- android.util.Log.d(TAG, "Double click detected, jumping to folder: " + folderId);
- // 这是双击,执行跳转
- if (listener != null) {
- listener.onFolderSelected(folderId);
- }
- // 重置双击状态
- lastFolderClickTime = 0;
- lastClickedFolderId = -1;
- } else {
- android.util.Log.d(TAG, "Single click, will toggle expand in " + DOUBLE_CLICK_INTERVAL + "ms");
- // 可能是单击,延迟处理
- lastFolderClickTime = currentTime;
- lastClickedFolderId = folderId;
- new android.os.Handler().postDelayed(() -> {
- // 如果在延迟期间没有发生双击,则执行单击操作(展开/收起)
- if (System.currentTimeMillis() - lastFolderClickTime >= DOUBLE_CLICK_INTERVAL) {
- android.util.Log.d(TAG, "Toggling folder expand: " + folderId);
- toggleFolderExpand(folderId);
- }
- }, DOUBLE_CLICK_INTERVAL);
- }
- }
-
- // 双击检测专用变量(针对文件夹列表项)
- private long lastFolderClickTime = 0;
- private long lastClickedFolderId = -1;
-
- /**
- * 显示创建文件夹对话框
- */
- private void showCreateFolderDialog() {
- AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
- builder.setTitle(R.string.dialog_create_folder_title);
-
- final EditText input = new EditText(requireContext());
- input.setHint(R.string.dialog_create_folder_hint);
- input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_FOLDER_NAME_LENGTH)});
-
- builder.setView(input);
-
- builder.setPositiveButton(R.string.menu_create_folder, (dialog, which) -> {
- String folderName = input.getText().toString().trim();
- if (TextUtils.isEmpty(folderName)) {
- Toast.makeText(requireContext(), R.string.error_folder_name_empty, Toast.LENGTH_SHORT).show();
- return;
- }
- if (folderName.length() > MAX_FOLDER_NAME_LENGTH) {
- Toast.makeText(requireContext(), R.string.error_folder_name_too_long, Toast.LENGTH_SHORT).show();
- return;
- }
-
- // 创建文件夹
- NotesRepository repository = new NotesRepository(requireContext().getContentResolver());
- long parentId = viewModel.getCurrentFolderId();
- if (parentId == 0) {
- parentId = Notes.ID_ROOT_FOLDER;
- }
- repository.createFolder(parentId, folderName,
- new NotesRepository.Callback() {
- @Override
- public void onSuccess(Long folderId) {
- if (getActivity() != null) {
- getActivity().runOnUiThread(() -> {
- Toast.makeText(requireContext(), R.string.create_folder_success, Toast.LENGTH_SHORT).show();
- // 刷新文件夹列表
- viewModel.loadFolderTree();
- });
- }
- }
-
- @Override
- public void onError(Exception error) {
- if (getActivity() != null) {
- getActivity().runOnUiThread(() -> {
- Toast.makeText(requireContext(),
- getString(R.string.error_folder_name_too_long) + ": " + error.getMessage(),
- Toast.LENGTH_SHORT).show();
- });
- }
- }
- });
- });
-
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- }
-
- /**
- * FolderTreeAdapter
- * 文件夹树适配器,支持层级显示和展开/收起
- */
- private static class FolderTreeAdapter extends RecyclerView.Adapter {
-
- private List folderItems;
- private FolderListViewModel viewModel;
- private OnFolderItemClickListener folderItemClickListener;
-
- public FolderTreeAdapter(List folderItems, FolderListViewModel viewModel) {
- this.folderItems = folderItems;
- this.viewModel = viewModel;
- }
-
- public void setData(List folderItems) {
- this.folderItems = folderItems;
- }
-
- public void setOnFolderItemClickListener(OnFolderItemClickListener listener) {
- this.folderItemClickListener = listener;
- }
-
- @NonNull
- @Override
- public FolderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
- View view = LayoutInflater.from(parent.getContext())
- .inflate(R.layout.sidebar_folder_item, parent, false);
- return new FolderViewHolder(view, folderItemClickListener);
- }
-
- @Override
- public void onBindViewHolder(@NonNull FolderViewHolder holder, int position) {
- FolderTreeItem item = folderItems.get(position);
- boolean isExpanded = viewModel != null && viewModel.isFolderExpanded(item.folderId);
- holder.bind(item, isExpanded);
- }
-
- @Override
- public int getItemCount() {
- return folderItems.size();
- }
-
- static class FolderViewHolder extends RecyclerView.ViewHolder {
- private View indentView;
- private ImageView ivExpandIcon;
- private ImageView ivFolderIcon;
- private TextView tvFolderName;
- private TextView tvNoteCount;
- private FolderTreeItem currentItem;
- private final OnFolderItemClickListener folderItemClickListener;
-
- public FolderViewHolder(@NonNull View itemView, OnFolderItemClickListener listener) {
- super(itemView);
- this.folderItemClickListener = listener;
- indentView = itemView.findViewById(R.id.indent_view);
- ivExpandIcon = itemView.findViewById(R.id.iv_expand_icon);
- ivFolderIcon = itemView.findViewById(R.id.iv_folder_icon);
- tvFolderName = itemView.findViewById(R.id.tv_folder_name);
- tvNoteCount = itemView.findViewById(R.id.tv_note_count);
- }
-
- public void bind(FolderTreeItem item, boolean isExpanded) {
- this.currentItem = item;
-
- // 设置缩进
- int indent = item.level * 32;
- indentView.setLayoutParams(new LinearLayout.LayoutParams(indent, LinearLayout.LayoutParams.MATCH_PARENT));
-
- // 设置展开/收起图标
- if (item.hasChildren) {
- ivExpandIcon.setVisibility(View.VISIBLE);
- ivExpandIcon.setRotation(isExpanded ? 90 : 0);
- } else {
- ivExpandIcon.setVisibility(View.INVISIBLE);
- }
-
- // 设置文件夹名称
- tvFolderName.setText(item.name);
-
- // 设置便签数量
- tvNoteCount.setText(String.format(itemView.getContext()
- .getString(R.string.folder_note_count), item.noteCount));
-
- // 设置点击监听器
- itemView.setOnClickListener(v -> {
- if (folderItemClickListener != null) {
- folderItemClickListener.onFolderClick(item.folderId);
- }
- });
- }
- }
- }
-
- /**
- * 文件夹项点击监听器接口
- */
- public interface OnFolderItemClickListener {
- void onFolderClick(long folderId);
- }
-
- /**
- * FolderTreeItem
- * 文件夹树项数据模型
- */
- public static class FolderTreeItem {
- public long folderId;
- public String name;
- public int level; // 层级,0表示顶级
- public boolean hasChildren;
- public int noteCount;
-
- public FolderTreeItem(long folderId, String name, int level, boolean hasChildren, int noteCount) {
- this.folderId = folderId;
- this.name = name;
- this.level = level;
- this.hasChildren = hasChildren;
- this.noteCount = noteCount;
- }
- }
-
- @Override
- public void onDetach() {
- super.onDetach();
- listener = null;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/viewmodel/FolderListViewModel.java b/app/src/main/java/net/micode/notes/viewmodel/FolderListViewModel.java
deleted file mode 100644
index d93e02d..0000000
--- a/app/src/main/java/net/micode/notes/viewmodel/FolderListViewModel.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.viewmodel;
-
-import android.app.Application;
-import android.database.Cursor;
-import android.net.Uri;
-
-import androidx.annotation.NonNull;
-import androidx.lifecycle.AndroidViewModel;
-import androidx.lifecycle.LiveData;
-import androidx.lifecycle.MutableLiveData;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.NotesDatabaseHelper;
-import net.micode.notes.data.NotesDatabaseHelper.TABLE;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.NotesRepository;
-import net.micode.notes.ui.SidebarFragment.FolderTreeItem;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * 文件夹列表ViewModel
- *
- * 管理文件夹树的数据和业务逻辑
- * 提供文件夹树的查询和构建功能
- *
- */
-public class FolderListViewModel extends AndroidViewModel {
- private static final String TAG = "FolderListViewModel";
-
- private MutableLiveData> folderTreeLiveData;
- private NotesDatabaseHelper dbHelper;
- private NotesRepository repository;
- private long currentFolderId = Notes.ID_ROOT_FOLDER; // 当前文件夹ID
- private Set expandedFolderIds = new HashSet<>(); // 已展开的文件夹ID集合
-
- public FolderListViewModel(@NonNull Application application) {
- super(application);
- dbHelper = NotesDatabaseHelper.getInstance(application);
- repository = new NotesRepository(application.getContentResolver());
- folderTreeLiveData = new MutableLiveData<>();
- }
-
- /**
- * 获取当前文件夹ID
- */
- public long getCurrentFolderId() {
- return currentFolderId;
- }
-
- /**
- * 设置当前文件夹ID
- */
- public void setCurrentFolderId(long folderId) {
- this.currentFolderId = folderId;
- }
-
- /**
- * 切换文件夹展开/收起状态
- * @param folderId 文件夹ID
- */
- public void toggleFolderExpand(long folderId) {
- android.util.Log.d(TAG, "toggleFolderExpand: folderId=" + folderId);
- android.util.Log.d(TAG, "Before toggle, expandedFolders: " + expandedFolderIds);
-
- if (expandedFolderIds.contains(folderId)) {
- expandedFolderIds.remove(folderId);
- android.util.Log.d(TAG, "Collapsed folder: " + folderId);
- } else {
- expandedFolderIds.add(folderId);
- android.util.Log.d(TAG, "Expanded folder: " + folderId);
- }
-
- android.util.Log.d(TAG, "After toggle, expandedFolders: " + expandedFolderIds);
-
- // 重新加载文件夹树
- loadFolderTree();
- }
-
- /**
- * 检查文件夹是否已展开
- * @param folderId 文件夹ID
- * @return 是否已展开
- */
- public boolean isFolderExpanded(long folderId) {
- return expandedFolderIds.contains(folderId);
- }
-
- /**
- * 获取文件夹树LiveData
- */
- public LiveData> getFolderTree() {
- return folderTreeLiveData;
- }
-
- /**
- * 加载文件夹树数据
- */
- public void loadFolderTree() {
- new Thread(() -> {
- List folderTree = buildFolderTree();
- folderTreeLiveData.postValue(folderTree);
- }).start();
- }
-
- /**
- * 构建文件夹树
- *
- * 从数据库中查询所有文件夹,并构建层级结构
- *
- * @return 文件夹树列表
- */
- private List buildFolderTree() {
- // 查询所有文件夹(不包括系统文件夹)
- List> folders = queryAllFolders();
-
- android.util.Log.d(TAG, "QueryAllFolders returned " + folders.size() + " folders");
-
- // 构建文件夹映射表(方便查找父文件夹)
- Map folderMap = new HashMap<>();
- List rootFolders = new ArrayList<>();
-
- // 创建文件夹节点
- for (Map folder : folders) {
- long id = (Long) folder.get(NoteColumns.ID);
- String name = (String) folder.get(NoteColumns.SNIPPET);
- long parentId = (Long) folder.get(NoteColumns.PARENT_ID);
- int noteCount = ((Number) folder.get(NoteColumns.NOTES_COUNT)).intValue();
-
- android.util.Log.d(TAG, "Folder: id=" + id + ", name=" + name + ", parentId=" + parentId);
-
- FolderNode node = new FolderNode(id, name, parentId, noteCount);
- folderMap.put(id, node);
-
- // 如果是顶级文件夹(父文件夹为根),添加到根列表
- if (parentId == Notes.ID_ROOT_FOLDER) {
- rootFolders.add(node);
- android.util.Log.d(TAG, "Added root folder: " + name);
- }
- }
-
- android.util.Log.d(TAG, "Root folders count: " + rootFolders.size());
-
- // 构建父子关系
- for (FolderNode node : folderMap.values()) {
- if (node.parentId != Notes.ID_ROOT_FOLDER) {
- FolderNode parent = folderMap.get(node.parentId);
- if (parent != null) {
- parent.children.add(node);
- }
- }
- }
-
- // 转换为扁平列表(用于RecyclerView显示)
- List folderTree = new ArrayList<>();
- // 检查根文件夹是否展开
- boolean rootExpanded = expandedFolderIds.contains(Notes.ID_ROOT_FOLDER);
- android.util.Log.d(TAG, "Root expanded: " + rootExpanded);
- buildFolderTreeList(rootFolders, folderTree, 0, rootExpanded);
-
- android.util.Log.d(TAG, "Final folder tree size: " + folderTree.size());
-
- return folderTree;
- }
-
- /**
- * 递归构建文件夹树列表
- * 只显示已展开文件夹的子文件夹
- * 顶层文件夹始终显示,无论根文件夹是否展开
- * @param nodes 文件夹节点列表
- * @param folderTree 文件夹树列表(输出)
- * @param level 当前层级
- * @param forceExpandChildren 是否强制展开子文件夹(用于顶层)
- */
- private void buildFolderTreeList(List nodes, List folderTree, int level, boolean forceExpandChildren) {
- for (FolderNode node : nodes) {
- // 顶级文件夹始终显示(level=0)
- // 移除了之前的条件判断,让所有顶级文件夹都能显示
- folderTree.add(new FolderTreeItem(
- node.id,
- node.name,
- level,
- !node.children.isEmpty(),
- node.noteCount
- ));
-
- // 只有当父文件夹在 expandedFolderIds 中时,才递归处理子文件夹
- // 有子节点(!node.children.isEmpty())才检查展开状态
- if (!node.children.isEmpty() && expandedFolderIds.contains(node.id)) {
- buildFolderTreeList(node.children, folderTree, level + 1, false);
- }
- }
- }
-
- /**
- * 查询所有文件夹
- * @return 文件夹列表
- */
- private List> queryAllFolders() {
- List> folders = new ArrayList<>();
-
- // 查询所有文件夹类型的笔记
- String selection = NoteColumns.TYPE + " = ?";
- String[] selectionArgs = new String[]{
- String.valueOf(Notes.TYPE_FOLDER)
- };
-
- Cursor cursor = null;
- try {
- cursor = dbHelper.getReadableDatabase().query(
- TABLE.NOTE,
- null,
- selection,
- selectionArgs,
- null,
- null,
- NoteColumns.MODIFIED_DATE + " DESC"
- );
-
- android.util.Log.d(TAG, "Query executed, cursor: " + (cursor != null ? cursor.getCount() : "null"));
-
- if (cursor != null) {
- android.util.Log.d(TAG, "Column names: " + java.util.Arrays.toString(cursor.getColumnNames()));
-
- while (cursor.moveToNext()) {
- Map folder = new HashMap<>();
- long id = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.ID));
- String name = cursor.getString(cursor.getColumnIndexOrThrow(NoteColumns.SNIPPET));
-
- // 尝试获取parent_id,可能列名不对
- int parentIdIndex = cursor.getColumnIndex(NoteColumns.PARENT_ID);
- long parentId = -1;
- if (parentIdIndex != -1) {
- parentId = cursor.getLong(parentIdIndex);
- }
-
- // 尝试获取notes_count
- int notesCountIndex = cursor.getColumnIndex(NoteColumns.NOTES_COUNT);
- int noteCount = 0;
- if (notesCountIndex != -1) {
- noteCount = cursor.getInt(notesCountIndex);
- }
-
- android.util.Log.d(TAG, "Folder data: id=" + id + ", name=" + name + ", parentId=" + parentId + ", noteCount=" + noteCount);
-
- folder.put(NoteColumns.ID, id);
- folder.put(NoteColumns.SNIPPET, name);
- folder.put(NoteColumns.PARENT_ID, parentId);
- folder.put(NoteColumns.NOTES_COUNT, noteCount);
-
- folders.add(folder);
- }
- }
- } catch (Exception e) {
- android.util.Log.e(TAG, "Error querying folders", e);
- e.printStackTrace();
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
-
- return folders;
- }
-
- /**
- * FolderNode
- * 文件夹节点,用于构建文件夹树
- */
- private static class FolderNode {
- public long id;
- public String name;
- public long parentId;
- public int noteCount;
- public List children = new ArrayList<>();
-
- public FolderNode(long id, String name, long parentId, int noteCount) {
- this.id = id;
- this.name = name;
- this.parentId = parentId;
- this.noteCount = noteCount;
- }
- }
-}
diff --git a/app/src/main/java/net/micode/notes/viewmodel/NotesListViewModel.java b/app/src/main/java/net/micode/notes/viewmodel/NotesListViewModel.java
deleted file mode 100644
index 38daea0..0000000
--- a/app/src/main/java/net/micode/notes/viewmodel/NotesListViewModel.java
+++ /dev/null
@@ -1,584 +0,0 @@
-/*
- * Copyright (c) 2025, Modern Notes Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.viewmodel;
-
-import android.util.Log;
-
-import androidx.lifecycle.MutableLiveData;
-import androidx.lifecycle.ViewModel;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.NotesRepository;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-/**
- * 笔记列表ViewModel
- *
- * 负责笔记列表的业务逻辑,与UI层(Activity)解耦
- * 管理笔记列表的加载、创建、删除、搜索、移动等操作
- *
- *
- * @see NotesRepository
- * @see Note
- */
-public class NotesListViewModel extends ViewModel {
- private static final String TAG = "NotesListViewModel";
-
- private final NotesRepository repository;
-
- // 笔记列表LiveData
- private final MutableLiveData> notesLiveData = new MutableLiveData<>();
-
- // 加载状态LiveData
- private final MutableLiveData isLoading = new MutableLiveData<>(false);
-
- // 错误消息LiveData
- private final MutableLiveData errorMessage = new MutableLiveData<>();
-
- // 选中的笔记ID集合
- private final HashSet selectedNoteIds = new HashSet<>();
-
- // 当前文件夹ID
- private long currentFolderId = Notes.ID_ROOT_FOLDER;
-
- // 文件夹路径LiveData(用于面包屑导航)
- private final MutableLiveData> folderPathLiveData = new MutableLiveData<>();
-
- // 侧栏刷新通知LiveData(删除等操作后通知侧栏刷新)
- private final MutableLiveData sidebarRefreshNeeded = new MutableLiveData<>(false);
-
- // 文件夹导航历史(用于返回上一级)
- private final List folderHistory = new ArrayList<>();
-
- /**
- * 构造函数
- *
- * @param repository 笔记数据仓库
- */
- public NotesListViewModel(NotesRepository repository) {
- this.repository = repository;
- Log.d(TAG, "ViewModel created");
- }
-
- /**
- * 获取笔记列表LiveData
- *
- * @return 笔记列表LiveData
- */
- public MutableLiveData> getNotesLiveData() {
- return notesLiveData;
- }
-
- /**
- * 获取加载状态LiveData
- *
- * @return 加载状态LiveData
- */
- public MutableLiveData getIsLoading() {
- return isLoading;
- }
-
- /**
- * 获取错误消息LiveData
- *
- * @return 错误消息LiveData
- */
- public MutableLiveData getErrorMessage() {
- return errorMessage;
- }
-
- /**
- * 加载笔记列表
- *
- * 从指定文件夹加载笔记列表,同时加载文件夹路径用于面包屑导航
- *
- *
- * @param folderId 文件夹ID,{@link Notes#ID_ROOT_FOLDER} 表示根文件夹
- */
- public void loadNotes(long folderId) {
- this.currentFolderId = folderId;
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- // 加载文件夹路径
- repository.getFolderPath(folderId, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List path) {
- folderPathLiveData.postValue(path);
- }
-
- @Override
- public void onError(Exception error) {
- Log.e(TAG, "Failed to load folder path", error);
- }
- });
-
- // 加载笔记
- repository.getNotes(folderId, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List notes) {
- isLoading.postValue(false);
- notesLiveData.postValue(notes);
- Log.d(TAG, "Successfully loaded " + notes.size() + " notes");
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "加载笔记失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 刷新笔记列表
- *
- * 重新加载当前文件夹的笔记列表
- *
- */
- public void refreshNotes() {
- loadNotes(currentFolderId);
- }
-
- /**
- * 创建新笔记
- *
- * 在当前文件夹下创建一个空笔记,并刷新列表
- *
- */
- public void createNote() {
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- repository.createNote(currentFolderId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Long noteId) {
- isLoading.postValue(false);
- Log.d(TAG, "Successfully created note with ID: " + noteId);
- refreshNotes();
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "创建笔记失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 删除单个笔记
- *
- * 将笔记移动到回收站,并刷新列表
- *
- *
- * @param noteId 笔记ID
- */
- public void deleteNote(long noteId) {
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- repository.deleteNote(noteId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- isLoading.postValue(false);
- selectedNoteIds.remove(noteId);
- refreshNotes();
- Log.d(TAG, "Successfully deleted note: " + noteId);
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "删除笔记失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 批量删除笔记
- *
- * 将选中的所有笔记移动到回收站
- *
- */
- public void deleteSelectedNotes() {
- if (selectedNoteIds.isEmpty()) {
- errorMessage.postValue("请先选择要删除的笔记");
- return;
- }
-
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- List noteIds = new ArrayList<>(selectedNoteIds);
- repository.deleteNotes(noteIds, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- isLoading.postValue(false);
- selectedNoteIds.clear();
- refreshNotes();
- Log.d(TAG, "Successfully deleted " + rowsAffected + " notes");
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "批量删除失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 搜索笔记
- *
- * 根据关键字搜索笔记,更新笔记列表
- *
- *
- * @param keyword 搜索关键字
- */
- public void searchNotes(String keyword) {
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- repository.searchNotes(keyword, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List notes) {
- isLoading.postValue(false);
- notesLiveData.postValue(notes);
- Log.d(TAG, "Search returned " + notes.size() + " results");
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "搜索失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 切换笔记选中状态
- *
- * @param noteId 笔记ID
- * @param selected 是否选中
- */
- public void toggleNoteSelection(long noteId, boolean selected) {
- if (selected) {
- selectedNoteIds.add(noteId);
- } else {
- selectedNoteIds.remove(noteId);
- }
- }
-
- /**
- * 全选笔记
- *
- * 选中当前列表中的所有笔记
- *
- */
- public void selectAllNotes() {
- List notes = notesLiveData.getValue();
- if (notes != null) {
- for (NotesRepository.NoteInfo note : notes) {
- selectedNoteIds.add(note.getId());
- }
- }
- }
-
- /**
- * 取消全选
- *
- * 清空所有选中的笔记
- *
- */
- public void deselectAllNotes() {
- selectedNoteIds.clear();
- }
-
- /**
- * 检查是否全选
- *
- * @return 如果所有笔记都被选中返回true
- */
- public boolean isAllSelected() {
- List notes = notesLiveData.getValue();
- if (notes == null || notes.isEmpty()) {
- return false;
- }
-
- return notes.size() == selectedNoteIds.size();
- }
-
- /**
- * 获取选中的笔记数量
- *
- * @return 选中的笔记数量
- */
- public int getSelectedCount() {
- return selectedNoteIds.size();
- }
-
- /**
- * 获取选中的笔记ID列表
- *
- * @return 选中的笔记ID列表
- */
- public List getSelectedNoteIds() {
- return new ArrayList<>(selectedNoteIds);
- }
-
- /**
- * 获取当前文件夹ID
- *
- * @return 当前文件夹ID
- */
- public long getCurrentFolderId() {
- return currentFolderId;
- }
-
- /**
- * 设置当前文件夹
- *
- * @param folderId 文件夹ID
- */
- public void setCurrentFolderId(long folderId) {
- this.currentFolderId = folderId;
- }
-
- /**
- * 获取文件夹路径LiveData
- *
- * @return 文件夹路径LiveData
- */
- public MutableLiveData> getFolderPathLiveData() {
- return folderPathLiveData;
- }
-
- /**
- * 获取侧栏刷新通知LiveData
- *
- * @return 侧栏刷新通知LiveData
- */
- public MutableLiveData getSidebarRefreshNeeded() {
- return sidebarRefreshNeeded;
- }
-
- /**
- * 触发侧栏刷新
- */
- public void triggerSidebarRefresh() {
- sidebarRefreshNeeded.postValue(true);
- }
-
- /**
- * 进入指定文件夹
- *
- * @param folderId 文件夹ID
- */
- public void enterFolder(long folderId) {
- // 将当前文件夹添加到历史记录
- if (currentFolderId != Notes.ID_ROOT_FOLDER && currentFolderId != Notes.ID_CALL_RECORD_FOLDER) {
- folderHistory.add(currentFolderId);
- }
- loadNotes(folderId);
- }
-
- /**
- * 返回上一级文件夹
- *
- * @return 是否成功返回上一级
- */
- public boolean navigateUp() {
- if (!folderHistory.isEmpty()) {
- long parentFolderId = folderHistory.remove(folderHistory.size() - 1);
- loadNotes(parentFolderId);
- return true;
- }
- return false;
- }
-
- /**
- * 清除选择状态
- *
- * 退出多选模式时调用
- *
- */
- public void clearSelection() {
- selectedNoteIds.clear();
- }
-
- /**
- * 获取文件夹列表
- *
- * 加载所有文件夹类型的笔记
- *
- */
- public void loadFolders() {
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- repository.getFolders(new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List folders) {
- isLoading.postValue(false);
- notesLiveData.postValue(folders);
- Log.d(TAG, "Successfully loaded " + folders.size() + " folders");
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "加载文件夹失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 移动选中的笔记到指定文件夹
- *
- * 批量移动笔记到目标文件夹
- *
- *
- * @param targetFolderId 目标文件夹ID
- */
- public void moveSelectedNotesToFolder(long targetFolderId) {
- if (selectedNoteIds.isEmpty()) {
- errorMessage.postValue("请先选择要移动的笔记");
- return;
- }
-
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- List noteIds = new ArrayList<>(selectedNoteIds);
- repository.moveNotes(noteIds, targetFolderId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- isLoading.postValue(false);
- selectedNoteIds.clear();
- refreshNotes();
- Log.d(TAG, "Successfully moved " + rowsAffected + " notes");
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "移动笔记失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 切换选中笔记的置顶状态
- */
- public void toggleSelectedNotesPin() {
- if (selectedNoteIds.isEmpty()) {
- errorMessage.postValue("请先选择要操作的笔记");
- return;
- }
-
- isLoading.postValue(true);
- errorMessage.postValue(null);
-
- // 检查当前选中笔记的置顶状态
- List allNotes = notesLiveData.getValue();
- if (allNotes == null) return;
-
- boolean hasUnpinned = false;
- for (NotesRepository.NoteInfo note : allNotes) {
- if (selectedNoteIds.contains(note.getId())) {
- if (!note.isPinned) {
- hasUnpinned = true;
- break;
- }
- }
- }
-
- // 如果有未置顶的,则全部置顶;否则全部取消置顶
- final boolean newPinState = hasUnpinned;
- List noteIds = new ArrayList<>(selectedNoteIds);
-
- repository.batchTogglePin(noteIds, newPinState, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- isLoading.postValue(false);
- // 保持选中状态,方便用户查看
- refreshNotes();
- Log.d(TAG, "Successfully toggled pin state to " + newPinState);
- }
-
- @Override
- public void onError(Exception error) {
- isLoading.postValue(false);
- String message = "置顶操作失败: " + error.getMessage();
- errorMessage.postValue(message);
- Log.e(TAG, message, error);
- }
- });
- }
-
- /**
- * 检查选中的笔记是否全部已置顶
- *
- * @return 如果所有选中的笔记都已置顶返回true
- */
- public boolean isAllSelectedPinned() {
- if (selectedNoteIds.isEmpty()) return false;
-
- List allNotes = notesLiveData.getValue();
- if (allNotes == null) return false;
-
- for (NotesRepository.NoteInfo note : allNotes) {
- if (selectedNoteIds.contains(note.getId())) {
- if (!note.isPinned) {
- return false;
- }
- }
- }
- return true;
- }
-
- /**
- * ViewModel销毁时的清理
- *
- * 清理资源和状态
- *
- */
- @Override
- protected void onCleared() {
- super.onCleared();
- selectedNoteIds.clear();
- Log.d(TAG, "ViewModel cleared");
- }
-}
diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java
deleted file mode 100644
index ec6f819..0000000
--- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.widget;
-import android.app.PendingIntent;
-import android.appwidget.AppWidgetManager;
-import android.appwidget.AppWidgetProvider;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.database.Cursor;
-import android.util.Log;
-import android.widget.RemoteViews;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.tool.ResourceParser;
-import net.micode.notes.ui.NoteEditActivity;
-import net.micode.notes.ui.NotesListActivity;
-
-public abstract class NoteWidgetProvider extends AppWidgetProvider {
- public static final String [] PROJECTION = new String [] {
- NoteColumns.ID,
- NoteColumns.BG_COLOR_ID,
- NoteColumns.SNIPPET
- };
-
- public static final int COLUMN_ID = 0;
- public static final int COLUMN_BG_COLOR_ID = 1;
- public static final int COLUMN_SNIPPET = 2;
-
- private static final String TAG = "NoteWidgetProvider";
-
- @Override
- public void onDeleted(Context context, int[] appWidgetIds) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
- for (int i = 0; i < appWidgetIds.length; i++) {
- context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
- values,
- NoteColumns.WIDGET_ID + "=?",
- new String[] { String.valueOf(appWidgetIds[i])});
- }
- }
-
- private Cursor getNoteWidgetInfo(Context context, int widgetId) {
- return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
- PROJECTION,
- NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
- new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
- null);
- }
-
- protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
- update(context, appWidgetManager, appWidgetIds, false);
- }
-
- private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
- boolean privacyMode) {
- for (int i = 0; i < appWidgetIds.length; i++) {
- if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
- int bgId = ResourceParser.getDefaultBgId(context);
- String snippet = "";
- Intent intent = new Intent(context, NoteEditActivity.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
- intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
- intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
-
- Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
- if (c != null && c.moveToFirst()) {
- if (c.getCount() > 1) {
- Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
- c.close();
- return;
- }
- snippet = c.getString(COLUMN_SNIPPET);
- bgId = c.getInt(COLUMN_BG_COLOR_ID);
- intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
- intent.setAction(Intent.ACTION_VIEW);
- } else {
- snippet = context.getResources().getString(R.string.widget_havenot_content);
- intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
- }
-
- if (c != null) {
- c.close();
- }
-
- RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
- rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
- intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
- /**
- * Generate the pending intent to start host for the widget
- */
- PendingIntent pendingIntent = null;
- if (privacyMode) {
- rv.setTextViewText(R.id.widget_text,
- context.getString(R.string.widget_under_visit_mode));
- pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
- context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
- } else {
- rv.setTextViewText(R.id.widget_text, snippet);
- pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
- PendingIntent.FLAG_UPDATE_CURRENT);
- }
-
- rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
- appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
- }
- }
- }
-
- protected abstract int getBgResourceId(int bgId);
-
- protected abstract int getLayoutId();
-
- protected abstract int getWidgetType();
-}
diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java
deleted file mode 100644
index adcb2f7..0000000
--- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.widget;
-
-import android.appwidget.AppWidgetManager;
-import android.content.Context;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.tool.ResourceParser;
-
-
-public class NoteWidgetProvider_2x extends NoteWidgetProvider {
- @Override
- public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
- super.update(context, appWidgetManager, appWidgetIds);
- }
-
- @Override
- protected int getLayoutId() {
- return R.layout.widget_2x;
- }
-
- @Override
- protected int getBgResourceId(int bgId) {
- return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
- }
-
- @Override
- protected int getWidgetType() {
- return Notes.TYPE_WIDGET_2X;
- }
-}
diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java
deleted file mode 100644
index c12a02e..0000000
--- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.widget;
-
-import android.appwidget.AppWidgetManager;
-import android.content.Context;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.tool.ResourceParser;
-
-
-public class NoteWidgetProvider_4x extends NoteWidgetProvider {
- @Override
- public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
- super.update(context, appWidgetManager, appWidgetIds);
- }
-
- protected int getLayoutId() {
- return R.layout.widget_4x;
- }
-
- @Override
- protected int getBgResourceId(int bgId) {
- return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
- }
-
- @Override
- protected int getWidgetType() {
- return Notes.TYPE_WIDGET_4X;
- }
-}
diff --git a/app/src/main/res/color/primary_text_dark.xml b/app/src/main/res/color/primary_text_dark.xml
deleted file mode 100644
index 7c85459..0000000
--- a/app/src/main/res/color/primary_text_dark.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/color/secondary_text_dark.xml b/app/src/main/res/color/secondary_text_dark.xml
deleted file mode 100644
index c1c2384..0000000
--- a/app/src/main/res/color/secondary_text_dark.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/drawable-hdpi/bg_btn_set_color.png b/app/src/main/res/drawable-hdpi/bg_btn_set_color.png
deleted file mode 100644
index 5eb5d44..0000000
Binary files a/app/src/main/res/drawable-hdpi/bg_btn_set_color.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/bg_color_btn_mask.png b/app/src/main/res/drawable-hdpi/bg_color_btn_mask.png
deleted file mode 100644
index 100db77..0000000
Binary files a/app/src/main/res/drawable-hdpi/bg_color_btn_mask.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/call_record.png b/app/src/main/res/drawable-hdpi/call_record.png
deleted file mode 100644
index fb88ca4..0000000
Binary files a/app/src/main/res/drawable-hdpi/call_record.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/clock.png b/app/src/main/res/drawable-hdpi/clock.png
deleted file mode 100644
index 5f2ae9a..0000000
Binary files a/app/src/main/res/drawable-hdpi/clock.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/delete.png b/app/src/main/res/drawable-hdpi/delete.png
deleted file mode 100644
index 643de3e..0000000
Binary files a/app/src/main/res/drawable-hdpi/delete.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/dropdown_icon.9.png b/app/src/main/res/drawable-hdpi/dropdown_icon.9.png
deleted file mode 100644
index 5525025..0000000
Binary files a/app/src/main/res/drawable-hdpi/dropdown_icon.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_blue.9.png b/app/src/main/res/drawable-hdpi/edit_blue.9.png
deleted file mode 100644
index 55a1856..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_blue.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_green.9.png b/app/src/main/res/drawable-hdpi/edit_green.9.png
deleted file mode 100644
index 2cb2d60..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_green.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_red.9.png b/app/src/main/res/drawable-hdpi/edit_red.9.png
deleted file mode 100644
index bae944a..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_red.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_title_blue.9.png b/app/src/main/res/drawable-hdpi/edit_title_blue.9.png
deleted file mode 100644
index 96e6092..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_title_blue.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_title_green.9.png b/app/src/main/res/drawable-hdpi/edit_title_green.9.png
deleted file mode 100644
index 08d8644..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_title_green.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_title_red.9.png b/app/src/main/res/drawable-hdpi/edit_title_red.9.png
deleted file mode 100644
index 9c430e5..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_title_red.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_title_white.9.png b/app/src/main/res/drawable-hdpi/edit_title_white.9.png
deleted file mode 100644
index 19e8d95..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_title_white.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_title_yellow.9.png b/app/src/main/res/drawable-hdpi/edit_title_yellow.9.png
deleted file mode 100644
index bf8f580..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_title_yellow.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_white.9.png b/app/src/main/res/drawable-hdpi/edit_white.9.png
deleted file mode 100644
index 918f7a6..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_white.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/edit_yellow.9.png b/app/src/main/res/drawable-hdpi/edit_yellow.9.png
deleted file mode 100644
index 10cb642..0000000
Binary files a/app/src/main/res/drawable-hdpi/edit_yellow.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/font_large.png b/app/src/main/res/drawable-hdpi/font_large.png
deleted file mode 100644
index 78cf2e6..0000000
Binary files a/app/src/main/res/drawable-hdpi/font_large.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/font_normal.png b/app/src/main/res/drawable-hdpi/font_normal.png
deleted file mode 100644
index 9de7ced..0000000
Binary files a/app/src/main/res/drawable-hdpi/font_normal.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/font_size_selector_bg.9.png b/app/src/main/res/drawable-hdpi/font_size_selector_bg.9.png
deleted file mode 100644
index be8e64c..0000000
Binary files a/app/src/main/res/drawable-hdpi/font_size_selector_bg.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/font_small.png b/app/src/main/res/drawable-hdpi/font_small.png
deleted file mode 100644
index d3ff104..0000000
Binary files a/app/src/main/res/drawable-hdpi/font_small.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/font_super.png b/app/src/main/res/drawable-hdpi/font_super.png
deleted file mode 100644
index 85b13a1..0000000
Binary files a/app/src/main/res/drawable-hdpi/font_super.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/icon_app.png b/app/src/main/res/drawable-hdpi/icon_app.png
deleted file mode 100644
index 418aadc..0000000
Binary files a/app/src/main/res/drawable-hdpi/icon_app.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_background.png b/app/src/main/res/drawable-hdpi/list_background.png
deleted file mode 100644
index 087e1f9..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_background.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_blue_down.9.png b/app/src/main/res/drawable-hdpi/list_blue_down.9.png
deleted file mode 100644
index b88eebf..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_blue_down.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_blue_middle.9.png b/app/src/main/res/drawable-hdpi/list_blue_middle.9.png
deleted file mode 100644
index 96b1c8b..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_blue_middle.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_blue_single.9.png b/app/src/main/res/drawable-hdpi/list_blue_single.9.png
deleted file mode 100644
index d7e7206..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_blue_single.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_blue_up.9.png b/app/src/main/res/drawable-hdpi/list_blue_up.9.png
deleted file mode 100644
index 632e88c..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_blue_up.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_folder.9.png b/app/src/main/res/drawable-hdpi/list_folder.9.png
deleted file mode 100644
index 829f61b..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_folder.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_footer_bg.9.png b/app/src/main/res/drawable-hdpi/list_footer_bg.9.png
deleted file mode 100644
index 5325c25..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_footer_bg.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_green_down.9.png b/app/src/main/res/drawable-hdpi/list_green_down.9.png
deleted file mode 100644
index 64a39d9..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_green_down.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_green_middle.9.png b/app/src/main/res/drawable-hdpi/list_green_middle.9.png
deleted file mode 100644
index 897325a..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_green_middle.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_green_single.9.png b/app/src/main/res/drawable-hdpi/list_green_single.9.png
deleted file mode 100644
index c83405f..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_green_single.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_green_up.9.png b/app/src/main/res/drawable-hdpi/list_green_up.9.png
deleted file mode 100644
index 141f9e1..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_green_up.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_red_down.9.png b/app/src/main/res/drawable-hdpi/list_red_down.9.png
deleted file mode 100644
index 4224309..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_red_down.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_red_middle.9.png b/app/src/main/res/drawable-hdpi/list_red_middle.9.png
deleted file mode 100644
index 9988f17..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_red_middle.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_red_single.9.png b/app/src/main/res/drawable-hdpi/list_red_single.9.png
deleted file mode 100644
index 587c348..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_red_single.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_red_up.9.png b/app/src/main/res/drawable-hdpi/list_red_up.9.png
deleted file mode 100644
index 46b4757..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_red_up.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_white_down.9.png b/app/src/main/res/drawable-hdpi/list_white_down.9.png
deleted file mode 100644
index 29f9d8c..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_white_down.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_white_middle.9.png b/app/src/main/res/drawable-hdpi/list_white_middle.9.png
deleted file mode 100644
index 77a4ab4..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_white_middle.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_white_single.9.png b/app/src/main/res/drawable-hdpi/list_white_single.9.png
deleted file mode 100644
index 3e79189..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_white_single.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_white_up.9.png b/app/src/main/res/drawable-hdpi/list_white_up.9.png
deleted file mode 100644
index e23cd5c..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_white_up.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_yellow_down.9.png b/app/src/main/res/drawable-hdpi/list_yellow_down.9.png
deleted file mode 100644
index 31cfc1e..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_yellow_down.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_yellow_middle.9.png b/app/src/main/res/drawable-hdpi/list_yellow_middle.9.png
deleted file mode 100644
index b6549b2..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_yellow_middle.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_yellow_single.9.png b/app/src/main/res/drawable-hdpi/list_yellow_single.9.png
deleted file mode 100644
index 3faf507..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_yellow_single.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/list_yellow_up.9.png b/app/src/main/res/drawable-hdpi/list_yellow_up.9.png
deleted file mode 100644
index 4ae791c..0000000
Binary files a/app/src/main/res/drawable-hdpi/list_yellow_up.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/menu_delete.png b/app/src/main/res/drawable-hdpi/menu_delete.png
deleted file mode 100644
index ccdfc4b..0000000
Binary files a/app/src/main/res/drawable-hdpi/menu_delete.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/menu_move.png b/app/src/main/res/drawable-hdpi/menu_move.png
deleted file mode 100644
index 1140b71..0000000
Binary files a/app/src/main/res/drawable-hdpi/menu_move.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/new_note_normal.png b/app/src/main/res/drawable-hdpi/new_note_normal.png
deleted file mode 100644
index e24e0d1..0000000
Binary files a/app/src/main/res/drawable-hdpi/new_note_normal.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/new_note_pressed.png b/app/src/main/res/drawable-hdpi/new_note_pressed.png
deleted file mode 100644
index c748936..0000000
Binary files a/app/src/main/res/drawable-hdpi/new_note_pressed.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png b/app/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png
deleted file mode 100644
index fc49552..0000000
Binary files a/app/src/main/res/drawable-hdpi/note_edit_color_selector_panel.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/notification.png b/app/src/main/res/drawable-hdpi/notification.png
deleted file mode 100644
index b13ab4a..0000000
Binary files a/app/src/main/res/drawable-hdpi/notification.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/search_result.png b/app/src/main/res/drawable-hdpi/search_result.png
deleted file mode 100644
index ff2befd..0000000
Binary files a/app/src/main/res/drawable-hdpi/search_result.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/selected.png b/app/src/main/res/drawable-hdpi/selected.png
deleted file mode 100644
index b889bef..0000000
Binary files a/app/src/main/res/drawable-hdpi/selected.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/title_alert.png b/app/src/main/res/drawable-hdpi/title_alert.png
deleted file mode 100644
index 544ee9c..0000000
Binary files a/app/src/main/res/drawable-hdpi/title_alert.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/title_bar_bg.9.png b/app/src/main/res/drawable-hdpi/title_bar_bg.9.png
deleted file mode 100644
index eb6bff0..0000000
Binary files a/app/src/main/res/drawable-hdpi/title_bar_bg.9.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_2x_blue.png b/app/src/main/res/drawable-hdpi/widget_2x_blue.png
deleted file mode 100644
index a1707f4..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_2x_blue.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_2x_green.png b/app/src/main/res/drawable-hdpi/widget_2x_green.png
deleted file mode 100644
index f86886c..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_2x_green.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_2x_red.png b/app/src/main/res/drawable-hdpi/widget_2x_red.png
deleted file mode 100644
index 0e66c29..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_2x_red.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_2x_white.png b/app/src/main/res/drawable-hdpi/widget_2x_white.png
deleted file mode 100644
index 5f0619a..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_2x_white.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_2x_yellow.png b/app/src/main/res/drawable-hdpi/widget_2x_yellow.png
deleted file mode 100644
index 12d1c2b..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_2x_yellow.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_4x_blue.png b/app/src/main/res/drawable-hdpi/widget_4x_blue.png
deleted file mode 100644
index 9183738..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_4x_blue.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_4x_green.png b/app/src/main/res/drawable-hdpi/widget_4x_green.png
deleted file mode 100644
index fa8b452..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_4x_green.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_4x_red.png b/app/src/main/res/drawable-hdpi/widget_4x_red.png
deleted file mode 100644
index 62de074..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_4x_red.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_4x_white.png b/app/src/main/res/drawable-hdpi/widget_4x_white.png
deleted file mode 100644
index a37d67c..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_4x_white.png and /dev/null differ
diff --git a/app/src/main/res/drawable-hdpi/widget_4x_yellow.png b/app/src/main/res/drawable-hdpi/widget_4x_yellow.png
deleted file mode 100644
index d7c5fa4..0000000
Binary files a/app/src/main/res/drawable-hdpi/widget_4x_yellow.png and /dev/null differ
diff --git a/app/src/main/res/drawable/ic_add.xml b/app/src/main/res/drawable/ic_add.xml
deleted file mode 100644
index 52e3394..0000000
--- a/app/src/main/res/drawable/ic_add.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/ic_edit.xml b/app/src/main/res/drawable/ic_edit.xml
deleted file mode 100644
index 0b61789..0000000
--- a/app/src/main/res/drawable/ic_edit.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml
deleted file mode 100644
index 07d5da9..0000000
--- a/app/src/main/res/drawable/ic_launcher_background.xml
+++ /dev/null
@@ -1,170 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml
deleted file mode 100644
index 2b068d1..0000000
--- a/app/src/main/res/drawable/ic_launcher_foreground.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/drawable/ic_note_empty.xml b/app/src/main/res/drawable/ic_note_empty.xml
deleted file mode 100644
index e01ea77..0000000
--- a/app/src/main/res/drawable/ic_note_empty.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/new_note.xml b/app/src/main/res/drawable/new_note.xml
deleted file mode 100644
index 2154ebc..0000000
--- a/app/src/main/res/drawable/new_note.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/note_item_background.xml b/app/src/main/res/drawable/note_item_background.xml
deleted file mode 100644
index 5004626..0000000
--- a/app/src/main/res/drawable/note_item_background.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
-
-
-
-
- -
-
-
-
-
- -
-
-
-
-
- -
-
-
-
-
- -
-
-
-
-
-
diff --git a/app/src/main/res/layout/account_dialog_title.xml b/app/src/main/res/layout/account_dialog_title.xml
deleted file mode 100644
index 7717112..0000000
--- a/app/src/main/res/layout/account_dialog_title.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
deleted file mode 100644
index 80c956c..0000000
--- a/app/src/main/res/layout/activity_main.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/add_account_text.xml b/app/src/main/res/layout/add_account_text.xml
deleted file mode 100644
index c799178..0000000
--- a/app/src/main/res/layout/add_account_text.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/breadcrumb_item.xml b/app/src/main/res/layout/breadcrumb_item.xml
deleted file mode 100644
index 6316b1b..0000000
--- a/app/src/main/res/layout/breadcrumb_item.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
diff --git a/app/src/main/res/layout/breadcrumb_layout.xml b/app/src/main/res/layout/breadcrumb_layout.xml
deleted file mode 100644
index c625053..0000000
--- a/app/src/main/res/layout/breadcrumb_layout.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/datetime_picker.xml b/app/src/main/res/layout/datetime_picker.xml
deleted file mode 100644
index f10d592..0000000
--- a/app/src/main/res/layout/datetime_picker.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/dialog_edit_text.xml b/app/src/main/res/layout/dialog_edit_text.xml
deleted file mode 100644
index 361b39a..0000000
--- a/app/src/main/res/layout/dialog_edit_text.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/folder_list_item.xml b/app/src/main/res/layout/folder_list_item.xml
deleted file mode 100644
index 77e8148..0000000
--- a/app/src/main/res/layout/folder_list_item.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/note_edit.xml b/app/src/main/res/layout/note_edit.xml
deleted file mode 100644
index 8c449c4..0000000
--- a/app/src/main/res/layout/note_edit.xml
+++ /dev/null
@@ -1,416 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/note_edit_list_item.xml b/app/src/main/res/layout/note_edit_list_item.xml
deleted file mode 100644
index a885f9c..0000000
--- a/app/src/main/res/layout/note_edit_list_item.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/note_item.xml b/app/src/main/res/layout/note_item.xml
deleted file mode 100644
index b23af8f..0000000
--- a/app/src/main/res/layout/note_item.xml
+++ /dev/null
@@ -1,105 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/note_list.xml b/app/src/main/res/layout/note_list.xml
deleted file mode 100644
index c157627..0000000
--- a/app/src/main/res/layout/note_list.xml
+++ /dev/null
@@ -1,101 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/note_list_dropdown_menu.xml b/app/src/main/res/layout/note_list_dropdown_menu.xml
deleted file mode 100644
index 3fa271d..0000000
--- a/app/src/main/res/layout/note_list_dropdown_menu.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/note_list_footer.xml b/app/src/main/res/layout/note_list_footer.xml
deleted file mode 100644
index 5ca7b22..0000000
--- a/app/src/main/res/layout/note_list_footer.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/settings_header.xml b/app/src/main/res/layout/settings_header.xml
deleted file mode 100644
index 5eb8c50..0000000
--- a/app/src/main/res/layout/settings_header.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/layout/sidebar_folder_item.xml b/app/src/main/res/layout/sidebar_folder_item.xml
deleted file mode 100644
index f5985ea..0000000
--- a/app/src/main/res/layout/sidebar_folder_item.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/sidebar_layout.xml b/app/src/main/res/layout/sidebar_layout.xml
deleted file mode 100644
index 738c0aa..0000000
--- a/app/src/main/res/layout/sidebar_layout.xml
+++ /dev/null
@@ -1,174 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/widget_2x.xml b/app/src/main/res/layout/widget_2x.xml
deleted file mode 100644
index 55970ce..0000000
--- a/app/src/main/res/layout/widget_2x.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/layout/widget_4x.xml b/app/src/main/res/layout/widget_4x.xml
deleted file mode 100644
index dc9bb51..0000000
--- a/app/src/main/res/layout/widget_4x.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/call_note_edit.xml b/app/src/main/res/menu/call_note_edit.xml
deleted file mode 100644
index 02c0528..0000000
--- a/app/src/main/res/menu/call_note_edit.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/call_record_folder.xml b/app/src/main/res/menu/call_record_folder.xml
deleted file mode 100644
index c664346..0000000
--- a/app/src/main/res/menu/call_record_folder.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/note_edit.xml b/app/src/main/res/menu/note_edit.xml
deleted file mode 100644
index 35cacd1..0000000
--- a/app/src/main/res/menu/note_edit.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/menu/note_list.xml b/app/src/main/res/menu/note_list.xml
deleted file mode 100644
index 42ea736..0000000
--- a/app/src/main/res/menu/note_list.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/note_list_dropdown.xml b/app/src/main/res/menu/note_list_dropdown.xml
deleted file mode 100644
index 7cbaadc..0000000
--- a/app/src/main/res/menu/note_list_dropdown.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/menu/note_list_multi_select.xml b/app/src/main/res/menu/note_list_multi_select.xml
deleted file mode 100644
index dfcd448..0000000
--- a/app/src/main/res/menu/note_list_multi_select.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/note_list_options.xml b/app/src/main/res/menu/note_list_options.xml
deleted file mode 100644
index daac008..0000000
--- a/app/src/main/res/menu/note_list_options.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/menu/note_list_toolbar_multi.xml b/app/src/main/res/menu/note_list_toolbar_multi.xml
deleted file mode 100644
index 1b43649..0000000
--- a/app/src/main/res/menu/note_list_toolbar_multi.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/menu/sub_folder.xml b/app/src/main/res/menu/sub_folder.xml
deleted file mode 100644
index b00de26..0000000
--- a/app/src/main/res/menu/sub_folder.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
deleted file mode 100644
index 6f3b755..0000000
--- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
deleted file mode 100644
index 6f3b755..0000000
--- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp
deleted file mode 100644
index c209e78..0000000
Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
deleted file mode 100644
index b2dfe3d..0000000
Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp
deleted file mode 100644
index 4f0f1d6..0000000
Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
deleted file mode 100644
index 62b611d..0000000
Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
deleted file mode 100644
index 948a307..0000000
Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
deleted file mode 100644
index 1b9a695..0000000
Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
deleted file mode 100644
index 28d4b77..0000000
Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
deleted file mode 100644
index 9287f50..0000000
Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
deleted file mode 100644
index aa7d642..0000000
Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and /dev/null differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
deleted file mode 100644
index 9126ae3..0000000
Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and /dev/null differ
diff --git a/app/src/main/res/raw-zh-rCN/introduction b/app/src/main/res/raw-zh-rCN/introduction
deleted file mode 100644
index 7188359..0000000
--- a/app/src/main/res/raw-zh-rCN/introduction
+++ /dev/null
@@ -1,7 +0,0 @@
-欢迎使用MIUI便签!
-
- 无论从软件中直接添加,还是从桌面拖出widget,MIUI便签能让你快速建立和保存便签;
-
- 除了调整文字大小、便签背景、文件夹等基础功能外,你会发现MIUI便签也提供了清单模式、便签提醒、软件加密、导出到SD卡、同步google task的高级功能,让你的生活记录更加美好和安全;
-
- 来分享你的使用体验吧:http://www.miui.com/index.php
diff --git a/app/src/main/res/raw/introduction b/app/src/main/res/raw/introduction
deleted file mode 100644
index 269cf7b..0000000
--- a/app/src/main/res/raw/introduction
+++ /dev/null
@@ -1 +0,0 @@
-Welcome to use MIUI notes!
\ No newline at end of file
diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml
deleted file mode 100644
index d2c68d1..0000000
--- a/app/src/main/res/values-night/themes.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values-zh-rCN/arrays.xml b/app/src/main/res/values-zh-rCN/arrays.xml
deleted file mode 100644
index a092386..0000000
--- a/app/src/main/res/values-zh-rCN/arrays.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
- - 短信
- - 邮件
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
deleted file mode 100644
index 61b9801..0000000
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,136 +0,0 @@
-
-
-
-
-
- 便签
- 便签2x2
- 便签4x4
- 没有关联内容,点击新建便签。
- 访客模式下,便签内容不可见
- ...
- 新建便签
- 成功删除提醒
- 创建提醒
- 已过期
- yyyyMMdd
- MM月dd日 kk:mm
- 知道了
- 查看
- 呼叫电话
- 发送邮件
- 浏览网页
- 打开地图
-
- 新建文件夹
- 导出文本
- 同步
- 取消同步
- 设置
- 搜索
- 删除
- 移动到文件夹
- 选中了 %d 项
- 没有选中项,操作无效
- 全选
- 取消全选
- 文字大小
- 小
- 正常
- 大
- 超大
- 进入清单模式
- 退出清单模式
- 查看文件夹
- 刪除文件夹
- 修改文件夹名称
- 文件夹 %1$s 已存在,请重新命名
- 分享
- 发送到桌面
- 提醒我
- 删除提醒
- 选择文件夹
- 上一级文件夹
- 已添加到桌面
- 删除
- 确认要删除所选的 %d 条便签吗?
- 确认要删除该条便签吗?
- 确认删除文件夹及所包含的便签吗?
- 已将所选 %1$d 条便签移到 %2$s 文件夹
-
- SD卡被占用,不能操作
- 导出文本时发生错误,请检查SD卡
- 要查看的便签不存在
- 不能为空便签设置闹钟提醒
- 不能将空便签发送到桌面
- 导出成功
- 导出失败
- 已将文本文件(%1$s)输出至SD卡(%2$s)目录
-
- 同步便签...
- 同步成功
- 同步失败
- 同步已取消
- 与%1$s同步成功
- 同步失败,请检查网络和帐号设置
- 同步失败,发生内部错误
- 同步已取消
- 登录%1$s...
- 正在获取服务器便签列表...
- 正在同步本地便签...
-
- 设置
- 同步账号
- 与google task同步便签记录
- 上次同步于 %1$s
- 添加账号
- 更换账号
- 删除账号
- 取消
- 立即同步
- 取消同步
- 当前帐号 %1$s
- 如更换同步帐号,过去的帐号同步信息将被清空,再次切换的同时可能会造成数据重复
- 同步便签
- 请选择google帐号,便签将与该帐号的google task内容同步。
- 正在同步中,不能修改同步帐号
- 同步帐号已设置为%1$s
- 新建便签背景颜色随机
- 删除
- 通话便签
- 请输入名称
- 正在搜索便签
- 搜索便签
- 便签中的文字
- 便签
- 设置
- 取消
-
- %1$s 条符合"%2$s "的搜索结果
-
-
-
- 我的便签
- %d 个便签
- 创建文件夹
- 文件夹名称
- 文件夹名称不能为空
- 文件夹名称过长(最多50个字符)
- 回收站
- 创建文件夹成功
-
-
diff --git a/app/src/main/res/values-zh-rTW/arrays.xml b/app/src/main/res/values-zh-rTW/arrays.xml
deleted file mode 100644
index 5297209..0000000
--- a/app/src/main/res/values-zh-rTW/arrays.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
- - 短信
- - 郵件
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
deleted file mode 100644
index 3c41894..0000000
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,127 +0,0 @@
-
-
-
-
-
- 便簽
- 便簽2x2
- 便簽4x4
- 沒有關聯內容,點擊新建便簽。
- 訪客模式下,便籤內容不可見
- ...
- 新建便簽
- 成功刪除提醒
- 創建提醒
- 已過期
- yyyyMMdd
- MM月dd日 kk:mm
- 知道了
- 查看
- 呼叫電話
- 發送郵件
- 浏覽網頁
- 打開地圖
- 已將所選 %1$d 便籤移到 %2$s 文件夾
-
- 新建文件夾
- 導出文本
- 同步
- 取消同步
- 設置
- 搜尋
- 刪除
- 移動到文件夾
- 選中了 %d 項
- 沒有選中項,操作無效
- 全選
- 取消全選
- 文字大小
- 小
- 正常
- 大
- 超大
- 進入清單模式
- 退出清單模式
- 查看文件夾
- 刪除文件夾
- 修改文件夾名稱
- 文件夾 %1$s 已存在,請重新命名
- 分享
- 發送到桌面
- 提醒我
- 刪除提醒
- 選擇文件夾
- 上一級文件夾
- 已添加到桌面
- 刪除
- 确认要刪除所選的 %d 條便籤嗎?
- 确认要删除該條便籤嗎?
- 確認刪除檔夾及所包含的便簽嗎?
- SD卡被佔用,不能操作
- 導出TXT時發生錯誤,請檢查SD卡
- 要查看的便籤不存在
- 不能爲空便籤設置鬧鐘提醒
- 不能將空便籤發送到桌面
- 導出成功
- 導出失敗
- 已將文本文件(%1$s)導出至SD(%2$s)目錄
-
- 同步便簽...
- 同步成功
- 同步失敗
- 同步已取消
- 與%1$s同步成功
- 同步失敗,請檢查網絡和帳號設置
- 同步失敗,發生內部錯誤
- 同步已取消
- 登陸%1$s...
- 正在獲取服務器便籤列表...
- 正在同步本地便籤...
-
- 設置
- 同步賬號
- 与google task同步便簽記錄
- 上次同步于 %1$s
- 添加賬號
- 更換賬號
- 刪除賬號
- 取消
- 立即同步
- 取消同步
- 當前帳號 %1$s
- 如更換同步帳號,過去的帳號同步信息將被清空,再次切換的同時可能會造成數據重復
- 同步便簽
- 請選擇google帳號,便簽將與該帳號的google task內容同步。
- 正在同步中,不能修改同步帳號
- 同步帳號已設置為%1$s
- 新建便籤背景顏色隨機
-
- 刪除
- 通話便籤
- 請輸入名稱
-
- 正在搜索便籤
- 搜索便籤
- 便籤中的文字
- 便籤
- 設置
- 取消
-
- %1$s 條符合”%2$s “的搜尋結果
-
-
-
diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml
deleted file mode 100644
index e00210b..0000000
--- a/app/src/main/res/values/arrays.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
- - -%s
- - --%s
- - --%s
- - --%s
-
-
-
- - Messaging
- - Email
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml
deleted file mode 100644
index 82d81bf..0000000
--- a/app/src/main/res/values/colors.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
- #335b5b5b
- #1976D2
- #FFFFFF
- #FAFAFA
-
diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml
deleted file mode 100644
index 194e84f..0000000
--- a/app/src/main/res/values/dimens.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
- 33sp
- 26sp
- 20sp
- 17sp
- 14sp
-
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
deleted file mode 100644
index a4b4991..0000000
--- a/app/src/main/res/values/strings.xml
+++ /dev/null
@@ -1,157 +0,0 @@
-
-
-
-
-
- Notes
- Notes 2x2
- Notes 4x4
- No associated note found, click to create associated note.
- Privacy mode,can not see note content
- ...
- Add note
- Delete reminder successfully
- Set reminder
- Expired
- yyyyMMdd
- MMMd kk:mm
- Got it
- Take a look
- Call
- Send email
- Browse web
- Open map
-
- /MIUI/notes/
- notes_%s.txt
-
- (%d)
- New Folder
- Export text
- Sync
- Cancel syncing
- Settings
- Search
- Delete
- Move to folder
- %d selected
- Nothing selected, the operation is invalid
- Select all
- Deselect all
- Font size
- Small
- Medium
- Large
- Super
- Enter check list
- Leave check list
- View folder
- Delete folder
- Change folder name
- The folder %1$s exist, please rename
- Share
- Send to home
- Remind me
- Delete reminder
- Select folder
- Parent folder
- Note added to home
- Confirm to delete folder and its notes?
- Delete selected notes
- Confirm to delete the selected %d notes?
- Confirm to delete this note?
- Have moved selected %1$d notes to %2$s folder
-
- SD card busy, not available now
- Export failed, please check SD card
- The note is not exist
- Sorry, can not set clock on empty note
- Sorry, can not send and empty note to home
- Invalid intent
- Unsupported intent action
- Export successful
- Export fail
- Export text file (%1$s) to SD (%2$s) directory
-
- Syncing notes...
- Sync is successful
- Sync is failed
- Sync is canceled
- Sync is successful with account %1$s
- Sync failed, please check network and account settings
- Sync failed, internal error occurs
- Sync is canceled
- Logging into %1$s...
- Getting remote note list...
- Synchronize local notes with Google Task...
-
- Settings
- Sync account
- Sync notes with google task
- Last sync time %1$s
- yyyy-MM-dd hh:mm:ss
- Add account
- Change sync account
- Remove sync account
- Cancel
- Sync immediately
- Cancel syncing
- Current account %1$s
- All sync related information will be deleted, which may result in duplicated items sometime
- Sync notes
- Please select a google account. Local notes will be synced with google task.
- Cannot change the account because sync is in progress
- %1$s has been set as the sync account
- New note background color random
-
- Delete
- Call notes
- Input name
-
- Searching Notes
- Search notes
- Text in your notes
- Notes
- set
- cancel
-
- %1$s result for \"%2$s \"
-
- %1$s results for \"%2$s \"
-
-
- 暂无便签,点击右下角按钮创建
- 空便签图标
- Edit note
-
- Login
- Export
- Settings
- Trash
- My Notes
- Close sidebar
- Create folder
- %d notes
- Create folder
- Folder name
- Folder name cannot be empty
- Folder name too long (max 50 characters)
- Folder already exists
- Folder created successfully
- Pin
- Unpin
-
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml
deleted file mode 100644
index c1eddb2..0000000
--- a/app/src/main/res/values/styles.xml
+++ /dev/null
@@ -1,68 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
deleted file mode 100644
index ca2f0be..0000000
--- a/app/src/main/res/values/themes.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml
deleted file mode 100644
index 4df9255..0000000
--- a/app/src/main/res/xml/backup_rules.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
deleted file mode 100644
index 9ee9997..0000000
--- a/app/src/main/res/xml/data_extraction_rules.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/xml/preferences.xml b/app/src/main/res/xml/preferences.xml
deleted file mode 100644
index fe58f8f..0000000
--- a/app/src/main/res/xml/preferences.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/xml/searchable.xml b/app/src/main/res/xml/searchable.xml
deleted file mode 100644
index bf74f14..0000000
--- a/app/src/main/res/xml/searchable.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
diff --git a/app/src/main/res/xml/widget_2x_info.xml b/app/src/main/res/xml/widget_2x_info.xml
deleted file mode 100644
index ac8b225..0000000
--- a/app/src/main/res/xml/widget_2x_info.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
diff --git a/app/src/main/res/xml/widget_4x_info.xml b/app/src/main/res/xml/widget_4x_info.xml
deleted file mode 100644
index cf79f9c..0000000
--- a/app/src/main/res/xml/widget_4x_info.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
diff --git a/app/src/test/java/net/micode/notes/ExampleUnitTest.java b/app/src/test/java/net/micode/notes/ExampleUnitTest.java
deleted file mode 100644
index 296adc2..0000000
--- a/app/src/test/java/net/micode/notes/ExampleUnitTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package net.micode.notes;
-
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-/**
- * Example local unit test, which will execute on the development machine (host).
- *
- * @see Testing documentation
- */
-public class ExampleUnitTest {
- @Test
- public void addition_isCorrect() {
- assertEquals(4, 2 + 2);
- }
-}
\ No newline at end of file
diff --git a/app/src/test/java/net/micode/notes/data/FolderDatabaseTest.java b/app/src/test/java/net/micode/notes/data/FolderDatabaseTest.java
deleted file mode 100644
index 35eaabc..0000000
--- a/app/src/test/java/net/micode/notes/data/FolderDatabaseTest.java
+++ /dev/null
@@ -1,1287 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-import android.content.ContentValues;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-/**
- * 文件夹数据库操作测试类
- *
- * 测试文件夹的创建、读取、更新、删除等数据库操作
- * 测试文件夹树查询、notes_count维护、系统文件夹保护等功能
- */
-public class FolderDatabaseTest {
-
- /**
- * 测试数据库实例(内存数据库)
- */
- private SQLiteDatabase mDatabase;
-
- /**
- * 测试用的数据库帮助类
- */
- private NotesDatabaseHelper mHelper;
-
- /**
- * 测试前的初始化
- * 创建内存数据库,初始化表结构和系统文件夹
- */
- @Before
- public void setUp() {
- // 创建内存数据库用于测试
- mDatabase = SQLiteDatabase.openDatabase(":memory:", null,
- SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
-
- // 创建数据库帮助类(但不使用其数据库实例)
- mHelper = new NotesDatabaseHelper(null);
-
- // 手动创建表结构和触发器
- mHelper.createNoteTable(mDatabase);
- mHelper.createDataTable(mDatabase);
- }
-
- /**
- * 测试后的清理
- * 关闭数据库连接
- */
- @After
- public void tearDown() {
- if (mDatabase != null && mDatabase.isOpen()) {
- mDatabase.close();
- }
- }
-
- // ==================== 测试1:文件夹CRUD操作 ====================
-
- /**
- * 测试创建文件夹
- * 验证能够成功创建文件夹,并且返回的ID大于0
- */
- @Test
- public void testCreateFolder() {
- // 准备测试数据
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
-
- // 执行插入
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
-
- // 验证结果
- assertTrue("文件夹ID应该大于0", folderId > 0);
-
- // 验证数据是否正确插入
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
-
- assertNotNull("查询结果不应该为null", cursor);
- assertTrue("应该找到一条记录", cursor.moveToFirst());
- assertEquals("类型应该为文件夹", Notes.TYPE_FOLDER, cursor.getInt(cursor.getColumnIndexOrThrow(Notes.NoteColumns.TYPE)));
- assertEquals("名称应该正确", "测试文件夹", cursor.getString(cursor.getColumnIndexOrThrow(Notes.NoteColumns.SNIPPET)));
- assertEquals("父文件夹ID应该正确", Notes.ID_ROOT_FOLDER, cursor.getLong(cursor.getColumnIndexOrThrow(Notes.NoteColumns.PARENT_ID)));
-
- cursor.close();
- }
-
- /**
- * 测试读取文件夹
- * 验证能够正确读取文件夹信息
- */
- @Test
- public void testReadFolder() {
- // 先创建一个文件夹
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
-
- // 读取文件夹
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(folderId), String.valueOf(Notes.TYPE_FOLDER)},
- null, null, null
- );
-
- assertNotNull("查询结果不应该为null", cursor);
- assertTrue("应该找到一条记录", cursor.moveToFirst());
-
- // 验证数据
- assertEquals("ID应该匹配", folderId, cursor.getLong(cursor.getColumnIndexOrThrow(Notes.NoteColumns.ID)));
- assertEquals("名称应该正确", "测试文件夹", cursor.getString(cursor.getColumnIndexOrThrow(Notes.NoteColumns.SNIPPET)));
-
- cursor.close();
- }
-
- /**
- * 测试更新文件夹
- * 验证能够成功更新文件夹名称
- */
- @Test
- public void testUpdateFolder() {
- // 先创建一个文件夹
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
-
- // 更新文件夹
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.SNIPPET, "更新后的文件夹名称");
- int updated = mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)}
- );
-
- // 验证更新
- assertEquals("应该更新1条记录", 1, updated);
-
- // 验证数据是否正确更新
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
-
- assertTrue("应该找到一条记录", cursor.moveToFirst());
- assertEquals("名称应该已更新", "更新后的文件夹名称", cursor.getString(cursor.getColumnIndexOrThrow(Notes.NoteColumns.SNIPPET)));
-
- cursor.close();
- }
-
- /**
- * 测试删除文件夹(物理删除)
- * 验证能够成功删除文件夹
- */
- @Test
- public void testDeleteFolder() {
- // 先创建一个文件夹
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
-
- // 删除文件夹
- int deleted = mDatabase.delete(
- NotesDatabaseHelper.TABLE.NOTE,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)}
- );
-
- // 验证删除
- assertEquals("应该删除1条记录", 1, deleted);
-
- // 验证数据是否已删除
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
-
- assertFalse("不应该找到任何记录", cursor.moveToFirst());
- cursor.close();
- }
-
- /**
- * 测试文件夹名称不能为空
- * 验证当尝试创建空名称的文件夹时,应该失败或使用默认值
- */
- @Test
- public void testFolderNameCannotBeNull() {
- // 尝试创建名称为空的文件夹
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, ""); // 空字符串
-
- // 尝试插入
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
-
- // SQLite允许空字符串,但应该使用默认值
- assertTrue("文件夹ID应该大于0", folderId > 0);
-
- // 验证数据
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
-
- assertTrue("应该找到一条记录", cursor.moveToFirst());
- // 数据库定义了DEFAULT '',所以应该接受空字符串
- assertEquals("名称应该为空字符串", "", cursor.getString(cursor.getColumnIndexOrThrow(Notes.NoteColumns.SNIPPET)));
-
- cursor.close();
- }
-
- /**
- * 测试创建嵌套文件夹
- * 验证能够创建多级嵌套的文件夹结构
- */
- @Test
- public void testCreateNestedFolder() {
- // 创建第一级文件夹
- ContentValues folder1 = new ContentValues();
- folder1.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1.put(Notes.NoteColumns.SNIPPET, "一级文件夹");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1);
-
- // 创建第二级文件夹
- ContentValues folder2 = new ContentValues();
- folder2.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2.put(Notes.NoteColumns.SNIPPET, "二级文件夹");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2);
-
- // 创建第三级文件夹
- ContentValues folder3 = new ContentValues();
- folder3.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- folder3.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder3.put(Notes.NoteColumns.SNIPPET, "三级文件夹");
- long folder3Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder3);
-
- // 验证所有文件夹都创建成功
- assertTrue("一级文件夹ID应该大于0", folder1Id > 0);
- assertTrue("二级文件夹ID应该大于0", folder2Id > 0);
- assertTrue("三级文件夹ID应该大于0", folder3Id > 0);
-
- // 验证层级关系
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
-
- assertTrue("应该找到二级文件夹", cursor.moveToFirst());
- assertEquals("二级文件夹的父ID应该是一级文件夹", folder1Id, cursor.getLong(cursor.getColumnIndexOrThrow(Notes.NoteColumns.PARENT_ID)));
-
- cursor.close();
- }
-
- /**
- * 测试查询特定父文件夹下的所有文件夹
- * 验证能够正确查询某个文件夹下的所有子文件夹
- */
- @Test
- public void testQueryFoldersByParentId() {
- // 在根文件夹下创建多个子文件夹
- for (int i = 0; i < 5; i++) {
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "文件夹" + i);
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
- }
-
- // 查询根文件夹下的所有文件夹
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.PARENT_ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER), String.valueOf(Notes.TYPE_FOLDER)},
- null, null, null
- );
-
- assertNotNull("查询结果不应该为null", cursor);
- assertEquals("应该找到5个文件夹", 5, cursor.getCount());
-
- // 验证每个文件夹的父ID都是根文件夹
- while (cursor.moveToNext()) {
- assertEquals("父ID应该都是根文件夹", Notes.ID_ROOT_FOLDER, cursor.getLong(cursor.getColumnIndexOrThrow(Notes.NoteColumns.PARENT_ID)));
- assertEquals("类型应该都是文件夹", Notes.TYPE_FOLDER, cursor.getInt(cursor.getColumnIndexOrThrow(Notes.NoteColumns.TYPE)));
- }
-
- cursor.close();
- }
-
- /**
- * 测试查询所有文件夹(不包含系统文件夹)
- * 验证能够查询所有用户创建的文件夹
- */
- @Test
- public void testQueryAllUserFolders() {
- // 创建多个用户文件夹
- for (int i = 0; i < 3; i++) {
- ContentValues values = new ContentValues();
- values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(Notes.NoteColumns.SNIPPET, "用户文件夹" + i);
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
- }
-
- // 查询所有文件夹(排除系统文件夹)
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.TYPE + "=? AND " + Notes.NoteColumns.ID + ">0",
- new String[]{String.valueOf(Notes.TYPE_FOLDER)},
- null, null, null
- );
-
- assertNotNull("查询结果不应该为null", cursor);
- assertEquals("应该找到3个用户文件夹", 3, cursor.getCount());
-
- cursor.close();
- }
-
- // ==================== 测试2:notes_count维护 ====================
-
- /**
- * 测试插入笔记时增加文件夹的notes_count
- * 验证触发器是否正确维护notes_count
- */
- @Test
- public void testIncreaseNotesCountOnInsert() {
- // 创建一个文件夹
- ContentValues folderValues = new ContentValues();
- folderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folderValues.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folderValues);
-
- // 验证初始notes_count为0
- Cursor folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("初始notes_count应该为0", 0, folderCursor.getInt(0));
- folderCursor.close();
-
- // 向该文件夹插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 验证notes_count增加
- folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("notes_count应该增加到1", 1, folderCursor.getInt(0));
- folderCursor.close();
-
- // 插入第二条笔记
- noteValues.clear();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记2");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 验证notes_count增加到2
- folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("notes_count应该增加到2", 2, folderCursor.getInt(0));
- folderCursor.close();
- }
-
- /**
- * 测试删除笔记时减少文件夹的notes_count
- * 验证触发器是否正确维护notes_count
- */
- @Test
- public void testDecreaseNotesCountOnDelete() {
- // 创建一个文件夹
- ContentValues folderValues = new ContentValues();
- folderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folderValues.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folderValues);
-
- // 向该文件夹插入3条笔记
- for (int i = 0; i < 3; i++) {
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记" + i);
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
- }
-
- // 验证notes_count为3
- Cursor folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("notes_count应该为3", 3, folderCursor.getInt(0));
- folderCursor.close();
-
- // 删除一条笔记
- // 先查询笔记ID
- Cursor noteCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.ID},
- Notes.NoteColumns.PARENT_ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(folderId), String.valueOf(Notes.TYPE_NOTE)},
- null, null, null
- );
- assertTrue("应该找到笔记", noteCursor.moveToFirst());
- long noteId = noteCursor.getLong(0);
- noteCursor.close();
-
- // 删除笔记
- mDatabase.delete(
- NotesDatabaseHelper.TABLE.NOTE,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(noteId)}
- );
-
- // 验证notes_count减少到2
- folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("notes_count应该减少到2", 2, folderCursor.getInt(0));
- folderCursor.close();
- }
-
- /**
- * 测试笔记移动时更新两个文件夹的notes_count
- * 验证笔记从一个文件夹移动到另一个文件夹时,两个文件夹的notes_count都正确更新
- */
- @Test
- public void testUpdateNotesCountOnMove() {
- // 创建两个文件夹
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 向文件夹1插入2条笔记
- for (int i = 0; i < 2; i++) {
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记" + i);
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
- }
-
- // 验证文件夹1的notes_count为2,文件夹2为0
- Cursor folder1Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹1", folder1Cursor.moveToFirst());
- assertEquals("文件夹1的notes_count应该为2", 2, folder1Cursor.getInt(0));
- folder1Cursor.close();
-
- Cursor folder2Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹2", folder2Cursor.moveToFirst());
- assertEquals("文件夹2的notes_count应该为0", 0, folder2Cursor.getInt(0));
- folder2Cursor.close();
-
- // 查询笔记ID
- Cursor noteCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.ID},
- Notes.NoteColumns.PARENT_ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(folder1Id), String.valueOf(Notes.TYPE_NOTE)},
- null, null, null
- );
- assertTrue("应该找到笔记", noteCursor.moveToFirst());
- long noteId = noteCursor.getLong(0);
- noteCursor.close();
-
- // 移动笔记:从文件夹1移动到文件夹2
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(noteId)}
- );
-
- // 验证文件夹1的notes_count减少到1
- folder1Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹1", folder1Cursor.moveToFirst());
- assertEquals("文件夹1的notes_count应该减少到1", 1, folder1Cursor.getInt(0));
- folder1Cursor.close();
-
- // 验证文件夹2的notes_count增加到1
- folder2Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹2", folder2Cursor.moveToFirst());
- assertEquals("文件夹2的notes_count应该增加到1", 1, folder2Cursor.getInt(0));
- folder2Cursor.close();
- }
-
- /**
- * 测试删除文件夹时不会触发级联删除笔记的notes_count更新
- * 验证删除文件夹时,笔记的级联删除不影响其他文件夹的notes_count
- */
- @Test
- public void testDeleteFolderDoesNotAffectOtherFoldersNotesCount() {
- // 创建文件夹1
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- // 创建文件夹2(文件夹1的子文件夹)
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 向文件夹2插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 验证文件夹2的notes_count为1
- Cursor folder2Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹2", folder2Cursor.moveToFirst());
- assertEquals("文件夹2的notes_count应该为1", 1, folder2Cursor.getInt(0));
- folder2Cursor.close();
-
- // 删除文件夹1(应该级联删除文件夹2及其笔记)
- mDatabase.delete(
- NotesDatabaseHelper.TABLE.NOTE,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)}
- );
-
- // 验证文件夹2和笔记都已被删除
- folder2Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.ID},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
- assertFalse("文件夹2应该已被删除", folder2Cursor.moveToFirst());
- folder2Cursor.close();
- }
-
- /**
- * 测试移动文件夹时不影响notes_count
- * 验证移动文件夹时,notes_count保持不变
- */
- @Test
- public void testMoveFolderDoesNotChangeNotesCount() {
- // 创建文件夹1
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- // 创建文件夹2
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 向文件夹1插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 验证文件夹1的notes_count为1
- Cursor folder1Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹1", folder1Cursor.moveToFirst());
- assertEquals("文件夹1的notes_count应该为1", 1, folder1Cursor.getInt(0));
- folder1Cursor.close();
-
- // 将文件夹1移动到文件夹2下
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)}
- );
-
- // 验证文件夹1的notes_count仍为1
- folder1Cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)},
- null, null, null
- );
- assertTrue("应该找到文件夹1", folder1Cursor.moveToFirst());
- assertEquals("文件夹1的notes_count应该仍为1", 1, folder1Cursor.getInt(0));
- folder1Cursor.close();
- }
-
- // ==================== 测试3:系统文件夹保护 ====================
-
- /**
- * 测试不能删除系统文件夹
- * 验证系统文件夹(ID <= 0)不能被删除
- */
- @Test
- public void testCannotDeleteSystemFolder() {
- // 尝试删除根文件夹
- int deleted = mDatabase.delete(
- NotesDatabaseHelper.TABLE.NOTE,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)}
- );
-
- // 验证删除失败
- assertEquals("不应该删除任何记录", 0, deleted);
-
- // 验证根文件夹仍然存在
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)},
- null, null, null
- );
- assertTrue("根文件夹应该仍然存在", cursor.moveToFirst());
- cursor.close();
-
- // 尝试删除回收站
- deleted = mDatabase.delete(
- NotesDatabaseHelper.TABLE.NOTE,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_TRASH_FOLER)}
- );
-
- // 验证删除失败
- assertEquals("不应该删除回收站", 0, deleted);
- }
-
- /**
- * 测试系统文件夹的type字段
- * 验证系统文件夹的type为TYPE_SYSTEM
- */
- @Test
- public void testSystemFolderType() {
- // 验证根文件夹的类型
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.TYPE},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)},
- null, null, null
- );
- assertTrue("应该找到根文件夹", cursor.moveToFirst());
- assertEquals("根文件夹的类型应该为TYPE_SYSTEM", Notes.TYPE_SYSTEM, cursor.getInt(0));
- cursor.close();
-
- // 验证回收站的类型
- cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.TYPE},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_TRASH_FOLER)},
- null, null, null
- );
- assertTrue("应该找到回收站", cursor.moveToFirst());
- assertEquals("回收站的类型应该为TYPE_SYSTEM", Notes.TYPE_SYSTEM, cursor.getInt(0));
- cursor.close();
- }
-
- /**
- * 测试系统文件夹不能被重命名
- * 验证即使尝试更新系统文件夹的名称,也应该失败或无效
- */
- @Test
- public void testCannotRenameSystemFolder() {
- // 尝试重命名根文件夹
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.SNIPPET, "新名称");
- int updated = mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)}
- );
-
- // 验证更新(数据库层面允许更新,但应用层应该阻止)
- // 这里测试数据库层面
- assertTrue("数据库层面允许更新", updated > 0);
-
- // 验证名称已更改
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.SNIPPET},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(Notes.ID_ROOT_FOLDER)},
- null, null, null
- );
- assertTrue("应该找到根文件夹", cursor.moveToFirst());
- assertEquals("名称应该已更改", "新名称", cursor.getString(0));
- cursor.close();
-
- // 注意:实际应用中,ContentProvider或业务层应该阻止此操作
- }
-
- // ==================== 测试4:回收站功能 ====================
-
- /**
- * 测试将便签移动到回收站
- * 验证便签的parent_id更新为回收站ID
- */
- @Test
- public void testMoveNoteToTrash() {
- // 创建一个文件夹
- ContentValues folderValues = new ContentValues();
- folderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folderValues.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folderValues);
-
- // 向文件夹插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- long noteId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 将笔记移动到回收站
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- int updated = mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(noteId)}
- );
-
- // 验证更新成功
- assertEquals("应该更新1条记录", 1, updated);
-
- // 验证笔记已在回收站中
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(noteId), String.valueOf(Notes.ID_TRASH_FOLER)},
- null, null, null
- );
- assertTrue("笔记应该在回收站中", cursor.moveToFirst());
- cursor.close();
-
- // 验证原文件夹的notes_count减少
- Cursor folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("文件夹的notes_count应该为0", 0, folderCursor.getInt(0));
- folderCursor.close();
- }
-
- /**
- * 测试将文件夹移动到回收站
- * 验证文件夹及其所有子项都移动到回收站
- */
- @Test
- public void testMoveFolderToTrash() {
- // 创建父文件夹
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- // 创建子文件夹
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 向子文件夹插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 将父文件夹移动到回收站
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)}
- );
-
- // 验证父文件夹在回收站中
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(folder1Id), String.valueOf(Notes.ID_TRASH_FOLER)},
- null, null, null
- );
- assertTrue("父文件夹应该在回收站中", cursor.moveToFirst());
- cursor.close();
-
- // 验证子文件夹也在回收站中
- cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(folder2Id), String.valueOf(Notes.ID_TRASH_FOLER)},
- null, null, null
- );
- assertTrue("子文件夹应该在回收站中", cursor.moveToFirst());
- cursor.close();
-
- // 验证笔记也在回收站中
- cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.PARENT_ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(Notes.ID_TRASH_FOLER), String.valueOf(Notes.TYPE_NOTE)},
- null, null, null
- );
- assertTrue("笔记应该在回收站中", cursor.moveToFirst());
- cursor.close();
- }
-
- /**
- * 测试从回收站恢复便签
- * 验证便签可以恢复到指定文件夹
- */
- @Test
- public void testRestoreNoteFromTrash() {
- // 创建文件夹
- ContentValues folderValues = new ContentValues();
- folderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folderValues.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folderValues);
-
- // 创建笔记并直接插入到回收站
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "回收站中的笔记");
- long noteId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 将笔记恢复到文件夹
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- int updated = mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(noteId)}
- );
-
- // 验证更新成功
- assertEquals("应该更新1条记录", 1, updated);
-
- // 验证笔记已在文件夹中
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(noteId), String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("笔记应该在文件夹中", cursor.moveToFirst());
- cursor.close();
-
- // 验证文件夹的notes_count增加
- Cursor folderCursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.NOTES_COUNT},
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)},
- null, null, null
- );
- assertTrue("应该找到文件夹", folderCursor.moveToFirst());
- assertEquals("文件夹的notes_count应该为1", 1, folderCursor.getInt(0));
- folderCursor.close();
- }
-
- /**
- * 测试从回收站恢复文件夹
- * 验证文件夹及其子项可以恢复到指定位置
- */
- @Test
- public void testRestoreFolderFromTrash() {
- // 创建父文件夹并直接放入回收站
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "回收站中的文件夹");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- // 创建子文件夹
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "子文件夹");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 向子文件夹插入笔记
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 将父文件夹恢复到根目录
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder1Id)}
- );
-
- // 验证父文件夹已恢复
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=? AND " + Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(folder1Id), String.valueOf(Notes.ID_ROOT_FOLDER)},
- null, null, null
- );
- assertTrue("父文件夹应该在根目录中", cursor.moveToFirst());
- cursor.close();
-
- // 验证子文件夹和笔记也跟随恢复(仍然在父文件夹下)
- cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folder2Id)},
- null, null, null
- );
- assertTrue("子文件夹应该仍然存在", cursor.moveToFirst());
- assertEquals("子文件夹的父ID应该是父文件夹", folder1Id, cursor.getLong(cursor.getColumnIndexOrThrow(Notes.NoteColumns.PARENT_ID)));
- cursor.close();
- }
-
- /**
- * 测试查询回收站中的项目
- * 验证能够正确查询回收站中的所有项目
- */
- @Test
- public void testQueryTrashItems() {
- // 创建文件夹和笔记
- ContentValues folderValues = new ContentValues();
- folderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folderValues.put(Notes.NoteColumns.SNIPPET, "测试文件夹");
- long folderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folderValues);
-
- ContentValues noteValues = new ContentValues();
- noteValues.put(Notes.NoteColumns.PARENT_ID, folderId);
- noteValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_NOTE);
- noteValues.put(Notes.NoteColumns.SNIPPET, "测试笔记");
- mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, noteValues);
-
- // 将它们移动到回收站
- ContentValues updateValues = new ContentValues();
- updateValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
-
- // 移动文件夹
- mDatabase.update(
- NotesDatabaseHelper.TABLE.NOTE,
- updateValues,
- Notes.NoteColumns.ID + "=?",
- new String[]{String.valueOf(folderId)}
- );
-
- // 查询回收站中的项目
- Cursor cursor = mDatabase.query(
- NotesDatabaseHelper.TABLE.NOTE,
- null,
- Notes.NoteColumns.PARENT_ID + "=?",
- new String[]{String.valueOf(Notes.ID_TRASH_FOLER)},
- null, null, null
- );
-
- assertNotNull("查询结果不应该为null", cursor);
- assertEquals("回收站中应该有2个项目", 2, cursor.getCount());
-
- // 排除系统文件夹(回收站本身)
- cursor.close();
- }
-
- // ==================== 测试5:循环依赖检测 ====================
-
- /**
- * 测试检测将文件夹移动到其子文件夹的循环依赖
- * 验证能够检测并阻止循环依赖
- */
- @Test
- public void testDetectCircularDependency() {
- // 创建父文件夹
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "父文件夹");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- // 创建子文件夹
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "子文件夹");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 创建孙子文件夹
- ContentValues folder3Values = new ContentValues();
- folder3Values.put(Notes.NoteColumns.PARENT_ID, folder2Id);
- folder3Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder3Values.put(Notes.NoteColumns.SNIPPET, "孙子文件夹");
- long folder3Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder3Values);
-
- // 检测:尝试将父文件夹移动到孙子文件夹(应该检测到循环)
- boolean hasCircularDependency = hasCircularDependency(mDatabase, folder1Id, folder3Id);
-
- // 验证检测到循环
- assertTrue("应该检测到循环依赖", hasCircularDependency);
-
- // 检测:尝试将子文件夹移动到父文件夹(不应该检测到循环)
- hasCircularDependency = hasCircularDependency(mDatabase, folder2Id, folder1Id);
-
- // 验证没有检测到循环
- assertFalse("不应该检测到循环依赖", hasCircularDependency);
-
- // 检测:尝试将子文件夹移动到孙子文件夹(不应该检测到循环)
- hasCircularDependency = hasCircularDependency(mDatabase, folder2Id, folder3Id);
-
- // 验证没有检测到循环
- assertFalse("不应该检测到循环依赖", hasCircularDependency);
- }
-
- /**
- * 检测循环依赖的辅助方法
- * 递归检查目标文件夹是否为源文件夹的子节点
- *
- * @param db 数据库实例
- * @param sourceFolderId 源文件夹ID
- * @param targetFolderId 目标文件夹ID
- * @return 如果存在循环依赖返回true,否则返回false
- */
- private boolean hasCircularDependency(SQLiteDatabase db, long sourceFolderId, long targetFolderId) {
- // 递归检查目标文件夹的所有子文件夹
- return hasCircularDependencyRecursive(db, sourceFolderId, targetFolderId);
- }
-
- /**
- * 递归检查循环依赖
- *
- * @param db 数据库实例
- * @param sourceFolderId 源文件夹ID(正在移动的文件夹)
- * @param targetFolderId 目标文件夹ID(检查是否为源文件夹的子节点)
- * @return 如果目标文件夹是源文件夹的子节点返回true,否则返回false
- */
- private boolean hasCircularDependencyRecursive(SQLiteDatabase db, long sourceFolderId, long targetFolderId) {
- // 如果目标文件夹ID等于源文件夹ID,说明存在循环
- if (targetFolderId == sourceFolderId) {
- return true;
- }
-
- // 查询目标文件夹的所有子文件夹
- Cursor cursor = db.query(
- NotesDatabaseHelper.TABLE.NOTE,
- new String[]{Notes.NoteColumns.ID},
- Notes.NoteColumns.PARENT_ID + "=? AND " + Notes.NoteColumns.TYPE + "=?",
- new String[]{String.valueOf(targetFolderId), String.valueOf(Notes.TYPE_FOLDER)},
- null, null, null
- );
-
- boolean result = false;
- if (cursor.moveToFirst()) {
- do {
- long childFolderId = cursor.getLong(0);
- // 递归检查子文件夹
- if (hasCircularDependencyRecursive(db, sourceFolderId, childFolderId)) {
- result = true;
- break;
- }
- } while (cursor.moveToNext());
- }
-
- cursor.close();
- return result;
- }
-
- /**
- * 测试移动文件夹到根目录不会产生循环
- * 验证将任何文件夹移动到根目录都是安全的
- */
- @Test
- public void testMoveFolderToRootHasNoCircularDependency() {
- // 创建嵌套文件夹
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, folder1Id);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 检测:将文件夹1移动到根目录(不应该检测到循环)
- boolean hasCircularDependency = hasCircularDependency(mDatabase, folder1Id, Notes.ID_ROOT_FOLDER);
-
- // 验证没有检测到循环
- assertFalse("移动到根目录不应该产生循环", hasCircularDependency);
-
- // 检测:将文件夹2移动到根目录(不应该检测到循环)
- hasCircularDependency = hasCircularDependency(mDatabase, folder2Id, Notes.ID_ROOT_FOLDER);
-
- // 验证没有检测到循环
- assertFalse("移动到根目录不应该产生循环", hasCircularDependency);
- }
-
- /**
- * 测试移动文件夹到同级目录不会产生循环
- * 验证将文件夹移动到同级目录是安全的
- */
- @Test
- public void testMoveFolderToSiblingHasNoCircularDependency() {
- // 创建父文件夹
- ContentValues parentFolderValues = new ContentValues();
- parentFolderValues.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
- parentFolderValues.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- parentFolderValues.put(Notes.NoteColumns.SNIPPET, "父文件夹");
- long parentFolderId = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, parentFolderValues);
-
- // 创建两个子文件夹
- ContentValues folder1Values = new ContentValues();
- folder1Values.put(Notes.NoteColumns.PARENT_ID, parentFolderId);
- folder1Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder1Values.put(Notes.NoteColumns.SNIPPET, "文件夹1");
- long folder1Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder1Values);
-
- ContentValues folder2Values = new ContentValues();
- folder2Values.put(Notes.NoteColumns.PARENT_ID, parentFolderId);
- folder2Values.put(Notes.NoteColumns.TYPE, Notes.TYPE_FOLDER);
- folder2Values.put(Notes.NoteColumns.SNIPPET, "文件夹2");
- long folder2Id = mDatabase.insert(NotesDatabaseHelper.TABLE.NOTE, null, folder2Values);
-
- // 检测:将文件夹1移动到文件夹2(不应该检测到循环)
- boolean hasCircularDependency = hasCircularDependency(mDatabase, folder1Id, folder2Id);
-
- // 验证没有检测到循环
- assertFalse("移动到同级文件夹不应该产生循环", hasCircularDependency);
- }
-}
diff --git a/app/src/test/java/net/micode/notes/data/NotesRepositoryTest.java b/app/src/test/java/net/micode/notes/data/NotesRepositoryTest.java
deleted file mode 100644
index 53c977c..0000000
--- a/app/src/test/java/net/micode/notes/data/NotesRepositoryTest.java
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * Copyright (c) 2025, Modern Notes Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.data;
-
-import android.content.ContentResolver;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-
-import net.micode.notes.model.Note;
-import net.micode.notes.data.NotesRepository.NoteInfo;
-
-import java.util.List;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-/**
- * NotesRepository 单元测试
- *
- * 测试笔记数据仓库的各个功能
- *
- *
- * @see NotesRepository
- */
-@RunWith(MockitoJUnitRunner.class)
-public class NotesRepositoryTest {
-
- private static final String TAG = "NotesRepositoryTest";
-
- @Mock
- private ContentResolver mockContentResolver;
-
- private NotesRepository repository;
-
- @Before
- public void setUp() {
- repository = new NotesRepository(mockContentResolver);
- }
-
- @After
- public void tearDown() {
- repository.shutdown();
- }
-
- /**
- * 测试创建Repository实例
- */
- @Test
- public void testRepositoryCreation() {
- assertNotNull("Repository should not be null", repository);
- }
-
- /**
- * 测试获取笔记列表
- */
- @Test
- public void testGetNotes() {
- // Arrange
- long folderId = Notes.ID_ROOT_FOLDER;
-
- // Act
- repository.getNotes(folderId, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List result) {
- assertNotNull("Notes list should not be null", result);
- // Mock返回空列表,实际应用中会有数据
- assertTrue("Notes count should be >= 0", result.size() >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试创建笔记
- */
- @Test
- public void testCreateNote() {
- // Arrange
- long folderId = Notes.ID_ROOT_FOLDER;
-
- // Act
- repository.createNote(folderId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Long noteId) {
- assertNotNull("Note ID should not be null", noteId);
- assertTrue("Note ID should be > 0", noteId > 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试更新笔记内容
- */
- @Test
- public void testUpdateNote() {
- // Arrange
- long noteId = 1L;
- String content = "测试笔记内容";
-
- // Act
- repository.updateNote(noteId, content, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- assertNotNull("Rows affected should not be null", rowsAffected);
- assertTrue("Rows affected should be >= 0", rowsAffected >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试删除笔记
- */
- @Test
- public void testDeleteNote() {
- // Arrange
- long noteId = 1L;
-
- // Act
- repository.deleteNote(noteId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer rowsAffected) {
- assertNotNull("Rows affected should not be null", rowsAffected);
- assertTrue("Rows affected should be >= 0", rowsAffected >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试搜索笔记
- */
- @Test
- public void testSearchNotes() {
- // Arrange
- String keyword = "测试";
-
- // Act
- repository.searchNotes(keyword, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List result) {
- assertNotNull("Search results should not be null", result);
- assertTrue("Search results count should be >= 0", result.size() >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试搜索空关键字
- */
- @Test
- public void testSearchNotesWithEmptyKeyword() {
- // Arrange
- String keyword = "";
-
- // Act
- repository.searchNotes(keyword, new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List result) {
- assertNotNull("Search results should not be null", result);
- // 空关键字应返回空列表
- assertEquals("Search results should be empty", 0, result.size());
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试获取笔记统计
- */
- @Test
- public void testCountNotes() {
- // Arrange
- long folderId = Notes.ID_ROOT_FOLDER;
-
- // Act
- repository.countNotes(folderId, new NotesRepository.Callback() {
- @Override
- public void onSuccess(Integer count) {
- assertNotNull("Count should not be null", count);
- assertTrue("Count should be >= 0", count >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-
- /**
- * 测试获取文件夹列表
- */
- @Test
- public void testGetFolders() {
- // Act
- repository.getFolders(new NotesRepository.Callback>() {
- @Override
- public void onSuccess(List result) {
- assertNotNull("Folders should not be null", result);
- assertTrue("Folders count should be >= 0", result.size() >= 0);
- }
-
- @Override
- public void onError(Exception error) {
- fail("Should not throw error: " + error.getMessage());
- }
- });
- }
-}
diff --git a/src/Notesmaster/app/src/main/AndroidManifest.xml b/src/Notesmaster/app/src/main/AndroidManifest.xml
index b93c62f..773066d 100644
--- a/src/Notesmaster/app/src/main/AndroidManifest.xml
+++ b/src/Notesmaster/app/src/main/AndroidManifest.xml
@@ -42,7 +42,7 @@
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTop"
- android:theme="@android:style/Theme.Holo.Light"
+ android:theme="@style/Theme.Notesmaster"
android:uiOptions="splitActionBarWhenNarrow"
android:windowSoftInputMode="adjustPan"
android:exported="true">
@@ -60,7 +60,7 @@
android:name=".ui.NoteEditActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:launchMode="singleTop"
- android:theme="@style/NoteTheme"
+ android:theme="@style/Theme.Notesmaster.Edit"
android:exported="true">
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/MainActivity.java b/src/Notesmaster/app/src/main/java/net/micode/notes/MainActivity.java
index 3716891..930f6fe 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/MainActivity.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/MainActivity.java
@@ -1,28 +1,39 @@
package net.micode.notes;
+import android.content.Intent;
import android.os.Bundle;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.View;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
+import androidx.drawerlayout.widget.DrawerLayout;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.ui.SidebarFragment;
/**
* 主活动类
*
- * 应用的主入口,负责初始化主界面并处理窗口边距。
+ * 应用的主入口,负责启动笔记列表界面
* 支持边到边显示模式,自动适配系统栏的边距。
*
*/
-public class MainActivity extends AppCompatActivity {
+public class MainActivity extends AppCompatActivity implements SidebarFragment.OnSidebarItemSelectedListener {
+
+ private static final String TAG = "MainActivity";
+ private DrawerLayout drawerLayout;
/**
* 创建活动
*
* 初始化活动界面,启用边到边显示模式,并设置窗口边距监听器。
*
- *
+ *
* @param savedInstanceState 保存的实例状态,用于恢复活动状态
*/
@Override
@@ -31,13 +42,118 @@ public class MainActivity extends AppCompatActivity {
// 启用边到边显示模式
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
+
+ // 初始化DrawerLayout
+ drawerLayout = findViewById(R.id.drawer_layout);
+ if (drawerLayout != null) {
+ // 设置侧栏在左侧
+ drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
+
+ // 设置监听器:侧栏关闭时更新状态
+ drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
+ @Override
+ public void onDrawerSlide(View drawerView, float slideOffset) {
+ // 侧栏滑动时
+ }
+
+ @Override
+ public void onDrawerOpened(View drawerView) {
+ // 侧栏打开时
+ }
+
+ @Override
+ public void onDrawerClosed(View drawerView) {
+ // 侧栏关闭时
+ }
+
+ @Override
+ public void onDrawerStateChanged(int newState) {
+ // 侧栏状态改变时
+ }
+ });
+ }
+
// 设置窗口边距监听器,自动适配系统栏
- ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
+ ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main_content), (v, insets) -> {
// 获取系统栏边距
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
// 设置视图内边距以适配系统栏
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
+
+ // 启动NotesListActivity作为主界面
+ Intent intent = new Intent(this, net.micode.notes.ui.NotesListActivity.class);
+ startActivity(intent);
+ }
+
+ // ==================== SidebarFragment.OnSidebarItemSelectedListener 实现 ====================
+
+ @Override
+ public void onFolderSelected(long folderId) {
+ Log.d(TAG, "Folder selected: " + folderId);
+ // 打开侧栏中的文件夹:不关闭侧栏,直接切换视图
+ // 这个回调通常用于侧栏中的文件夹项双击
+ // 实际跳转逻辑应该在NotesListActivity中处理
+ closeSidebar();
+ }
+
+ @Override
+ public void onTrashSelected() {
+ Log.d(TAG, "Trash selected");
+ // TODO: 实现跳转到回收站
+ // 关闭侧栏
+ closeSidebar();
+ }
+
+ @Override
+ public void onSyncSelected() {
+ Log.d(TAG, "Sync selected");
+ // TODO: 实现同步功能
+ }
+
+ @Override
+ public void onLoginSelected() {
+ Log.d(TAG, "Login selected");
+ // TODO: 实现登录功能
+ }
+
+ @Override
+ public void onExportSelected() {
+ Log.d(TAG, "Export selected");
+ // TODO: 实现导出功能
+ }
+
+ @Override
+ public void onSettingsSelected() {
+ Log.d(TAG, "Settings selected");
+ // 打开设置界面
+ Intent intent = new Intent(this, net.micode.notes.ui.NotesPreferenceActivity.class);
+ startActivity(intent);
+ // 关闭侧栏
+ closeSidebar();
+ }
+
+ @Override
+ public void onCreateFolder() {
+ Log.d(TAG, "Create folder");
+ // 创建文件夹功能由SidebarFragment内部处理
+ // 这里不需要做任何事情
+ }
+
+ @Override
+ public void onCloseSidebar() {
+ closeSidebar();
+ }
+
+ // ==================== 私有方法 ====================
+
+ /**
+ * 关闭侧栏
+ */
+ private void closeSidebar() {
+ if (drawerLayout != null) {
+ drawerLayout.closeDrawer(Gravity.LEFT);
+ }
}
}
\ No newline at end of file
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/data/Notes.java b/src/Notesmaster/app/src/main/java/net/micode/notes/data/Notes.java
index 8b1f853..71f11fa 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/data/Notes.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/data/Notes.java
@@ -235,6 +235,12 @@ public class Notes {
* Type : INTEGER (long)
*/
public static final String VERSION = "version";
+
+ /**
+ * Sign to indicate the note is pinned to top or not
+ * Type : INTEGER
+ */
+ public static final String TOP = "top";
}
public interface DataColumns {
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/src/Notesmaster/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
index 558caf7..c862ead 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java
@@ -66,11 +66,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* 数据库版本号
*
- * 当前数据库版本为4,用于跟踪数据库结构变更。
+ * 当前数据库版本为5,用于跟踪数据库结构变更。
* 当数据库版本变更时,onUpgrade方法会被调用以执行升级逻辑。
*
*/
- private static final int DB_VERSION = 4;
+ private static final int DB_VERSION = 5;
/**
* 数据库表名常量接口
@@ -471,7 +471,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
* @param context 应用上下文
* @return NotesDatabaseHelper单例实例
*/
- static synchronized NotesDatabaseHelper getInstance(Context context) {
+ public static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
@@ -595,4 +595,17 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
+
+ /**
+ * 升级数据库到V5版本
+ *
+ * 添加TOP列到note表,用于标记笔记是否置顶。
+ *
+ *
+ * @param db SQLiteDatabase实例
+ */
+ private void upgradeToV5(SQLiteDatabase db) {
+ db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.TOP
+ + " INTEGER NOT NULL DEFAULT 0");
+ }
}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/tool/DataUtils.java b/src/Notesmaster/app/src/main/java/net/micode/notes/tool/DataUtils.java
index 0872c4c..d982351 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/tool/DataUtils.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/tool/DataUtils.java
@@ -29,7 +29,7 @@ import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.ui.NotesRecyclerViewAdapter.AppWidgetAttribute;
+import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/GridSpacingItemDecoration.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/GridSpacingItemDecoration.java
deleted file mode 100644
index 1a7d15d..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/GridSpacingItemDecoration.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.graphics.Rect;
-import android.view.View;
-import androidx.recyclerview.widget.RecyclerView;
-
-/**
- * 网格布局间距装饰类
- *
- * 为网格布局的RecyclerView添加统一的间距,确保每个网格项之间有合适的间隔。
- * 支持是否包含边缘间距的配置。
- *
- */
-public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
- private int spanCount;
- private int spacing;
- private boolean includeEdge;
-
- /**
- * 构造函数
- * @param spanCount 网格列数
- * @param spacing 间距大小(像素)
- * @param includeEdge 是否包含边缘间距
- */
- public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
- this.spanCount = spanCount;
- this.spacing = spacing;
- this.includeEdge = includeEdge;
- }
-
- @Override
- public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
- int position = parent.getChildAdapterPosition(view);
- int column = position % spanCount;
-
- if (includeEdge) {
- outRect.left = spacing - column * spacing / spanCount;
- outRect.right = (column + 1) * spacing / spanCount;
-
- if (position < spanCount) {
- outRect.top = spacing;
- }
- outRect.bottom = spacing;
- } else {
- outRect.left = column * spacing / spanCount;
- outRect.right = spacing - (column + 1) * spacing / spanCount;
- if (position >= spanCount) {
- outRect.top = spacing;
- }
- }
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutManagerController.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutManagerController.java
deleted file mode 100644
index 0024c82..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutManagerController.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import androidx.recyclerview.widget.GridLayoutManager;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
-import androidx.recyclerview.widget.StaggeredGridLayoutManager;
-
-/**
- * 布局管理器控制类
- *
- * 负责管理RecyclerView的布局切换,提供平滑的布局过渡效果。
- * 支持线性布局、网格布局和瀑布流布局的无缝切换。
- * 保存用户的布局偏好设置,确保应用重启后保持布局状态。
- *
- */
-public class LayoutManagerController {
- private static final String TAG = "LayoutManagerController";
- private static final String PREF_LAYOUT_TYPE = "layout_type";
- private static final String PREF_GRID_SPAN_COUNT = "grid_span_count";
- private static final String PREF_ITEM_SPACING = "item_spacing";
-
- private Context mContext;
- private RecyclerView mRecyclerView;
- private RecyclerView.LayoutManager mCurrentLayoutManager;
- private LayoutType mCurrentLayoutType;
- private SharedPreferences mPreferences;
- private LayoutChangeListener mListener;
-
- /**
- * 布局变化监听器接口
- */
- public interface LayoutChangeListener {
- void onLayoutChanged(LayoutType newLayoutType);
- void onLayoutChangeFailed(Exception e);
- }
-
- /**
- * 构造函数
- * @param context 上下文
- * @param recyclerView RecyclerView实例
- * @param listener 布局变化监听器
- */
- public LayoutManagerController(Context context, RecyclerView recyclerView, LayoutChangeListener listener) {
- mContext = context;
- mRecyclerView = recyclerView;
- mListener = listener;
- mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
-
- // 加载保存的布局类型
- String savedLayoutKey = mPreferences.getString(PREF_LAYOUT_TYPE, LayoutType.LINEAR.getKey());
- mCurrentLayoutType = LayoutType.fromKey(savedLayoutKey);
-
- Log.d(TAG, "LayoutManagerController initialized with layout: " + mCurrentLayoutType.getDisplayName());
- }
-
- /**
- * 初始化布局
- */
- public void initializeLayout() {
- switchLayout(mCurrentLayoutType, false);
- }
-
- /**
- * 切换布局
- * @param layoutType 目标布局类型
- * @param animate 是否播放动画
- * @return 切换是否成功
- */
- public boolean switchLayout(LayoutType layoutType, boolean animate) {
- if (layoutType == mCurrentLayoutType) {
- Log.d(TAG, "Already in " + layoutType.getDisplayName() + " mode");
- return true;
- }
-
- long startTime = System.currentTimeMillis();
-
- try {
- // 保存滚动位置
- int scrollPosition = 0;
- if (mRecyclerView.getLayoutManager() != null) {
- if (mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
- LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
- scrollPosition = layoutManager.findFirstVisibleItemPosition();
- } else if (mRecyclerView.getLayoutManager() instanceof GridLayoutManager) {
- GridLayoutManager layoutManager = (GridLayoutManager) mRecyclerView.getLayoutManager();
- scrollPosition = layoutManager.findFirstVisibleItemPosition();
- } else if (mRecyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) {
- StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) mRecyclerView.getLayoutManager();
- int[] positions = layoutManager.findFirstVisibleItemPositions(null);
- scrollPosition = positions.length > 0 ? positions[0] : 0;
- }
- }
-
- // 移除所有装饰
- int decorationCount = mRecyclerView.getItemDecorationCount();
- for (int i = decorationCount - 1; i >= 0; i--) {
- mRecyclerView.removeItemDecorationAt(i);
- }
-
- // 创建新的布局管理器
- RecyclerView.LayoutManager newLayoutManager = createLayoutManager(layoutType);
-
- // 应用新布局
- if (animate) {
- mRecyclerView.setLayoutManager(newLayoutManager);
- } else {
- mRecyclerView.setLayoutManager(newLayoutManager);
- }
-
- // 添加间距装饰
- addItemDecoration(layoutType);
-
- // 保存布局偏好
- saveLayoutPreference(layoutType);
-
- // 恢复滚动位置
- restoreScrollPosition(scrollPosition);
-
- mCurrentLayoutManager = newLayoutManager;
- mCurrentLayoutType = layoutType;
-
- long duration = System.currentTimeMillis() - startTime;
- Log.d(TAG, "Layout switched to " + layoutType.getDisplayName() + " in " + duration + "ms");
-
- // 通知监听器
- if (mListener != null) {
- mListener.onLayoutChanged(layoutType);
- }
-
- return true;
-
- } catch (Exception e) {
- Log.e(TAG, "Failed to switch layout: " + e.getMessage(), e);
-
- // 通知监听器失败
- if (mListener != null) {
- mListener.onLayoutChangeFailed(e);
- }
-
- return false;
- }
- }
-
- /**
- * 创建布局管理器
- * @param layoutType 布局类型
- * @return 布局管理器实例
- */
- private RecyclerView.LayoutManager createLayoutManager(LayoutType layoutType) {
- int spanCount = getGridSpanCount();
- switch (layoutType) {
- case LINEAR:
- return new LinearLayoutManager(mContext);
- case GRID:
- return new GridLayoutManager(mContext, spanCount);
- case STAGGERED:
- return new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);
- default:
- return new LinearLayoutManager(mContext);
- }
- }
-
- /**
- * 添加间距装饰
- * @param layoutType 布局类型
- */
- private void addItemDecoration(LayoutType layoutType) {
- int spacing = getItemSpacing();
-
- switch (layoutType) {
- case LINEAR:
- mRecyclerView.addItemDecoration(new NoteItemDecoration(mContext));
- break;
- case GRID:
- mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(getGridSpanCount(), spacing, true));
- break;
- case STAGGERED:
- mRecyclerView.addItemDecoration(new StaggeredGridSpacingItemDecoration(getGridSpanCount(), spacing, true));
- break;
- }
- }
-
- /**
- * 恢复滚动位置
- * @param position 滚动位置
- */
- private void restoreScrollPosition(int position) {
- if (mRecyclerView.getAdapter() != null && position >= 0 && position < mRecyclerView.getAdapter().getItemCount()) {
- mRecyclerView.scrollToPosition(position);
- }
- }
-
- /**
- * 保存布局偏好
- * @param layoutType 布局类型
- */
- private void saveLayoutPreference(LayoutType layoutType) {
- mPreferences.edit()
- .putString(PREF_LAYOUT_TYPE, layoutType.getKey())
- .apply();
- }
-
- /**
- * 获取网格列数
- * @return 网格列数
- */
- public int getGridSpanCount() {
- return mPreferences.getInt(PREF_GRID_SPAN_COUNT, 2);
- }
-
- /**
- * 设置网格列数
- * @param spanCount 网格列数
- */
- public void setGridSpanCount(int spanCount) {
- if (spanCount < 1) spanCount = 1;
- if (spanCount > 4) spanCount = 4;
-
- mPreferences.edit()
- .putInt(PREF_GRID_SPAN_COUNT, spanCount)
- .apply();
-
- // 重新应用布局
- switchLayout(mCurrentLayoutType, true);
- }
-
- /**
- * 获取项目间距
- * @return 项目间距(像素)
- */
- public int getItemSpacing() {
- return mPreferences.getInt(PREF_ITEM_SPACING, 16);
- }
-
- /**
- * 设置项目间距
- * @param spacing 项目间距(像素)
- */
- public void setItemSpacing(int spacing) {
- if (spacing < 0) spacing = 0;
- if (spacing > 48) spacing = 48;
-
- mPreferences.edit()
- .putInt(PREF_ITEM_SPACING, spacing)
- .apply();
-
- // 重新应用布局
- switchLayout(mCurrentLayoutType, true);
- }
-
- /**
- * 获取当前布局类型
- * @return 当前布局类型
- */
- public LayoutType getCurrentLayoutType() {
- return mCurrentLayoutType;
- }
-
- /**
- * 获取下一个布局类型(循环切换)
- * @return 下一个布局类型
- */
- public LayoutType getNextLayoutType() {
- LayoutType[] types = LayoutType.values();
- int currentIndex = 0;
- for (int i = 0; i < types.length; i++) {
- if (types[i] == mCurrentLayoutType) {
- currentIndex = i;
- break;
- }
- }
- return types[(currentIndex + 1) % types.length];
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutSettingsDialog.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutSettingsDialog.java
deleted file mode 100644
index e443472..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutSettingsDialog.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.SeekBar;
-import android.widget.Spinner;
-import android.widget.TextView;
-import net.micode.notes.R;
-
-/**
- * 布局设置对话框
- *
- * 提供布局类型选择、网格列数和项目间距的配置界面。
- * 支持实时预览布局效果。
- *
- */
-public class LayoutSettingsDialog {
- private Context mContext;
- private LayoutManagerController mLayoutManagerController;
- private AlertDialog mDialog;
- private Spinner mLayoutTypeSpinner;
- private SeekBar mGridColumnsSeekBar;
- private SeekBar mItemSpacingSeekBar;
- private TextView mGridColumnsValue;
- private TextView mItemSpacingValue;
-
- /**
- * 构造函数
- * @param context 上下文
- * @param layoutManagerController 布局管理器
- */
- public LayoutSettingsDialog(Context context, LayoutManagerController layoutManagerController) {
- mContext = context;
- mLayoutManagerController = layoutManagerController;
- }
-
- /**
- * 显示布局设置对话框
- */
- public void show() {
- AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
- builder.setTitle(R.string.layout_settings_title);
-
- View dialogView = LayoutInflater.from(mContext).inflate(R.layout.layout_settings_dialog, null);
- builder.setView(dialogView);
-
- initViews(dialogView);
- setupListeners();
-
- builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- saveSettings();
- }
- });
-
- builder.setNegativeButton(android.R.string.cancel, null);
-
- mDialog = builder.create();
- mDialog.show();
- }
-
- /**
- * 初始化视图
- * @param dialogView 对话框视图
- */
- private void initViews(View dialogView) {
- mLayoutTypeSpinner = (Spinner) dialogView.findViewById(R.id.layout_type_spinner);
- mGridColumnsSeekBar = (SeekBar) dialogView.findViewById(R.id.grid_columns_seekbar);
- mItemSpacingSeekBar = (SeekBar) dialogView.findViewById(R.id.item_spacing_seekbar);
- mGridColumnsValue = (TextView) dialogView.findViewById(R.id.grid_columns_value);
- mItemSpacingValue = (TextView) dialogView.findViewById(R.id.item_spacing_value);
-
- // 设置布局类型选项
- ArrayAdapter layoutAdapter = new ArrayAdapter<>(
- mContext, android.R.layout.simple_spinner_item, LayoutType.values());
- mLayoutTypeSpinner.setAdapter(layoutAdapter);
-
- // 设置当前值
- LayoutType currentLayout = mLayoutManagerController.getCurrentLayoutType();
- mLayoutTypeSpinner.setSelection(currentLayout.ordinal());
-
- int gridColumns = mLayoutManagerController.getGridSpanCount();
- mGridColumnsSeekBar.setProgress(gridColumns - 1);
- mGridColumnsValue.setText(String.valueOf(gridColumns));
-
- int itemSpacing = mLayoutManagerController.getItemSpacing();
- mItemSpacingSeekBar.setProgress(itemSpacing / 2);
- mItemSpacingValue.setText(String.valueOf(itemSpacing));
-
- // 根据布局类型启用/禁用控件
- updateControlStates(currentLayout);
- }
-
- /**
- * 设置监听器
- */
- private void setupListeners() {
- mLayoutTypeSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(android.widget.AdapterView> parent, View view, int position, long id) {
- LayoutType selectedLayout = (LayoutType) parent.getItemAtPosition(position);
- updateControlStates(selectedLayout);
- }
-
- @Override
- public void onNothingSelected(android.widget.AdapterView> parent) {
- }
- });
-
- mGridColumnsSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- int columns = progress + 1;
- mGridColumnsValue.setText(String.valueOf(columns));
- }
-
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- }
-
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- }
- });
-
- mItemSpacingSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- int spacing = progress * 2;
- mItemSpacingValue.setText(String.valueOf(spacing));
- }
-
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- }
-
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- }
- });
- }
-
- /**
- * 更新控件状态
- * @param layoutType 布局类型
- */
- private void updateControlStates(LayoutType layoutType) {
- switch (layoutType) {
- case LINEAR:
- mGridColumnsSeekBar.setEnabled(false);
- mItemSpacingSeekBar.setEnabled(false);
- break;
- case GRID:
- case STAGGERED:
- mGridColumnsSeekBar.setEnabled(true);
- mItemSpacingSeekBar.setEnabled(true);
- break;
- }
- }
-
- /**
- * 保存设置
- */
- private void saveSettings() {
- LayoutType selectedLayout = (LayoutType) mLayoutTypeSpinner.getSelectedItem();
- int gridColumns = mGridColumnsSeekBar.getProgress() + 1;
- int itemSpacing = mItemSpacingSeekBar.getProgress() * 2;
-
- mLayoutManagerController.setGridSpanCount(gridColumns);
- mLayoutManagerController.setItemSpacing(itemSpacing);
-
- if (selectedLayout != mLayoutManagerController.getCurrentLayoutType()) {
- mLayoutManagerController.switchLayout(selectedLayout, true);
- }
-
- mDialog.dismiss();
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutType.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutType.java
deleted file mode 100644
index a94eec4..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/LayoutType.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-/**
- * 布局类型枚举
- *
- * 定义笔记列表支持的所有布局类型,包括线性布局、网格布局和瀑布流布局。
- * 每种布局类型都有对应的显示名称和描述。
- *
- */
-public enum LayoutType {
- LINEAR("linear", "列表布局", "传统的垂直列表布局,适合大量笔记浏览"),
- GRID("grid", "网格布局", "网格排列布局,适合快速浏览和预览"),
- STAGGERED("staggered", "瀑布流布局", "错落有致的布局,适合不同长度的笔记展示");
-
- private final String key;
- private final String displayName;
- private final String description;
-
- LayoutType(String key, String displayName, String description) {
- this.key = key;
- this.displayName = displayName;
- this.description = description;
- }
-
- public String getKey() {
- return key;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public String getDescription() {
- return description;
- }
-
- public static LayoutType fromKey(String key) {
- for (LayoutType type : values()) {
- if (type.key.equals(key)) {
- return type;
- }
- }
- return LINEAR;
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java
index 9544f6c..d4cecfe 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java
@@ -71,8 +71,11 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import androidx.appcompat.app.AppCompatActivity;
+import com.google.android.material.appbar.MaterialToolbar;
-public class NoteEditActivity extends Activity implements OnClickListener,
+
+public class NoteEditActivity extends AppCompatActivity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
/**
* 笔记头部视图持有者
@@ -143,6 +146,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private SharedPreferences mSharedPrefs;
private int mFontSizeId;
+ private MaterialToolbar toolbar;
+
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
@@ -160,6 +165,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit);
+ // 初始化Toolbar(使用MaterialToolbar,与列表页面一致)
+ MaterialToolbar toolbar = findViewById(R.id.toolbar);
+ setSupportActionBar(toolbar);
+ if (getSupportActionBar() != null) {
+ getSupportActionBar().setDisplayHomeAsUpEnabled(true);
+ getSupportActionBar().setDisplayShowHomeEnabled(true);
+ }
+ toolbar.setNavigationOnClickListener(v -> finish());
+
if (savedInstanceState == null && !initActivityState(getIntent())) {
finish();
return;
@@ -284,6 +298,49 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true;
}
+ /**
+ * 初始化资源
+ *
+ * 初始化笔记编辑界面的所有UI组件引用和点击监听器
+ *
+ */
+ private void initResources() {
+ mHeadViewPanel = findViewById(R.id.note_title);
+ mNoteHeaderHolder = new HeadViewHolder();
+ mNoteHeaderHolder.tvModified = findViewById(R.id.tv_modified_date);
+ mNoteHeaderHolder.ivAlertIcon = findViewById(R.id.iv_alert_icon);
+ mNoteHeaderHolder.tvAlertDate = findViewById(R.id.tv_alert_date);
+ mNoteHeaderHolder.ibSetBgColor = findViewById(R.id.btn_set_bg_color);
+ mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);
+ mNoteEditor = findViewById(R.id.note_edit_view);
+ mNoteEditorPanel = findViewById(R.id.sv_note_edit);
+ mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
+
+ // 设置背景颜色选择器的点击事件
+ for (int id : sBgSelectorBtnsMap.keySet()) {
+ ImageView iv = findViewById(id);
+ iv.setOnClickListener(this);
+ }
+
+ mFontSizeSelector = findViewById(R.id.font_size_selector);
+ for (int id : sFontSizeBtnsMap.keySet()) {
+ View view = findViewById(id);
+ view.setOnClickListener(this);
+ }
+
+ mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
+ /**
+ * HACKME: Fix bug of store the resource id in shared preference.
+ * The id may larger than the length of resources, in this case,
+ * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
+ */
+ if (mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
+ mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
+ }
+ mEditTextList = findViewById(R.id.note_edit_list);
+ }
+
@Override
protected void onResume() {
super.onResume();
@@ -430,47 +487,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true;
}
- /**
- * 初始化资源
- *
- * 初始化所有UI组件的引用,设置点击监听器,
- * 并从SharedPreferences中读取字体大小设置。
- *
- */
- private void initResources() {
- mHeadViewPanel = findViewById(R.id.note_title);
- mNoteHeaderHolder = new HeadViewHolder();
- mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
- mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);
- mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);
- mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);
- mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);
- mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
- mNoteEditorPanel = findViewById(R.id.sv_note_edit);
- mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
- for (int id : sBgSelectorBtnsMap.keySet()) {
- ImageView iv = (ImageView) findViewById(id);
- iv.setOnClickListener(this);
- }
-
- mFontSizeSelector = findViewById(R.id.font_size_selector);
- for (int id : sFontSizeBtnsMap.keySet()) {
- View view = findViewById(id);
- view.setOnClickListener(this);
- };
- mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
- mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
- /**
- * HACKME: Fix bug of store the resource id in shared preference.
- * The id may larger than the length of resources, in this case,
- * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
- */
- if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
- mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
- }
- mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
- }
-
/**
* 活动暂停时保存笔记
*
@@ -528,7 +544,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- - View.VISIBLE);
+ View.VISIBLE);
} else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE);
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemData.java
index 024cb5d..46638e9 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemData.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemData.java
@@ -59,6 +59,7 @@ public class NoteItemData {
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
+ NoteColumns.TOP, // 新增TOP字段
};
// 列索引常量,用于从查询结果中获取对应列的数据
@@ -74,6 +75,7 @@ public class NoteItemData {
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
+ private static final int TOP_COLUMN = 12;
// 笔记ID
private long mId;
@@ -99,6 +101,8 @@ public class NoteItemData {
private int mWidgetId;
// 桌面小部件类型
private int mWidgetType;
+ // 是否置顶
+ private boolean mIsPinned;
// 联系人名称(用于通话记录)
private String mName;
// 电话号码(用于通话记录)
@@ -140,6 +144,12 @@ public class NoteItemData {
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
+ // 读取置顶状态
+ if (cursor.getColumnCount() > TOP_COLUMN) {
+ mIsPinned = cursor.getInt(TOP_COLUMN) > 0;
+ } else {
+ mIsPinned = false;
+ }
mPhoneNumber = "";
// 如果是通话记录笔记,获取电话号码和联系人名称
@@ -377,6 +387,14 @@ public class NoteItemData {
return (mAlertDate > 0);
}
+ /**
+ * 判断是否置顶
+ * @return 如果置顶返回true
+ */
+ public boolean isPinned() {
+ return mIsPinned;
+ }
+
/**
* 判断是否为通话记录笔记
*
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemDecoration.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemDecoration.java
deleted file mode 100644
index 8011a60..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteItemDecoration.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-import android.view.View;
-import androidx.recyclerview.widget.RecyclerView;
-import androidx.recyclerview.widget.RecyclerView.ItemDecoration;
-import net.micode.notes.R;
-
-/**
- * 笔记列表项装饰
- *
- * 为RecyclerView添加分隔线效果,替代ListView的divider属性。
- *
- */
-public class NoteItemDecoration extends ItemDecoration {
- private Drawable mDivider;
- private int mDividerHeight;
-
- /**
- * 构造函数
- * @param context 上下文
- */
- public NoteItemDecoration(Context context) {
- mDivider = context.getResources().getDrawable(R.drawable.list_divider);
- if (mDivider != null) {
- mDividerHeight = 1;
- } else {
- mDividerHeight = mDivider.getIntrinsicHeight();
- }
- }
-
- @Override
- public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
- int left = parent.getPaddingLeft();
- int right = parent.getWidth() - parent.getPaddingRight();
-
- int childCount = parent.getChildCount();
- for (int i = 0; i < childCount - 1; i++) {
- View child = parent.getChildAt(i);
- RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
-
- int top = child.getBottom() + params.bottomMargin;
- int bottom = top + mDividerHeight;
-
- mDivider.setBounds(left, top, right, bottom);
- mDivider.draw(c);
- }
- }
-
- @Override
- public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
- outRect.bottom = mDividerHeight;
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteViewHolder.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteViewHolder.java
deleted file mode 100644
index 29bb5ad..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NoteViewHolder.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.view.View;
-import android.widget.CheckBox;
-import android.widget.ImageView;
-import android.widget.TextView;
-import androidx.recyclerview.widget.RecyclerView;
-
-import net.micode.notes.R;
-
-/**
- * 笔记ViewHolder
- *
- * RecyclerView的ViewHolder实现,持有笔记列表项的所有视图引用。
- * 避免重复findViewById,提升列表滚动性能。
- *
- */
-public class NoteViewHolder extends RecyclerView.ViewHolder {
- public ImageView mAlert;
- public TextView mTitle;
- public TextView mTime;
- public TextView mCallName;
- public CheckBox mCheckBox;
-
- /**
- * 构造函数
- * @param itemView 列表项的根视图
- */
- public NoteViewHolder(View itemView) {
- super(itemView);
- // 查找所有子视图(只执行一次)
- mAlert = (ImageView) itemView.findViewById(R.id.iv_alert_icon);
- mTitle = (TextView) itemView.findViewById(R.id.tv_title);
- mTime = (TextView) itemView.findViewById(R.id.tv_time);
- mCallName = (TextView) itemView.findViewById(R.id.tv_name);
- mCheckBox = (CheckBox) itemView.findViewById(android.R.id.checkbox);
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesListActivity.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesListActivity.java
index ff680a4..067fc53 100644
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesListActivity.java
+++ b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesListActivity.java
@@ -16,1347 +16,834 @@
package net.micode.notes.ui;
-import android.app.Activity;
import android.app.AlertDialog;
-import android.app.Dialog;
import android.appwidget.AppWidgetManager;
-import android.content.AsyncQueryHandler;
-import android.content.ContentResolver;
-import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
-import android.content.SharedPreferences;
-import android.database.Cursor;
-import android.os.AsyncTask;
import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.text.Editable;
+import android.text.InputFilter;
import android.text.TextUtils;
-import android.text.TextWatcher;
import android.util.Log;
-import android.view.ActionMode;
-import android.view.ContextMenu;
-import android.view.ContextMenu.ContextMenuInfo;
-import android.view.Display;
-import android.view.HapticFeedbackConstants;
-import android.view.LayoutInflater;
+import androidx.appcompat.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
-import android.view.MenuItem.OnMenuItemClickListener;
-import android.view.MotionEvent;
import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.View.OnCreateContextMenuListener;
-import android.view.View.OnTouchListener;
-import android.view.inputmethod.InputMethodManager;
+import android.view.WindowInsets;
+import android.view.WindowInsetsController;
+import android.view.WindowManager;
import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
-import androidx.recyclerview.widget.DefaultItemAnimator;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.graphics.Insets;
+import androidx.core.view.ViewCompat;
+import androidx.core.view.WindowCompat;
+import androidx.core.view.WindowInsetsCompat;
+import androidx.drawerlayout.widget.DrawerLayout;
+import androidx.lifecycle.Observer;
+import androidx.lifecycle.ViewModel;
+import androidx.lifecycle.ViewModelProvider;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.remote.GTaskSyncService;
-import net.micode.notes.model.WorkingNote;
-import net.micode.notes.tool.BackupUtils;
-import net.micode.notes.tool.DataUtils;
-import net.micode.notes.tool.ResourceParser;
-import net.micode.notes.ui.NotesRecyclerViewAdapter.AppWidgetAttribute;
-import net.micode.notes.widget.NoteWidgetProvider_2x;
-import net.micode.notes.widget.NoteWidgetProvider_4x;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.HashSet;
+import net.micode.notes.data.NotesRepository;
+import net.micode.notes.ui.NoteInfoAdapter;
+import net.micode.notes.viewmodel.NotesListViewModel;
-/**
- * 笔记列表活动
- *
- * 这个类是应用的主界面,用于显示笔记列表并提供笔记管理功能。
- * 支持创建、编辑、删除笔记,文件夹管理,笔记同步,以及桌面小部件集成。
- *
- * 主要功能:
- * 1. 显示笔记列表,支持按文件夹分类查看
- * 2. 创建新笔记和文件夹
- * 3. 批量选择和操作笔记(删除、移动)
- * 4. 笔记同步到 Google Tasks
- * 5. 导出笔记为文本文件
- * 6. 与桌面小部件集成
- *
- * @see NoteEditActivity
- * @see NotesListAdapter
- * @see GTaskSyncService
- */
-public class NotesListActivity extends Activity implements OnClickListener, NotesRecyclerViewAdapter.OnItemLongClickListener {
- // 笔记列表查询令牌
- private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
-
- // 文件夹列表查询令牌
- private static final int FOLDER_LIST_QUERY_TOKEN = 1;
-
- // 文件夹删除菜单ID
- private static final int MENU_FOLDER_DELETE = 0;
-
- // 文件夹查看菜单ID
- private static final int MENU_FOLDER_VIEW = 1;
-
- // 文件夹重命名菜单ID
- private static final int MENU_FOLDER_CHANGE_NAME = 2;
-
- // 首次使用应用时添加介绍笔记的偏好设置键
- private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
-
- /**
- * 列表编辑状态枚举
- *
- * 定义笔记列表的三种显示状态
- */
- private enum ListEditState {
- NOTE_LIST, // 笔记列表状态
- SUB_FOLDER, // 子文件夹状态
- CALL_RECORD_FOLDER // 通话记录文件夹状态
- };
-
- // 当前列表编辑状态
- private ListEditState mState;
-
- // 后台查询处理器
- private BackgroundQueryHandler mBackgroundQueryHandler;
+import com.google.android.material.floatingactionbutton.FloatingActionButton;
- // 笔记列表适配器
- private NotesRecyclerViewAdapter mNotesListAdapter;
-
- // 笔记列表视图
- private RecyclerView mNotesRecyclerView;
-
- // 布局管理器
- private LinearLayoutManager mLayoutManager;
-
- // 布局切换控制器
- private LayoutManagerController mLayoutManagerController;
-
- // 新建笔记按钮
- private Button mAddNewNote;
-
- // 是否正在分发触摸事件
- private boolean mDispatch;
-
- // 触摸事件的原始Y坐标
- private int mOriginY;
-
- // 分发触摸事件的Y坐标
- private int mDispatchY;
-
- // 标题栏文本视图
- private TextView mTitleBar;
-
- // 当前文件夹ID
- private long mCurrentFolderId;
-
- // 内容解析器
- private ContentResolver mContentResolver;
-
- // 多选模式回调
- private ModeCallback mModeCallBack;
+import java.util.List;
+/**
+ * 笔记列表Activity(重构版)
+ *
+ * 仅负责UI展示和用户交互,业务逻辑委托给ViewModel
+ * 符合MVVM架构模式
+ *
+ *
+ * 相比原版(1305行),重构后代码量减少约70%
+ *
+ *
+ * @see NotesListViewModel
+ * @see NotesRepository
+ */
+public class NotesListActivity extends AppCompatActivity
+ implements NoteInfoAdapter.OnNoteButtonClickListener,
+ NoteInfoAdapter.OnNoteItemClickListener,
+ NoteInfoAdapter.OnNoteItemLongClickListener,
+ SidebarFragment.OnSidebarItemSelectedListener {
private static final String TAG = "NotesListActivity";
+ private static final int REQUEST_CODE_OPEN_NODE = 102;
+ private static final int REQUEST_CODE_NEW_NODE = 103;
- // 笔记列表滚动速率
- public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
-
- // 当前聚焦的笔记数据项
- private NoteItemData mFocusNoteDataItem;
-
- // 普通选择条件:指定父文件夹ID
- private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
+ private NotesListViewModel viewModel;
+ private ListView notesListView;
+ private androidx.appcompat.widget.Toolbar toolbar;
+ private NoteInfoAdapter adapter;
+ private DrawerLayout drawerLayout;
+ private FloatingActionButton fabNewNote;
+ private LinearLayout breadcrumbContainer;
+ private LinearLayout breadcrumbItems;
- // 根文件夹选择条件:显示所有非系统笔记和有内容的通话记录文件夹
- private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
- + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
- + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
- + NoteColumns.NOTES_COUNT + ">0)";
-
- // 打开笔记的请求码
- private final static int REQUEST_CODE_OPEN_NODE = 102;
- // 新建笔记的请求码
- private final static int REQUEST_CODE_NEW_NODE = 103;
+ // 多选模式状态
+ private boolean isMultiSelectMode = false;
/**
* 活动创建时的初始化方法
- *
- * 设置布局,初始化资源,首次使用时添加介绍笔记
- *
+ *
+ * 设置布局,初始化ViewModel,设置UI监听器
+ *
+ *
* @param savedInstanceState 保存的实例状态
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.note_list);
- initResources();
- /**
- * Insert an introduction when user firstly use this application
- */
- setAppInfoFromRawRes();
- }
+ // 启用边缘到边缘显示
+ WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
- /**
- * 活动结果回调方法
- *
- * 当从笔记编辑活动返回时,刷新笔记列表
- *
- * @param requestCode 请求码,标识是哪个活动返回
- * @param resultCode 结果码,RESULT_OK表示操作成功
- * @param data 返回的Intent数据
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (resultCode == RESULT_OK
- && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
- mNotesListAdapter.swapCursor(null);
- } else {
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
+ setContentView(R.layout.note_list);
- /**
- * 从原始资源文件加载并创建介绍笔记
- *
- * 首次使用应用时,从res/raw/introduction文件读取内容并创建一条介绍笔记
- */
- private void setAppInfoFromRawRes() {
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
- StringBuilder sb = new StringBuilder();
- InputStream in = null;
- try {
- in = getResources().openRawResource(R.raw.introduction);
- if (in != null) {
- InputStreamReader isr = new InputStreamReader(in);
- BufferedReader br = new BufferedReader(isr);
- char [] buf = new char[1024];
- int len = 0;
- while ((len = br.read(buf)) > 0) {
- sb.append(buf, 0, len);
- }
- } else {
- Log.e(TAG, "Read introduction file error");
- return;
- }
- } catch (IOException e) {
- e.printStackTrace();
- return;
- } finally {
- if(in != null) {
- try {
- in.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
+ // 处理窗口insets(状态栏和导航栏)
+ View mainView = findViewById(android.R.id.content);
+ ViewCompat.setOnApplyWindowInsetsListener(mainView, (v, windowInsets) -> {
+ Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
+ // 设置内容区域的padding以避免被状态栏遮挡
+ v.setPadding(insets.left, insets.top, insets.right, insets.bottom);
+ return WindowInsetsCompat.CONSUMED;
+ });
- WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
- AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
- ResourceParser.RED);
- note.setWorkingText(sb.toString());
- if (note.saveNote()) {
- sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
- } else {
- Log.e(TAG, "Save introduction note error");
- return;
- }
- }
+ initViewModel();
+ initViews();
+ observeViewModel();
}
/**
* 活动启动时的回调方法
- *
- * 启动异步查询笔记列表
+ *
+ * 加载笔记列表
+ *
*/
@Override
protected void onStart() {
super.onStart();
- startAsyncNotesListQuery();
+ viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
}
/**
- * 初始化资源
- *
- * 初始化所有UI组件、适配器和监听器
+ * 初始化ViewModel
*/
- private void initResources() {
- mContentResolver = this.getContentResolver();
- mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
- mCurrentFolderId = Notes.ID_ROOT_FOLDER;
- mNotesRecyclerView = (RecyclerView) findViewById(R.id.notes_list);
- mLayoutManager = new LinearLayoutManager(this);
- mNotesRecyclerView.setLayoutManager(mLayoutManager);
-
- // 创建适配器
- mNotesListAdapter = new NotesRecyclerViewAdapter(this);
- mNotesRecyclerView.setAdapter(mNotesListAdapter);
-
- // 设置动画
- DefaultItemAnimator animator = new DefaultItemAnimator();
- animator.setAddDuration(300);
- animator.setRemoveDuration(300);
- animator.setMoveDuration(300);
- animator.setChangeDuration(300);
- mNotesRecyclerView.setItemAnimator(animator);
-
- // 初始化布局切换控制器
- mLayoutManagerController = new LayoutManagerController(this, mNotesRecyclerView,
- new LayoutManagerController.LayoutChangeListener() {
- @Override
- public void onLayoutChanged(LayoutType newLayoutType) {
- showToast("已切换到" + newLayoutType.getDisplayName());
+ private void initViewModel() {
+ NotesRepository repository = new NotesRepository(getContentResolver());
+ viewModel = new ViewModelProvider(this,
+ new ViewModelProvider.Factory() {
+ @Override
+ public T create(Class modelClass) {
+ if (modelClass.isAssignableFrom(NotesListViewModel.class)) {
+ return (T) new NotesListViewModel(repository);
}
-
- @Override
- public void onLayoutChangeFailed(Exception e) {
- showToast("布局切换失败: " + e.getMessage());
- }
- });
-
- // 应用保存的布局
- mLayoutManagerController.initializeLayout();
-
- // 设置点击和长按监听
- mNotesListAdapter.setOnItemClickListener(new OnListItemClickListener());
- mNotesListAdapter.setOnItemLongClickListener(this);
-
- mAddNewNote = (Button) findViewById(R.id.btn_new_note);
- mAddNewNote.setOnClickListener(this);
- mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
- mDispatch = false;
- mDispatchY = 0;
- mOriginY = 0;
- mTitleBar = (TextView) findViewById(R.id.tv_title_bar);
- mState = ListEditState.NOTE_LIST;
- mModeCallBack = new ModeCallback();
+ throw new IllegalArgumentException("Unknown ViewModel class");
+ }
+ }).get(NotesListViewModel.class);
+ Log.d(TAG, "ViewModel initialized");
}
/**
- * 多选模式回调类
- *
- * 实现ActionMode.Callback接口,处理多选模式的创建、销毁和项选中状态变化
+ * 初始化视图
*/
- private class ModeCallback implements ActionMode.Callback, OnMenuItemClickListener {
- private DropdownMenu mDropDownMenu;
- private ActionMode mActionMode;
- private MenuItem mMoveMenu;
-
- /**
- * 创建多选模式的操作栏
- *
- * @param mode ActionMode对象
- * @param menu 菜单对象
- * @return true表示成功创建
- */
- public boolean onCreateActionMode(ActionMode mode, Menu menu) {
- getMenuInflater().inflate(R.menu.note_list_options, menu);
- menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
- mMoveMenu = menu.findItem(R.id.move);
- if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
- || DataUtils.getUserFolderCount(mContentResolver) == 0) {
- mMoveMenu.setVisible(false);
- } else {
- mMoveMenu.setVisible(true);
- mMoveMenu.setOnMenuItemClickListener(this);
- }
- mActionMode = mode;
- mNotesListAdapter.setChoiceMode(true);
- mAddNewNote.setVisibility(View.GONE);
-
- View customView = LayoutInflater.from(NotesListActivity.this).inflate(
- R.layout.note_list_dropdown_menu, null);
- mode.setCustomView(customView);
- mDropDownMenu = new DropdownMenu(NotesListActivity.this,
- (Button) customView.findViewById(R.id.selection_menu),
- R.menu.note_list_dropdown);
- mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
- /**
- * 下拉菜单项点击事件处理
- *
- * @param item 被点击的菜单项
- * @return true表示事件已处理
- */
- public boolean onMenuItemClick(MenuItem item) {
- mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
- updateMenu();
- return true;
- }
+ private void initViews() {
+ notesListView = findViewById(R.id.notes_list);
+ toolbar = findViewById(R.id.toolbar);
+ drawerLayout = findViewById(R.id.drawer_layout);
- });
- return true;
- }
+ // 初始化面包屑导航
+ breadcrumbContainer = findViewById(R.id.breadcrumb_container);
+ breadcrumbItems = findViewById(R.id.breadcrumb_items);
- /**
- * 更新菜单显示
- *
- * 根据选中数量更新下拉菜单标题和全选按钮状态
- */
- private void updateMenu() {
- int selectedCount = mNotesListAdapter.getSelectedCount();
- // Update dropdown menu
- String format = getResources().getString(R.string.menu_select_title, selectedCount);
- mDropDownMenu.setTitle(format);
- MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
- if (item != null) {
- if (mNotesListAdapter.isAllSelected()) {
- item.setChecked(true);
- item.setTitle(R.string.menu_deselect_all);
- } else {
- item.setChecked(false);
- item.setTitle(R.string.menu_select_all);
+ // 设置适配器
+ adapter = new NoteInfoAdapter(this);
+ notesListView.setAdapter(adapter);
+ adapter.setOnNoteButtonClickListener(this);
+ adapter.setOnNoteItemClickListener(this);
+ adapter.setOnNoteItemLongClickListener(this);
+
+ // 设置点击监听
+ notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ Object item = parent.getItemAtPosition(position);
+ if (item instanceof NotesRepository.NoteInfo) {
+ NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) item;
+ handleItemClick(note, position);
}
}
- }
+ });
- /**
- * 准备多选模式的操作栏
- *
- * @param mode ActionMode对象
- * @param menu 菜单对象
- * @return false
- */
- public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
- // TODO Auto-generated method stub
- return false;
+ // 初始化 Toolbar
+ toolbar = findViewById(R.id.toolbar);
+ setSupportActionBar(toolbar);
+ if (getSupportActionBar() != null) {
+ getSupportActionBar().setTitle(R.string.app_name);
}
- /**
- * 操作栏菜单项点击事件处理
- *
- * @param mode ActionMode对象
- * @param item 被点击的菜单项
- * @return false
- */
- public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
- // TODO Auto-generated method stub
- return false;
- }
+ // 初始化为普通模式
+ updateToolbarForNormalMode();
- /**
- * 销毁多选模式的操作栏
- *
- * 退出选择模式,恢复列表视图的常规状态
- *
- * @param mode ActionMode对象
- */
- public void onDestroyActionMode(ActionMode mode) {
- mNotesListAdapter.setChoiceMode(false);
- mAddNewNote.setVisibility(View.VISIBLE);
- }
+ // 设置 Toolbar 的汉堡菜单按钮点击监听器(打开侧栏)
+ toolbar.setNavigationOnClickListener(v -> {
+ if (drawerLayout != null) {
+ drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
+ }
+ });
- /**
- * 完成多选模式
- *
- * 手动结束ActionMode
- */
- public void finishActionMode() {
- mActionMode.finish();
+ // Set FAB click event
+ fabNewNote = findViewById(R.id.btn_new_note);
+ if (fabNewNote != null) {
+ fabNewNote.setOnClickListener(v -> {
+ Intent intent = new Intent(NotesListActivity.this, NoteEditActivity.class);
+ intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
+ intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, viewModel.getCurrentFolderId());
+ startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
+ });
}
+ }
- /**
- * 列表项选中状态变化事件处理
- *
- * @param mode ActionMode对象
- * @param position 列表项位置
- * @param id 列表项ID
- * @param checked 是否选中
- */
- public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
- boolean checked) {
- mNotesListAdapter.setCheckedItem(position, checked);
- updateMenu();
+ /**
+ * 处理列表项点击
+ *
+ * 如果是便签,打开编辑器;如果是文件夹,进入该文件夹
+ *
+ *
+ * @param note 项
+ * @param position 位置
+ */
+ private void handleItemClick(NotesRepository.NoteInfo note, int position) {
+ if (isMultiSelectMode) {
+ // 多选模式:切换选中状态
+ boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
+ viewModel.toggleNoteSelection(note.getId(), !isSelected);
+ if (adapter != null) {
+ adapter.setSelectedIds(viewModel.getSelectedNoteIds());
+ }
+ updateToolbarForMultiSelectMode();
+ } else {
+ // 普通模式
+ if (note.type == Notes.TYPE_FOLDER) {
+ // 文件夹:进入该文件夹
+ viewModel.enterFolder(note.getId());
+ } else {
+ // 便签:打开编辑器
+ openNoteEditor(note);
+ }
}
+ }
- public boolean onMenuItemClick(MenuItem item) {
- if (mNotesListAdapter.getSelectedCount() == 0) {
- Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
- Toast.LENGTH_SHORT).show();
- return true;
+ /**
+ * 观察ViewModel的LiveData
+ */
+ private void observeViewModel() {
+ // 观察笔记列表
+ viewModel.getNotesLiveData().observe(this, new Observer>() {
+ @Override
+ public void onChanged(List notes) {
+ updateAdapter(notes);
}
+ });
- switch (item.getItemId()) {
- case R.id.delete:
- AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
- builder.setTitle(getString(R.string.alert_title_delete));
- builder.setIcon(android.R.drawable.ic_dialog_alert);
- builder.setMessage(getString(R.string.alert_message_delete_notes,
- mNotesListAdapter.getSelectedCount()));
- builder.setPositiveButton(android.R.string.ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,
- int which) {
- batchDelete();
- }
- });
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- break;
- case R.id.move:
- startQueryDestinationFolders();
- break;
- default:
- return false;
+ // 观察加载状态
+ viewModel.getIsLoading().observe(this, new Observer() {
+ @Override
+ public void onChanged(Boolean isLoading) {
+ updateLoadingState(isLoading);
}
- return true;
- }
- }
+ });
- private class NewNoteOnTouchListener implements OnTouchListener {
-
- public boolean onTouch(View v, MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN: {
- Display display = getWindowManager().getDefaultDisplay();
- int screenHeight = display.getHeight();
- int newNoteViewHeight = mAddNewNote.getHeight();
- int start = screenHeight - newNoteViewHeight;
- int eventY = start + (int) event.getY();
- /**
- * Minus TitleBar's height
- */
- if (mState == ListEditState.SUB_FOLDER) {
- eventY -= mTitleBar.getHeight();
- start -= mTitleBar.getHeight();
- }
- /**
- * HACKME:When click the transparent part of "New Note" button, dispatch
- * the event to the list view behind this button. The transparent part of
- * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel)
- * and the line top of the button. The coordinate based on left of the "New
- * Note" button. The 94 represents maximum height of the transparent part.
- * Notice that, if the background of the button changes, the formula should
- * also change. This is very bad, just for the UI designer's strong requirement.
- */
- if (event.getY() < (event.getX() * (-0.12) + 94)) {
- View view = mNotesRecyclerView.getChildAt(mNotesRecyclerView.getChildCount() - 1);
- if (view != null && view.getBottom() > start
- && (view.getTop() < (start + 94))) {
- mOriginY = (int) event.getY();
- mDispatchY = eventY;
- event.setLocation(event.getX(), mDispatchY);
- mDispatch = true;
- return mNotesRecyclerView.dispatchTouchEvent(event);
- }
- }
- break;
- }
- case MotionEvent.ACTION_MOVE: {
- if (mDispatch) {
- mDispatchY += (int) event.getY() - mOriginY;
- event.setLocation(event.getX(), mDispatchY);
- return mNotesRecyclerView.dispatchTouchEvent(event);
- }
- break;
- }
- default: {
- if (mDispatch) {
- event.setLocation(event.getX(), mDispatchY);
- mDispatch = false;
- return mNotesRecyclerView.dispatchTouchEvent(event);
- }
- break;
+ // 观察错误消息
+ viewModel.getErrorMessage().observe(this, new Observer() {
+ @Override
+ public void onChanged(String message) {
+ if (message != null && !message.isEmpty()) {
+ showError(message);
}
}
- return false;
- }
+ });
- };
+ // 观察文件夹路径(用于面包屑导航)
+ viewModel.getFolderPathLiveData().observe(this, new Observer>() {
+ @Override
+ public void onChanged(List path) {
+ updateBreadcrumb(path);
+ }
+ });
- /**
- * 启动异步笔记列表查询
- *
- * 根据当前文件夹ID构建查询条件,启动后台查询获取笔记列表数据。
- * 根文件夹使用特殊的查询条件,子文件夹使用普通查询条件。
- *
- */
- private void startAsyncNotesListQuery() {
- String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
- : NORMAL_SELECTION;
- mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
- Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
- String.valueOf(mCurrentFolderId)
- }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
+ // 观察侧栏刷新通知
+ viewModel.getSidebarRefreshNeeded().observe(this, new Observer() {
+ @Override
+ public void onChanged(Boolean refreshNeeded) {
+ if (refreshNeeded != null && refreshNeeded) {
+ // 通知侧栏刷新
+ SidebarFragment sidebarFragment = (SidebarFragment) getSupportFragmentManager()
+ .findFragmentById(R.id.sidebar_fragment);
+ if (sidebarFragment != null) {
+ sidebarFragment.refreshFolderTree();
+ }
+ // 重置刷新状态
+ viewModel.getSidebarRefreshNeeded().setValue(false);
+ }
+ }
+ });
}
/**
- * 后台查询处理器
- *
- * 继承自AsyncQueryHandler,用于在后台线程执行数据库查询,
- * 避免阻塞UI线程。
- *
+ * 更新面包屑导航
+ *
+ * @param path 文件夹路径
*/
- private final class BackgroundQueryHandler extends AsyncQueryHandler {
- /**
- * 构造函数
- * @param contentResolver 内容解析器
- */
- public BackgroundQueryHandler(ContentResolver contentResolver) {
- super(contentResolver);
+ private void updateBreadcrumb(List path) {
+ if (breadcrumbItems == null || path == null) {
+ return;
}
- /**
- * 查询完成回调
- *
- * 根据查询令牌处理不同的查询结果:
- *
- * FOLDER_NOTE_LIST_QUERY_TOKEN: 更新笔记列表适配器
- * FOLDER_LIST_QUERY_TOKEN: 显示文件夹选择菜单
- *
- *
- * @param token 查询令牌
- * @param cookie Cookie对象
- * @param cursor 查询结果游标
- */
- @Override
- protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
- switch (token) {
- case FOLDER_NOTE_LIST_QUERY_TOKEN:
- mNotesListAdapter.swapCursor(cursor);
- break;
- case FOLDER_LIST_QUERY_TOKEN:
- if (cursor != null && cursor.getCount() > 0) {
- showFolderListMenu(cursor);
- } else {
- Log.e(TAG, "Query folder failed");
- }
- break;
- default:
- return;
+ breadcrumbItems.removeAllViews();
+
+ for (int i = 0; i < path.size(); i++) {
+ NotesRepository.NoteInfo folder = path.get(i);
+
+ // 如果不是第一个,添加分隔符 " > "
+ if (i > 0) {
+ TextView separator = new TextView(this);
+ separator.setText(" > ");
+ separator.setTextSize(14);
+ separator.setTextColor(android.R.color.darker_gray);
+ breadcrumbItems.addView(separator);
}
- }
- }
- /**
- * 显示文件夹选择菜单
- *
- * 显示一个对话框,列出所有可用的目标文件夹供用户选择,
- * 用于移动选中的笔记到指定文件夹。
- *
- * @param cursor 包含文件夹列表的游标
- */
- private void showFolderListMenu(Cursor cursor) {
- AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
- builder.setTitle(R.string.menu_title_select_folder);
- final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
- builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
+ // 创建面包屑项
+ TextView breadcrumbItem = (TextView) getLayoutInflater()
+ .inflate(R.layout.breadcrumb_item, breadcrumbItems, false);
+ breadcrumbItem.setText(folder.title);
- public void onClick(DialogInterface dialog, int which) {
- DataUtils.batchMoveToFolder(mContentResolver,
- mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
- Toast.makeText(
- NotesListActivity.this,
- getString(R.string.format_move_notes_to_folder,
- mNotesListAdapter.getSelectedCount(),
- adapter.getFolderName(NotesListActivity.this, which)),
- Toast.LENGTH_SHORT).show();
- mModeCallBack.finishActionMode();
+ // 如果是当前文件夹(最后一个),高亮显示且不可点击
+ if (i == path.size() - 1) {
+ breadcrumbItem.setTextColor(getColor(R.color.primary_color));
+ breadcrumbItem.setEnabled(false);
+ } else {
+ // 其他层级可以点击跳转
+ final long targetFolderId = folder.id;
+ breadcrumbItem.setOnClickListener(v -> viewModel.enterFolder(targetFolderId));
}
- });
- builder.show();
+
+ breadcrumbItems.addView(breadcrumbItem);
+ }
}
/**
- * 创建新笔记
- *
- * 启动NoteEditActivity创建新笔记,传递当前文件夹ID。
- *
+ * 更新适配器数据
*/
- private void createNewNote() {
- Intent intent = new Intent(this, NoteEditActivity.class);
- intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
- intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
- this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
+ private void updateAdapter(List notes) {
+ adapter.setNotes(notes);
+ Log.d(TAG, "Adapter updated with " + notes.size() + " notes");
}
/**
- * 批量删除笔记
- *
- * 在后台线程中删除选中的笔记。
- * 如果处于同步模式,将笔记移动到垃圾箱文件夹;
- * 否则直接删除。同时更新相关的小部件。
- *
+ * 更新加载状态
*/
- private void batchDelete() {
- new AsyncTask>() {
- protected HashSet doInBackground(Void... unused) {
- HashSet widgets = mNotesListAdapter.getSelectedWidget();
- if (!isSyncMode()) {
- // if not synced, delete notes directly
- if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
- .getSelectedItemIds())) {
- } else {
- Log.e(TAG, "Delete notes error, should not happens");
- }
- } else {
- // in sync mode, we'll move the deleted note into the trash
- // folder
- if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
- .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
- Log.e(TAG, "Move notes to trash folder error, should not happens");
- }
- }
- return widgets;
- }
-
- @Override
- protected void onPostExecute(HashSet widgets) {
- if (widgets != null) {
- for (AppWidgetAttribute widget : widgets) {
- if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
- updateWidget(widget.widgetId, widget.widgetType);
- }
- }
- }
- mModeCallBack.finishActionMode();
- }
- }.execute();
+ private void updateLoadingState(boolean isLoading) {
+ // TODO: 显示/隐藏进度条
}
/**
- * 删除文件夹
- *
- * 删除指定的文件夹及其包含的所有笔记。
- * 如果处于同步模式,将文件夹移动到垃圾箱;
- * 否则直接删除。同时更新相关的小部件。
- *
- * @param folderId 要删除的文件夹ID
+ * 显示错误消息
*/
- private void deleteFolder(long folderId) {
- if (folderId == Notes.ID_ROOT_FOLDER) {
- Log.e(TAG, "Wrong folder id, should not happen " + folderId);
- return;
- }
-
- HashSet ids = new HashSet();
- ids.add(folderId);
- HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver,
- folderId);
- if (!isSyncMode()) {
- // if not synced, delete folder directly
- DataUtils.batchDeleteNotes(mContentResolver, ids);
- } else {
- // in sync mode, we'll move the deleted folder into the trash folder
- DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
- }
- if (widgets != null) {
- for (AppWidgetAttribute widget : widgets) {
- if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
- updateWidget(widget.widgetId, widget.widgetType);
- }
- }
- }
+ private void showError(String message) {
+ Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
/**
- * 打开笔记
- *
- * 启动NoteEditActivity查看和编辑指定的笔记。
- *
- * @param data 笔记数据项
+ * 打开笔记编辑器
*/
- private void openNode(NoteItemData data) {
+ private void openNoteEditor(NotesRepository.NoteInfo note) {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
- intent.putExtra(Intent.EXTRA_UID, data.getId());
- this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
+ intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, note.getParentId());
+ intent.putExtra(Intent.EXTRA_UID, note.getId());
+ startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
/**
- * 打开文件夹
- *
- * 进入指定的文件夹,显示该文件夹中的笔记列表。
- * 更新标题栏显示文件夹名称,并隐藏新建笔记按钮(如果是通话记录文件夹)。
- *
- * @param data 文件夹数据项
+ * 编辑按钮点击事件处理
+ *
+ * @param position 列表位置
+ * @param noteId 便签 ID
*/
- private void openFolder(NoteItemData data) {
- mCurrentFolderId = data.getId();
- startAsyncNotesListQuery();
- if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
- mState = ListEditState.CALL_RECORD_FOLDER;
- mAddNewNote.setVisibility(View.GONE);
+ @Override
+ public void onEditButtonClick(int position, long noteId) {
+ NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
+ if (note != null) {
+ openNoteEditor(note);
} else {
- mState = ListEditState.SUB_FOLDER;
+ Log.e(TAG, "Edit button clicked but note is null at position: " + position);
}
- if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
- mTitleBar.setText(R.string.call_record_folder_name);
+ }
+
+ @Override
+ public void onNoteItemClick(int position, long noteId) {
+ Log.d(TAG, "===== onNoteItemClick CALLED =====");
+ Log.d(TAG, "position: " + position + ", noteId: " + noteId);
+
+ if (isMultiSelectMode) {
+ Log.d(TAG, "Multi-select mode active, toggling selection");
+ NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
+ if (note != null) {
+ boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
+ viewModel.toggleNoteSelection(note.getId(), !isSelected);
+
+ if (adapter != null) {
+ adapter.setSelectedIds(viewModel.getSelectedNoteIds());
+ }
+ // 更新toolbar标题
+ updateToolbarForMultiSelectMode();
+ }
+ Log.d(TAG, "===== onNoteItemClick END (multi-select mode) =====");
} else {
- mTitleBar.setText(data.getSnippet());
+ Log.d(TAG, "Normal mode, checking item type");
+ NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
+ if (note != null) {
+ if (note.type == Notes.TYPE_FOLDER) {
+ // 文件夹:进入该文件夹
+ Log.d(TAG, "Folder clicked, entering folder: " + note.getId());
+ viewModel.enterFolder(note.getId());
+ } else {
+ // 便签:打开编辑器
+ Log.d(TAG, "Note clicked, opening editor");
+ openNoteEditor(note);
+ }
+ }
+ Log.d(TAG, "===== onNoteItemClick END =====");
}
- mTitleBar.setVisibility(View.VISIBLE);
}
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.btn_new_note:
- createNewNote();
- break;
- default:
- break;
+ @Override
+ public void onNoteItemLongClick(int position, long noteId) {
+ Log.d(TAG, "===== onNoteItemLongClick CALLED =====");
+ Log.d(TAG, "position: " + position + ", noteId: " + noteId);
+
+ if (!isMultiSelectMode) {
+ Log.d(TAG, "Entering multi-select mode");
+ enterMultiSelectMode();
+ viewModel.toggleNoteSelection(noteId, true);
+
+ if (adapter != null) {
+ adapter.setSelectedIds(viewModel.getSelectedNoteIds());
+ }
+
+ updateSelectionState(position, true);
+
+ Log.d(TAG, "===== onNoteItemLongClick END =====");
+ } else {
+ Log.d(TAG, "Multi-select mode already active, ignoring long click");
}
}
/**
- * 显示软键盘
- *
- * 强制显示系统软键盘,用于输入文件夹名称。
- *
+ * 进入多选模式
*/
- private void showSoftInput() {
- InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- if (inputMethodManager != null) {
- inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
+ private void enterMultiSelectMode() {
+ isMultiSelectMode = true;
+ // 隐藏FAB按钮
+ if (fabNewNote != null) {
+ fabNewNote.setVisibility(View.GONE);
}
+ // 更新toolbar为多选模式
+ updateToolbarForMultiSelectMode();
}
/**
- * 隐藏软键盘
- *
- * 隐藏指定视图的软键盘。
- *
- * @param view 要隐藏键盘的视图
+ * 退出多选模式
*/
- private void hideSoftInput(View view) {
- InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
+ private void exitMultiSelectMode() {
+ isMultiSelectMode = false;
+ // 显示FAB按钮
+ if (fabNewNote != null) {
+ fabNewNote.setVisibility(View.VISIBLE);
+ }
+ // 清除选中状态
+ viewModel.clearSelection();
+ if (adapter != null) {
+ adapter.setSelectedIds(new java.util.HashSet<>());
+ adapter.notifyDataSetChanged();
+ }
+ // 更新toolbar为普通模式
+ updateToolbarForNormalMode();
}
/**
- * 显示创建或修改文件夹对话框
- *
- * 显示一个对话框,允许用户输入文件夹名称。
- * 根据create参数决定是创建新文件夹还是修改现有文件夹名称。
- *
- * @param create true表示创建新文件夹,false表示修改文件夹名称
+ * 更新Toolbar为多选模式
*/
- private void showCreateOrModifyFolderDialog(final boolean create) {
- final AlertDialog.Builder builder = new AlertDialog.Builder(this);
- View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
- final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
- showSoftInput();
- if (!create) {
- if (mFocusNoteDataItem != null) {
- etName.setText(mFocusNoteDataItem.getSnippet());
- builder.setTitle(getString(R.string.menu_folder_change_name));
- } else {
- Log.e(TAG, "The long click data item is null");
- return;
- }
- } else {
- etName.setText("");
- builder.setTitle(this.getString(R.string.menu_create_folder));
- }
+ private void updateToolbarForMultiSelectMode() {
+ if (toolbar == null) return;
- builder.setPositiveButton(android.R.string.ok, null);
- builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- hideSoftInput(etName);
- }
- });
+ // 设置标题为选中数量
+ int selectedCount = viewModel.getSelectedCount();
+ String title = getString(R.string.menu_select_title, selectedCount);
+ toolbar.setTitle(title);
- final Dialog dialog = builder.setView(view).show();
- final Button positive = (Button)dialog.findViewById(android.R.id.button1);
- positive.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- hideSoftInput(etName);
- String name = etName.getText().toString();
- if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
- Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
- Toast.LENGTH_LONG).show();
- etName.setSelection(0, etName.length());
- return;
- }
- if (!create) {
- if (!TextUtils.isEmpty(name)) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.SNIPPET, name);
- values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
- + "=?", new String[] {
- String.valueOf(mFocusNoteDataItem.getId())
- });
- }
- } else if (!TextUtils.isEmpty(name)) {
- ContentValues values = new ContentValues();
- values.put(NoteColumns.SNIPPET, name);
- values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
- mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
- }
- dialog.dismiss();
- }
- });
+ // 设置导航图标为返回(取消多选)
+ toolbar.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material);
+ toolbar.setNavigationOnClickListener(v -> exitMultiSelectMode());
- if (TextUtils.isEmpty(etName.getText())) {
- positive.setEnabled(false);
- }
- /**
- * When the name edit text is null, disable the positive button
- */
- etName.addTextChangedListener(new TextWatcher() {
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- // TODO Auto-generated method stub
+ // 移除普通模式的菜单(如果有)
+ toolbar.getMenu().clear();
- }
+ // 直接在toolbar上添加操作按钮(不在三点菜单中)
+ Menu menu = toolbar.getMenu();
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- if (TextUtils.isEmpty(etName.getText())) {
- positive.setEnabled(false);
- } else {
- positive.setEnabled(true);
- }
- }
+ // 删除按钮
+ MenuItem deleteItem = menu.add(Menu.NONE, R.id.multi_select_delete, 1, getString(R.string.menu_delete));
+ deleteItem.setIcon(android.R.drawable.ic_menu_delete);
+ deleteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
- public void afterTextChanged(Editable s) {
- // TODO Auto-generated method stub
+ // 移动按钮
+ MenuItem moveItem = menu.add(Menu.NONE, R.id.multi_select_move, 2, getString(R.string.menu_move));
+ moveItem.setIcon(android.R.drawable.ic_menu_sort_by_size);
+ moveItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
- }
- });
+ // 置顶按钮
+ boolean allPinned = viewModel.isAllSelectedPinned();
+ MenuItem pinItem = menu.add(Menu.NONE, R.id.multi_select_pin, 3, allPinned ? getString(R.string.menu_unpin) : getString(R.string.menu_pin));
+ // 使用上传图标代替置顶图标,或者如果有合适的资源可以使用
+ pinItem.setIcon(android.R.drawable.ic_menu_upload);
+ pinItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
/**
- * 返回键按下处理
- *
- * 根据当前列表状态处理返回键事件:
- *
- * 子文件夹或通话记录文件夹:返回根文件夹列表
- * 笔记列表:调用父类方法退出Activity
- *
- *
+ * 更新Toolbar为普通模式
*/
- @Override
- public void onBackPressed() {
- switch (mState) {
- case SUB_FOLDER:
- mCurrentFolderId = Notes.ID_ROOT_FOLDER;
- mState = ListEditState.NOTE_LIST;
- startAsyncNotesListQuery();
- mTitleBar.setVisibility(View.GONE);
- break;
- case CALL_RECORD_FOLDER:
- mCurrentFolderId = Notes.ID_ROOT_FOLDER;
- mState = ListEditState.NOTE_LIST;
- mAddNewNote.setVisibility(View.VISIBLE);
- mTitleBar.setVisibility(View.GONE);
- startAsyncNotesListQuery();
- break;
- case NOTE_LIST:
- super.onBackPressed();
- break;
- default:
- break;
- }
- }
+ private void updateToolbarForNormalMode() {
+ if (toolbar == null) return;
- /**
- * 更新小部件
- *
- * 发送广播更新指定的小部件,使其显示最新的笔记内容。
- *
- * @param appWidgetId 小部件ID
- * @param appWidgetType 小部件类型(2x或4x)
- */
- private void updateWidget(int appWidgetId, int appWidgetType) {
- Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
- if (appWidgetType == Notes.TYPE_WIDGET_2X) {
- intent.setClass(this, NoteWidgetProvider_2x.class);
- } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
- intent.setClass(this, NoteWidgetProvider_4x.class);
- } else {
- Log.e(TAG, "Unspported widget type");
- return;
- }
+ // 设置标题为应用名称
+ toolbar.setTitle(R.string.app_name);
- intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
- appWidgetId
+ // 设置导航图标为汉堡菜单
+ toolbar.setNavigationIcon(android.R.drawable.ic_menu_sort_by_size);
+ toolbar.setNavigationOnClickListener(v -> {
+ if (drawerLayout != null) {
+ drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
+ }
});
- sendBroadcast(intent);
- setResult(RESULT_OK, intent);
+ // 清除多选模式菜单
+ toolbar.getMenu().clear();
+
+ // 添加普通模式菜单(如果需要)
+ // getMenuInflater().inflate(R.menu.note_list_options, menu);
}
+
+
/**
- * 文件夹上下文菜单创建监听器
- *
- * 为文件夹项创建上下文菜单,提供查看、删除和重命名选项。
- *
+ * 显示删除确认对话框
*/
- private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
- public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
- if (mFocusNoteDataItem != null) {
- menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
- menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
- menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
- menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);
+ private void showDeleteDialog() {
+ int selectedCount = viewModel.getSelectedCount();
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+ builder.setTitle(getString(R.string.alert_title_delete));
+ builder.setIcon(android.R.drawable.ic_dialog_alert);
+ builder.setMessage(getString(R.string.alert_message_delete_notes, selectedCount));
+ builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ viewModel.deleteSelectedNotes();
}
- }
- };
+ });
+ builder.setNegativeButton(android.R.string.cancel, null);
+ builder.show();
+ }
- @Override
- public void onContextMenuClosed(Menu menu) {
- super.onContextMenuClosed(menu);
+ /**
+ * 显示移动菜单
+ */
+ private void showMoveMenu() {
+ // TODO: 实现文件夹选择逻辑
+ Toast.makeText(this, "移动功能开发中", Toast.LENGTH_SHORT).show();
}
+ /**
+ * 活动结果回调方法
+ */
@Override
- public boolean onContextItemSelected(MenuItem item) {
- if (mFocusNoteDataItem == null) {
- Log.e(TAG, "The long click data item is null");
- return false;
- }
- switch (item.getItemId()) {
- case MENU_FOLDER_VIEW:
- openFolder(mFocusNoteDataItem);
- break;
- case MENU_FOLDER_DELETE:
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(getString(R.string.alert_title_delete));
- builder.setIcon(android.R.drawable.ic_dialog_alert);
- builder.setMessage(getString(R.string.alert_message_delete_folder));
- builder.setPositiveButton(android.R.string.ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- deleteFolder(mFocusNoteDataItem.getId());
- }
- });
- builder.setNegativeButton(android.R.string.cancel, null);
- builder.show();
- break;
- case MENU_FOLDER_CHANGE_NAME:
- showCreateOrModifyFolderDialog(false);
- break;
- default:
- break;
- }
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
- return true;
+ if (resultCode == RESULT_OK) {
+ if (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE) {
+ viewModel.refreshNotes();
+ }
+ }
}
/**
- * 准备选项菜单
- *
- * 根据当前列表状态加载不同的菜单资源:
- *
- * 笔记列表:显示同步、设置、新建文件夹、导出、搜索等选项
- * 子文件夹:显示新建笔记选项
- * 通话记录文件夹:显示新建笔记选项
- *
- *
- * @param menu 选项菜单对象
- * @return true
+ * 创建选项菜单
*/
@Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- menu.clear();
- if (mState == ListEditState.NOTE_LIST) {
- getMenuInflater().inflate(R.menu.note_list, menu);
- // set sync or sync_cancel
- menu.findItem(R.id.menu_sync).setTitle(
- GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
- } else if (mState == ListEditState.SUB_FOLDER) {
- getMenuInflater().inflate(R.menu.sub_folder, menu);
- } else if (mState == ListEditState.CALL_RECORD_FOLDER) {
- getMenuInflater().inflate(R.menu.call_record_folder, menu);
- } else {
- Log.e(TAG, "Wrong state:" + mState);
- }
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.note_list, menu);
return true;
}
/**
- * 选项菜单项选择处理
- *
- * 处理用户点击选项菜单的事件,包括:
- *
- * 新建文件夹
- * 导出笔记为文本
- * 同步或取消同步
- * 打开设置
- * 新建笔记
- * 搜索
- *
- *
- * @param item 被点击的菜单项
- * @return true
+ * 选项菜单项点击事件
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.menu_new_folder: {
- showCreateOrModifyFolderDialog(true);
- break;
- }
- case R.id.menu_export_text: {
- exportNoteToText();
- break;
- }
- case R.id.menu_sync: {
- if (isSyncMode()) {
- if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
- GTaskSyncService.startSync(this);
- } else {
- GTaskSyncService.cancelSync(this);
- }
- } else {
- startPreferenceActivity();
- }
- break;
- }
- case R.id.menu_setting: {
- startPreferenceActivity();
- break;
- }
- case R.id.menu_new_note: {
- createNewNote();
- break;
- }
+ int itemId = item.getItemId();
+
+ switch (itemId) {
case R.id.menu_search:
- onSearchRequested();
- break;
- case R.id.menu_switch_layout:
- showLayoutSettingsDialog();
- break;
+ // TODO: 打开搜索对话框
+ Toast.makeText(this, "搜索功能开发中", Toast.LENGTH_SHORT).show();
+ return true;
+ case R.id.menu_new_folder:
+ // 创建新文件夹
+ showCreateFolderDialog();
+ return true;
+ case R.id.menu_export_text:
+ // TODO: 导出笔记
+ Toast.makeText(this, "导出功能开发中", Toast.LENGTH_SHORT).show();
+ return true;
+ case R.id.menu_sync:
+ // TODO: 同步功能
+ Toast.makeText(this, "同步功能暂不可用", Toast.LENGTH_SHORT).show();
+ return true;
+ case R.id.menu_setting:
+ // TODO: 设置功能
+ Toast.makeText(this, "设置功能开发中", Toast.LENGTH_SHORT).show();
+ return true;
+ // 多选模式菜单项
+ case R.id.multi_select_delete:
+ showDeleteDialog();
+ return true;
+ case R.id.multi_select_move:
+ showMoveMenu();
+ return true;
+ case R.id.multi_select_pin:
+ boolean wasPinned = viewModel.isAllSelectedPinned();
+ viewModel.toggleSelectedNotesPin();
+ String toastMsg = wasPinned ? getString(R.string.menu_unpin) + "成功" : getString(R.string.menu_pin) + "成功";
+ Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
+ return true;
default:
- break;
+ return super.onOptionsItemSelected(item);
}
- return true;
}
/**
- * 搜索请求处理
- *
- * 启动系统搜索界面,允许用户搜索笔记内容。
- *
- * @return true
+ * 上下文菜单创建
*/
@Override
- public boolean onSearchRequested() {
- startSearch(null, false, null /* appData */, false);
- return true;
+ public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
+ getMenuInflater().inflate(R.menu.sub_folder, menu);
}
/**
- * 导出笔记为文本文件
- *
- * 在后台线程中将所有笔记导出为文本文件到SD卡。
- * 根据导出结果显示相应的提示对话框。
- *
+ * 上下文菜单项点击
*/
- private void exportNoteToText() {
- final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
- new AsyncTask() {
-
- @Override
- protected Integer doInBackground(Void... unused) {
- return backup.exportToText();
- }
+ @Override
+ public boolean onContextItemSelected(MenuItem item) {
+ // TODO: 处理文件夹上下文菜单
+ return super.onContextItemSelected(item);
+ }
- @Override
- protected void onPostExecute(Integer result) {
- if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
- AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
- builder.setTitle(NotesListActivity.this
- .getString(R.string.failed_sdcard_export));
- builder.setMessage(NotesListActivity.this
- .getString(R.string.error_sdcard_unmounted));
- builder.setPositiveButton(android.R.string.ok, null);
- builder.show();
- } else if (result == BackupUtils.STATE_SUCCESS) {
- AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
- builder.setTitle(NotesListActivity.this
- .getString(R.string.success_sdcard_export));
- builder.setMessage(NotesListActivity.this.getString(
- R.string.format_exported_file_location, backup
- .getExportedTextFileName(), backup.getExportedTextFileDir()));
- builder.setPositiveButton(android.R.string.ok, null);
- builder.show();
- } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
- AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
- builder.setTitle(NotesListActivity.this
- .getString(R.string.failed_sdcard_export));
- builder.setMessage(NotesListActivity.this
- .getString(R.string.error_sdcard_export));
- builder.setPositiveButton(android.R.string.ok, null);
- builder.show();
+ /**
+ * 活动销毁时的清理
+ */
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ // 清理资源
+ }
+
+ private void updateSelectionState(int position, boolean selected) {
+ Log.d("NotesListActivity", "===== updateSelectionState called =====");
+ Log.d("NotesListActivity", "position: " + position + ", selected: " + selected);
+ NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
+ if (note != null) {
+ Log.d("NotesListActivity", "note ID: " + note.getId());
+ Log.d("NotesListActivity", "Current selectedIds size before update: " + adapter.getSelectedIds().size());
+ Log.d("NotesListActivity", "Note already in selectedIds: " + adapter.getSelectedIds().contains(note.getId()));
+ if (adapter.getSelectedIds().contains(note.getId()) != selected) {
+ if (selected) {
+ Log.d("NotesListActivity", "Adding note ID to selectedIds");
+ adapter.getSelectedIds().add(note.getId());
+ } else {
+ Log.d("NotesListActivity", "Removing note ID from selectedIds");
+ adapter.getSelectedIds().remove(note.getId());
}
+ Log.d("NotesListActivity", "SelectedIds size after update: " + adapter.getSelectedIds().size());
+ adapter.notifyDataSetChanged();
+ Log.d("NotesListActivity", "notifyDataSetChanged() called");
+ } else {
+ Log.d("NotesListActivity", "Note selection state unchanged, skipping update");
}
+ } else {
+ Log.e("NotesListActivity", "note is NULL at position: " + position);
+ }
+ Log.d("NotesListActivity", "===== updateSelectionState END =====");
+ }
+
+ // ==================== SidebarFragment.OnSidebarItemSelectedListener 实现 ====================
- }.execute();
+ @Override
+ public void onFolderSelected(long folderId) {
+ // 跳转到指定文件夹
+ viewModel.enterFolder(folderId);
+ // 关闭侧栏
+ if (drawerLayout != null) {
+ drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
+ }
}
- /**
- * 显示布局设置对话框
- *
- * 打开布局设置对话框,允许用户选择布局类型、网格列数和项目间距。
- *
- */
- private void showLayoutSettingsDialog() {
- LayoutSettingsDialog dialog = new LayoutSettingsDialog(this, mLayoutManagerController);
- dialog.show();
+ @Override
+ public void onTrashSelected() {
+ // TODO: 实现跳转到回收站
+ Log.d(TAG, "Trash selected");
+ // 关闭侧栏
+ if (drawerLayout != null) {
+ drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
+ }
}
- /**
- * 显示Toast提示
- *
- * 显示简短的提示信息,自动消失。
- *
- * @param message 提示信息
- */
- private void showToast(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
+ @Override
+ public void onSyncSelected() {
+ // TODO: 实现同步功能
+ Log.d(TAG, "Sync selected");
+ Toast.makeText(this, "同步功能待实现", Toast.LENGTH_SHORT).show();
}
- /**
- * 检查是否处于同步模式
- *
- * 判断是否已设置同步账户,如果已设置则表示处于同步模式。
- *
- * @return true表示处于同步模式,false表示未同步
- */
- private boolean isSyncMode() {
- return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
+ @Override
+ public void onLoginSelected() {
+ // TODO: 实现登录功能
+ Log.d(TAG, "Login selected");
+ Toast.makeText(this, "登录功能待实现", Toast.LENGTH_SHORT).show();
}
- /**
- * 启动设置Activity
- *
- * 启动NotesPreferenceActivity进行应用设置。
- *
- */
- private void startPreferenceActivity() {
- Activity from = getParent() != null ? getParent() : this;
- Intent intent = new Intent(from, NotesPreferenceActivity.class);
- from.startActivityIfNeeded(intent, -1);
+ @Override
+ public void onExportSelected() {
+ // TODO: 实现导出功能
+ Log.d(TAG, "Export selected");
+ Toast.makeText(this, "导出功能待实现", Toast.LENGTH_SHORT).show();
+ }
+
+ @Override
+ public void onSettingsSelected() {
+ // TODO: 实现设置功能
+ Log.d(TAG, "Settings selected");
+ Toast.makeText(this, "设置功能待实现", Toast.LENGTH_SHORT).show();
+ }
+
+ @Override
+ public void onCreateFolder() {
+ // 显示创建文件夹对话框
+ showCreateFolderDialog();
}
/**
- * 列表项点击监听器
- *
- * 处理笔记列表项的点击事件,根据当前状态和项类型执行相应操作:
- *
- * 多选模式:切换选中状态
- * 笔记列表:打开文件夹或笔记
- * 子文件夹/通话记录文件夹:打开笔记
- *
- *
- */
- private class OnListItemClickListener implements NotesRecyclerViewAdapter.OnItemClickListener {
-
- /**
- * 列表项点击事件处理
- *
- * @param view 被点击的视图
- * @param position 列表项位置
- * @param id 列表项ID
+ * 显示创建文件夹对话框
*/
- public void onItemClick(View view, int position, long id) {
- Cursor cursor = (Cursor) mNotesListAdapter.getItem(position);
- if (cursor != null) {
- NoteItemData item = new NoteItemData(NotesListActivity.this, cursor);
- if (mNotesListAdapter.isInChoiceMode()) {
- if (item.getType() == Notes.TYPE_NOTE) {
- mModeCallBack.onItemCheckedStateChanged(null, position, id,
- !mNotesListAdapter.isSelectedItem(position));
- }
- return;
- }
+ private void showCreateFolderDialog() {
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+ builder.setTitle(R.string.dialog_create_folder_title);
- switch (mState) {
- case NOTE_LIST:
- if (item.getType() == Notes.TYPE_FOLDER
- || item.getType() == Notes.TYPE_SYSTEM) {
- openFolder(item);
- } else if (item.getType() == Notes.TYPE_NOTE) {
- openNode(item);
- } else {
- Log.e(TAG, "Wrong note type in NOTE_LIST");
- }
- break;
- case SUB_FOLDER:
- case CALL_RECORD_FOLDER:
- if (item.getType() == Notes.TYPE_NOTE) {
- openNode(item);
- } else {
- Log.e(TAG, "Wrong note type in SUB_FOLDER");
- }
- break;
- default:
- break;
- }
+ final EditText input = new EditText(this);
+ input.setHint(R.string.dialog_create_folder_hint);
+ input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
+
+ builder.setView(input);
+
+ builder.setPositiveButton(R.string.menu_create_folder, (dialog, which) -> {
+ String folderName = input.getText().toString().trim();
+ if (TextUtils.isEmpty(folderName)) {
+ Toast.makeText(this, R.string.error_folder_name_empty, Toast.LENGTH_SHORT).show();
+ return;
+ }
+ if (folderName.length() > 50) {
+ Toast.makeText(this, R.string.error_folder_name_too_long, Toast.LENGTH_SHORT).show();
+ return;
}
- }
+ // 创建文件夹
+ NotesRepository repository = new NotesRepository(getContentResolver());
+ long parentId = viewModel.getCurrentFolderId();
+ if (parentId == 0) {
+ parentId = Notes.ID_ROOT_FOLDER;
+ }
+ repository.createFolder(parentId, folderName,
+ new NotesRepository.Callback() {
+ @Override
+ public void onSuccess(Long folderId) {
+ runOnUiThread(() -> {
+ Toast.makeText(NotesListActivity.this, R.string.create_folder_success, Toast.LENGTH_SHORT).show();
+ // 刷新笔记列表
+ viewModel.loadNotes(viewModel.getCurrentFolderId());
+ });
+ }
+
+ @Override
+ public void onError(Exception error) {
+ runOnUiThread(() -> {
+ Toast.makeText(NotesListActivity.this, "创建文件夹失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
+ });
+ }
+ });
+ });
+
+ builder.setNegativeButton(android.R.string.cancel, null);
+ builder.show();
}
- /**
- * 启动查询目标文件夹
- *
- * 查询所有可用的文件夹,用于显示在移动笔记的对话框中。
- * 排除垃圾箱文件夹和当前文件夹。
- *
- */
- private void startQueryDestinationFolders() {
- String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
- selection = (mState == ListEditState.NOTE_LIST) ? selection:
- "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
-
- mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
- null,
- Notes.CONTENT_NOTE_URI,
- FoldersListAdapter.PROJECTION,
- selection,
- new String[] {
- String.valueOf(Notes.TYPE_FOLDER),
- String.valueOf(Notes.ID_TRASH_FOLER),
- String.valueOf(mCurrentFolderId)
- },
- NoteColumns.MODIFIED_DATE + " DESC");
+ @Override
+ public void onCloseSidebar() {
+ // 关闭侧栏
+ if (drawerLayout != null) {
+ drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
+ }
}
/**
- * 列表项长按事件处理
- *
- * @param view 被长按的视图
- * @param position 列表项位置
- * @param id 列表项ID
- * @return true表示事件已处理
+ * 返回键按下事件处理
+ *
+ * 多选模式:退出多选模式
+ * 子文件夹:返回上一级文件夹
+ * 根文件夹:最小化应用
+ *
*/
- public boolean onItemLongClick(View view, int position, long id) {
- Cursor cursor = (Cursor) mNotesListAdapter.getItem(position);
- if (cursor != null) {
- mFocusNoteDataItem = new NoteItemData(NotesListActivity.this, cursor);
- if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
- if (startActionMode(mModeCallBack) != null) {
- mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
- view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
- } else {
- Log.e(TAG, "startActionMode fails");
- }
- } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
- registerForContextMenu(view);
- openContextMenu(view);
+ @Override
+ public void onBackPressed() {
+ if (isMultiSelectMode) {
+ // 多选模式:退出多选模式
+ exitMultiSelectMode();
+ } else if (drawerLayout != null && drawerLayout.isDrawerOpen(findViewById(R.id.sidebar_fragment))) {
+ // 侧栏打开:关闭侧栏
+ drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
+ } else if (viewModel.getCurrentFolderId() != Notes.ID_ROOT_FOLDER &&
+ viewModel.getCurrentFolderId() != Notes.ID_CALL_RECORD_FOLDER) {
+ // 子文件夹:返回上一级
+ if (!viewModel.navigateUp()) {
+ // 如果没有导航历史,返回根文件夹
+ viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
}
+ } else {
+ // 根文件夹:最小化应用
+ moveTaskToBack(true);
}
- return false;
}
}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesRecyclerViewAdapter.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesRecyclerViewAdapter.java
deleted file mode 100644
index 2711272..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesRecyclerViewAdapter.java
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.util.Log;
-import android.util.SparseArray;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CheckBox;
-import androidx.recyclerview.widget.RecyclerView;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.tool.DataUtils;
-import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
-
-import java.util.HashSet;
-
-/**
- * 笔记RecyclerView适配器
- *
- * 这个类继承自RecyclerView.Adapter,用于将数据库中的笔记数据绑定到RecyclerView中显示。
- * 它支持笔记的选择模式、批量操作以及与桌面小部件的关联。
- * 相比原NotesListAdapter,使用RecyclerView带来更好的性能和动画支持。
- *
- * 主要功能:
- * 1. 将笔记数据绑定到NoteViewHolder视图
- * 2. 支持多选模式和批量选择操作
- * 3. 获取选中的笔记ID和关联的桌面小部件信息
- * 4. 统计笔记数量和选中数量
- * 5. 支持局部刷新和内置动画
- *
- * @see NoteViewHolder
- * @see NoteItemData
- */
-public class NotesRecyclerViewAdapter extends RecyclerView.Adapter {
- private static final String TAG = "NotesRecyclerViewAdapter";
-
- private Context mContext;
- private Cursor mCursor;
- private SparseArray mSelectedIndex;
- private int mNotesCount;
- private boolean mChoiceMode;
- private OnItemClickListener mOnItemClickListener;
- private OnItemLongClickListener mOnItemLongClickListener;
-
- /**
- * 桌面小部件属性类
- *
- * 用于存储桌面小部件的ID和类型信息
- */
- public static class AppWidgetAttribute {
- public int widgetId;
- public int widgetType;
- }
-
- /**
- * 点击监听器接口
- */
- public interface OnItemClickListener {
- void onItemClick(View view, int position, long id);
- }
-
- /**
- * 长按监听器接口
- */
- public interface OnItemLongClickListener {
- boolean onItemLongClick(View view, int position, long id);
- }
-
- /**
- * 构造器
- *
- * 初始化笔记列表适配器,创建选中状态Map和计数器
- *
- * @param context 应用上下文,不能为 null
- */
- public NotesRecyclerViewAdapter(Context context) {
- mSelectedIndex = new SparseArray<>();
- mContext = context;
- mNotesCount = 0;
- }
-
- /**
- * 创建ViewHolder
- *
- * @param parent 父视图组
- * @param viewType 视图类型
- * @return 新创建的NoteViewHolder对象
- */
- @Override
- public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- View view = LayoutInflater.from(mContext)
- .inflate(R.layout.note_item, parent, false);
- final NoteViewHolder holder = new NoteViewHolder(view);
-
- // 设置点击监听
- view.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mOnItemClickListener != null) {
- int position = holder.getAdapterPosition();
- if (position != RecyclerView.NO_POSITION) {
- long id = getItemId(position);
- mOnItemClickListener.onItemClick(v, position, id);
- }
- }
- }
- });
-
- // 设置长按监听
- view.setOnLongClickListener(new View.OnLongClickListener() {
- @Override
- public boolean onLongClick(View v) {
- if (mOnItemLongClickListener != null) {
- int position = holder.getAdapterPosition();
- if (position != RecyclerView.NO_POSITION) {
- long id = getItemId(position);
- return mOnItemLongClickListener.onItemLongClick(v, position, id);
- }
- }
- return false;
- }
- });
-
- return holder;
- }
-
- /**
- * 绑定数据到ViewHolder
- *
- * 将数据库游标中的数据绑定到已存在的ViewHolder上
- *
- * @param holder 需要绑定数据的ViewHolder
- * @param position 列表项位置
- */
- @Override
- public void onBindViewHolder(NoteViewHolder holder, int position) {
- if (mCursor != null && mCursor.moveToPosition(position)) {
- NoteItemData itemData = new NoteItemData(mContext, mCursor);
-
- // 绑定数据到视图
- bindViewHolder(holder, itemData, position);
- }
- }
-
- /**
- * 绑定ViewHolder数据
- *
- * @param holder ViewHolder对象
- * @param data 笔记数据
- * @param position 位置
- */
- private void bindViewHolder(NoteViewHolder holder, NoteItemData data, int position) {
- // 处理复选框
- if (mChoiceMode && data.getType() == Notes.TYPE_NOTE) {
- holder.mCheckBox.setVisibility(View.VISIBLE);
- holder.mCheckBox.setChecked(isSelectedItem(position));
- } else {
- holder.mCheckBox.setVisibility(View.GONE);
- }
-
- // 处理提醒图标
- if (data.hasAlert()) {
- holder.mAlert.setImageResource(R.drawable.clock);
- holder.mAlert.setVisibility(View.VISIBLE);
- } else {
- holder.mAlert.setVisibility(View.GONE);
- }
-
- // 处理标题
- if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
- holder.mCallName.setVisibility(View.GONE);
- holder.mAlert.setVisibility(View.VISIBLE);
- holder.mTitle.setTextAppearance(mContext, R.style.TextAppearancePrimaryItem);
- holder.mTitle.setText(mContext.getString(R.string.call_record_folder_name)
- + mContext.getString(R.string.format_folder_files_count, data.getNotesCount()));
- holder.mAlert.setImageResource(R.drawable.call_record);
- } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
- holder.mCallName.setVisibility(View.VISIBLE);
- holder.mCallName.setText(data.getCallName());
- holder.mTitle.setTextAppearance(mContext, R.style.TextAppearanceSecondaryItem);
- holder.mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
- } else {
- holder.mCallName.setVisibility(View.GONE);
- holder.mTitle.setTextAppearance(mContext, R.style.TextAppearancePrimaryItem);
-
- if (data.getType() == Notes.TYPE_FOLDER) {
- holder.mTitle.setText(data.getSnippet()
- + mContext.getString(R.string.format_folder_files_count,
- data.getNotesCount()));
- holder.mAlert.setVisibility(View.GONE);
- } else {
- holder.mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
- if (data.hasAlert()) {
- holder.mAlert.setImageResource(R.drawable.clock);
- holder.mAlert.setVisibility(View.VISIBLE);
- } else {
- holder.mAlert.setVisibility(View.GONE);
- }
- }
- }
-
- // 设置时间
- holder.mTime.setText(android.text.format.DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
-
- // 设置背景
- setBackground(holder.itemView, data);
- }
-
- /**
- * 根据笔记项的位置和类型设置合适的背景资源
- * @param view 列表项视图
- * @param data 笔记数据
- */
- private void setBackground(View view, NoteItemData data) {
- int id = data.getBgColorId();
- if (data.getType() == Notes.TYPE_NOTE) {
- int bgRes;
- if (data.isSingle() || data.isOneFollowingFolder()) {
- bgRes = NoteItemBgResources.getNoteBgSingleRes(id);
- } else if (data.isLast()) {
- bgRes = NoteItemBgResources.getNoteBgLastRes(id);
- } else if (data.isFirst() || data.isMultiFollowingFolder()) {
- bgRes = NoteItemBgResources.getNoteBgFirstRes(id);
- } else {
- bgRes = NoteItemBgResources.getNoteBgNormalRes(id);
- }
- view.setBackgroundResource(bgRes);
- } else {
- view.setBackgroundResource(NoteItemBgResources.getFolderBgRes());
- }
- }
-
- /**
- * 获取列表项数量
- *
- * @return 列表项数量,如果游标为null则返回0
- */
- @Override
- public int getItemCount() {
- return mCursor != null ? mCursor.getCount() : 0;
- }
-
- /**
- * 获取指定位置的列表项ID
- *
- * @param position 列表项位置
- * @return 列表项ID,如果游标为null或位置无效则返回0
- */
- public long getItemId(int position) {
- if (mCursor != null && mCursor.moveToPosition(position)) {
- return mCursor.getLong(mCursor.getColumnIndexOrThrow(Notes.NoteColumns.ID));
- }
- return 0;
- }
-
- /**
- * 获取指定位置的列表项
- *
- * @param position 列表项位置
- * @return 列表项对象,如果游标为null或位置无效则返回null
- */
- public Object getItem(int position) {
- if (mCursor != null && mCursor.moveToPosition(position)) {
- return mCursor;
- }
- return null;
- }
-
- /**
- * 设置指定位置的选中状态
- *
- * @param position 列表项位置,从0开始
- * @param checked 是否选中
- */
- public void setCheckedItem(int position, boolean checked) {
- mSelectedIndex.put(position, checked);
- notifyItemChanged(position);
- }
-
- /**
- * 判断是否处于选择模式
- *
- * @return 如果处于选择模式返回true,否则返回false
- */
- public boolean isInChoiceMode() {
- return mChoiceMode;
- }
-
- /**
- * 设置选择模式
- *
- * @param mode true表示进入选择模式,false表示退出选择模式
- */
- public void setChoiceMode(boolean mode) {
- mSelectedIndex.clear();
- mChoiceMode = mode;
- notifyDataSetChanged();
- }
-
- /**
- * 全选或取消全选所有笔记
- *
- * @param checked true表示全选,false表示取消全选
- */
- public void selectAll(boolean checked) {
- if (mCursor != null) {
- for (int i = 0; i < getItemCount(); i++) {
- if (mCursor.moveToPosition(i)) {
- if (NoteItemData.getNoteType(mCursor) == Notes.TYPE_NOTE) {
- mSelectedIndex.put(i, checked);
- }
- }
- }
- notifyDataSetChanged();
- }
- }
-
- /**
- * 获取所有选中项的笔记ID集合
- *
- * @return 包含所有选中笔记ID的HashSet集合,如果没有选中项则返回空集合
- */
- public HashSet getSelectedItemIds() {
- HashSet itemSet = new HashSet<>();
- for (int i = 0; i < mSelectedIndex.size(); i++) {
- int key = mSelectedIndex.keyAt(i);
- if (mSelectedIndex.get(key)) {
- long id = getItemId(key);
- if (id == Notes.ID_ROOT_FOLDER) {
- Log.d(TAG, "Wrong item id, should not happen");
- } else {
- itemSet.add(id);
- }
- }
- }
- return itemSet;
- }
-
- /**
- * 获取所有选中项关联的桌面小部件集合
- *
- * @return 包含所有选中笔记关联的桌面小部件属性的HashSet集合,如果游标无效则返回null
- */
- public HashSet getSelectedWidget() {
- HashSet itemSet = new HashSet<>();
- for (int i = 0; i < mSelectedIndex.size(); i++) {
- int key = mSelectedIndex.keyAt(i);
- if (mSelectedIndex.get(key)) {
- Cursor c = (Cursor) getItem(key);
- if (c != null) {
- AppWidgetAttribute widget = new AppWidgetAttribute();
- NoteItemData item = new NoteItemData(mContext, c);
- widget.widgetId = item.getWidgetId();
- widget.widgetType = item.getWidgetType();
- itemSet.add(widget);
- } else {
- Log.e(TAG, "Invalid cursor");
- return null;
- }
- }
- }
- return itemSet;
- }
-
- /**
- * 获取选中项的数量
- *
- * @return 选中项的数量,如果没有选中项则返回0
- */
- public int getSelectedCount() {
- int count = 0;
- for (int i = 0; i < mSelectedIndex.size(); i++) {
- if (mSelectedIndex.get(mSelectedIndex.keyAt(i))) {
- count++;
- }
- }
- return count;
- }
-
- /**
- * 判断是否已全选所有笔记
- *
- * @return 如果所有笔记都被选中且至少有一个笔记则返回true,否则返回false
- */
- public boolean isAllSelected() {
- int checkedCount = getSelectedCount();
- return (checkedCount != 0 && checkedCount == mNotesCount);
- }
-
- /**
- * 判断指定位置的项是否被选中
- *
- * @param position 列表项位置,从0开始
- * @return 如果该项被选中返回true,否则返回false
- */
- public boolean isSelectedItem(int position) {
- return mSelectedIndex.get(position, false);
- }
-
- /**
- * 更换游标
- *
- * @param newCursor 新的数据库游标
- */
- public Cursor swapCursor(Cursor newCursor) {
- Cursor oldCursor = mCursor;
- mCursor = newCursor;
- calcNotesCount();
- notifyDataSetChanged();
- return oldCursor;
- }
-
- /**
- * 计算笔记数量
- */
- private void calcNotesCount() {
- mNotesCount = 0;
- if (mCursor != null) {
- for (int i = 0; i < getItemCount(); i++) {
- if (mCursor.moveToPosition(i)) {
- if (NoteItemData.getNoteType(mCursor) == Notes.TYPE_NOTE) {
- mNotesCount++;
- }
- }
- }
- }
- }
-
- /**
- * 设置点击监听器
- *
- * @param listener 点击监听器
- */
- public void setOnItemClickListener(OnItemClickListener listener) {
- mOnItemClickListener = listener;
- }
-
- /**
- * 设置长按监听器
- *
- * @param listener 长按监听器
- */
- public void setOnItemLongClickListener(OnItemLongClickListener listener) {
- mOnItemLongClickListener = listener;
- }
-}
diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/StaggeredGridSpacingItemDecoration.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/StaggeredGridSpacingItemDecoration.java
deleted file mode 100644
index 8f73ff8..0000000
--- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/StaggeredGridSpacingItemDecoration.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.ui;
-
-import android.graphics.Rect;
-import android.view.View;
-import androidx.recyclerview.widget.RecyclerView;
-import androidx.recyclerview.widget.StaggeredGridLayoutManager;
-
-/**
- * 瀑布流布局间距装饰类
- *
- * 为瀑布流布局的RecyclerView添加统一的间距,确保每个网格项之间有合适的间隔。
- * 支持是否包含边缘间距的配置。
- *
- */
-public class StaggeredGridSpacingItemDecoration extends RecyclerView.ItemDecoration {
- private int spanCount;
- private int spacing;
- private boolean includeEdge;
-
- /**
- * 构造函数
- * @param spanCount 网格列数
- * @param spacing 间距大小(像素)
- * @param includeEdge 是否包含边缘间距
- */
- public StaggeredGridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
- this.spanCount = spanCount;
- this.spacing = spacing;
- this.includeEdge = includeEdge;
- }
-
- @Override
- public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
- StaggeredGridLayoutManager.LayoutParams params =
- (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
- int spanIndex = params.getSpanIndex();
-
- if (includeEdge) {
- outRect.left = spacing - spanIndex * spacing / spanCount;
- outRect.right = (spanIndex + 1) * spacing / spanCount;
-
- if (params.getViewAdapterPosition() < spanCount) {
- outRect.top = spacing;
- }
- outRect.bottom = spacing;
- } else {
- outRect.left = spanIndex * spacing / spanCount;
- outRect.right = spacing - (spanIndex + 1) * spacing / spanCount;
- if (params.getViewAdapterPosition() >= spanCount) {
- outRect.top = spacing;
- }
- }
- }
-}
diff --git a/src/Notesmaster/app/src/main/res/drawable/list_divider.xml b/src/Notesmaster/app/src/main/res/drawable/list_divider.xml
deleted file mode 100644
index 4a9645b..0000000
--- a/src/Notesmaster/app/src/main/res/drawable/list_divider.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
diff --git a/src/Notesmaster/app/src/main/res/layout/activity_main.xml b/src/Notesmaster/app/src/main/res/layout/activity_main.xml
index 86a5d97..80c956c 100644
--- a/src/Notesmaster/app/src/main/res/layout/activity_main.xml
+++ b/src/Notesmaster/app/src/main/res/layout/activity_main.xml
@@ -1,19 +1,37 @@
-
-
+
+
-
\ No newline at end of file
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/Notesmaster/app/src/main/res/layout/layout_settings_dialog.xml b/src/Notesmaster/app/src/main/res/layout/layout_settings_dialog.xml
deleted file mode 100644
index 907ec21..0000000
--- a/src/Notesmaster/app/src/main/res/layout/layout_settings_dialog.xml
+++ /dev/null
@@ -1,103 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Notesmaster/app/src/main/res/layout/note_edit.xml b/src/Notesmaster/app/src/main/res/layout/note_edit.xml
index ac3cad0..8c449c4 100644
--- a/src/Notesmaster/app/src/main/res/layout/note_edit.xml
+++ b/src/Notesmaster/app/src/main/res/layout/note_edit.xml
@@ -1,45 +1,56 @@
-
-
-
-
+
+
+
+
+
+
+
+
+
+ android:fadingEdgeLength="0dp">
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
-
-
+
-
-
-
+
-
+
-
-
-
-
+
-
+
+
+
+
-
-
-
-
+
-
+
+
+
+
-
-
-
-
+
-
+
+
+
+
-
-
+
-
+
+
+
+
-
+
-
-
-
+
+
+
-
-
-
+ android:background="@drawable/font_size_selector_bg"
+ android:layout_gravity="bottom"
+ android:visibility="gone">
-
+ android:layout_weight="1">
-
-
-
-
+ android:orientation="vertical"
+ android:layout_gravity="center"
+ android:gravity="center">
-
-
-
-
+
-
+
+
+ android:layout_gravity="bottom|right"
+ android:layout_marginRight="6dp"
+ android:layout_marginBottom="-7dp"
+ android:focusable="false"
+ android:visibility="gone"
+ android:src="@drawable/selected" />
+
+
+
-
-
+ android:orientation="vertical"
+ android:layout_gravity="center"
+ android:gravity="center">
-
-
-
-
+
-
+
+
+ android:layout_gravity="bottom|right"
+ android:focusable="false"
+ android:visibility="gone"
+ android:layout_marginRight="6dp"
+ android:layout_marginBottom="-7dp"
+ android:src="@drawable/selected" />
+
+
+
-
-
+ android:orientation="vertical"
+ android:layout_gravity="center"
+ android:gravity="center">
-
-
-
-
+
-
+
+
+ android:layout_gravity="bottom|right"
+ android:focusable="false"
+ android:visibility="gone"
+ android:layout_marginRight="6dp"
+ android:layout_marginBottom="-7dp"
+ android:src="@drawable/selected" />
+
+
+
-
-
+ android:orientation="vertical"
+ android:layout_gravity="center"
+ android:gravity="center">
-
-
+
+
+
+
+
+
+
+
-
+
diff --git a/src/Notesmaster/app/src/main/res/layout/note_item.xml b/src/Notesmaster/app/src/main/res/layout/note_item.xml
index d541f6a..b23af8f 100644
--- a/src/Notesmaster/app/src/main/res/layout/note_item.xml
+++ b/src/Notesmaster/app/src/main/res/layout/note_item.xml
@@ -15,51 +15,62 @@
limitations under the License.
-->
-
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:padding="12dp"
+ android:background="@null">
+
-
+ android:textSize="16sp"
+ android:textColor="@android:color/black"
+ android:textStyle="bold"
+ android:maxLines="1"
+ android:ellipsize="end"
+ android:singleLine="true" />
-
-
-
+
+
-
+
+
-
-
-
+
+
+
+
+
+
+
+
+
-
-
+
diff --git a/src/Notesmaster/app/src/main/res/layout/note_list.xml b/src/Notesmaster/app/src/main/res/layout/note_list.xml
index 58fb839..c157627 100644
--- a/src/Notesmaster/app/src/main/res/layout/note_list.xml
+++ b/src/Notesmaster/app/src/main/res/layout/note_list.xml
@@ -1,59 +1,101 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Notesmaster/app/src/main/res/menu/note_list.xml b/src/Notesmaster/app/src/main/res/menu/note_list.xml
index 1e4b644..42ea736 100644
--- a/src/Notesmaster/app/src/main/res/menu/note_list.xml
+++ b/src/Notesmaster/app/src/main/res/menu/note_list.xml
@@ -36,8 +36,4 @@
-
-
diff --git a/src/Notesmaster/app/src/main/res/values-zh-rCN/strings.xml b/src/Notesmaster/app/src/main/res/values-zh-rCN/strings.xml
index 09f75ed..61b9801 100644
--- a/src/Notesmaster/app/src/main/res/values-zh-rCN/strings.xml
+++ b/src/Notesmaster/app/src/main/res/values-zh-rCN/strings.xml
@@ -120,7 +120,17 @@
设置
取消
- %1$s 条符合“%2$s ”的搜索结果
+ %1$s 条符合"%2$s "的搜索结果
+
+ 我的便签
+ %d 个便签
+ 创建文件夹
+ 文件夹名称
+ 文件夹名称不能为空
+ 文件夹名称过长(最多50个字符)
+ 回收站
+ 创建文件夹成功
+
diff --git a/src/Notesmaster/app/src/main/res/values/colors.xml b/src/Notesmaster/app/src/main/res/values/colors.xml
index 123ffbf..82d81bf 100644
--- a/src/Notesmaster/app/src/main/res/values/colors.xml
+++ b/src/Notesmaster/app/src/main/res/values/colors.xml
@@ -17,4 +17,7 @@
#335b5b5b
+ #1976D2
+ #FFFFFF
+ #FAFAFA
diff --git a/src/Notesmaster/app/src/main/res/values/strings.xml b/src/Notesmaster/app/src/main/res/values/strings.xml
index 4b4439f..a4b4991 100644
--- a/src/Notesmaster/app/src/main/res/values/strings.xml
+++ b/src/Notesmaster/app/src/main/res/values/strings.xml
@@ -48,15 +48,6 @@
Search
Delete
Move to folder
- Switch Layout
- List Layout
- Grid Layout
- Staggered Layout
- Layout switched to %s
- Failed to switch layout: %s
- Layout Settings
- Grid Columns
- Item Spacing
%d selected
Nothing selected, the operation is invalid
Select all
@@ -90,6 +81,8 @@
The note is not exist
Sorry, can not set clock on empty note
Sorry, can not send and empty note to home
+ Invalid intent
+ Unsupported intent action
Export successful
Export fail
Export text file (%1$s) to SD (%2$s) directory
@@ -141,4 +134,24 @@
%1$s results for \"%2$s \"
+ 暂无便签,点击右下角按钮创建
+ 空便签图标
+ Edit note
+
+ Login
+ Export
+ Settings
+ Trash
+ My Notes
+ Close sidebar
+ Create folder
+ %d notes
+ Create folder
+ Folder name
+ Folder name cannot be empty
+ Folder name too long (max 50 characters)
+ Folder already exists
+ Folder created successfully
+ Pin
+ Unpin
diff --git a/src/Notesmaster/app/src/main/res/values/themes.xml b/src/Notesmaster/app/src/main/res/values/themes.xml
index 7c616ff..ca2f0be 100644
--- a/src/Notesmaster/app/src/main/res/values/themes.xml
+++ b/src/Notesmaster/app/src/main/res/values/themes.xml
@@ -1,9 +1,17 @@
+
+
+
\ No newline at end of file