develop
焦胜 3 months ago
parent c8bf53be18
commit 7f0417e77b

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -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<String, String> 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<String, String>();
}
// 检查缓存中是否存在该号码的姓名,存在则直接返回
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;
}
}
}

@ -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();
}

@ -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 IDR.layout.widget_2x
*
*
* 1.
* 2.
* 3. widget_2x.xml2xUI
*/
@Override
protected int getLayoutId() {
return R.layout.widget_2x; // 返回2x尺寸专用布局
}
/**
*
*
* @param bgId ID
* @return int drawableID
*
*
* 1. ResourceParserID
* 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; // 类型标识常量
}
}

@ -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 IDR.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 DrawableID
*
*
* 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. noteswidget_type
* 2. SELECT * FROM notes WHERE widget_type = 4
* 3. 使
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; // 类型标识常量值为4
}
}

@ -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_FOLERID_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
*/
// 查询所有笔记和文件夹的URIcontent://micode_notes/note
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
// 查询所有数据项的URIcontent://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 URIcontent://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 URIcontent://micode_notes/call_note
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -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

@ -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;
}
}
Loading…
Cancel
Save