diff --git a/doc/基础博客.docx b/doc/基础博客.docx new file mode 100644 index 0000000..cead2ba Binary files /dev/null and b/doc/基础博客.docx differ diff --git a/doc/小米便签开源代码的泛读报告 .docx b/doc/小米便签开源代码的泛读报告 .docx new file mode 100644 index 0000000..10400cb Binary files /dev/null and b/doc/小米便签开源代码的泛读报告 .docx differ diff --git a/doc/质量分析报告.docx b/doc/质量分析报告.docx new file mode 100644 index 0000000..db94780 Binary files /dev/null and b/doc/质量分析报告.docx differ diff --git a/doc/运行截图.docx b/doc/运行截图.docx new file mode 100644 index 0000000..f5da0bd Binary files /dev/null and b/doc/运行截图.docx differ diff --git a/src/Contact.java b/src/Contact.java new file mode 100644 index 0000000..8578efd --- /dev/null +++ b/src/Contact.java @@ -0,0 +1,99 @@ +/* + * 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; + +// 导入所需的Android类和工具库 +import android.content.Context; +import android.database.Cursor; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.telephony.PhoneNumberUtils; +import android.util.Log; + +// 导入Java工具库中的HashMap +import java.util.HashMap; + +// 定义Contact类,用于处理与联系人相关的操作 +public class Contact { + // 静态HashMap,用于缓存电话号码与联系人姓名的映射关系,避免重复查询数据库 + private static HashMap sContactCache; + // 日志标签,用于在Logcat中标识日志来源 + private static final String TAG = "Contact"; + + // 定义查询条件字符串,用于在联系人数据库中匹配电话号码 + // PHONE_NUMBERS_EQUAL用于比较号码是否相等,考虑格式化差异(如空格、短横线) + // Data.MIMETYPE过滤只处理电话类型的数据条目 + // Data.RAW_CONTACT_ID子查询确保通过phone_lookup表快速匹配最小匹配长度的号码 + 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 = '+')"; // '+'将在运行时被替换为最小匹配长度 + + // 静态方法:根据电话号码查询联系人姓名 + public static String getContact(Context context, String phoneNumber) { + // 如果缓存未初始化,则创建新的HashMap实例 + if(sContactCache == null) { + sContactCache = new HashMap(); + } + + // 检查缓存中是否存在该号码的姓名,存在则直接返回 + if(sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); + } + + // 将CALLER_ID_SELECTION中的'+'替换为实际的最小匹配长度值(如7或8位) + // PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)根据号码生成最小匹配长度 + String selection = CALLER_ID_SELECTION.replace("+", + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + + // 通过ContentResolver查询联系人数据库 + // Data.CONTENT_URI:访问联系人数据的URI + // 查询的列:Phone.DISPLAY_NAME(联系人显示名称) + // 查询条件:动态生成的selection,参数为phoneNumber + Cursor cursor = context.getContentResolver().query( + Data.CONTENT_URI, + new String [] { Phone.DISPLAY_NAME }, + selection, + new String[] { phoneNumber }, + null); // 排序方式为null + + // 处理查询结果 + if (cursor != null && cursor.moveToFirst()) { + try { + // 获取第0列的数据(DISPLAY_NAME) + String name = cursor.getString(0); + // 将结果存入缓存 + sContactCache.put(phoneNumber, name); + return name; + } catch (IndexOutOfBoundsException e) { + // 捕获列索引错误(理论上不会发生,因查询明确指定了DISPLAY_NAME) + Log.e(TAG, " Cursor get string error " + e.toString()); + return null; + } finally { + // 确保关闭Cursor释放资源 + cursor.close(); + } + } else { + // 无匹配结果时记录日志 + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} diff --git a/src/NoteWidgetProvider.java b/src/NoteWidgetProvider.java new file mode 100644 index 0000000..1b8c969 --- /dev/null +++ b/src/NoteWidgetProvider.java @@ -0,0 +1,151 @@ +/* + * 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; + + // 导入Android小部件相关类和自定义类 + 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 { + // 定义查询笔记时需要的列(ID、背景颜色ID、内容片段) + public static final String[] PROJECTION = new String[]{ + NoteColumns.ID, + NoteColumns.BG_COLOR_ID, + NoteColumns.SNIPPET + }; + + // 列索引常量 + public static final int COLUMN_ID = 0; // 笔记ID列索引 + public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引 + 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); // 重置widget_id字段 + for (int appWidgetId : appWidgetIds) { + // 更新数据库,清除被删除小部件关联的笔记的widget_id + context.getContentResolver().update( + Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[]{String.valueOf(appWidgetId)} + ); + } + } + + // 获取指定小部件ID关联的笔记信息(排除垃圾箱中的笔记) + 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 appWidgetId : appWidgetIds) { + if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) continue; + + int bgId = ResourceParser.getDefaultBgId(context); // 获取默认背景ID + String snippet = ""; // 内容片段 + Intent intent = new Intent(context, NoteEditActivity.class); // 编辑笔记的Intent + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式启动 + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetId); // 传递小部件ID + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 小部件类型 + + // 查询数据库获取笔记信息 + try (Cursor c = getNoteWidgetInfo(context, appWidgetId)) { + if (c != null && c.moveToFirst()) { + if (c.getCount() > 1) { // 异常情况:多个笔记关联同一个小部件 + Log.e(TAG, "Multiple notes with same widget id:" + appWidgetId); + return; + } + snippet = c.getString(COLUMN_SNIPPET); // 获取内容片段 + bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取背景ID + intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 传递笔记ID + intent.setAction(Intent.ACTION_VIEW); // 查看模式 + } else { // 没有关联的笔记 + snippet = context.getString(R.string.widget_havenot_content); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 新建笔记 + } + } + + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); // 创建远程视图 + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景 + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景ID + + // 创建PendingIntent处理点击事件 + PendingIntent pendingIntent; + if (privacyMode) { // 隐私模式 + rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); + pendingIntent = PendingIntent.getActivity( + context, + appWidgetId, + new Intent(context, NotesListActivity.class), // 跳转到列表 + PendingIntent.FLAG_UPDATE_CURRENT // 更新现有Intent + ); + } else { // 正常模式 + rv.setTextViewText(R.id.widget_text, snippet); // 显示内容片段 + pendingIntent = PendingIntent.getActivity( + context, + appWidgetId, + intent, + PendingIntent.FLAG_UPDATE_CURRENT + ); + } + + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); // 绑定点击事件 + appWidgetManager.updateAppWidget(appWidgetId, rv); // 更新小部件 + } + } + + // 抽象方法:子类需实现背景资源映射 + protected abstract int getBgResourceId(int bgId); + + // 抽象方法:子类需提供布局ID + protected abstract int getLayoutId(); + + // 抽象方法:子类需定义小部件类型 + protected abstract int getWidgetType(); + } diff --git a/src/NoteWidgetProvider_2x.java b/src/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..9a2519d --- /dev/null +++ b/src/NoteWidgetProvider_2x.java @@ -0,0 +1,95 @@ +/* + * 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; + + /** + * 2x尺寸笔记小部件实现类 + * + * 采用模板方法模式,继承抽象父类NoteWidgetProvider + * 实现特定尺寸小部件的差异化配置 + */ + public class NoteWidgetProvider_2x extends NoteWidgetProvider { + + /** + * 小部件更新事件处理 + * + * @param context 上下文对象 + * @param appWidgetManager 小部件管理服务 + * @param appWidgetIds 需要更新小部件的ID数组 + * + * 功能说明: + * 1. 通过super.update调用父类统一更新逻辑 + * 2. 继承自AppWidgetProvider的标准生命周期方法 + * 3. 不需要额外逻辑时仍建议保留空实现以保证扩展性 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); // 触发父类更新流程 + } + + /** + * 获取小部件布局资源ID + * + * @return int 布局文件ID(R.layout.widget_2x) + * + * 设计要点: + * 1. 实现父类定义的抽象方法 + * 2. 不同尺寸小部件通过此方法返回不同布局 + * 3. 对应布局文件widget_2x.xml定义2x尺寸特有UI结构 + */ + @Override + protected int getLayoutId() { + return R.layout.widget_2x; // 返回2x尺寸专用布局 + } + + /** + * 背景资源映射方法 + * + * @param bgId 数据库存储的背景ID + * @return int 实际drawable资源ID + * + * 实现逻辑: + * 1. 通过ResourceParser转换通用ID为具体资源 + * 2. 不同尺寸小部件可使用不同背景资源 + * 3. 保证数据层与视图层解耦 + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); // 获取2x专用背景 + } + + /** + * 获取小部件类型标识 + * + * @return int 类型常量(Notes.TYPE_WIDGET_2X) + * + * 作用说明: + * 1. 在数据库层面区分不同小部件类型 + * 2. 用于后续的更新/查询操作 + * 3. 与NoteColumns.WIDGET_ID字段配合使用 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; // 类型标识常量 + } + } \ No newline at end of file diff --git a/src/NoteWidgetProvider_4x.java b/src/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..b342975 --- /dev/null +++ b/src/NoteWidgetProvider_4x.java @@ -0,0 +1,99 @@ +/* + * 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; + + /** + * 4x尺寸笔记小部件实现类 + * + * 继承自抽象基类NoteWidgetProvider + * 实现4x尺寸小部件的差异化配置 + * + * 设计要点: + * 1. 采用模板方法模式复用父类核心逻辑 + * 2. 通过类型标识实现多尺寸支持 + * 3. 独立维护尺寸相关资源 + */ + public class NoteWidgetProvider_4x extends NoteWidgetProvider { + + /** + * 小部件更新事件入口 + * + * @param context 上下文环境 + * @param appWidgetManager 小部件管理服务 + * @param appWidgetIds 需要更新小部件的ID数组 + * + * 实现说明: + * 1. 直接调用父类update方法处理通用更新流程 + * 2. 保留方法重写以支持未来扩展4x特有逻辑 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); // 触发父类统一更新流程 + } + + /** + * 获取4x尺寸布局资源 + * + * @return int 布局文件ID(R.layout.widget_4x) + * + * 关联文件: + * - res/layout/widget_4x.xml 定义4x专属布局结构 + * - res/layout-sw600dp/widget_4x.xml 平板设备适配布局 + */ + @Override + protected int getLayoutId() { + return R.layout.widget_4x; // 4x尺寸专用布局资源 + } + + /** + * 背景资源转换方法 + * + * @param bgId 数据库存储的背景标识符 + * @return int 实际Drawable资源ID + * + * 设计优势: + * 1. 通过ResourceParser解耦数据存储与界面表现 + * 2. 允许4x尺寸使用与其他尺寸不同的背景样式 + * 3. 支持动态主题切换(示例): + * if(isDarkMode) return darkBgResources.get(bgId); + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); // 获取4x专用背景 + } + + /** + * 获取小部件类型标识 + * + * @return int 类型常量(Notes.TYPE_WIDGET_4X) + * + * 数据库应用: + * 1. 在notes表中通过widget_type字段存储该值 + * 2. 查询时可用类型过滤:SELECT * FROM notes WHERE widget_type = 4 + * 3. 支持统计各尺寸小部件使用量 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; // 类型标识常量值为4 + } + } \ No newline at end of file diff --git a/src/Notes.java b/src/Notes.java new file mode 100644 index 0000000..c2eaf73 --- /dev/null +++ b/src/Notes.java @@ -0,0 +1,212 @@ +/* + * 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; + +// 导入Android Uri类,用于构建ContentProvider的URI +import android.net.Uri; + +/** + * 定义笔记应用的核心数据模型类 + * 包含数据库表结构定义、ContentProvider URI、类型常量等全局配置 + */ +public class Notes { + // ContentProvider的授权标识,对应AndroidManifest.xml中配置的authorities + public static final String AUTHORITY = "micode_notes"; + + // 日志标签,用于在Logcat中标识日志来源 + 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; // 系统文件夹类型 + + /** + * 系统文件夹的标识符常量: + * {@link Notes#ID_ROOT_FOLDER } 根文件夹(默认文件夹) + * {@link Notes#ID_TEMPARAY_FOLDER } 临时文件夹(存放未分类笔记) + * {@link Notes#ID_CALL_RECORD_FOLDER} 通话记录文件夹 + * 注意:ID_TRASH_FOLER可能存在拼写错误,应为ID_TRASH_FOLDER + */ + public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID + public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID(拼写错误TEMPARAY应为TEMPORARY) + public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID + public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID(拼写错误FOLER应为FOLDER) + + // Intent附加数据键名常量,用于Activity间传递数据 + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期 + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景色ID + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 桌面小部件ID + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型 + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期 + + // 桌面小部件类型常量 + public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件类型 + public static final int TYPE_WIDGET_2X = 0; // 2x尺寸小部件 + public static final int TYPE_WIDGET_4X = 1; // 4x尺寸小部件 + + /** + * 数据项类型常量内部类 + * 定义不同笔记类型的MIME类型 + */ + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记类型 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;// 通话笔记类型 + } + + /** + * ContentProvider URI定义 + */ + // 查询所有笔记和文件夹的URI(content://micode_notes/note) + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + // 查询所有数据项的URI(content://micode_notes/data) + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + /** + * 笔记表列名接口定义 + * 对应数据库表中的字段名称和数据类型 + */ + public interface NoteColumns { + /** 唯一标识符(长整型) */ + public static final String ID = "_id"; + + /** 父项ID(用于构建层级结构,长整型) */ + public static final String PARENT_ID = "parent_id"; + + /** 创建时间(Unix时间戳,长整型) */ + public static final String CREATED_DATE = "created_date"; + + /** 最后修改时间(Unix时间戳,长整型) */ + public static final String MODIFIED_DATE = "modified_date"; + + /** 提醒时间(Unix时间戳,长整型) */ + public static final String ALERTED_DATE = "alert_date"; + + /** 内容摘要(文件夹名称或笔记前几句文本) */ + public static final String SNIPPET = "snippet"; + + /** 关联的桌面小部件ID(长整型) */ + public static final String WIDGET_ID = "widget_id"; + + /** 小部件类型(0:2x,1:4x,长整型) */ + public static final String WIDGET_TYPE = "widget_type"; + + /** 背景颜色ID(长整型) */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** 是否有附件(0/1整型) */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** 包含的笔记数量(仅文件夹有效,长整型) */ + public static final String NOTES_COUNT = "notes_count"; + + /** 条目类型(0笔记/1文件夹/2系统,整型) */ + public static final String TYPE = "type"; + + /** 同步ID(用于云端同步,长整型) */ + public static final String SYNC_ID = "sync_id"; + + /** 本地修改标记(0未修改/1已修改,整型) */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** 移动前的原始父ID(用于临时文件夹操作,整型) */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** Google Task ID(同步相关,文本) */ + public static final String GTASK_ID = "gtask_id"; + + /** 数据版本号(长整型) */ + public static final String VERSION = "version"; + } + + /** + * 数据表列名接口定义 + * 存储笔记的具体内容数据 + */ + public interface DataColumns { + /** 唯一标识符(长整型) */ + public static final String ID = "_id"; + + /** MIME类型(决定数据项类型,如text_note/call_note) */ + public static final String MIME_TYPE = "mime_type"; + + /** 关联的笔记ID(外键,长整型) */ + public static final String NOTE_ID = "note_id"; + + /** 创建时间(Unix时间戳,长整型) */ + public static final String CREATED_DATE = "created_date"; + + /** 最后修改时间(Unix时间戳,长整型) */ + public static final String MODIFIED_DATE = "modified_date"; + + /** 主要内容(文本笔记的完整内容) */ + public static final String CONTENT = "content"; + + // 通用数据列(根据MIME_TYPE不同用途不同) + /** 通用整型数据1(如文本笔记的列表模式) */ + public static final String DATA1 = "data1"; + + /** 通用整型数据2 */ + public static final String DATA2 = "data2"; + + /** 通用文本数据3(如通话记录的电话号码) */ + public static final String DATA3 = "data3"; + + /** 通用文本数据4 */ + public static final String DATA4 = "data4"; + + /** 通用文本数据5 */ + public static final String DATA5 = "data5"; + } + + /** + * 文本笔记数据定义(继承DataColumns) + */ + public static final class TextNote implements DataColumns { + /** 列表模式标识(DATA1列,1=清单模式,0=普通模式) */ + public static final String MODE = DATA1; + public static final int MODE_CHECK_LIST = 1; // 清单模式常量 + + // MIME类型定义 + 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"; // 单条目类型 + + // 文本笔记的ContentProvider URI(content://micode_notes/text_note) + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + /** + * 通话记录笔记数据定义(继承DataColumns) + */ + public static final class CallNote implements DataColumns { + /** 通话日期(使用DATA1列存储Unix时间戳) */ + public static final String CALL_DATE = DATA1; + + /** 电话号码(使用DATA3列存储) */ + public static final String PHONE_NUMBER = DATA3; + + // MIME类型定义 + 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"; // 单条目类型 + + // 通话笔记的ContentProvider URI(content://micode_notes/call_note) + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} \ No newline at end of file diff --git a/src/NotesDatabaseHelper.java b/src/NotesDatabaseHelper.java new file mode 100644 index 0000000..6049e78 --- /dev/null +++ b/src/NotesDatabaseHelper.java @@ -0,0 +1,375 @@ +/* + * 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; + +// 导入Android数据库操作相关类 +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 + * 负责数据库创建、版本升级及表结构管理 + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + // 数据库名称常量 + private static final String DB_NAME = "note.db"; + // 数据库版本号(当前版本4) + private static final int DB_VERSION = 4; + + // 表名接口定义 + public interface TABLE { + String NOTE = "note"; // 笔记元数据表 + String DATA = "data"; // 笔记内容数据表 + } + + // 日志标签 + private static final String TAG = "NotesDatabaseHelper"; + + // 单例实例(线程安全) + private static NotesDatabaseHelper mInstance; + + /******************** 表结构定义SQL语句 ********************/ + + // 创建笔记表的SQL(包含15个字段) + 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," + // 父文件夹ID + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +// 提醒时间戳 + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景色ID + 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," + // 关联小部件ID + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +// 小部件类型 + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +// 本地修改标记 + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 原父ID + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 数据版本 + ")"; + + // 创建数据表的SQL(包含11个字段) + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键 + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型 + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联笔记ID + 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," + // 扩展字段1(整型) + DataColumns.DATA2 + " INTEGER," + // 扩展字段2(整型) + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 扩展字段3(文本) + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 扩展字段4(文本) + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 扩展字段5(文本) + ")"; + + // 创建数据表note_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 + ");"; + + /******************** 触发器定义 ********************/ + + // 更新笔记父文件夹时增加目标文件夹计数 + 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"; + + // 更新笔记父文件夹时减少原文件夹计数 + 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"; + + // 插入新笔记时增加父文件夹计数 + 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"; + + // 删除笔记时减少父文件夹计数 + 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"; + + // 插入文本数据时更新笔记摘要 + 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"; + + // 更新文本数据时更新笔记摘要 + 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"; + + // 删除文本数据时清空笔记摘要 + 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"; + + // 删除笔记时级联删除关联数据 + 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"; + + // 删除文件夹时级联删除子笔记 + 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"; + + // 移动文件夹到回收站时同步移动子笔记 + 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"; + + /******************** 构造函数与单例方法 ********************/ + + // 私有构造函数(单例模式) + private NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + // 获取单例实例(线程安全) + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + /******************** 数据库生命周期方法 ********************/ + + @Override + public void onCreate(SQLiteDatabase db) { + // 创建笔记表及相关触发器 + createNoteTable(db); + // 创建数据表及相关触发器 + createDataTable(db); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; // 是否重建触发器标记 + boolean skipV2 = false; // 是否跳过V2升级标记 + + // 版本1升级到V2(完全重建表) + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // 包含V2到V3的升级 + oldVersion++; + } + + // 版本2升级到V3(添加GTASK_ID和回收站) + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; // 需要重建触发器 + oldVersion++; + } + + // 版本3升级到V4(添加版本字段) + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + + // 需要时重建触发器 + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + // 版本检查异常处理 + if (oldVersion != newVersion) { + throw new IllegalStateException("数据库升级失败,当前版本:" + oldVersion + ",目标版本:" + newVersion); + } + } + + /******************** 表创建方法 ********************/ + + // 创建笔记表(含系统文件夹初始化) + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行建表SQL + reCreateNoteTableTriggers(db); // 重建触发器 + createSystemFolder(db); // 初始化系统文件夹 + Log.d(TAG, "笔记表已创建"); + } + + // 重建笔记表触发器(升级时使用) + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + // 删除旧触发器 + String[] triggers = { + "increase_folder_count_on_update", + "decrease_folder_count_on_update", + "decrease_folder_count_on_delete", + "delete_data_on_delete", + "increase_folder_count_on_insert", + "folder_delete_notes_on_delete", + "folder_move_notes_on_trash" + }; + for (String trigger : triggers) { + db.execSQL("DROP TRIGGER IF EXISTS " + trigger); + } + + // 重新创建核心触发器 + 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); + } + + // 初始化系统文件夹(根目录/通话记录/临时/回收站) + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + // 创建通话记录文件夹 + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 创建根文件夹 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 创建临时文件夹(注意拼写错误TEMPARAY) + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + // 创建回收站文件夹(注意拼写错误FOLER) + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + // 创建数据表(含内容更新触发器) + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); // 执行建表SQL + reCreateDataTableTriggers(db); // 重建触发器 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建索引 + Log.d(TAG, "数据表已创建"); + } + + // 重建数据表触发器 + private void reCreateDataTableTriggers(SQLiteDatabase db) { + // 删除旧触发器 + String[] triggers = { + "update_note_content_on_insert", + "update_note_content_on_update", + "update_note_content_on_delete" + }; + for (String trigger : triggers) { + db.execSQL("DROP TRIGGER IF EXISTS " + trigger); + } + + // 重新创建内容更新触发器 + 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); + } + + /******************** 数据库升级方法 ********************/ + + // 升级到V2版本(完全重建表结构) + 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和回收站) + private void upgradeToV3(SQLiteDatabase db) { + // 删除废弃的修改时间触发器 + 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"); + + // 添加Google任务ID字段 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID diff --git a/src/NotesProvider.java b/src/NotesProvider.java new file mode 100644 index 0000000..d817488 --- /dev/null +++ b/src/NotesProvider.java @@ -0,0 +1,281 @@ +/* + * 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; + + // 导入必要的Android类和自定义类 + 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; + + // 自定义ContentProvider,用于管理笔记数据的访问 + public class NotesProvider extends ContentProvider { + // URI匹配器,用于解析不同的URI请求 + private static final UriMatcher mMatcher; + // 数据库帮助类实例 + private NotesDatabaseHelper mHelper; + // 日志标签 + private static final String TAG = "NotesProvider"; + + // 定义URI匹配的常量 + private static final int URI_NOTE = 1; // 整个笔记表 + private static final int URI_NOTE_ITEM = 2; // 单个笔记项 + private static final int URI_DATA = 3; // 整个数据表 + private static final int URI_DATA_ITEM = 4; // 单个数据项 + private static final int URI_SEARCH = 5; // 搜索请求 + private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议请求 + + // 静态代码块初始化URI匹配器 + static { + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配"content://authority/note" + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配"content://authority/note/[id]" + 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); + } + + // 搜索结果的列投影,用于搜索建议 + 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语句,过滤回收站和只查普通笔记 + 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; + + // ContentProvider创建时初始化数据库帮助类 + @Override + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + // 处理查询请求 + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + // 根据URI类型执行不同查询 + 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("参数错误"); + } + String searchString = null; + // 获取搜索关键字 + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else { + searchString = uri.getQueryParameter("pattern"); + } + if (TextUtils.isEmpty(searchString)) return null; + try { + searchString = String.format("%%%s%%", searchString); // 构造LIKE参数 + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "异常: " + ex.toString()); + } + break; + default: + throw new IllegalArgumentException("未知URI " + uri); + } + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); // 设置数据变化监听 + } + return c; + } + + // 处理插入操作 + @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, "数据格式错误: " + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("未知URI " + uri); + } + // 通知数据变化 + if (noteId > 0) { + getContext().getContentResolver().notifyChange(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + if (dataId > 0) { + getContext().getContentResolver().notifyChange(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + return ContentUris.withAppendedId(uri, insertedId); // 返回新插入项的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 = uri.getPathSegments().get(1); + 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 = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("未知URI " + uri); + } + if (count > 0) { + if (deleteData) { // 数据删除需要通知笔记URI更新 + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); // 通知当前URI变化 + } + return count; + } + + // 处理更新操作 + @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 = 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 = uri.getPathSegments().get(1); + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("未知URI " + uri); + } + if (count > 0) { + if (updateData) { // 数据更新需要通知笔记URI + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + // 辅助方法:拼接查询条件 + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + // 增加笔记版本号(用于同步/冲突检测) + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE ").append(TABLE.NOTE) + .append(" SET ").append(NoteColumns.VERSION).append("=").append(NoteColumns.VERSION).append("+1 "); + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + if (id > 0) { + sql.append(NoteColumns.ID).append("=").append(id); + } + // 注意:这里直接拼接selection参数可能存在SQL注入风险 + String selectString = id > 0 ? parseSelection(selection) : selection; + if (!TextUtils.isEmpty(selectString)) { + for (String arg : selectionArgs) { + selectString = selectString.replaceFirst("\\?", arg); // 替换占位符 + } + sql.append(selectString); + } + } + mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL + } + + // 未实现的方法(需返回MIME类型) + @Override + public String getType(Uri uri) { + return null; + } + } \ No newline at end of file