代码注释

guoxinyao
guoxinyao 2 months ago
parent 6534cf9a3c
commit 3f0dfaa996

@ -0,0 +1,87 @@
/*
* (c) 2010-2011MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.data; // 声明包名,表示这是联系人数据的包
import android.content.Context; // 导入 Context 类,以访问应用程序的环境
import android.database.Cursor; // 导入 Cursor 类,用于操作数据库查询结果
import android.provider.ContactsContract.CommonDataKinds.Phone; // 导入 Phone 类,以访问联系人电话数据
import android.provider.ContactsContract.Data; // 导入 Data 类,以访问联系人数据
import android.telephony.PhoneNumberUtils; // 导入 PhoneNumberUtils 类,以提供电话相关的实用方法
import android.util.Log; // 导入 Log 类,用于记录日志信息
import java.util.HashMap; // 导入 HashMap 类,用于存储联系人信息的缓存
public class Contact {
private static HashMap<String, String> sContactCache; // 静态 HashMap用于缓存电话号码和对应的联系人名称
private static final String TAG = "Contact"; // 日志标签,用于标识日志信息
// 用于通过电话号码查询联系人的 SQL 选择条件
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 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 检查缓存是否为空,如果为空,则初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); // 创建一个新的 HashMap 以缓存联系人信息
}
// 检查缓存中是否已经存在该电话号码的联系人名称
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); // 如果存在,直接返回缓存中的联系人名称
}
// 替换选择条件中的占位符 '+' 为电话号码的最小匹配格式
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人数据
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, // 查询的内容 URI
new String[] { Phone.DISPLAY_NAME }, // 要返回的列,这里只返回联系人名称
selection, // 选择条件
new String[] { phoneNumber }, // 查询参数(电话号码)
null); // 附加查询选项,通常为 null
// 检查 Cursor 是否不为空且有结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取查询结果中的联系人名称
String name = cursor.getString(0); // 从 Cursor 中获取第一个字段,即联系人名称
sContactCache.put(phoneNumber, name); // 将获取到的联系人名称存入缓存
return name; // 返回联系人名称
} catch (IndexOutOfBoundsException e) {
// 处理索引超出范围异常
Log.e(TAG, "Cursor get string error " + e.toString()); // 记录错误日志
return null; // 返回 null
} finally {
cursor.close(); // 确保 Cursor 在使用后关闭,以释放资源
}
} else {
// 如果没有找到匹配的联系人,记录调试信息
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; // 返回 null
}
}
}

@ -0,0 +1,280 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.net.Uri;
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; // 系统类型
/**
*
* {@link Notes#ID_ROOT_FOLDER}
* {@link Notes#ID_TEMPARAY_FOLDER}
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; // 垃圾箱文件夹ID
// Intent附加数据的键值
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 小部件类型
public static class DataConstants {
// 数据项的 MIME 类型
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 笔记的 MIME 类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话记录的 MIME 类型
}
/**
* 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
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
*
* <P> : TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
*
* <P> </P>
* <P> : INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* :
* <P> : INTEGER </P>
*/
public static final String TYPE = "type";
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String LAST_SYNC_ID = "last_sync_id"; // 最后同步 ID
}
}
/**
*
* <P> : INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* ID
* <P> : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* gtask ID
* <P> : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
public interface DataColumns {
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* MIME
* <P> : TEXT </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* ID
* <P> : INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> : TEXT </P>
*/
public static final String CONTENT = "content";
/**
* {@link #MIME_TYPE}
*
* <P> : INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* {@link #MIME_TYPE}
*
* <P> : INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* {@link #MIME_TYPE}
*
* <P> : TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* {@link #MIME_TYPE}
*
* <P> : TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* {@link #MIME_TYPE}
*
* <P> : TEXT </P>
*/
public static final String DATA5 = "data5";
}
public static final class TextNote implements DataColumns {
/**
*
* <P> : Integer 1: 0: </P>
*/
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"); // 查询文本笔记的 URI
}
public static final class CallNote implements DataColumns {
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
*
* <P> : TEXT </P>
*/
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"); // 查询通话记录的 URI
}

