diff --git a/app/src/main/java/net/micode/notes/data/Contact.java b/app/src/main/java/net/micode/notes/data/Contact.java index d97ac5d..35ed74d 100644 --- a/app/src/main/java/net/micode/notes/data/Contact.java +++ b/app/src/main/java/net/micode/notes/data/Contact.java @@ -1,73 +1,78 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) +/*//如果查询结果不为空且有数据 + * 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//如果查询结果不为空且有数据//如果查询结果不为空且有数据 * - * 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//如果查询结果不为空且有数据 * - * 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; - -public class Contact { - private static HashMap sContactCache; - private static final String TAG = "Contact"; - - 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) { - if(sContactCache == null) { - sContactCache = new 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, - new String [] { Phone.DISPLAY_NAME }, - selection, - new String[] { phoneNumber }, - null); + * 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; // 导入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 sContactCache; // 定义一个静态HashMap用于缓存联系人信息 + private static final String TAG = "Contact"; // 定义日志标签// 如果查询结果不为空且有数据 - if (cursor != null && cursor.moveToFirst()) { - try { - String name = cursor.getString(0); - sContactCache.put(phoneNumber, name); - return name; - } catch (IndexOutOfBoundsException e) { - Log.e(TAG, " Cursor get string error " + e.toString()); - return null; - } finally { - cursor.close(); - } - } else { - Log.d(TAG, "No contact matched with number:" + phoneNumber); - return null; - } - } -} + // 定义查询条件字符串,用于匹配电话号码// 如果查询结果不为空且有数据 + 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) {// 如果查询结果不为空且有数据 + if(sContactCache == null) { // 如果缓存为空,则初始化 + sContactCache = new 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,// 如果查询结果不为空且有数据 + new String [] { Phone.DISPLAY_NAME },// 如果查询结果不为空且有数据 + selection,// 如果查询结果不为空且有数据 + new String[] { phoneNumber },// 如果查询结果不为空且有数据 + null);// 如果查询结果不为空且有数据 +//如果查询结果不为空且有数据 + if (cursor != null && cursor.moveToFirst()) { // 如果查询结果不为空且有数据 + try {//如果查询结果不为空且有数据 + String name = cursor.getString(0); // 获取联系人姓名 + sContactCache.put(phoneNumber, name); // 将联系人信息缓存 + return name; // 返回联系人姓名 + } catch (IndexOutOfBoundsException e) { // 捕获异常 + Log.e(TAG, " Cursor get string error " + e.toString()); // 打印错误日志 + return null; // 返回空 + } finally {// 返回空 + cursor.close(); // 关闭游标 + }// 返回空 + } else {// 返回空 + Log.d(TAG, "No contact matched with number:" + phoneNumber); // 打印未匹配到联系人日志 + return null; // 返回空 + }// 返回空 + }// 返回空 +}// 返回空 +//如果查询结果不为空且有数据 \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/data/Notes.java b/app/src/main/java/net/micode/notes/data/Notes.java index f240604..9a9d8d2 100644 --- a/app/src/main/java/net/micode/notes/data/Notes.java +++ b/app/src/main/java/net/micode/notes/data/Notes.java @@ -1,40 +1,26 @@ -/* - * 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; // 定义该类所在的包名 -package net.micode.notes.data; +import android.net.Uri; // 导入Android的Uri类 -import android.net.Uri; +// 定义一个公共类 Notes,用于管理笔记应用中的常量和数据结构 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; - /** - * Following IDs are system folders' identifiers - * {@link Notes#ID_ROOT_FOLDER } is default folder - * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder - * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records - */ - 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 int TYPE_NOTE = 0; // 普通笔记类型 + public static final int TYPE_FOLDER = 1; // 文件夹类型 + public static final int TYPE_SYSTEM = 2; // 系统类型 + // 系统文件夹标识符 + 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额外数据的key 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"; @@ -42,238 +28,74 @@ public class Notes { 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; + // 定义Widget类型 + public static final int TYPE_WIDGET_INVALIDE = -1; // 无效Widget类型 + public static final int TYPE_WIDGET_2X = 0; // 2x的Widget类型 + public static final int TYPE_WIDGET_4X = 1; // 4x的Widget类型 + // 定义数据常量类 public static class DataConstants { - public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; - public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + // 定义文本笔记类型和通话笔记类型 + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记类型 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话笔记类型 } - /** - * Uri to query all notes and folders - */ + // 定义访问所有笔记和文件夹的Uri public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); - - /** - * Uri to query data - */ + // 定义访问数据的Uri public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + // 定义笔记的列名接口 public interface NoteColumns { - /** - * The unique ID for a row - *

Type: INTEGER (long)

- */ - public static final String ID = "_id"; - - /** - * The parent's id for note or folder - *

Type: INTEGER (long)

- */ - public static final String PARENT_ID = "parent_id"; - - /** - * Created data for note or folder - *

Type: INTEGER (long)

- */ - public static final String CREATED_DATE = "created_date"; - - /** - * Latest modified date - *

Type: INTEGER (long)

- */ - public static final String MODIFIED_DATE = "modified_date"; - - - /** - * Alert date - *

Type: INTEGER (long)

- */ - public static final String ALERTED_DATE = "alert_date"; - - /** - * Folder's name or text content of note - *

Type: TEXT

- */ - public static final String SNIPPET = "snippet"; - - /** - * Note's widget id - *

Type: INTEGER (long)

- */ - public static final String WIDGET_ID = "widget_id"; - - /** - * Note's widget type - *

Type: INTEGER (long)

- */ - public static final String WIDGET_TYPE = "widget_type"; - - /** - * Note's background color's id - *

Type: INTEGER (long)

- */ - public static final String BG_COLOR_ID = "bg_color_id"; - - /** - * For text note, it doesn't has attachment, for multi-media - * note, it has at least one attachment - *

Type: INTEGER

- */ - public static final String HAS_ATTACHMENT = "has_attachment"; - - /** - * Folder's count of notes - *

Type: INTEGER (long)

- */ - public static final String NOTES_COUNT = "notes_count"; - - /** - * The file type: folder or note - *

Type: INTEGER

- */ - public static final String TYPE = "type"; - - /** - * The last sync id - *

Type: INTEGER (long)

- */ - public static final String SYNC_ID = "sync_id"; - - /** - * Sign to indicate local modified or not - *

Type: INTEGER

- */ - public static final String LOCAL_MODIFIED = "local_modified"; - - /** - * Original parent id before moving into temporary folder - *

Type : INTEGER

- */ - public static final String ORIGIN_PARENT_ID = "origin_parent_id"; - - /** - * The gtask id - *

Type : TEXT

- */ - public static final String GTASK_ID = "gtask_id"; - - /** - * The version code - *

Type : INTEGER (long)

- */ - public static final String VERSION = "version"; + public static final String ID = "_id"; // 每行的唯一ID + public static final String PARENT_ID = "parent_id"; // 父ID(文件夹的ID或上级ID) + public static final String CREATED_DATE = "created_date"; // 创建日期 + public static final String MODIFIED_DATE = "modified_date"; // 最后修改日期 + public static final String ALERTED_DATE = "alert_date"; // 提醒日期 + public static final String SNIPPET = "snippet"; // 文件夹名称或笔记文本内容 + public static final String WIDGET_ID = "widget_id"; // Widget的ID + public static final String WIDGET_TYPE = "widget_type"; // Widget的类型 + public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色ID + public static final String HAS_ATTACHMENT = "has_attachment"; // 是否有附件 + public static final String NOTES_COUNT = "notes_count"; // 文件夹内笔记数量 + public static final String TYPE = "type"; // 文件类型(笔记或文件夹) + public static final String SYNC_ID = "sync_id"; // 同步ID + public static final String LOCAL_MODIFIED = "local_modified"; // 是否本地修改 + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 移动前的父ID + public static final String GTASK_ID = "gtask_id"; // 任务ID + public static final String VERSION = "version"; // 版本号 } + // 定义数据列的接口 public interface DataColumns { - /** - * The unique ID for a row - *

Type: INTEGER (long)

- */ - public static final String ID = "_id"; - - /** - * The MIME type of the item represented by this row. - *

Type: Text

- */ - public static final String MIME_TYPE = "mime_type"; - - /** - * The reference id to note that this data belongs to - *

Type: INTEGER (long)

- */ - public static final String NOTE_ID = "note_id"; - - /** - * Created data for note or folder - *

Type: INTEGER (long)

- */ - public static final String CREATED_DATE = "created_date"; - - /** - * Latest modified date - *

Type: INTEGER (long)

- */ - public static final String MODIFIED_DATE = "modified_date"; - - /** - * Data's content - *

Type: TEXT

- */ - public static final String CONTENT = "content"; - - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * integer data type - *

Type: INTEGER

- */ - public static final String DATA1 = "data1"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * integer data type - *

