From b97c594138ff72bfe9b899bc4eaf0940bd698ffe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E9=AA=90=E7=91=9E?= <3349293156@qq.com> Date: Thu, 3 Apr 2025 17:30:22 +0800 Subject: [PATCH] add --- src/蔡建宇/contact.java | 96 +++++++ src/蔡建宇/notes.java | 256 +++++++++++++++++++ src/蔡建宇/notesdatabasehelper.java | 168 +++++++++++++ src/蔡建宇/notesprovider.java | 331 +++++++++++++++++++++++++ 4 files changed, 851 insertions(+) create mode 100644 src/蔡建宇/contact.java create mode 100644 src/蔡建宇/notes.java create mode 100644 src/蔡建宇/notesdatabasehelper.java create mode 100644 src/蔡建宇/notesprovider.java diff --git a/src/蔡建宇/contact.java b/src/蔡建宇/contact.java new file mode 100644 index 0000000..18723cd --- /dev/null +++ b/src/蔡建宇/contact.java @@ -0,0 +1,96 @@ +/* + * 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.Context; +import android.database.Cursor; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.telephony.PhoneNumberUtils; +import android.util.Log; + +import java.util.HashMap; + +/** + * Contact类用于管理和查询联系人信息。 + */ +public class Contact { + // 缓存联系人信息的HashMap + private static HashMap sContactCache; + // 日志输出的标签 + private static final String TAG = "Contact"; + + // 查询联系人的selection字符串 + 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); + } + + // 构建查询selection + 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 { + // 从Cursor获取联系人姓名 + 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 + cursor.close(); + } + } else { + // 记录没有找到联系人的日志 + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} \ No newline at end of file diff --git a/src/蔡建宇/notes.java b/src/蔡建宇/notes.java new file mode 100644 index 0000000..1b43cf9 --- /dev/null +++ b/src/蔡建宇/notes.java @@ -0,0 +1,256 @@ +package net.micode.notes.data; + +import android.net.Uri; + +public class Notes { + 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; + public static final int ID_TEMPARAY_FOLDER = -1; + public static final int ID_CALL_RECORD_FOLDER = -2; + public static final int ID_TRASH_FOLER = -3; + + 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"; + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_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"; + 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; + 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 + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * 查询数据的 Uri + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + public interface NoteColumns { + /** + * 行的唯一 ID + *

类型: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * 笔记或文件夹的父 ID + *

类型: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * 笔记或文件夹的创建日期 + *

类型: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最后修改日期 + *

类型: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * 提醒日期 + *

类型: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * 文件夹名称或笔记的文本内容 + *

类型: TEXT

+ */ + public static final String SNIPPET = "snippet"; + + /** + * 笔记的小部件 ID + *

类型: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * 笔记的小部件类型 + *

类型: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * 笔记的背景颜色 ID + *

类型: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * 对于文本笔记,没有附件;对于多媒体笔记,至少有一个附件 + *

类型: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * 文件夹中的笔记数量 + *

类型: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * 文件类型:文件夹或笔记 + *

类型: INTEGER

+ */ + public static final String TYPE = "type"; + + /** + * 最后同步的 ID + *

类型: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * 标记本地是否已修改 + *

类型: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * 移动到临时文件夹前的原始父 ID + *

类型 : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * Google 任务 ID + *

类型 : TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * 版本号 + *

类型 : INTEGER (long)

+ */ + public static final String VERSION = "version"; + } + + public interface DataColumns { + /** + * 行的唯一 ID + *

类型: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * 此行表示的项目的 MIME 类型 + *

类型: 文本

+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * 此数据所属笔记的引用 ID + *

类型: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; + + /** + * 笔记或文件夹的创建日期 + *

类型: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * 最后修改日期 + *

类型: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * 数据内容 + *

类型: TEXT

+ */ + public static final String CONTENT = "content"; + + /** + * 通用数据列,其含义取决于 {@link #MIMETYPE},用于整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA1 = "data1"; + + /** + * 通用数据列,其含义取决于 {@link #MIMETYPE},用于整数数据类型 + *

类型: INTEGER

+ */ + public static final String DATA2 = "data2"; + + /** + * 通用数据列,其含义取决于 {@link #MIMETYPE},用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA3 = "data3"; + + /** + * 通用数据列,其含义取决于 {@link #MIMETYPE},用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * 通用数据列,其含义取决于 {@link #MIMETYPE},用于文本数据类型 + *

类型: TEXT

+ */ + public static final String DATA5 = "data5"; + } + + public static final class TextNote implements DataColumns { + /** + * 模式,指示文本是否为检查列表模式 + *

类型: Integer 1:检查列表模式 0:普通模式

+ */ + 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 { + /** + * 此记录的通话日期 + *

类型: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1; + + /** + * 此记录的电话号码 + *

类型: 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/src/蔡建宇/notesdatabasehelper.java b/src/蔡建宇/notesdatabasehelper.java new file mode 100644 index 0000000..0402373 --- /dev/null +++ b/src/蔡建宇/notesdatabasehelper.java @@ -0,0 +1,168 @@ +/* + * 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; + +/** + * NotesDatabaseHelper类用于管理便签应用的数据库创建和版本升级。 + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + private static final String DB_NAME = "note.db"; // 数据库名称 + private static final int DB_VERSION = 4; // 数据库版本 + + /** + * 数据库表名接口 + */ + public interface TABLE { + public static final String NOTE = "note"; // 便签表 + public static final String DATA = "data"; // 数据表 + } + + private static final String TAG = "NotesDatabaseHelper"; // 日志标签 + private static NotesDatabaseHelper mInstance; // 单例实例 + + /** + * 创建便签表的SQL语句 + */ + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + // 便签ID + 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语句 + */ + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + // 数据ID + 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 + ")"; + + /** + * 创建数据表便签ID索引的SQL语句 + */ + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + // 定义触发器SQL语句... + + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + /** + * 创建便签表 + */ + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + + /** + * 重新创建便签表触发器 + */ + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + // 删除旧触发器... + // 创建新触发器... + } + + /** + * 创建系统文件夹 + */ + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + // 插入系统文件夹... + } + + /** + * 创建数据表 + */ + 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"); + } + + /** + * 重新创建数据表触发器 + */ + private void reCreateDataTableTriggers(SQLiteDatabase db) { + // 删除旧触发器... + // 创建新触发器... + } + + /** + * 获取单例实例 + */ + 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) { + // 升级数据库版本... + } + + // 升级方法... +} diff --git a/src/蔡建宇/notesprovider.java b/src/蔡建宇/notesprovider.java new file mode 100644 index 0000000..87b3744 --- /dev/null +++ b/src/蔡建宇/notesprovider.java @@ -0,0 +1,331 @@ +/* + * 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; + +/** + * NotesProvider类是便签应用的内容提供者,用于管理便签数据的增删改查操作。 + * 它处理对便签和数据表的查询、插入、更新和删除请求,并提供搜索建议。 + */ +public class NotesProvider extends ContentProvider { + private static final UriMatcher mMatcher; // 用于匹配URI的匹配器 + + 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; // 匹配搜索建议请求 + + static { + // 初始化URI匹配器 + 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、意图额外数据、文本1、文本2、图标1、意图动作和意图数据类型。 + */ + 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查询语句。 + * 从便签表中选择ID、摘要、类型等列,其中摘要包含搜索字符串,且便签不在回收站中。 + */ + 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; + + @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; + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 查询便签表 + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + // 查询单个便签项 + 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 = 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) { + 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); + 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); + } + 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, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + 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); + } + + @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("Unknown URI " + uri); + } + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + 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("Unknown URI " + uri); + } + + if (count > 0) { + if (updateData) { + 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 "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + 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()); + } + + @Override + public String getType(Uri uri) { + // 返回给定URI的MIME类型 + return null; + } +}