@ -0,0 +1,342 @@
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;
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
")";
// 创建数据表的NOTE_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 + ");"; // 为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";
/**
* {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* {@link DataConstants#NOTE}
*/
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";
/**
* {@link DataConstants#NOTE}
*/
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 + "'" + // 仅当删除的数据类型为NOTE时触发
" BEGIN" +
" UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.SNIPPET + "=''" + // 将笔记摘要设置为空
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + // 根据被删除数据的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 + ";" + // 根据已删除笔记的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 + ";" + // 根据已删除文件夹的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 + // 当新父级ID为垃圾箱ID时触发
" BEGIN" +
" UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + // 将父级ID设置为垃圾箱ID
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + // 更新与已移除的文件夹ID相关的笔记
" END";
// NotesDatabaseHelper构造函数初始化数据库帮助器
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); // 调用父类构造函数,设置数据库名称和版本
}
// 创建笔记表的方法
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行创建笔记表的SQL语句
reCreateNoteTableTriggers(db); // 重新创建与笔记表相关的触发器
createSystemFolder(db); // 创建系统文件夹
Log.d(TAG, "note table has been created"); // 打印日志,指示笔记表已创建
}
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除已存在的触发器,防止重复创建
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record folder for call notes
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); // 插入通话记录文件夹
/**
* root folder which is default folder
*/
values.clear(); // 清空之前的内容
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); // 插入根文件夹
/**
* temporary folder which is used for moving note
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); // 插入临时文件夹
/**
* create trash folder
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); // 插入垃圾箱文件夹
}
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); // 执行创建数据表的SQL语句
reCreateDataTableTriggers(db); // 重新创建与数据表相关的触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建数据表中NOTE_ID的索引
Log.d(TAG, "data table has been created"); // 打印日志,指示数据表已创建
}
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
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升级
if (oldVersion == 1) {
upgradeToV2(db); // 升级到版本2
skipV2 = true; // 设置为跳过v2的标记
oldVersion++;
}
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); // 升级到版本3
reCreateTriggers = true; // 设置为需要重新创建触发器
oldVersion++;
}
if (oldVersion == 3) {
upgradeToV4(db); // 升级到版本4
oldVersion++;
}
if (reCreateTriggers) {
reCreateNoteTableTriggers(db); // 重新创建与笔记表相关的触发器
reCreateDataTableTriggers(db); // 重新创建与数据表相关的触发器
}
// 如果旧版本不等于新版本,抛出异常
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion + " fails");
}
}
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); // 重新创建数据表
}
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); // 插入垃圾箱文件夹
}
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0");
}

@ -0,0 +1,295 @@
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;
public class NotesProvider extends ContentProvider {
// 定义 UriMatcher 以匹配不同的 URI
private static final UriMatcher mMatcher;
// 数据库帮助类的实例
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider"; // 日志标签
// 定义 URI 常量
private static final int URI_NOTE = 1; // 笔记 URI
private static final int URI_NOTE_ITEM = 2; // 单个笔记项 URI
private static final int URI_DATA = 3; // 数据 URI
private static final int URI_DATA_ITEM = 4; // 单个数据项 URI
private static final int URI_SEARCH = 5; // 搜索 URI
private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议 URI
// 静态初始化块,初始化 UriMatcher
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配笔记 URI
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单个笔记项 URI
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配数据 URI
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 匹配单个数据项 URI
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 匹配搜索 URI
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); // 匹配搜索建议 URI
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); // 匹配带参数的搜索建议 URI
}
/**
* x'0A' SQLite '\n'
* '\n'
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 用于搜索笔记的 SQL 查询语句
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; // 声明 ID 变量
// 根据 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 = uri.getPathSegments().get(1); // 获取 URI 中的 ID
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); // 获取 URI 中的 ID
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");
}
// 如果搜索字符串为空,返回 null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 格式化搜索字符串以用于 LIKE 查询
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); // 执行原始查询
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString()); // 记录异常
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri); // 未知 URI 异常
}
// 设置通知 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; // 声明 ID 变量
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)) { // 确保包含笔记 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 异常
}
// 通知笔记 URI 更新
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// 通知数据 URI 更新
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; // 声明 ID 字符串
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); // 获取 URI 中的 ID
long noteId = Long.valueOf(id);
if (noteId <= 0) { // 系统文件夹 ID 小于等于 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); // 获取 URI 中的 ID
count = db.delete(TABLE.DATA, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + 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; // 声明 ID 字符串
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); // 获取 URI 中的 ID
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 根据 ID 增加笔记版本号
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); // 获取 URI 中的 ID
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); // 执行更新操作
updateData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri); // 未知 URI 异常
}
if (count > 0) {
if (updateData) { // 如果更新了数据项,通知笔记 URI 更新
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null); // 通知 URI 更新
}
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 语句
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)) { // 如果指定了 ID 或选择条件,添加限制条件
sql.append(" WHERE ");
}
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); // 添加 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()); // 执行 SQL 语句
}
@Override
public String getType(Uri uri) {
return null; // 返回类型为 null
}
Loading…
Cancel
Save