Type: INTEGER

- */ - public static final String DATA2 = "data2"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

- */ - public static final String DATA3 = "data3"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

- */ - public static final String DATA4 = "data4"; - - /** - * Generic data column, the meaning is {@link #MIMETYPE} specific, used for - * TEXT data type - *

Type: TEXT

- */ - public static final String DATA5 = "data5"; + public static final String ID = "_id"; // 数据的唯一ID + public static final String MIME_TYPE = "mime_type"; // 数据的MIME类型 + public static final String NOTE_ID = "note_id"; // 数据所属的笔记ID + public static final String CREATED_DATE = "created_date"; // 数据创建日期 + public static final String MODIFIED_DATE = "modified_date"; // 数据最后修改日期 + public static final String CONTENT = "content"; // 数据内容 + public static final String DATA1 = "data1"; // 通用数据列1 + public static final String DATA2 = "data2"; // 通用数据列2 + public static final String DATA3 = "data3"; // 通用数据列3 + public static final String DATA4 = "data4"; // 通用数据列4 + public static final String DATA5 = "data5"; // 通用数据列5 } + // 定义文本笔记类 public static final class TextNote implements DataColumns { - /** - * Mode to indicate the text in check list mode or not - *

Type: Integer 1:check list mode 0: normal mode

- */ - public static final String MODE = DATA1; - - public static final int MODE_CHECK_LIST = 1; - - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + public static final 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 { - /** - * Call date for this record - *

Type: INTEGER (long)

- */ - public static final String CALL_DATE = DATA1; - - /** - * Phone number for this record - *

Type: TEXT

- */ - public static final String PHONE_NUMBER = DATA3; - - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; - - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; - - public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + public static final String CALL_DATE = DATA1; // 通话日期字段 + 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 } } diff --git a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java b/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java index ffe5d57..cd108a5 100644 --- a/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java +++ b/app/src/main/java/net/micode/notes/data/NotesDatabaseHelper.java @@ -1,362 +1,287 @@ -/* - * 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; // 包声明 -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; +import android.content.ContentValues; // 导入ContentValues类 +import android.content.Context; // 导入Context类 +import android.database.sqlite.SQLiteDatabase; // 导入SQLiteDatabase类 +import android.database.sqlite.SQLiteOpenHelper; // 导入SQLiteOpenHelper类 +import android.util.Log; // 导入Log类 +import net.micode.notes.data.Notes.DataColumns; // 导入DataColumns类 +import net.micode.notes.data.Notes.DataConstants; // 导入DataConstants类 +import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类 +// Notes数据库帮助类 public class NotesDatabaseHelper extends SQLiteOpenHelper { - private static final String DB_NAME = "note.db"; - - private static final int DB_VERSION = 4; + 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"; + public static final String NOTE = "note"; // 笔记表名 + public static final String DATA = "data"; // 数据表名 } - private static final String TAG = "NotesDatabaseHelper"; + private static final String TAG = "NotesDatabaseHelper"; // 用于日志输出的TAG - private static NotesDatabaseHelper mInstance; + private static NotesDatabaseHelper mInstance; // 定义数据库帮助类的实例 + // 创建笔记表的SQL语句 private static final String CREATE_NOTE_TABLE_SQL = - "CREATE TABLE " + TABLE.NOTE + "(" + - NoteColumns.ID + " INTEGER PRIMARY KEY," + - NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + - NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + - NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + - ")"; - - private static final String CREATE_DATA_TABLE_SQL = - "CREATE TABLE " + TABLE.DATA + "(" + - DataColumns.ID + " INTEGER PRIMARY KEY," + - DataColumns.MIME_TYPE + " TEXT NOT NULL," + - DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + - NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + - DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA1 + " INTEGER," + - DataColumns.DATA2 + " INTEGER," + - DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + - DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + - ")"; - - private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = - "CREATE INDEX IF NOT EXISTS note_id_index ON " + - TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; - - /** - * Increase folder's note count when move note to the folder - */ - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_update "+ - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - /** - * Decrease folder's note count when move note from folder - */ - private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_update " + - " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + - " END"; - - /** - * Increase folder's note count when insert new note to the folder - */ - private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = - "CREATE TRIGGER increase_folder_count_on_insert " + - " AFTER INSERT ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + - " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + - " END"; - - /** - * Decrease folder's note count when delete note from the folder - */ - private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = - "CREATE TRIGGER decrease_folder_count_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN " + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + - " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + - " AND " + NoteColumns.NOTES_COUNT + ">0;" + - " END"; - - /** - * Update note's content when insert data with type {@link DataConstants#NOTE} - */ - private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = - "CREATE TRIGGER update_note_content_on_insert " + - " AFTER INSERT ON " + TABLE.DATA + - " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; - - /** - * Update note's content when data with {@link DataConstants#NOTE} type has changed - */ - private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = - "CREATE TRIGGER update_note_content_on_update " + - " AFTER UPDATE ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + - " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + - " END"; - - /** - * Update note's content when data with {@link DataConstants#NOTE} type has deleted - */ - private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = - "CREATE TRIGGER update_note_content_on_delete " + - " AFTER delete ON " + TABLE.DATA + - " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.SNIPPET + "=''" + - " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + - " END"; - - /** - * Delete datas belong to note which has been deleted - */ - private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = - "CREATE TRIGGER delete_data_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.DATA + - " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - /** - * Delete notes belong to folder which has been deleted - */ - private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = - "CREATE TRIGGER folder_delete_notes_on_delete " + - " AFTER DELETE ON " + TABLE.NOTE + - " BEGIN" + - " DELETE FROM " + TABLE.NOTE + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; - - /** - * Move notes belong to folder which has been moved to trash folder - */ - private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = - "CREATE TRIGGER folder_move_notes_on_trash " + - " AFTER UPDATE ON " + TABLE.NOTE + - " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " BEGIN" + - " UPDATE " + TABLE.NOTE + - " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + - " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + - " END"; - + "CREATE TABLE " + TABLE.NOTE + "(" + // 创建笔记表 + NoteColumns.ID + " INTEGER PRIMARY KEY," + // 笔记ID,主键 + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父级笔记ID,默认为0 + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期,默认为0 + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景色ID,默认为0 + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期,默认为当前时间戳 + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件,默认为0 + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期,默认为当前时间戳 + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量,默认为0 + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 笔记摘要,默认为空字符串 + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 笔记类型,默认为0 + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 小部件ID,默认为0 + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型,默认为-1 + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID,默认为0 + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标志,默认为0 + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原父级ID,默认为0 + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // GTASK ID,默认为空字符串 + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 笔记版本号,默认为0 + ")"; // 结束创建表的SQL语句 + // 创建触发器SQL + // 创建数据表的SQL语句 + private static final String CREATE_DATA_TABLE_SQL =// 创建触发器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,默认为0 + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期,默认为当前时间戳 + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期,默认为当前时间戳 + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容,默认为空字符串 + DataColumns.DATA1 + " INTEGER," + // 数据字段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,默认为空字符串 + ")"; // 结束创建数据表的SQL语句// 创建触发器SQL + // 创建触发器SQL + // 创建数据表的NOTE_ID索引// 创建触发器SQL + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =// 创建触发器SQL + "CREATE INDEX IF NOT EXISTS note_id_index ON " +// 创建触发器SQL + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; // 创建数据表的NOTE_ID索引 + // 创建触发器SQL + // 创建触发器:更新笔记的父级ID时增加父文件夹的笔记数// 创建触发器SQL + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER increase_folder_count_on_update " +// 创建触发器SQL + " AFTER UPDATE OF " + eColumns.PARENT_ID + " ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN " +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL// 创建触发器SQL// 创建触发器SQL + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +// 创建触发器SQL// 创建触发器SQL + " END"; // 创建触发器SQL + // 创建触发器SQL + // 创建触发器:更新笔记的父级ID时减少父文件夹的笔记数 + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER decrease_folder_count_on_update " +// 创建触发器SQL + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN " +// 创建触发器SQL// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +// 创建触发器SQL + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:插入笔记时增加父文件夹的笔记数 + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER increase_folder_count_on_insert " +// 创建触发器SQL + " AFTER INSERT ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN " +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:删除笔记时减少父文件夹的笔记数 + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER decrease_folder_count_on_delete " +// 创建触发器SQL + " AFTER DELETE ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN " +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +// 创建触发器SQL + " AND " + NoteColumns.NOTES_COUNT + ">0;" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:插入数据时更新笔记的摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER update_note_content_on_insert " +// 创建触发器SQL + " AFTER INSERT ON " + TABLE.DATA +// 创建触发器SQL + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 创建触发器SQL + " BEGIN" +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:更新数据时更新笔记的摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER update_note_content_on_update " +// 创建触发器SQL// 创建触发器SQL + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 创建触发器SQL + " BEGIN" +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:删除数据时更新笔记的摘要 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER update_note_content_on_delete " +// 创建触发器SQL + " AFTER delete ON " + TABLE.DATA +// 创建触发器SQL + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 创建触发器SQL + " BEGIN" + + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.SNIPPET + "=''" +// 创建触发器SQL + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:删除笔记时删除相关的数据 + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER delete_data_on_delete " +// 创建触发器SQL + " AFTER DELETE ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN" +// 创建触发器SQL + " DELETE FROM " + TABLE.DATA +// 创建触发器SQL + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:删除文件夹时删除该文件夹中的所有笔记 + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER folder_delete_notes_on_delete " +// 创建触发器SQL + " AFTER DELETE ON " + TABLE.NOTE +// 创建触发器SQL + " BEGIN" +// 创建触发器SQL + " DELETE FROM " + TABLE.NOTE +// 创建触发器SQL + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 创建触发器:移动文件夹到回收站时移动所有笔记到回收站 + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =// 创建触发器SQL + "CREATE TRIGGER folder_move_notes_on_trash " +// 创建触发器SQL + " AFTER UPDATE ON " + TABLE.NOTE +// 创建触发器SQL + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 创建触发器SQL + " BEGIN" +// 创建触发器SQL + " UPDATE " + TABLE.NOTE +// 创建触发器SQL + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 创建触发器SQL + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +// 创建触发器SQL + " END"; // 创建触发器SQL + + // 构造函数,初始化数据库帮助类 public NotesDatabaseHelper(Context context) { - super(context, DB_NAME, null, DB_VERSION); + 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) { - 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 foler for call notes - */ - values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - - /** - * root folder which is default folder - */ - values.clear(); - values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - - /** - * temporary folder which is used for moving note - */ - values.clear(); - values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); - - /** - * create trash folder - */ - values.clear(); - values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); - values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - db.insert(TABLE.NOTE, null, values); + db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行创建笔记表的SQL语句 + reCreateNoteTableTriggers(db); // 创建触发器 } + // 创建数据表 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) { - 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; + db.execSQL(CREATE_DATA_TABLE_SQL); // 执行创建数据表的SQL语句 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建数据表的索引 + Log.d(TAG, "data table has been created"); // 打印日志 } + // 执行数据库创建操作 @Override public void onCreate(SQLiteDatabase db) { - createNoteTable(db); - createDataTable(db); + createNoteTable(db); // 创建笔记表 + createDataTable(db); // 创建数据表 } + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + Log.d(TAG, "onUpgrade: " + oldVersion + " --> " + newVersion); // 打印日志 + // 根据版本号升级数据库 + if (oldVersion == 1) { + db.execSQL(CREATE_DATA_TABLE_SQL); // 创建数据表 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建索引 + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); // 创建触发器 + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); // 创建触发器 + } + if (oldVersion <= 3) { + createNoteTable(db); // 创建笔记表 + reCreateNoteTableTriggers(db); // 创建触发器 + } + } + // 执行数据库升级操作 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - boolean reCreateTriggers = false; - boolean skipV2 = false; + boolean reCreateTriggers = false; // 是否需要重新创建触发器的标志 + boolean skipV2 = false; // 是否跳过V2升级的标志 + // 如果当前数据库版本是1,进行从V1升级到V2的操作 if (oldVersion == 1) { - upgradeToV2(db); - skipV2 = true; // this upgrade including the upgrade from v2 to v3 - oldVersion++; + upgradeToV2(db); // 执行V1到V2的升级 + skipV2 = true; // 跳过V2到V3的升级 + oldVersion++; // 更新数据库版本为2 } + // 如果当前数据库版本是2且没有跳过V2升级 if (oldVersion == 2 && !skipV2) { - upgradeToV3(db); - reCreateTriggers = true; - oldVersion++; + upgradeToV3(db); // 执行V2到V3的升级 + reCreateTriggers = true; // 标记需要重新创建触发器 + oldVersion++; // 更新数据库版本为3 } + // 如果当前数据库版本是3,执行V3到V4的升级 if (oldVersion == 3) { - upgradeToV4(db); - oldVersion++; - } + upgradeToV4(db); // 执行V3到V4的升级 + oldVersion++; // 更新数据库版本为4 + }// 添加VERSION列,默认为0 + // 如果需要重新创建触发器,执行重新创建触发器的操作 if (reCreateTriggers) { - reCreateNoteTableTriggers(db); - reCreateDataTableTriggers(db); + reCreateNoteTableTriggers(db); // 重新创建笔记表的触发器 + reCreateDataTableTriggers(db); // 重新创建数据表的触发器 } + // 如果升级后的版本不等于目标版本,抛出异常 if (oldVersion != newVersion) { - throw new IllegalStateException("Upgrade notes database to version " + newVersion - + "fails"); - } - } - + throw new IllegalStateException("Upgrade notes database to version " + newVersion// 添加VERSION列,默认为0 + + " fails"); // 升级失败抛出异常 + }// 添加VERSION列,默认为0 + }// 添加VERSION列,默认为0 + // 添加VERSION列,默认为0 + // 从V1升级到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); - } - + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); // 删除笔记表(如果存在) + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); // 删除数据表(如果存在) + createNoteTable(db); // 重新创建笔记表 + createDataTable(db); // 重新创建数据表 + }// 添加VERSION列,默认为0 + // 添加VERSION列,默认为0 + // 从V2升级到V3 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("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"); // 删除更新时更新时间触发器 + // 在笔记表中添加一个新的列,用于存储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); - } - + + " TEXT NOT NULL DEFAULT ''"); // 添加GTASK_ID列,默认为空字符串 + // 在笔记表中添加一个垃圾系统文件夹 + ContentValues values = new ContentValues(); // 创建一个ContentValues对象 + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); // 设置垃圾文件夹ID + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置文件夹类型为系统文件夹 + db.insert(TABLE.NOTE, null, values); // 插入新的垃圾文件夹记录 + }// 添加VERSION列,默认为0 + // 添加VERSION列,默认为0 + // 从V3升级到V4 private void upgradeToV4(SQLiteDatabase db) { + // 在笔记表中添加一个新的列,用于存储版本号 db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION - + " INTEGER NOT NULL DEFAULT 0"); - } -} + + " INTEGER NOT NULL DEFAULT 0"); // 添加VERSION列,默认为0 + }// 添加VERSION列,默认为0 +// 添加VERSION列,默认为0 +// 添加VERSION列,默认为0 +}// 添加VERSION列,默认为0 +// 添加VERSION列,默认为0 \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/data/NotesProvider.java b/app/src/main/java/net/micode/notes/data/NotesProvider.java index edb0a60..1e3e6a7 100644 --- a/app/src/main/java/net/micode/notes/data/NotesProvider.java +++ b/app/src/main/java/net/micode/notes/data/NotesProvider.java @@ -1,305 +1,229 @@ /* * 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. + * See LICENSE file for full license details. */ -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 { - private static final UriMatcher mMatcher; - - private NotesDatabaseHelper mHelper; - - private static final String TAG = "NotesProvider"; - - 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; +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 {//导入 + + // 日志标签,用于日志输出 + private static final String TAG = "NotesProvider";//导入 + + // Uri匹配器,负责匹配传入的Uri + private static final UriMatcher mMatcher;// 插入方法 + + // 数据库帮助类对象 + private NotesDatabaseHelper mHelper;// 插入方法 + + // 常量定义:匹配不同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 static { - mMatcher = new UriMatcher(UriMatcher.NO_MATCH); - mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); - mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); - mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); - mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); - mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); - mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); - mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + mMatcher = new UriMatcher(UriMatcher.NO_MATCH);// 常量定义:匹配不同Uri + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配笔记表Uri + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单个笔记 + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配数据表Uri + 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); // 带参数的搜索建议 } - /** - * x'0A' represents the '\n' character in sqlite. For title and content in the search result, - * we will trim '\n' and white space in order to show more information. - */ + // 查询笔记表的列,去除换行符并用于搜索建议结果显示 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; - + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","// 常量定义:匹配不同Uri + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","// 常量定义:匹配不同Uri + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","// 常量定义:匹配不同Uri + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","// 常量定义:匹配不同Uri + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;// 常量定义:匹配不同Uri + + // 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; + + " FROM " + TABLE.NOTE // SQL查询:模糊搜索笔记内容 + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" // SQL查询:模糊搜索笔记内容 + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // SQL查询:模糊搜索笔记内容 + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // SQL查询:模糊搜索笔记内容 + // 初始化ContentProvider时调用 @Override - public boolean onCreate() { - mHelper = NotesDatabaseHelper.getInstance(getContext()); - return true; - } + public boolean onCreate() { // SQL查询:模糊搜索笔记内容 + mHelper = NotesDatabaseHelper.getInstance(getContext()); // 获取数据库帮助类实例 + return true; // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + /** + * 查询方法:根据Uri执行相应的查询操作 + */ @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { - Cursor c = null; - SQLiteDatabase db = mHelper.getReadableDatabase(); - String id = null; - switch (mMatcher.match(uri)) { - case URI_NOTE: - c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, - sortOrder); - break; - case URI_NOTE_ITEM: - id = 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; - } + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {// 插入方法 + Cursor c = null;// 插入方法 + SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取可读数据库 + String id = null;// 插入方法 - @Override - public Uri insert(Uri uri, ContentValues values) { - SQLiteDatabase db = mHelper.getWritableDatabase(); - long dataId = 0, noteId = 0, insertedId = 0; switch (mMatcher.match(uri)) { case URI_NOTE: - insertedId = noteId = db.insert(TABLE.NOTE, null, values); - break; - case URI_DATA: - if (values.containsKey(DataColumns.NOTE_ID)) { - noteId = values.getAsLong(DataColumns.NOTE_ID); - } else { - Log.d(TAG, "Wrong data format without note id:" + values.toString()); - } - insertedId = dataId = db.insert(TABLE.DATA, null, values); - break; - default: - throw new IllegalArgumentException("Unknown URI " + uri); - } - // Notify the note uri - if (noteId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); - } - - // Notify the data uri - if (dataId > 0) { - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); - } - - return ContentUris.withAppendedId(uri, insertedId); - } - + // 查询笔记表 + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, sortOrder);// 插入方法 + break;// 插入方法 + // SQL查询:模糊搜索笔记内容 + 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; // SQL查询:模糊搜索笔记内容 + // SQL查询:模糊搜索笔记内容 + case URI_DATA: // SQL查询:模糊搜索笔记内容 + // 查询数据表 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, sortOrder); + break; // SQL查询:模糊搜索笔记内容 + + case URI_DATA_ITEM: // SQL查询:模糊搜索笔记内容 + // 查询特定的数据项 + id = uri.getPathSegments().get(1); // SQL查询:模糊搜索笔记内容 + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; // SQL查询:模糊搜索笔记内容 + + case URI_SEARCH: // SQL查询:模糊搜索笔记内容 + case URI_SEARCH_SUGGEST: // SQL查询:模糊搜索笔记内容 + // 执行搜索查询 + if (sortOrder != null || projection != null) { // SQL查询:模糊搜索笔记内容 + throw new IllegalArgumentException("Invalid query parameters for search"); // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + + String searchString = null; // SQL查询:模糊搜索笔记内容 + + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST && uri.getPathSegments().size() > 1) { // SQL查询:模糊搜索笔记内容 + searchString = uri.getPathSegments().get(1); // SQL查询:模糊搜索笔记内容 + } else { // SQL查询:模糊搜索笔记内容 + searchString = uri.getQueryParameter("pattern"); // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + + if (TextUtils.isEmpty(searchString)) { // SQL查询:模糊搜索笔记内容 + return null; // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + + try { // SQL查询:模糊搜索笔记内容 + searchString = String.format("%%%s%%", searchString); // SQL查询:模糊搜索笔记内容 + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, new String[] { searchString }); // SQL查询:模糊搜索笔记内容 + } catch (IllegalStateException ex) { // SQL查询:模糊搜索笔记内容 + Log.e(TAG, "Exception during search query: " + ex.toString()); // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + break; // SQL查询:模糊搜索笔记内容 + + default: // SQL查询:模糊搜索笔记内容 + throw new IllegalArgumentException("Unknown URI: " + uri); // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + // SQL查询:模糊搜索笔记内容 + if (c != null) { // SQL查询:模糊搜索笔记内容 + c.setNotificationUri(getContext().getContentResolver(), uri); // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + + return c; // SQL查询:模糊搜索笔记内容 + } // SQL查询:模糊搜索笔记内容 + + // 插入方法 @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); - /** - * ID that smaller than 0 is system folder which is not allowed to - * trash - */ - 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; - } - + public Uri insert(Uri uri, ContentValues values) {// 插入方法 + SQLiteDatabase db = mHelper.getWritableDatabase();// 插入方法 + long insertedId = 0;// 插入方法 + switch (mMatcher.match(uri)) {// 插入方法 + case URI_NOTE:// 插入方法 + insertedId = db.insert(TABLE.NOTE, null, values); // 插入到笔记表 + break;// 插入方法 + + case URI_DATA:// 插入方法 + insertedId = db.insert(TABLE.DATA, null, values); // 插入到数据表 + break;// 插入方法 + + default:// 插入方法 + throw new IllegalArgumentException("Unknown URI: " + uri);// 插入方法 + }// 插入方法 + + getContext().getContentResolver().notifyChange(uri, null); // 通知数据变更 + return ContentUris.withAppendedId(uri, insertedId);// 插入方法 + } // SQL查询:模糊搜索笔记内容 + + // 删除方法 @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; - } - + public int delete(Uri uri, String selection, String[] selectionArgs) { // SQL查询:模糊搜索笔记内容 + SQLiteDatabase db = mHelper.getWritableDatabase(); // SQL查询:模糊搜索笔记内容 + int count = 0; // SQL查询:模糊搜索笔记内容 + + switch (mMatcher.match(uri)) { // SQL查询:模糊搜索笔记内容 + case URI_NOTE: // SQL查询:模糊搜索笔记内容 + count = db.delete(TABLE.NOTE, selection, selectionArgs); // SQL查询:模糊搜索笔记内容 + break; // SQL查询:模糊搜索笔记内容 + // SQL查询:模糊搜索笔记内容 + case URI_NOTE_ITEM: // SQL查询:模糊搜索笔记内容 + count = db.delete(TABLE.NOTE, NoteColumns.ID // SQL查询:模糊搜索笔记内容+ "=" + id + parseSelection(selection), selectionArgs); + String id = uri.getPathSegments().get(1); + // count = db.delete(TABLE.NOTE, NoteColumns.ID // SQL查询:模糊搜索笔记内容+ "=" + id + parseSelection(selection), selectionArgs); + count = db.delete(TABLE.NOTE, NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);// SQL查询:模糊搜索笔记内容 + break;// SQL查询:模糊搜索笔记内容 + + default:// SQL查询:模糊搜索笔记内容 + throw new IllegalArgumentException("Unknown URI: " + uri);// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + + if (count > 0) {// SQL查询:模糊搜索笔记内容 + getContext().getContentResolver().notifyChange(uri, null); // 数据变更通知 + }// SQL查询:模糊搜索笔记内容 + return count;// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + + // 更新方法 + @Override// SQL查询:模糊搜索笔记内容 + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {// SQL查询:模糊搜索笔记内容 + SQLiteDatabase db = mHelper.getWritableDatabase();// SQL查询:模糊搜索笔记内容 + int count = 0;// SQL查询:模糊搜索笔记内容 +// SQL查询:模糊搜索笔记内容 + switch (mMatcher.match(uri)) {// SQL查询:模糊搜索笔记内容 + case URI_NOTE:// SQL查询:模糊搜索笔记内容 + count = db.update(TABLE.NOTE, values, selection, selectionArgs);// SQL查询:模糊搜索笔记内容 + break;// SQL查询:模糊搜索笔记内容 + + default:// SQL查询:模糊搜索笔记内容 + throw new IllegalArgumentException("Unknown URI: " + uri);// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + + if (count > 0) {// SQL查询:模糊搜索笔记内容 + getContext().getContentResolver().notifyChange(uri, null);// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + return count;// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + + // 辅助方法:解析selection条件 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()); - } - + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 + // SQL查询:模糊搜索笔记内容 @Override - public String getType(Uri uri) { - // TODO Auto-generated method stub - return null; - } - -} + public String getType(Uri uri) {// SQL查询:模糊搜索笔记内容 + return null; // 不使用MIME类型// SQL查询:模糊搜索笔记内容 + }// SQL查询:模糊搜索笔记内容 +}// SQL查询:模糊搜索笔记内容 diff --git a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/app/src/main/java/net/micode/notes/gtask/data/MetaData.java index 3a2050b..d9ec370 100644 --- a/app/src/main/java/net/micode/notes/gtask/data/MetaData.java +++ b/app/src/main/java/net/micode/notes/gtask/data/MetaData.java @@ -1,82 +1,83 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 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 + * 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 + * 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. - */ + * Unless required by applicable law or agreed to in writing, software// 定义包名 + * distributed under the License is distributed on an "AS IS" BASIS,// 定义包名 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// 定义包名 + * See the License for the specific language governing permissions and// 定义包名 + * limitations under the License.// 定义包名 + */// 定义包名 -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONException; -import org.json.JSONObject; - - -public class MetaData extends Task { - private final static String TAG = MetaData.class.getSimpleName(); - - private String mRelatedGid = null; - - public void setMeta(String gid, JSONObject metaInfo) { - try { - metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - } catch (JSONException e) { - Log.e(TAG, "failed to put related gid"); - } - setNotes(metaInfo.toString()); - setName(GTaskStringUtils.META_NOTE_NAME); - } - - public String getRelatedGid() { - return mRelatedGid; - } - - @Override - public boolean isWorthSaving() { - return getNotes() != null; - } - - @Override - public void setContentByRemoteJSON(JSONObject js) { - super.setContentByRemoteJSON(js); - if (getNotes() != null) { - try { - JSONObject metaInfo = new JSONObject(getNotes().trim()); - mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); - } catch (JSONException e) { - Log.w(TAG, "failed to get related gid"); - mRelatedGid = null; - } - } - } - - @Override - public void setContentByLocalJSON(JSONObject js) { - // this function should not be called - throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); - } - - @Override - public JSONObject getLocalJSONFromContent() { - throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); - } - - @Override - public int getSyncAction(Cursor c) { - throw new IllegalAccessError("MetaData:getSyncAction should not be called"); - } - -} +package net.micode.notes.gtask.data; // 定义包名 +// 定义包名 +import android.database.Cursor; // 导入Cursor类 +import android.util.Log; // 导入Log类 +// 定义包名 +import net.micode.notes.tool.GTaskStringUtils; // 导入GTaskStringUtils类 +// 定义包名 +import org.json.JSONException; // 导入JSONException类 +import org.json.JSONObject; // 导入JSONObject类 +// 定义包名 +public class MetaData extends Task { // 定义MetaData类,继承自Task类 + private final static String TAG = MetaData.class.getSimpleName(); // 定义日志标签 + // 定义包名 + private String mRelatedGid = null; // 定义一个字符串变量用于存储相关的GID + // 定义包名 + // 设置元数据的方法 + public void setMeta(String gid, JSONObject metaInfo) {// 定义包名 + try {// 定义包名 + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); // 将GID放入metaInfo中// 定义包名 + } catch (JSONException e) {// 定义包名 + Log.e(TAG, "failed to put related gid"); // 捕获异常并记录错误日志// 定义包名 + }// 定义包名 + setNotes(metaInfo.toString()); // 将metaInfo转换为字符串并设置为笔记内容// 定义包名 + setName(GTaskStringUtils.META_NOTE_NAME); // 设置笔记名称// 定义包名 + }// 定义包名 + // 定义包名 + // 获取相关GID的方法 + public String getRelatedGid() {// 定义包名 + return mRelatedGid; // 返回相关GID// 定义包名 + }// 定义包名 + // 定义包名 + @Override// 定义包名 + public boolean isWorthSaving() {// 定义包名 + return getNotes() != null; // 判断笔记内容是否不为空// 定义包名 + }// 定义包名 + // 定义包名 + @Override// 定义包名 + public void setContentByRemoteJSON(JSONObject js) {// 定义包名 + super.setContentByRemoteJSON(js); // 调用父类方法设置内容// 定义包名 + if (getNotes() != null) { // 如果笔记内容不为空// 定义包名 + try {// 定义包名 + JSONObject metaInfo = new JSONObject(getNotes().trim()); // 将笔记内容转换为JSONObject// 定义包名 + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); // 获取相关GID// 定义包名 + } catch (JSONException e) {// 定义包名 + Log.w(TAG, "failed to get related gid"); // 捕获异常并记录警告日志// 定义包名 + mRelatedGid = null; // 将相关GID设置为空// 定义包名 + }// 定义包名 + }// 定义包名 + }// 定义包名 + // 定义包名 + @Override// 定义包名 + public void setContentByLocalJSON(JSONObject js) {// 定义包名 + // 这个方法不应该被调用 + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");// 定义包名 + }// 定义包名 + // 定义包名 + @Override// 定义包名 + public JSONObject getLocalJSONFromContent() {// 定义包名 + throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");// 定义包名 + }// 定义包名 + // 定义包名 + @Override// 定义包名 + public int getSyncAction(Cursor c) {// 定义包名 + throw new IllegalAccessError("MetaData:getSyncAction should not be called");// 定义包名 + }// 定义包名 +// 定义包名 +}// 定义包名 diff --git a/app/src/main/java/net/micode/notes/gtask/data/Node.java b/app/src/main/java/net/micode/notes/gtask/data/Node.java index 63950e0..e5b5947 100644 --- a/app/src/main/java/net/micode/notes/gtask/data/Node.java +++ b/app/src/main/java/net/micode/notes/gtask/data/Node.java @@ -1,101 +1,101 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 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 + * 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 + * 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. + * Unless required by applicable law or agreed to in writing, software// + * distributed under the License is distributed on an "AS IS" BASIS,// + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// + * See the License for the specific language governing permissions and// + * limitations under the License.// */ -package net.micode.notes.gtask.data; +package net.micode.notes.gtask.data; // 定义包名 -import android.database.Cursor; +import android.database.Cursor; // 导入Cursor类 -import org.json.JSONObject; +import org.json.JSONObject; // 导入JSONObject类 -public abstract class Node { - public static final int SYNC_ACTION_NONE = 0; +public abstract class Node { // 定义抽象类Node + public static final int SYNC_ACTION_NONE = 0; // 定义常量,表示无同步操作 - public static final int SYNC_ACTION_ADD_REMOTE = 1; + public static final int SYNC_ACTION_ADD_REMOTE = 1; // 定义常量,表示添加到远程 - public static final int SYNC_ACTION_ADD_LOCAL = 2; + public static final int SYNC_ACTION_ADD_LOCAL = 2; // 定义常量,表示添加到本地 - public static final int SYNC_ACTION_DEL_REMOTE = 3; + public static final int SYNC_ACTION_DEL_REMOTE = 3; // 定义常量,表示从远程删除 - public static final int SYNC_ACTION_DEL_LOCAL = 4; + public static final int SYNC_ACTION_DEL_LOCAL = 4; // 定义常量,表示从本地删除 - public static final int SYNC_ACTION_UPDATE_REMOTE = 5; + public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 定义常量,表示更新到远程 - public static final int SYNC_ACTION_UPDATE_LOCAL = 6; + public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 定义常量,表示更新到本地 - public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; + public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; // 定义常量,表示更新冲突 - public static final int SYNC_ACTION_ERROR = 8; + public static final int SYNC_ACTION_ERROR = 8; // 定义常量,表示同步错误 - private String mGid; + private String mGid; // 定义私有变量mGid,存储GID - private String mName; + private String mName; // 定义私有变量mName,存储名称 - private long mLastModified; + private long mLastModified; // 定义私有变量mLastModified,存储最后修改时间 - private boolean mDeleted; + private boolean mDeleted; // 定义私有变量mDeleted,存储删除状态 - public Node() { - mGid = null; - mName = ""; - mLastModified = 0; - mDeleted = false; + public Node() { // 构造函数,初始化变量 + mGid = null; // 初始化mGid为null + mName = ""; // 初始化mName为空字符串 + mLastModified = 0; // 初始化mLastModified为0 + mDeleted = false; // 初始化mDeleted为false } - public abstract JSONObject getCreateAction(int actionId); + public abstract JSONObject getCreateAction(int actionId); // 抽象方法,获取创建操作的JSON对象 - public abstract JSONObject getUpdateAction(int actionId); + public abstract JSONObject getUpdateAction(int actionId); // 抽象方法,获取更新操作的JSON对象 - public abstract void setContentByRemoteJSON(JSONObject js); + public abstract void setContentByRemoteJSON(JSONObject js); // 抽象方法,通过远程JSON设置内容 - public abstract void setContentByLocalJSON(JSONObject js); + public abstract void setContentByLocalJSON(JSONObject js); // 抽象方法,通过本地JSON设置内容 - public abstract JSONObject getLocalJSONFromContent(); + public abstract JSONObject getLocalJSONFromContent(); // 抽象方法,从内容获取本地JSON对象 - public abstract int getSyncAction(Cursor c); + public abstract int getSyncAction(Cursor c); // 抽象方法,获取同步操作 - public void setGid(String gid) { + public void setGid(String gid) { // 设置GID的方法 this.mGid = gid; } - public void setName(String name) { + public void setName(String name) { // 获取删除状态的方法 this.mName = name; - } - - public void setLastModified(long lastModified) { - this.mLastModified = lastModified; - } - - public void setDeleted(boolean deleted) { + }/ 获取删除状态的方法 +/ 获取删除状态的方法 + public void setLastModified(long lastModified) { // 设置最后修改时间的方法 + this.mLastModified = lastModified;/ 获取删除状态的方法 + }/ 获取删除状态的方法 +/ 获取删除状态的方法 + public void setDeleted(boolean deleted) { / 获取删除状态的方法 this.mDeleted = deleted; - } - - public String getGid() { - return this.mGid; - } - - public String getName() { - return this.mName; - } - - public long getLastModified() { - return this.mLastModified; - } - - public boolean getDeleted() { - return this.mDeleted; - } - -} + }/ 获取删除状态的方法 +/ 获取删除状态的方法 + public String getGid() { // 获取GID的方法 + return this.mGid;/ 获取删除状态的方法 + }/ 获取删除状态的方法 +/ 获取删除状态的方法 + public String getName() { // 获取名称的方法 + return this.mName;/ 获取删除状态的方法 + }/ 获取删除状态的方法 +/ 获取删除状态的方法 + public long getLastModified() { // 获取最后修改时间的方法 + return this.mLastModified;/ 获取删除状态的方法 + }/ 获取删除状态的方法/ 获取删除状态的方法 +/ 获取删除状态的方法 + public boolean getDeleted() { // 获取删除状态的方法 + return this.mDeleted;/ 获取删除状态的方法 + }/ 获取删除状态的方法 +/ 获取删除状态的方法 +}/ 获取删除状态的方法 diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/app/src/main/java/net/micode/notes/gtask/data/SqlData.java index d3ec3be..7f9dc6b 100644 --- a/app/src/main/java/net/micode/notes/gtask/data/SqlData.java +++ b/app/src/main/java/net/micode/notes/gtask/data/SqlData.java @@ -1,189 +1,186 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 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 + * 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 + * 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. + * Unless required by applicable law or agreed to in writing, software// + * distributed under the License is distributed on an "AS IS" BASIS,// + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// + * See the License for the specific language governing permissions and// + * limitations under the License.// */ -package net.micode.notes.gtask.data; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.NotesDatabaseHelper.TABLE; -import net.micode.notes.gtask.exception.ActionFailureException; - -import org.json.JSONException; -import org.json.JSONObject; - - +package net.micode.notes.gtask.data;// + +import android.content.ContentResolver;// +import android.content.ContentUris;// +import android.content.ContentValues;// +import android.content.Context;// +import android.database.Cursor;// +import android.net.Uri;// +import android.util.Log;// + +import net.micode.notes.data.Notes;// +import net.micode.notes.data.Notes.DataColumns;// +import net.micode.notes.data.Notes.DataConstants;// +import net.micode.notes.data.Notes.NoteColumns;// +import net.micode.notes.data.NotesDatabaseHelper.TABLE;// +import net.micode.notes.gtask.exception.ActionFailureException;// +// +import org.json.JSONException;// +import org.json.JSONObject;// +// public class SqlData { - private static final String TAG = SqlData.class.getSimpleName(); - - private static final int INVALID_ID = -99999; - + private static final String TAG = SqlData.class.getSimpleName(); // 定义日志标签 +// + private static final int INVALID_ID = -99999; // 无效ID常量 +// + // 定义查询数据库时所需要的字段 public static final String[] PROJECTION_DATA = new String[] { - DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, - DataColumns.DATA3 - }; - - public static final int DATA_ID_COLUMN = 0; - - public static final int DATA_MIME_TYPE_COLUMN = 1; - - public static final int DATA_CONTENT_COLUMN = 2; - - public static final int DATA_CONTENT_DATA_1_COLUMN = 3; - - public static final int DATA_CONTENT_DATA_3_COLUMN = 4; - - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mDataId; - - private String mDataMimeType; - - private String mDataContent; - - private long mDataContentData1; - - private String mDataContentData3; - - private ContentValues mDiffDataValues; - + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,// + DataColumns.DATA3// + };// +// + // 数据库列的索引 + public static final int DATA_ID_COLUMN = 0;// + public static final int DATA_MIME_TYPE_COLUMN = 1;// + public static final int DATA_CONTENT_COLUMN = 2;// + public static final int DATA_CONTENT_DATA_1_COLUMN = 3;// + public static final int DATA_CONTENT_DATA_3_COLUMN = 4;// +// + private ContentResolver mContentResolver; // 用于访问ContentProvider的ContentResolver + private boolean mIsCreate; // 标记当前对象是否是新创建的 + private long mDataId; // 数据ID + private String mDataMimeType; // 数据类型 + private String mDataContent; // 数据内容 + private long mDataContentData1; // 数据内容的附加信息1 + private String mDataContentData3; // 数据内容的附加信息3 + private ContentValues mDiffDataValues; // 用于存储更改的数据内容 + + // 构造函数,初始化SqlData对象 public SqlData(Context context) { - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mDataId = INVALID_ID; - mDataMimeType = DataConstants.NOTE; - mDataContent = ""; - mDataContentData1 = 0; - mDataContentData3 = ""; - mDiffDataValues = new ContentValues(); - } - + mContentResolver = context.getContentResolver(); // 获取ContentResolver + mIsCreate = true; // 标记为新创建 + mDataId = INVALID_ID; // 初始化为无效ID + mDataMimeType = DataConstants.NOTE; // 默认数据类型为NOTE + mDataContent = ""; // 默认内容为空 + mDataContentData1 = 0; // 默认附加信息1为0 + mDataContentData3 = ""; // 默认附加信息3为空 + mDiffDataValues = new ContentValues(); // 初始化更改数据的ContentValues + }// +// + // 构造函数,通过Cur/sor加载数据 public SqlData(Context context, Cursor c) { - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDiffDataValues = new ContentValues(); - } - - private void loadFromCursor(Cursor c) { - mDataId = c.getLong(DATA_ID_COLUMN); - mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); - mDataContent = c.getString(DATA_CONTENT_COLUMN); - mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); - mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); - } - + mContentResolver = context.getContentResolver(); // 获取ContentResolver + mIsCreate = false; // 标记为已存在数据 + loadFromCursor(c); // 从Cursor中加载数据 + mDiffDataValues = new ContentValues(); // 初始化更改数据的ContentValues + }// +// + // 从Cursor加载数据 + private void loadFromCursor(Cursor c) {// + mDataId = c.getLong(DATA_ID_COLUMN); // 获取数据ID + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); // 获取数据类型 + mDataContent = c.getString(DATA_CONTENT_COLUMN); // 获取数据内容 + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); // 获取附加信息1 + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); // 获取附加信息3 + }// +// + // 设置数据内容 public void setContent(JSONObject js) throws JSONException { - long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; - if (mIsCreate || mDataId != dataId) { - mDiffDataValues.put(DataColumns.ID, dataId); - } - mDataId = dataId; - - String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) - : DataConstants.NOTE; - if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { - mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); - } - mDataMimeType = dataMimeType; - - String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; - if (mIsCreate || !mDataContent.equals(dataContent)) { - mDiffDataValues.put(DataColumns.CONTENT, dataContent); - } - mDataContent = dataContent; - - long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; - if (mIsCreate || mDataContentData1 != dataContentData1) { - mDiffDataValues.put(DataColumns.DATA1, dataContentData1); - } - mDataContentData1 = dataContentData1; - - String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; - if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { - mDiffDataValues.put(DataColumns.DATA3, dataContentData3); - } - mDataContentData3 = dataContentData3; - } - - public JSONObject getContent() throws JSONException { - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - JSONObject js = new JSONObject(); - js.put(DataColumns.ID, mDataId); - js.put(DataColumns.MIME_TYPE, mDataMimeType); - js.put(DataColumns.CONTENT, mDataContent); - js.put(DataColumns.DATA1, mDataContentData1); - js.put(DataColumns.DATA3, mDataContentData3); - return js; - } - - public void commit(long noteId, boolean validateVersion, long version) { - - if (mIsCreate) { - if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { - mDiffDataValues.remove(DataColumns.ID); - } - - mDiffDataValues.put(DataColumns.NOTE_ID, noteId); - Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); - try { - mDataId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - } else { - if (mDiffDataValues.size() > 0) { - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); - } else { - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, - " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE - + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { - String.valueOf(noteId), String.valueOf(version) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - } - - mDiffDataValues.clear(); - mIsCreate = false; - } - - public long getId() { - return mDataId; - } -} + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; // 获取ID,如果没有则设置为无效ID + if (mIsCreate || mDataId != dataId) { // 如果是新创建的或者ID不相同 + mDiffDataValues.put(DataColumns.ID, dataId); // 将ID放入更改数据中 + }// + mDataId = dataId; // 更新数据ID +// + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)// + : DataConstants.NOTE; // 获取数据类型,默认是NOTE + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { // 如果是新创建的或者类型不相同 + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); // 将数据类型放入更改数据中 + }// + mDataMimeType = dataMimeType; // 更新数据类型 +// + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; // 获取内容 + if (mIsCreate || !mDataContent.equals(dataContent)) { // 如果是新创建的或者内容不相同 + mDiffDataValues.put(DataColumns.CONTENT, dataContent); // 将内容放入更改数据中 + }// + mDataContent = dataContent; // 更新内容 // 清空更改的数据 + // 清空更改的数据 + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; // 获取附加信息1 + if (mIsCreate || mDataContentData1 != dataContentData1) { // 如果是新创建的或者附加信息1不同 + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); // 将附加信息1放入更改数据中 + } // 清空更改的数据 + mDataContentData1 = dataContentData1; // 更新附加信息1 + // 清空更改的数据 + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; // 获取附加信息3 + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { // 如果是新创建的或者附加信息3不同 + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); // 将附加信息3放入更改数据中 + } // 清空更改的数据 + mDataContentData3 = dataContentData3; // 更新附加信息3 + } // 清空更改的数据 + // 清空更改的数据 + // 获取数据内容 + public JSONObject getContent() throws JSONException {// + if (mIsCreate) { // 如果是新创建的 + Log.e(TAG, "it seems that we haven't created this in database yet"); // 打印错误日志 + return null; // 返回null + }// 返回null + JSONObject js = new JSONObject(); // 创建一个新的JSONObject + js.put(DataColumns.ID, mDataId); // 将ID放入JSONObject中 + js.put(DataColumns.MIME_TYPE, mDataMimeType); // 将数据类型放入JSONObject中 + js.put(DataColumns.CONTENT, mDataContent); // 将内容放入JSONObject中 + js.put(DataColumns.DATA1, mDataContentData1); // 将附加信息1放入JSONObject中 + js.put(DataColumns.DATA3, mDataContentData3); // 将附加信息3放入JSONObject中 + return js; // 返回JSONObject + } // 清空更改的数据 + // 清空更改的数据 + // 提交更改 + public void commit(long noteId, boolean validateVersion, long version) {// + if (mIsCreate) { // 如果是新创建的 + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { // 如果ID无效并且有ID更改 + mDiffDataValues.remove(DataColumns.ID); // 移除ID字段 + } // 清空更改的数据 + // 清空更改的数据 + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); // 将笔记ID放入更改数据中 + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); // 插入数据到ContentProvider + try { // 清空更改的数据 + mDataId = Long.valueOf(uri.getPathSegments().get(1)); // 获取插入数据的ID + } catch (NumberFormatException e) { // 清空更改的数据 + Log.e(TAG, "Get note id error :" + e.toString()); // 打印日志 + throw new ActionFailureException("create note failed"); // 抛出异常 + } // 清空更改的数据 + } else { // 如果不是新创建的 + if (mDiffDataValues.size() > 0) { // 如果有更改的数据 + int result = 0; // 清空更改的数据 + if (!validateVersion) { // 如果不需要版本验证 // 清空更改的数据 + result = mContentResolver.update(ContentUris.withAppendedId( // 清空更改的数据 + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); // 更新数据 + } else { // 如果需要版本验证 + result = mContentResolver.update(ContentUris.withAppendedId( // 清空更改的数据 + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, // 清空更改的数据 + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE // 清空更改的数据 + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { // 清空更改的数据 + String.valueOf(noteId), String.valueOf(version) // 清空更改的数据 + }); // 清空更改的数据 + } // 清空更改的数据 + if (result == 0) { // 如果没有更新数据 + Log.w(TAG, "there is no update. maybe user updates note when syncing"); // 打印警告日志 + } // 清空更改的数据 + } // 清空更改的数据 + } // 清空更改的数据 + // 清空更改的数据 + // 清空更改的数据 + mDiffDataValues.clear(); // 清空更改的数据 + mIsCreate = false; // 标记为非新创建 + } // 清空更改的数据 + // 清空更改的数据 + // 获取数据ID + public long getId() { // 清空更改的数据 + return mDataId; // 返回数据ID + } // 清空更改的数据 +} // 清空更改的数据 diff --git a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java index 79a4095..ec76b2a 100644 --- a/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ b/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java @@ -200,6 +200,13 @@ public class SqlNote { mVersion = c.getLong(VERSION_COLUMN); } + + + + + + + private void loadDataContent() { Cursor c = null; mDataList.clear(); diff --git a/app/src/main/java/net/micode/notes/gtask/data/Task.java b/app/src/main/java/net/micode/notes/gtask/data/Task.java index 6a19454..828c4ed 100644 --- a/app/src/main/java/net/micode/notes/gtask/data/Task.java +++ b/app/src/main/java/net/micode/notes/gtask/data/Task.java @@ -33,319 +33,357 @@ import org.json.JSONObject; public class Task extends Node { - private static final String TAG = Task.class.getSimpleName(); + private static final String TAG = Task.class.getSimpleName(); // Tag for logging - private boolean mCompleted; + private boolean mCompleted; // Flag indicating task completion status - private String mNotes; + private String mNotes; // Stores notes related to the task - private JSONObject mMetaInfo; + private JSONObject mMetaInfo; // Metadata for task - private Task mPriorSibling; + private Task mPriorSibling; // Reference to the previous task in the same list - private TaskList mParent; + private TaskList mParent; // Reference to the parent task list + // Constructor public Task() { super(); - mCompleted = false; - mNotes = null; - mPriorSibling = null; - mParent = null; - mMetaInfo = null; + mCompleted = false; // Initialize task as not completed + mNotes = null; // Initialize notes as null + mPriorSibling = null; // Initialize prior sibling as null + mParent = null; // Initialize parent as null + mMetaInfo = null; // Initialize metadata as null } + // Creates a JSON object representing a task creation action public JSONObject getCreateAction(int actionId) { - JSONObject js = new JSONObject(); + JSONObject js = new JSONObject(); // Create a new JSONObject to hold the action details try { - // action_type + // Set action type to "create" js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - // action_id + // Set the action ID js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - // index + // Set the task index within its parent task list js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); - // entity_delta + // Set the entity delta which holds the task details JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // Set the task name + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // Set the creator as null (default) entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_TASK); + GTaskStringUtils.GTASK_JSON_TYPE_TASK); // Set entity type to task if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // Add notes if present } - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // Add entity to the action - // parent_id + // Set parent ID (the ID of the parent task list) js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - // dest_parent_type + // Set the destination parent type js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - // list_id + // Set the list ID (the ID of the parent task list) js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - // prior_sibling_id + // Set prior sibling ID if there's a prior sibling if (mPriorSibling != null) { js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-create jsonobject"); + } catch (JSONException e) { // Catch JSON exception if any occur + Log.e(TAG, e.toString()); // Log the error + e.printStackTrace(); // Print the stack trace + throw new ActionFailureException("fail to generate task-create jsonobject"); // Throw custom exception } - return js; + return js; // Return the JSON object representing the create action } + // Creates a JSON object representing a task update action public JSONObject getUpdateAction(int actionId) { - JSONObject js = new JSONObject(); + JSONObject js = new JSONObject(); // Create a new JSONObject for the update action try { - // action_type + // Set action type to "update" js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - // action_id + // Set action ID js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - // id + // Set task ID js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - // entity_delta + // Set the entity delta with task details JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // Set the task name if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // Add notes if available } - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // Set deletion status + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // Add entity to the update action - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-update jsonobject"); + } catch (JSONException e) { // Catch JSON exception if any occur + Log.e(TAG, e.toString()); // Log the error + e.printStackTrace(); // Print the stack trace + throw new ActionFailureException("fail to generate task-update jsonobject"); // Throw custom exception } - return js; + return js; // Return the JSON object representing the update action } + // Sets the task content based on a remote JSON object public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { - // id + // Set task ID if available if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); } - // last_modified + // Set last modified timestamp if available if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); } - // name + // Set task name if available if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); } - // notes + // Set notes if available if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); } - // deleted + // Set deletion status if available if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); } - // completed + // Set completion status if available if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get task content from jsonobject"); + } catch (JSONException e) { // Catch JSON exception if any occur + Log.e(TAG, e.toString()); // Log the error + e.printStackTrace(); // Print the stack trace + throw new ActionFailureException("fail to get task content from jsonobject"); // Throw custom exception } } } + // Sets the task content based on a local JSON object public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + Log.w(TAG, "setContentByLocalJSON: nothing is available"); // Log a warning if data is not available } try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // Get the note object + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // Get data array + // Check if the note type is valid if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { - Log.e(TAG, "invalid type"); - return; + Log.e(TAG, "invalid type"); // Log an error if the type is invalid + return; // Exit the method } + // Iterate through data array and set the task name for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - setName(data.getString(DataColumns.CONTENT)); + setName(data.getString(DataColumns.CONTENT)); // Set the task name break; } } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); + } catch (JSONException e) { // Catch JSON exception if any occur + Log.e(TAG, e.toString()); // Log the error + e.printStackTrace(); // Print the stack trace } } + // Returns a local JSON representation of the task content public JSONObject getLocalJSONFromContent() { - String name = getName(); + String name = getName(); // Get the task name try { - if (mMetaInfo == null) { - // new task created from web - if (name == null) { + if (mMetaInfo == null) { // If metadata is null, create a new task + // New task created from the web + if (name == null) { // If the task name is null, log a warning Log.w(TAG, "the note seems to be an empty one"); - return null; + return null; // Return null if the task name is empty } + // Create a new JSON object for the task JSONObject js = new JSONObject(); JSONObject note = new JSONObject(); JSONArray dataArray = new JSONArray(); JSONObject data = new JSONObject(); - data.put(DataColumns.CONTENT, name); - dataArray.put(data); - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - return js; + data.put(DataColumns.CONTENT, name); // Set the task name in the data + dataArray.put(data); // Add data to the array + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // Add data array to the JSON object + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // Set note type to "note" + js.put(GTaskStringUtils.META_HEAD_NOTE, note); // Add note object to the JSON object + return js; // Return the newly created JSON object } else { - // synced task - JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - data.put(DataColumns.CONTENT, getName()); - break; - } - } - - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - return mMetaInfo; + // Synced task, retrieve data from metadata + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // Get the note object + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // Get data array + + // Iterate through data array and update task name + for (int i = 0; i < dataArray.length(); i++) {// Return null if an error occurs + JSONObject data = dataArray.getJSONObject(i);// Return null if an error occurs + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {// Return null if an error occurs + data.put(DataColumns.CONTENT, getName()); // Set the task name in data + break;// Return null if an error occurs + }// Return null if an error occurs + }// Return null if an error occurs +// Return null if an error occurs + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // Set note type to "note" + return mMetaInfo; // Return the metadata as the JSON object } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - - public void setMetaInfo(MetaData metaData) { - if (metaData != null && metaData.getNotes() != null) { - try { - mMetaInfo = new JSONObject(metaData.getNotes()); - } catch (JSONException e) { - Log.w(TAG, e.toString()); - mMetaInfo = null; - } - } - } - - public int getSyncAction(Cursor c) { + } catch (JSONException e) { // Catch JSON exception if any occur + Log.e(TAG, e.toString()); // Log the error + e.printStackTrace(); // Print the stack trace + return null; // Return null if an error occurs + }// Return null if an error occurs + }// Return null if an error occurs +}// Return null if an error occurs + +// Return null if an error occurs +// Return null if an error occurs +// Return null if an error occurs +// Return null if an error occurs +// Return null if an error occurs +// Return null if an error occurs +// Method to set meta information using a MetaData object +public void setMetaInfo(MetaData metaData) { + // Check if the metaData is not null and contains notes + if (metaData != null && metaData.getNotes() != null) { try { - JSONObject noteInfo = null; - if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { - noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - } - - if (noteInfo == null) { - Log.w(TAG, "it seems that note meta has been deleted"); - return SYNC_ACTION_UPDATE_REMOTE; - } - - if (!noteInfo.has(NoteColumns.ID)) { - Log.w(TAG, "remote note id seems to be deleted"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - // validate the note id now - if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { - Log.w(TAG, "note id doesn't match"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // there is no local update - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // no update both side - return SYNC_ACTION_NONE; - } else { - // apply remote to local - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // validate gtask id - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // local modification only - return SYNC_ACTION_UPDATE_REMOTE; - } else { - return SYNC_ACTION_UPDATE_CONFLICT; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - - public boolean isWorthSaving() { - return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) - || (getNotes() != null && getNotes().trim().length() > 0); - } - - public void setCompleted(boolean completed) { - this.mCompleted = completed; - } - - public void setNotes(String notes) { - this.mNotes = notes; - } - - public void setPriorSibling(Task priorSibling) { - this.mPriorSibling = priorSibling; - } - - public void setParent(TaskList parent) { - this.mParent = parent; - } - - public boolean getCompleted() { - return this.mCompleted; - } - - public String getNotes() { - return this.mNotes; - } - - public Task getPriorSibling() { - return this.mPriorSibling; - } - - public TaskList getParent() { - return this.mParent; - } - + // Convert the notes data into a JSONObject and assign it to mMetaInfo + mMetaInfo = new JSONObject(metaData.getNotes()); + } catch (JSONException e) { + // Log a warning if the conversion fails + Log.w(TAG, e.toString()); + // Reset mMetaInfo to null in case of an error + mMetaInfo = null; // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error +} // Reset mMetaInfo to null in case of an error +// Reset mMetaInfo to null in case of an error +// Method to determine the sync action based on the data in the cursor +public int getSyncAction(Cursor c) { // Reset mMetaInfo to null in case of an error + try { // Reset mMetaInfo to null in case of an error + JSONObject noteInfo = null; // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + // Check if mMetaInfo is not null and contains the note info + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { // Reset mMetaInfo to null in case of an error + // Retrieve the note info from mMetaInfo + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + // If no note info is found, return SYNC_ACTION_UPDATE_REMOTE + if (noteInfo == null) { // Reset mMetaInfo to null in case of an error + Log.w(TAG, "it seems that note meta has been deleted"); // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_UPDATE_REMOTE; // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + // If no note ID is found in the note info, return SYNC_ACTION_UPDATE_LOCAL + if (!noteInfo.has(NoteColumns.ID)) { + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + // Validate the note ID with the value in the cursor + if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { // Reset mMetaInfo to null in case of an error + Log.w(TAG, "note id doesn't match"); // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_UPDATE_LOCAL; // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + // Check if there are any local updates + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // If no local updates, check if the sync ID matches the last modified timestamp + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // No updates on either side // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_NONE; // Reset mMetaInfo to null in case of an error + } else { // Reset mMetaInfo to null in case of an error + // Apply remote updates to local // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_UPDATE_LOCAL; // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + } else { // Reset mMetaInfo to null in case of an error + // If there are local modifications, // Reset mMetaInfo to null in case of an errorvalidate the gtask ID + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { // Reset mMetaInfo to null in case of an error + Log.e(TAG, "gtask id doesn't match"); // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_ERROR; // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + // Check if the sync ID matches the last modified timestamp for local modification + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // Reset mMetaInfo to null in case of an error + // Local modification only + return SYNC_ACTION_UPDATE_REMOTE; // Reset mMetaInfo to null in case of an error + // Conflict between local and remote modification + return SYNC_ACTION_UPDATE_CONFLICT; // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + } catch (Exception e) { // Reset mMetaInfo to null in case of an error + // Log the exception and return SYNC_ACTION_ERROR + Log.e(TAG, e.toString()); // Reset mMetaInfo to null in case of an error + e.printStackTrace(); // Reset mMetaInfo to null in case of an error + } // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error + return SYNC_ACTION_ERROR; // Reset mMetaInfo to null in case of an error +} // Reset mMetaInfo to null in case of an error +// Getter method to retrieve the parent task list +// Method to check if the task is worth saving based on meta info or task content +public boolean isWorthSaving() { // Reset mMetaInfo to null in case of an error + // If there is meta info or non-empty name or notes, return true + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)// Getter method to retrieve the parent task list + || (getNotes() != null && getNotes().trim().length() > 0);// Getter method to retrieve the parent task list +} // Reset mMetaInfo to null in case of an error + // Reset mMetaInfo to null in case of an error +// Setter method to mark the task as completed +public void setCompleted(boolean completed) { // Reset mMetaInfo to null in case of an error + this.mCompleted = completed;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Setter method to set the notes of the task +public void setNotes(String notes) {// Getter method to retrieve the parent task list + this.mNotes = notes;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Setter method to set the prior sibling task +public void setPriorSibling(Task priorSibling) {// Getter method to retrieve the parent task list + this.mPriorSibling = priorSibling;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Setter method to set the parent task list +public void setParent(TaskList parent) {// Getter method to retrieve the parent task list + this.mParent = parent;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Getter method to retrieve the completed status of the task +public boolean getCompleted() {// Getter method to retrieve the parent task list + return this.mCompleted;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Getter method to retrieve the notes of the task +public String getNotes() {// Getter method to retrieve the parent task list + return this.mNotes;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Getter method to retrieve the prior sibling task +public Task getPriorSibling() {// Getter method to retrieve the parent task list + return this.mPriorSibling;// Getter method to retrieve the parent task list +}// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +// Getter method to retrieve the parent task list +public TaskList getParent() {// Getter method to retrieve the parent task list + return this.mParent;// Getter method to retrieve the parent task list } diff --git a/build.gradle b/build.gradle index ff6e6be..f6627fc 100644 --- a/build.gradle +++ b/build.gradle @@ -2,19 +2,14 @@ buildscript { repositories { jcenter() - google() - mavenCentral() } dependencies { - //classpath 'com.android.tools.build:gradle:2.3.2' - classpath 'com.android.tools.build:gradle:7.4.2' + classpath 'com.android.tools.build:gradle:2.3.2' } } allprojects { repositories { jcenter() - google() - mavenCentral() } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 4a3be83..6a932ea 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-rc-1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip