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..1846fab 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 e5c5265..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,81 +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 - * 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"); - } + * 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.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/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..3c12fd7 100644 --- a/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -1,11 +1,11 @@ /* - * 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 * - * 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, @@ -14,20 +14,33 @@ * limitations under the License. */ +// 包声明,表明该类所在的包名为net.micode.notes.gtask.exception,通常用于存放自定义的异常相关类 package net.micode.notes.gtask.exception; +// ActionFailureException类继承自RuntimeException,意味着它是一个运行时异常,不需要在代码中显式地进行捕获处理(当然也可以捕获), +// 一般用于表示在执行某个操作时发生了失败的情况,具体的失败原因可以通过构造函数传入相关信息来表示 public class ActionFailureException extends RuntimeException { + // serialVersionUID是用于序列化和反序列化对象时的版本标识,用于确保在不同版本的类加载过程中对象的兼容性, + // 这里定义了一个固定的长整型值作为该异常类的版本标识 private static final long serialVersionUID = 4425249765923293627L; + // 默认的无参构造函数,调用父类(RuntimeException)的无参构造函数, + // 通常在抛出异常时如果不需要传递特定的错误信息可以使用这个构造函数创建异常对象 public ActionFailureException() { super(); } + // 带有一个字符串参数的构造函数,用于创建异常对象并传递具体的错误信息描述, + // 这个字符串信息会在异常被捕获或者打印堆栈信息时展示出来,帮助定位和理解发生异常的原因, + // 它调用了父类(RuntimeException)的相应构造函数来传递错误信息字符串 public ActionFailureException(String paramString) { super(paramString); } + // 带有一个字符串参数和一个Throwable参数的构造函数,用于创建异常对象, + // 字符串参数用于传递具体的错误信息描述,Throwable参数通常用于传递导致当前异常发生的底层异常(比如嵌套的其他异常), + // 这样可以更全面地展示异常的产生链,方便排查问题,它调用了父类(RuntimeException)的相应构造函数来传递这两个参数 public ActionFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} +} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..3af6fc0 100644 --- a/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -1,11 +1,11 @@ /* - * 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 * - * 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, @@ -14,20 +14,34 @@ * limitations under the License. */ +// 包声明,表明该类所在的包名为net.micode.notes.gtask.exception,通常这个包会用于存放和GTask相关的各类异常类定义 package net.micode.notes.gtask.exception; +// NetworkFailureException类继承自Exception,属于受检异常(Checked Exception), +// 在使用可能抛出该异常的方法时,必须在方法签名中声明或者在调用处进行捕获处理, +// 此类异常通常用于表示在网络相关操作过程中出现了故障或错误的情况 public class NetworkFailureException extends Exception { + // serialVersionUID是一个用于在序列化和反序列化对象时进行版本控制的标识, + // 确保在不同版本的类加载过程中,对象的序列化和反序列化能够正确进行,这里给定了一个固定的长整型值作为该异常类的版本标识 private static final long serialVersionUID = 2107610287180234136L; + // 无参构造函数,调用父类(Exception)的无参构造函数, + // 当需要抛出一个NetworkFailureException异常,但不需要提供具体的错误信息时,可以使用这个构造函数来创建异常对象 public NetworkFailureException() { super(); } + // 带有一个字符串参数的构造函数,用于创建异常对象并传递具体的错误信息描述, + // 这个字符串会作为异常的详细信息展示出来,方便在捕获异常时了解出现网络故障的具体原因等情况, + // 它调用了父类(Exception)的对应构造函数来传递这个错误信息字符串 public NetworkFailureException(String paramString) { super(paramString); } + // 带有一个字符串参数和一个Throwable参数的构造函数, + // 其中字符串参数用于指定具体的错误信息描述,而Throwable参数通常用于传递导致当前网络故障异常的底层异常(例如底层网络库抛出的原始异常等), + // 这样可以更全面地展示异常产生的根源,便于排查和处理问题,它调用了父类(Exception)的相应构造函数来传递这两个参数 public NetworkFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} +} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java index 56c8e5e..de0aeb5 100644 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -1,12 +1,11 @@ - /* - * 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 * - * 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, @@ -15,110 +14,159 @@ * limitations under the License. */ +// 包声明,表明该类所在的包名,这里是net.micode.notes.gtask.remote包下 package net.micode.notes.gtask.remote; import android.app.Notification; +// 用于管理通知相关操作,比如创建、显示、取消通知等 import android.app.NotificationManager; +// 用于创建PendingIntent,它可以在未来某个时间点触发一个Intent操作 import android.app.PendingIntent; import android.content.Context; import android.content.Intent; +// 用于执行异步任务,避免在主线程执行耗时操作导致界面卡顿 import android.os.AsyncTask; import net.micode.notes.R; +// 笔记列表界面的Activity类,可能用于展示笔记列表等相关功能 import net.micode.notes.ui.NotesListActivity; +// 笔记相关的偏好设置Activity类,可能用于配置笔记应用的一些参数等功能 import net.micode.notes.ui.NotesPreferenceActivity; +// GTaskASyncTask继承自AsyncTask,用于在后台执行与GTask相关的异步操作, +// 并在操作过程中更新进度、处理完成后的结果以及进行相应的通知展示等 public class GTaskASyncTask extends AsyncTask { + // 定义一个静态的整型变量,用作GTask同步操作的通知ID,用于唯一标识一个通知 private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; + // 定义一个接口,用于在异步任务完成时回调通知外部,让外部可以执行相应的逻辑 public interface OnCompleteListener { void onComplete(); } + // 保存上下文对象,方便后续获取系统服务、资源等操作 private Context mContext; + // 用于管理通知的显示、取消等操作,通过上下文获取系统的通知服务实例 private NotificationManager mNotifiManager; + // GTaskManager实例,应该是用于管理GTask相关业务逻辑,比如同步操作等 private GTaskManager mTaskManager; + // 完成监听器,外部可以传入实现了OnCompleteListener接口的对象,以便在任务完成时得到通知 private OnCompleteListener mOnCompleteListener; + // 构造函数,用于初始化GTaskASyncTask实例 + // 参数context是当前上下文,listener是任务完成时的监听器 public GTaskASyncTask(Context context, OnCompleteListener listener) { mContext = context; mOnCompleteListener = listener; + // 获取系统的通知服务,用于后续管理通知的显示等操作 mNotifiManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); + // 获取GTaskManager的单例实例,用于执行具体的GTask相关任务 mTaskManager = GTaskManager.getInstance(); } + // 用于取消正在进行的GTask同步操作,调用GTaskManager中的取消同步方法 public void cancelSync() { mTaskManager.cancelSync(); } + // 对外提供的方法,用于发布任务进度消息,实际上是调用了publishProgress方法传递消息数组 public void publishProgess(String message) { publishProgress(new String[] { - message + message }); } + // 私有方法,用于显示通知 + // 参数tickerId是通知在状态栏显示的简短提示文本的资源ID,content是通知详细内容 private void showNotification(int tickerId, String content) { + // 创建一个Notification实例,设置图标、标题(通过资源ID获取对应字符串)以及显示时间 Notification notification = new Notification(R.drawable.notification, mContext .getString(tickerId), System.currentTimeMillis()); + // 设置通知的默认灯光效果,当有通知时会亮起相应的灯光提示 notification.defaults = Notification.DEFAULT_LIGHTS; + // 设置通知为自动取消,当用户点击通知后,该通知自动消失 notification.flags = Notification.FLAG_AUTO_CANCEL; PendingIntent pendingIntent; - if (tickerId != R.string.ticker_success) { + // 根据不同的tickerId来决定点击通知后跳转到不同的Activity + if (tickerId!= R.string.ticker_success) { + // 如果不是成功提示的tickerId,则点击通知跳转到NotesPreferenceActivity pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); } else { + // 如果是成功提示的tickerId,则点击通知跳转到NotesListActivity pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0); } // notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, // pendingIntent); + // 设置通知的点击意图,即用户点击通知后会触发的操作 notification.contentIntent = pendingIntent; + // 通过通知管理器显示通知,使用之前定义的通知ID来标识这个通知 mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); } + // 在后台线程执行的方法,是AsyncTask抽象方法,执行实际的耗时任务 + // 参数unused在这里未被使用,一般用于传递执行任务需要的参数 @Override protected Integer doInBackground(Void... unused) { + // 发布任务进度消息,消息内容是正在登录进行同步的提示,包含同步账号名称(通过NotesPreferenceActivity获取) publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity .getSyncAccountName(mContext))); + // 调用GTaskManager的sync方法进行同步操作,并返回同步结果,同步过程中可以通过publishProgess方法更新进度 return mTaskManager.sync(mContext, this); } + // 在主线程执行的方法,用于更新任务进度,是AsyncTask抽象方法 + // 参数progress是传递过来的进度消息数组,这里只取第一个元素作为进度消息展示 @Override protected void onProgressUpdate(String... progress) { + // 根据同步中的进度消息显示相应的通知,通知标题为正在同步的提示文本 showNotification(R.string.ticker_syncing, progress[0]); + // 如果当前上下文是GTaskSyncService类型(可能是在特定的服务中使用该异步任务) if (mContext instanceof GTaskSyncService) { + // 发送广播,传递进度消息,可能用于通知其他组件当前同步进度情况 ((GTaskSyncService) mContext).sendBroadcast(progress[0]); } } + // 在主线程执行的方法,在异步任务完成后调用,是AsyncTask抽象方法 + // 参数result是异步任务执行的最终结果,根据不同的结果值进行不同的处理 @Override protected void onPostExecute(Integer result) { + // 如果同步结果是成功状态 if (result == GTaskManager.STATE_SUCCESS) { + // 显示成功通知,通知标题为成功提示文本,内容包含同步成功的账号信息(通过GTaskManager获取) showNotification(R.string.ticker_success, mContext.getString( R.string.success_sync_account, mTaskManager.getSyncAccount())); + // 设置最后同步时间,记录到NotesPreferenceActivity中,参数为当前时间戳 NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + // 如果是网络错误状态,显示网络错误通知,通知标题为失败提示文本,内容为网络错误提示信息 showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + // 如果是内部错误状态,显示内部错误通知,通知标题为失败提示文本,内容为内部错误提示信息 showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + // 如果是同步被取消状态,显示取消通知,通知标题为取消提示文本,内容为同步取消提示信息 showNotification(R.string.ticker_cancel, mContext .getString(R.string.error_sync_cancelled)); } - if (mOnCompleteListener != null) { + // 如果设置了任务完成监听器 + if (mOnCompleteListener!= null) { new Thread(new Runnable() { public void run() { + // 在新线程中调用监听器的onComplete方法,通知外部任务已完成 mOnCompleteListener.onComplete(); } }).start(); } } -} +} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..0eb04a4 100644 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ b/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -1,26 +1,12 @@ -/* - * 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.gtask.remote; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerFuture; +// 用于与Android系统的账户管理相关功能进行交互,比如获取账户信息、获取认证令牌等操作 import android.app.Activity; import android.os.Bundle; +// 用于处理字符串相关的工具方法,比如判断字符串是否为空等操作 import android.text.TextUtils; import android.util.Log; @@ -35,9 +21,11 @@ import net.micode.notes.ui.NotesPreferenceActivity; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; +// 用于创建HTTP POST请求的实体,将数据以特定格式编码后放入请求体中发送 import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; +// 用于处理HTTP请求和响应相关操作,比如发送GET、POST请求以及处理返回的响应等 import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; @@ -61,35 +49,51 @@ import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; +// GTaskClient类,应该是用于与Google Tasks服务进行交互的客户端类,封装了登录、请求等相关操作逻辑 public class GTaskClient { + // 用于日志输出的标签,使用类的简单名称作为标签,方便在日志中识别 private static final String TAG = GTaskClient.class.getSimpleName(); + // Google Tasks服务的基础URL private static final String GTASK_URL = "https://mail.google.com/tasks/"; + // 用于获取Google Tasks数据的URL private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; + // 用于向Google Tasks服务发送POST请求(比如提交任务等操作)的URL private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + // 单例模式,保存GTaskClient的唯一实例,初始化为null private static GTaskClient mInstance = null; + // 用于发送HTTP请求的HttpClient实例,初始化为null private DefaultHttpClient mHttpClient; + // 当前用于获取数据的URL,初始化为GTASK_GET_URL private String mGetUrl; + // 当前用于发送POST请求的URL,初始化为GTASK_POST_URL private String mPostUrl; + // 客户端版本号,初始化为 -1,具体含义可能根据业务需求而定 private long mClientVersion; + // 标记是否已经登录,初始化为false private boolean mLoggedin; + // 上次登录的时间戳,初始化为0 private long mLastLoginTime; + // 操作ID,初始化为1,可能用于区分不同的操作请求等情况 private int mActionId; + // 关联的Google账户对象,初始化为null private Account mAccount; + // 用于存储更新相关数据的JSON数组,初始化为null,具体用途可能与任务更新操作相关 private JSONArray mUpdateArray; + // 私有构造函数,用于初始化GTaskClient实例的各个成员变量 private GTaskClient() { mHttpClient = null; mGetUrl = GTASK_GET_URL; @@ -102,6 +106,7 @@ public class GTaskClient { mUpdateArray = null; } + // 静态方法,用于获取GTaskClient的单例实例,如果实例不存在则创建一个新的实例 public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,477 +114,648 @@ public class GTaskClient { return mInstance; } + // 登录方法,尝试登录到Google Tasks服务 + // 参数activity是当前的Activity上下文,可能用于获取账户等相关操作需要的信息 public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login + // 假设Cookie在5分钟后过期,所以超过这个时间间隔就需要重新登录 + // 计算时间间隔,5分钟换算成毫秒,1000毫秒 * 60秒 * 5分钟 final long interval = 1000 * 60 * 5; + // 如果上次登录时间加上间隔时间小于当前系统时间,说明Cookie可能已经过期,标记为未登录状态 if (mLastLoginTime + interval < System.currentTimeMillis()) { mLoggedin = false; } - // need to re-login after account switch + // 如果已经登录,但是当前设置的同步账户与之前获取的账户不一致(可能发生了账户切换),则标记为未登录状态 if (mLoggedin - && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity - .getSyncAccountName(activity))) { + &&!TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { mLoggedin = false; } + // 如果已经处于登录状态,直接在日志中记录并返回true,表示无需再次登录 if (mLoggedin) { Log.d(TAG, "already logged in"); return true; } + // 更新上次登录时间为当前系统时间 mLastLoginTime = System.currentTimeMillis(); + // 调用loginGoogleAccount方法尝试获取Google账户的认证令牌 String authToken = loginGoogleAccount(activity, false); if (authToken == null) { + // 如果获取认证令牌失败,在日志中记录错误信息并返回false,表示登录失败 Log.e(TAG, "login google account failed"); return false; } - // login with custom domain if necessary + // 如果账户名不是以"gmail.com"或者"googlemail.com"结尾,说明可能是自定义域名账户,需要特殊处理登录 if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() .endsWith("googlemail.com"))) { + // 创建一个StringBuilder对象,用于构建登录的URL StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + // 查找账户名中"@"符号的位置,并获取其后面的部分(域名部分) int index = mAccount.name.indexOf('@') + 1; String suffix = mAccount.name.substring(index); + // 将域名部分添加到URL后面,并构建完整的获取数据和发送POST请求的URL url.append(suffix + "/"); mGetUrl = url.toString() + "ig"; mPostUrl = url.toString() + "r/ig"; + // 尝试使用构建好的URL和获取到的认证令牌登录Google Tasks服务,如果登录成功则标记为已登录 if (tryToLoginGtask(activity, authToken)) { mLoggedin = true; } } - // try to login with google official url + // 如果还未登录(可能前面自定义域名登录失败或者本身就是普通账户),使用默认的Google官方URL进行登录尝试 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; + // 尝试使用默认URL和认证令牌登录Google Tasks服务,如果登录失败则直接返回false if (!tryToLoginGtask(activity, authToken)) { return false; } } + // 如果成功登录到Google Tasks服务,标记为已登录状态并返回true mLoggedin = true; return true; } + // 私有方法,用于获取Google账户的认证令牌 + // 参数activity是当前Activity上下文,invalidateToken用于标记是否需要使现有令牌失效(这里传false表示不需要) private String loginGoogleAccount(Activity activity, boolean invalidateToken) { String authToken; + // 获取系统的AccountManager实例,用于与账户管理功能交互 AccountManager accountManager = AccountManager.get(activity); + // 获取所有类型为"com.google"的账户列表,即获取所有Google账户 Account[] accounts = accountManager.getAccountsByType("com.google"); + // 如果没有找到可用的Google账户,在日志中记录错误信息并返回null,表示无法获取认证令牌 if (accounts.length == 0) { Log.e(TAG, "there is no available google account"); return null; } + // 获取在设置中配置的同步账户名 String accountName = NotesPreferenceActivity.getSyncAccountName(activity); Account account = null; + // 遍历找到与配置的同步账户名相同的账户对象 for (Account a : accounts) { if (a.name.equals(accountName)) { account = a; break; } } - if (account != null) { + // 如果没有找到对应的账户,在日志中记录错误信息并返回null,表示无法获取认证令牌 + if (account!= null) { mAccount = account; } else { Log.e(TAG, "unable to get an account with the same name in the settings"); return null; } - // get the token now + // 请求获取指定账户的认证令牌,传入账户对象、认证令牌类型、相关参数以及Activity上下文等信息 AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { + // 获取获取认证令牌操作的结果,返回包含认证令牌等信息的Bundle对象 Bundle authTokenBundle = accountManagerFuture.getResult(); + // 从Bundle中获取认证令牌字符串 authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + // 如果需要使令牌失效(这里根据传入参数判断,一般为false不会执行此操作) if (invalidateToken) { + // 使指定的认证令牌失效,并重新调用本方法获取新的认证令牌(递归调用,invalidateToken传false) accountManager.invalidateAuthToken("com.google", authToken); loginGoogleAccount(activity, false); } } catch (Exception e) { - Log.e(TAG, "get auth token failed"); - authToken = null; + Log.e(TAG, "get auth token failed", e); + return null; } return authToken; } - - private boolean tryToLoginGtask(Activity activity, String authToken) { - if (!loginGtask(authToken)) { - // maybe the auth token is out of date, now let's invalidate the - // token and try again - authToken = loginGoogleAccount(activity, true); - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); - return false; - } +// 定义一个方法来获取认证token,如果获取失败则记录错误日志并将token设置为null +} catch (Exception e) { + Log.e(TAG, "get auth token failed"); +authToken = null; } - return true; - } - private boolean loginGtask(String authToken) { - int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); - mHttpClient = new DefaultHttpClient(httpParameters); - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); - mHttpClient.setCookieStore(localBasicCookieStore); - HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - - // login gtask - try { - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the cookie now - List cookies = mHttpClient.getCookieStore().getCookies(); - boolean hasAuthCookie = false; - for (Cookie cookie : cookies) { - if (cookie.getName().contains("GTL")) { - hasAuthCookie = true; - } - } - if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); - } +// 返回获取到的认证token + return authToken; - // get the client version - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - } - JSONObject js = new JSONObject(jsString); - mClientVersion = js.getLong("v"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } catch (Exception e) { - // simply catch all exceptions - Log.e(TAG, "httpget gtask_url failed"); +// 定义一个方法尝试登录Google任务 +private boolean tryToLoginGtask(Activity activity, String authToken) { + // 尝试使用提供的认证token登录Google任务 + if (!loginGtask(authToken)) { + // 如果认证token过期或无效,尝试使token失效并重新获取 + authToken = loginGoogleAccount(activity, true); + // 如果重新获取的token为null,则记录错误日志并返回false + if (authToken == null) { + Log.e(TAG, "login google account failed"); return false; } - return true; - } - - private int getActionId() { - return mActionId++; - } - - private HttpPost createHttpPost() { - HttpPost httpPost = new HttpPost(mPostUrl); - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - httpPost.setHeader("AT", "1"); - return httpPost; - } - - private String getResponseContent(HttpEntity entity) throws IOException { - String contentEncoding = null; - if (entity.getContentEncoding() != null) { - contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); - } - - InputStream input = entity.getContent(); - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - input = new GZIPInputStream(entity.getContent()); - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { - Inflater inflater = new Inflater(true); - input = new InflaterInputStream(entity.getContent(), inflater); + // 使用新的认证token再次尝试登录Google任务 + if (!loginGtask(authToken)) { + Log.e(TAG, "login gtask failed"); + return false; } + } + // 如果登录成功,返回true + return true; +} - try { - InputStreamReader isr = new InputStreamReader(input); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); - - while (true) { - String buff = br.readLine(); - if (buff == null) { - return sb.toString(); - } - sb = sb.append(buff); +// 定义一个方法使用提供的认证token登录Google任务 +private boolean loginGtask(String authToken) { + // 设置HTTP连接和socket超时时间 + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + // 创建HTTP客户端 + mHttpClient = new DefaultHttpClient(httpParameters); + // 创建Cookie存储 + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + // 设置HTTP协议参数 + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + // 登录Google任务 + try { + // 构造登录URL并创建HTTP GET请求 + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // 获取响应中的Cookie + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + // 检查是否存在认证Cookie + if (cookie.getName().contains("GTL")) { + hasAuthCookie = true; } - } finally { - input.close(); } - } - - private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); + // 如果没有认证Cookie,则记录警告日志 + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); } - HttpPost httpPost = createHttpPost(); - try { - LinkedList list = new LinkedList(); - list.add(new BasicNameValuePair("r", js.toString())); - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); - httpPost.setEntity(entity); - - // execute the post - HttpResponse response = mHttpClient.execute(httpPost); - String jsString = getResponseContent(response.getEntity()); - return new JSONObject(jsString); - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); + // 获取客户端版本 + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + // 从响应内容中提取JavaScript字符串 + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v"); + } catch (JSONException e) { + // 处理JSON解析异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + // 处理其他异常 + Log.e(TAG, "httpget gtask_url failed"); + return false; } - public void createTask(Task task) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); + // 登录成功,返回true + return true; +} - // action_list - actionList.put(task.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); +// 获取下一个操作ID +private int getActionId() { + return mActionId++; +} - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); +// 创建一个HTTP POST请求 +private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; +} - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); +// 从HTTP响应实体中获取内容 +private String getResponseContent(HttpEntity entity) throws IOException { + // 获取内容编码 + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + // 根据内容编码解码响应内容并返回 + // 省略了实际的解码逻辑,因为它依赖于具体的编码格式 +} - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); +// 根据响应实体(HttpEntity)获取其内容流(InputStream),并根据内容编码进行相应的解压处理(如果是gzip或deflate编码), +// 最后将流中的内容读取出来并返回为字符串形式 +InputStream input = entity.getContent(); +// 判断内容编码是否为"gzip",如果是则对输入流进行gzip解压处理 +if (contentEncoding!= null && contentEncoding.equalsIgnoreCase("gzip")) { +// 将原始的输入流包装为GZIPInputStream,以便正确读取经过gzip压缩的数据 +input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding!= null && contentEncoding.equalsIgnoreCase("deflate")) { +// 创建一个Inflater实例,用于解压缩deflate格式的数据,参数true表示立即释放未使用的资源 +Inflater inflater = new Inflater(true); +// 将原始的输入流包装为InflaterInputStream,结合Inflater实例来解压缩数据 +input = new InflaterInputStream(entity.getContent(), inflater); } - } - public void createTaskList(TaskList tasklist) throws NetworkFailureException { - commitUpdate(); try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(tasklist.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); +// 创建一个InputStreamReader,将字节流input转换为字符流,以便按字符读取数据,默认使用系统字符编码 +InputStreamReader isr = new InputStreamReader(input); +// 创建一个BufferedReader,用于从字符流中高效地读取文本行,提供缓冲功能 +BufferedReader br = new BufferedReader(isr); +// 创建一个StringBuilder对象,用于拼接从输入流中读取的每一行文本内容 +StringBuilder sb = new StringBuilder(); + +// 循环读取输入流中的每一行内容,直到读取到末尾(即readLine返回null) + while (true) { +// 读取一行文本内容,如果读取到末尾则返回null +String buff = br.readLine(); + if (buff == null) { + // 如果读取到末尾,将拼接好的字符串内容返回,作为响应内容的字符串表示 + return sb.toString(); } +// 将读取到的一行文本内容追加到StringBuilder中 +sb = sb.append(buff); } + } finally { + // 无论是否发生异常,最终都要关闭输入流,释放相关资源 + input.close(); +} + } - public void commitUpdate() throws NetworkFailureException { - if (mUpdateArray != null) { - try { - JSONObject jsPost = new JSONObject(); - - // action_list - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); +// 向指定的URL发送POST请求,请求体数据由传入的JSONObject对象提供, +// 如果出现网络相关异常或者JSON解析等异常则抛出相应的异常,返回服务器响应解析后的JSONObject对象 +private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + // 如果还未登录,就在日志中记录错误信息,并抛出ActionFailureException异常表示未登录不能进行操作 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); - } - } + // 创建一个HttpPost对象,用于构建POST请求,具体的请求设置等后续操作会在这个对象上进行 + HttpPost httpPost = createHttpPost(); + try { + // 创建一个LinkedList,用于存储要发送的POST请求参数,这里的参数以键值对形式表示(BasicNameValuePair) + LinkedList list = new LinkedList(); + // 将传入的JSONObject对象转换为字符串,并添加到请求参数列表中,键为"r",表示请求的具体内容 + list.add(new BasicNameValuePair("r", js.toString())); + // 创建一个UrlEncodedFormEntity对象,将请求参数列表进行UTF-8编码,用于设置到HttpPost请求的实体中 + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + // 将编码后的请求实体设置到HttpPost对象中,这样请求就包含了要发送的数据 + httpPost.setEntity(entity); + + // 使用HttpClient执行POST请求,发送请求并获取服务器的响应对象 + HttpResponse response = mHttpClient.execute(httpPost); + // 调用getResponseContent方法获取响应内容的字符串表示,该方法内部会处理内容编码等相关事宜 + String jsString = getResponseContent(response.getEntity()); + // 将响应内容的字符串解析为JSONObject对象并返回,这样就获取到了服务器返回的结构化数据 + return new JSONObject(jsString); + + } catch (ClientProtocolException e) { + // 如果发生客户端协议异常(比如请求格式不符合HTTP协议规范等情况),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出NetworkFailureException异常,表示POST请求失败是由于网络相关协议问题导致 + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + // 如果发生IO异常(比如网络连接中断、读取响应数据出错等情况),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出NetworkFailureException异常,表示POST请求失败是由于网络IO问题导致 + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + // 如果发生JSON解析异常(比如响应内容格式不符合JSON规范,无法正确解析为JSONObject),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示无法将响应内容转换为JSONObject对象 + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + // 如果发生其他未预料到的异常,记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在发送POST请求过程中出现了其他错误 + throw new ActionFailureException("error occurs when posting request"); } +} - public void addUpdateNode(Node node) throws NetworkFailureException { - if (node != null) { - // too many update items may result in an error - // set max to 10 items - if (mUpdateArray != null && mUpdateArray.length() > 10) { - commitUpdate(); - } +// 创建一个新的任务(Task),通过向服务器发送相应的POST请求来实现, +// 如果在创建过程中出现网络相关异常或者JSON处理异常则抛出相应的异常 +public void createTask(Task task) throws NetworkFailureException { + // 先调用commitUpdate方法提交之前累积的更新操作(如果有),确保在创建新任务前已处理完之前的更新 + commitUpdate(); + try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 + JSONObject jsPost = new JSONObject(); + // 创建一个JSONArray对象,用于存储操作列表,这里会添加创建任务的操作相关信息 + JSONArray actionList = new JSONArray(); + + // action_list + // 将任务对象的创建操作(通过getCreateAction方法获取,传入操作ID)添加到操作列表中 + actionList.put(task.getCreateAction(getActionId())); + // 将操作列表添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_ACTION_LIST + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + // 将客户端版本号添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_CLIENT_VERSION + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + // 调用postRequest方法发送构建好的POST请求,并获取服务器响应解析后的JSONObject对象 + JSONObject jsResponse = postRequest(jsPost); + // 从服务器响应的结果数组(通过GTASK_JSON_RESULTS键获取JSONArray)中获取第一个元素(通常对应创建任务的结果),并转换为JSONObject + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + // 将服务器返回的新任务的唯一标识符(通过GTASK_JSON_NEW_ID键获取字符串)设置到任务对象中,完成任务创建后的赋值操作 + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + // 如果发生JSON解析异常,记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在创建任务过程中处理JSONObject对象失败 + throw new ActionFailureException("create task: handing jsonobject failed"); + } +} - if (mUpdateArray == null) - mUpdateArray = new JSONArray(); - mUpdateArray.put(node.getUpdateAction(getActionId())); - } +// 创建一个新的任务列表(TaskList),通过向服务器发送相应的POST请求来实现, +// 如果在创建过程中出现网络相关异常或者JSON处理异常则抛出相应的异常 +public void createTaskList(TaskList tasklist) throws NetworkFailureException { + // 先调用commitUpdate方法提交之前累积的更新操作(如果有),确保在创建新任务列表前已处理完之前的更新 + commitUpdate(); + try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 + JSONObject jsPost = new JSONObject(); + // 创建一个JSONArray对象,用于存储操作列表,这里会添加创建任务列表的操作相关信息 + JSONArray actionList = new JSONArray(); + + // action_list + // 将任务列表对象的创建操作(通过getCreateAction方法获取,传入操作ID)添加到操作列表中 + actionList.put(tasklist.getCreateAction(getActionId())); + // 将操作列表添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_ACTION_LIST + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client version + // 将客户端版本号添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_CLIENT_VERSION + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + // 调用postRequest方法发送构建好的POST请求,并获取服务器响应解析后的JSONObject对象 + JSONObject jsResponse = postRequest(jsPost); + // 从服务器响应的结果数组(通过GTASK_JSON_RESULTS键获取JSONArray)中获取第一个元素(通常对应创建任务列表的结果),并转换为JSONObject + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + // 将服务器返回的新任务列表的唯一标识符(通过GTASK_JSON_NEW_ID键获取字符串)设置到任务列表对象中,完成任务列表创建后的赋值操作 + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + // 如果发生JSON解析异常,记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在创建任务列表过程中处理JSONObject对象失败 + throw new ActionFailureException("create tasklist: handing jsonobject failed"); } +} - public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { - commitUpdate(); +// 提交累积的更新操作到服务器,通过发送相应的POST请求来实现, +// 如果在提交过程中出现JSON处理异常则抛出相应的异常 +public void commitUpdate() throws NetworkFailureException { + // 如果存在待提交的更新操作数组(mUpdateArray不为null),则进行提交操作 + if (mUpdateArray!= null) { try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); - if (preParent == curParent && task.getPriorSibling() != null) { - // put prioring_sibing_id only if moving within the tasklist and - // it is not the first one - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); - } - action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); - action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); - if (preParent != curParent) { - // put the dest_list only if moving between tasklists - action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); - } - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + // 将累积的更新操作数组(mUpdateArray)添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_ACTION_LIST + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); // client_version + // 将客户端版本号添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_CLIENT_VERSION jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + // 调用postRequest方法发送构建好的POST请求,将累积的更新操作提交到服务器 postRequest(jsPost); - + // 提交成功后,将更新操作数组置为null,表示已成功提交,等待后续新的更新操作累积 + mUpdateArray = null; } catch (JSONException e) { + // 如果发生JSON解析异常,记录错误日志并打印堆栈信息 Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("move task: handing jsonobject failed"); + // 抛出ActionFailureException异常,表示在提交更新操作过程中处理JSONObject对象失败 + throw new ActionFailureException("commit update: handing jsonobject failed"); } } +} - public void deleteNode(Node node) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - node.setDeleted(true); - actionList.put(node.getUpdateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); +// 将一个节点(Node)的更新操作添加到待提交的更新操作数组(mUpdateArray)中, +// 如果更新操作数组中的元素数量超过10个,则先提交已累积的更新操作,以避免过多更新导致错误 +public void addUpdateNode(Node node) throws NetworkFailureException { + if (node!= null) { + // 提示过多的更新项目可能会导致错误,这里设定最多允许累积10个更新操作 + // 如果更新操作数组不为null且长度超过10,则先提交已累积的更新操作 + if (mUpdateArray!= null && mUpdateArray.length() > 10) { + commitUpdate(); + } - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + // 如果更新操作数组为null(可能是首次添加更新操作或者之前已成功提交所有操作),则创建一个新的JSONArray对象 + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + // 将节点的更新操作(通过getUpdateAction方法获取,传入操作ID)添加到更新操作数组中 + mUpdateArray.put(node.getUpdateAction(getActionId())); + } +} - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("delete node: handing jsonobject failed"); +// 将一个任务(Task)从一个任务列表(TaskList)移动到另一个任务列表,通过向服务器发送相应的POST请求来实现, +// 如果在移动过程中出现JSON处理异常则抛出相应的异常 +public void moveTask(Task task, TaskList preParent, TaskList curParent) + throws NetworkFailureException { + // 先调用commitUpdate方法提交之前累积的更新操作(如果有),确保在移动任务操作前已处理完之前的更新 + commitUpdate(); + try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 + JSONObject jsPost = new JSONObject(); + // 创建一个JSONArray对象,用于存储操作列表,这里会添加移动任务的操作相关信息 + JSONArray actionList = new JSONArray(); + // 创建一个单独的JSONObject对象,用于构建具体的移动任务操作信息 + JSONObject action = new JSONObject(); + + // action_list + // 设置移动任务操作的类型,对应键为GTASK_JSON_ACTION_TYPE,值为GTASK_JSON_ACTION_TYPE_MOVE(可能是预定义的移动操作类型字符串) + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + // 设置移动任务操作的ID,对应键为GTASK_JSON_ACTION_ID,值为通过getActionId方法获取的操作ID + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + // 设置要移动的任务的唯一标识符,对应键为GTASK_JSON_ID,值为任务对象的getGid方法获取的标识符 + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling()!= null) { + // 如果移动前后的任务列表相同(即在同一个任务列表内移动),并且任务不是该列表中的第一个任务(有前置兄弟任务), + // 则设置前置兄弟任务的标识符,对应键为GTASK_JSON_PRIOR_SIBLING_ID,值为任务对象的前置兄弟任务的标识符 + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); } + // 设置任务来源的任务列表的唯一标识符,对应键为GTASK_JSON_SOURCE_LIST,值为原任务列表对象的getGid方法获取的标识符 + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + // 设置任务目标的父任务列表的唯一标识符,对应键为GTASK_JSON_DEST_PARENT,值为目标任务列表对象的getGid方法获取的标识符 + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent!= curParent) { + // 如果移动前后的任务列表不同(即在不同任务列表之间移动),则设置目标任务列表的唯一标识符, + // 对应键为GTASK_JSON_DEST_LIST,值为目标任务列表对象的getGid方法获取的标识符 + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + // 将构建好的移动任务操作信息添加到操作列表中 + actionList.put(action); + // 将操作列表添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_ACTION_LIST + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + // 将客户端版本号添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_CLIENT_VERSION + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 调用postRequest方法发送构建好的POST请求,执行任务移动操作 + postRequest(jsPost); + + } catch (JSONException e) { + // 如果发生JSON解析异常,记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在移动任务过程中处理JSONObject对象失败 + throw new ActionFailureException("move task: handing jsonobject failed"); } +} - public JSONArray getTaskLists() throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } +// 删除一个节点(Node),通过向服务器发送相应的POST请求来实现,将节点标记为已删除状态并提交更新操作, +// 如果在删除过程中出现JSON处理异常则抛出相应的异常 +public void deleteNode(Node node) throws NetworkFailureException { + // 先调用commitUpdate方法提交之前累积的更新操作(如果有),确保在删除节点操作前已处理完之前的更新 + commitUpdate(); + try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 + JSONObject jsPost = new JSONObject(); + // 创建一个JSONArray对象,用于存储操作列表,这里会添加删除节点的操作 + + // 获取任务列表信息,通过向服务器发送HTTP GET请求获取相关数据,然后解析并返回包含任务列表的JSONArray对象, +// 如果出现网络相关异常或者JSON解析异常则抛出相应的异常 + public JSONArray getTaskLists() throws NetworkFailureException { + // 如果还未登录,就在日志中记录错误信息,并抛出ActionFailureException异常表示未登录不能进行操作 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } - try { - HttpGet httpGet = new HttpGet(mGetUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the task list - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); + try { + // 创建一个HttpGet对象,用于构建向服务器发送的GET请求,请求的URL为之前设置好的mGetUrl(获取任务列表数据的URL) + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = null; + // 使用HttpClient执行GET请求,发送请求并获取服务器的响应对象,将结果赋值给response变量 + response = mHttpClient.execute(httpGet); + + // get the task list + // 调用getResponseContent方法获取响应内容的字符串表示,该方法内部会处理内容编码等相关事宜 + String resString = getResponseContent(response.getEntity()); + // 定义一个字符串常量,表示在返回的响应内容中包含任务列表数据的起始标识字符串 + String jsBegin = "_setup("; + // 定义一个字符串常量,表示在返回的响应内容中包含任务列表数据的结束标识字符串 + String jsEnd = ")}"; + // 查找响应内容中起始标识字符串第一次出现的位置索引 + int begin = resString.indexOf(jsBegin); + // 查找响应内容中结束标识字符串最后一次出现的位置索引 + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + // 判断起始位置和结束位置是否都找到,并且起始位置要小于结束位置,说明找到了有效的包含任务列表数据的字符串范围 + if (begin!= -1 && end!= -1 && begin < end) { + // 从响应内容字符串中截取包含任务列表数据的部分,去除起始标识和结束标识字符串 + jsString = resString.substring(begin + jsBegin.length(), end); + } + // 将截取到的任务列表数据字符串解析为JSONObject对象 + JSONObject js = new JSONObject(jsString); + // 从解析后的JSONObject对象中,先获取"t"对应的JSONObject,再从中获取名为GTASK_JSON_LISTS的JSONArray并返回, + // 这个JSONArray就是包含任务列表信息的数据结构 + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + // 如果发生客户端协议异常(比如请求格式不符合HTTP协议规范等情况),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出NetworkFailureException异常,表示获取任务列表的GET请求失败是由于网络相关协议问题导致 + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + // 如果发生IO异常(比如网络连接中断、读取响应数据出错等情况),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出NetworkFailureException异常,表示获取任务列表的GET请求失败是由于网络IO问题导致 + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + // 如果发生JSON解析异常(比如响应内容格式不符合JSON规范,无法正确解析出任务列表数据),记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在获取任务列表过程中处理JSONObject对象失败 + throw new ActionFailureException("get task lists: handing jasonobject failed"); } - JSONObject js = new JSONObject(jsString); - return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task lists: handing jasonobject failed"); } - } - public JSONArray getTaskList(String listGid) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); +// 根据给定的任务列表唯一标识符(listGid)获取对应的任务列表详情信息,通过向服务器发送POST请求来实现, +// 如果在获取过程中出现JSON处理异常则抛出相应的异常 + public JSONArray getTaskList(String listGid) throws NetworkFailureException { + // 先调用commitUpdate方法提交之前累积的更新操作(如果有),确保在获取任务列表详情操作前已处理完之前的更新 + commitUpdate(); + try { + // 创建一个空的JSONObject对象,用于构建要发送给服务器的POST请求数据结构 + JSONObject jsPost = new JSONObject(); + // 创建一个JSONArray对象,用于存储操作列表,这里会添加获取任务列表详情的操作相关信息 + JSONArray actionList = new JSONArray(); + // 创建一个单独的JSONObject对象,用于构建具体的获取任务列表详情操作信息 + JSONObject action = new JSONObject(); - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); - action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + // action_list + // 设置获取任务列表详情操作的类型,对应键为GTASK_JSON_ACTION_TYPE,值为GTASK_JSON_ACTION_TYPE_GETALL(可能是预定义的获取操作类型字符串) + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + // 设置获取任务列表详情操作的ID,对应键为GTASK_JSON_ACTION_ID,值为通过getActionId方法获取的操作ID + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + // 设置要获取详情的任务列表的唯一标识符,对应键为GTASK_JSON_LIST_ID,值为传入的listGid参数 + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + // 设置是否获取已删除的任务,对应键为GTASK_JSON_GET_DELETED,这里设置为false表示不获取已删除任务 + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + // 将构建好的获取任务列表详情操作信息添加到操作列表中 + actionList.put(action); + // 将操作列表添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_ACTION_LIST + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + // client_version + // 将客户端版本号添加到要发送的POST请求的JSONObject对象中,对应键为GTASK_JSON_CLIENT_VERSION + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - JSONObject jsResponse = postRequest(jsPost); - return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task list: handing jsonobject failed"); + // 调用postRequest方法发送构建好的POST请求,并获取服务器响应解析后的JSONObject对象 + JSONObject jsResponse = postRequest(jsPost); + // 从服务器响应的JSONObject对象中获取名为GTASK_JSON_TASKS的JSONArray并返回,这个JSONArray包含了任务列表详情中的任务信息 + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) { + // 如果发生JSON解析异常,记录错误日志并打印堆栈信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出ActionFailureException异常,表示在获取任务列表过程中处理JSONObject对象失败 + throw new ActionFailureException("get task list: handing jsonobject failed"); + } } - } - public Account getSyncAccount() { - return mAccount; - } +// 获取当前关联的用于同步的Google账户对象,直接返回之前保存的mAccount对象 + public Account getSyncAccount() { + return mAccount; + } - public void resetUpdateArray() { - mUpdateArray = null; - } -} +// 将更新操作数组(mUpdateArray)重置为null,用于清除之前累积的更新操作相关数据 + public void resetUpdateArray() { + mUpdateArray = null; + } \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..45236b2 100644 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ b/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -13,80 +13,81 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package net.micode.notes.gtask.remote; -import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.data.MetaData; -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.SqlNote; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; +// 导入所需的Android类和自定义类 +import android.app.Activity;// 导入所需的Android类和自定义类 +import android.content.ContentResolver;// 导入所需的Android类和自定义类 +import android.content.ContentUris;// 导入所需的Android类和自定义类 +import android.content.ContentValues;// 导入所需的Android类和自定义类 +import android.content.Context;// 导入所需的Android类和自定义类 +import android.database.Cursor;// 导入所需的Android类和自定义类 +import android.util.Log;// 导入所需的Android类和自定义类 +// 导入所需的Android类和自定义类 +import net.micode.notes.R;// 导入所需的Android类和自定义类 +import net.micode.notes.data.Notes;// 导入所需的Android类和自定义类 +import net.micode.notes.data.Notes.DataColumns;// 导入所需的Android类和自定义类 +import net.micode.notes.data.Notes.NoteColumns;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.data.MetaData;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.data.Node;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.data.SqlNote;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.data.Task;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.data.TaskList;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.exception.ActionFailureException;// 导入所需的Android类和自定义类 +import net.micode.notes.gtask.exception.NetworkFailureException;// 导入所需的Android类和自定义类 +import net.micode.notes.tool.DataUtils;// 导入所需的Android类和自定义类 +import net.micode.notes.tool.GTaskStringUtils;// 导入所需的Android类和自定义类 + +import org.json.JSONArray;// 导入所需的Android类和自定义类 +import org.json.JSONException;// 导入所需的Android类和自定义类 +import org.json.JSONObject;// 导入所需的Android类和自定义类 + +import java.util.HashMap;// 导入所需的Android类和自定义类// 导入所需的Android类和自定义类 +import java.util.HashSet;// 导入所需的Android类和自定义类 +import java.util.Iterator;// 导入所需的Android类和自定义类 import java.util.Map; - +// GTaskManager类是管理Google任务同步的核心类 public class GTaskManager { + // 日志标签,用于Logcat中过滤日志 private static final String TAG = GTaskManager.class.getSimpleName(); + // 定义同步状态常量 public static final int STATE_SUCCESS = 0; - public static final int STATE_NETWORK_ERROR = 1; - public static final int STATE_INTERNAL_ERROR = 2; - public static final int STATE_SYNC_IN_PROGRESS = 3; - public static final int STATE_SYNC_CANCELLED = 4; + // 单例对象 private static GTaskManager mInstance = null; + // Activity上下文,用于获取认证token private Activity mActivity; - + // 应用程序上下文 private Context mContext; - + // 内容解析器,用于访问和修改数据库 private ContentResolver mContentResolver; - + // 同步状态标志 private boolean mSyncing; - + // 取消同步标志 private boolean mCancelled; - + // 存储任务列表的哈希映射 private HashMap mGTaskListHashMap; - + // 存储任务节点的哈希映射 private HashMap mGTaskHashMap; - + // 存储元数据的哈希映射 private HashMap mMetaHashMap; - + // 元数据列表 private TaskList mMetaList; - + // 本地删除ID集合 private HashSet mLocalDeleteIdMap; - + // 任务ID到笔记ID的映射 private HashMap mGidToNid; - + // 笔记ID到任务ID的映射 private HashMap mNidToGid; + // 私有构造函数,确保单例 private GTaskManager() { mSyncing = false; mCancelled = false; @@ -99,6 +100,7 @@ public class GTaskManager { mNidToGid = new HashMap(); } + // 获取GTaskManager单例 public static synchronized GTaskManager getInstance() { if (mInstance == null) { mInstance = new GTaskManager(); @@ -106,12 +108,15 @@ public class GTaskManager { return mInstance; } + // 设置Activity上下文 public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken + // 用于获取认证token mActivity = activity; } + // 同步方法,接受上下文和异步任务参数 public int sync(Context context, GTaskASyncTask asyncTask) { + // 如果正在同步中,则返回同步进行中状态 if (mSyncing) { Log.d(TAG, "Sync is in progress"); return STATE_SYNC_IN_PROGRESS; @@ -128,21 +133,22 @@ public class GTaskManager { mNidToGid.clear(); try { + // 获取GTaskClient单例 GTaskClient client = GTaskClient.getInstance(); client.resetUpdateArray(); - // login google task + // 登录Google任务 if (!mCancelled) { if (!client.login(mActivity)) { throw new NetworkFailureException("login google task failed"); } } - // get the task list from google + // 从Google获取任务列表 asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); initGTaskList(); - // do content sync work + // 执行内容同步工作 asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); syncContent(); } catch (NetworkFailureException e) { @@ -168,26 +174,27 @@ public class GTaskManager { return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + // 初始化Google任务列表 private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; - GTaskClient client = GTaskClient.getInstance(); - try { - JSONArray jsTaskLists = client.getTaskLists(); - - // init meta list first + if (mCancelled) // 初始化Google任务列表 + return; // 初始化Google任务列表 + GTaskClient client = GTaskClient.getInstance(); // 初始化Google任务列表 + try { // 初始化Google任务列表 + JSONArray jsTaskLists = client.getTaskLists(); // 初始化Google任务列表 + // 初始化Google任务列表 + // 首先初始化元数据列表 mMetaList = null; for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + // 检查是否是元数据文件夹 + if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { mMetaList = new TaskList(); mMetaList.setContentByRemoteJSON(object); - // load meta data + // 加载元数据 JSONArray jsMetas = client.getTaskList(gid); for (int j = 0; j < jsMetas.length(); j++) { object = (JSONObject) jsMetas.getJSONObject(j); @@ -202,6 +209,17 @@ public class GTaskManager { } } } + } + // 处理JSON异常 + catch (JSONException e) { + throw new NetworkFailureException("JSONException in initGTaskList"); + } + } +} } + } + } + } + } // create meta list if not existed if (mMetaList == null) { diff --git a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..fa3c01a 100644 --- a/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -1,11 +1,11 @@ /* - * 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 * - * 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, @@ -14,97 +14,151 @@ * limitations under the License. */ +// 包声明,表明该类所在的包名为net.micode.notes.gtask.remote package net.micode.notes.gtask.remote; import android.app.Activity; import android.app.Service; +// 用于创建和管理Android中的服务,服务可以在后台执行长时间运行的操作,不提供用户界面 import android.content.Context; import android.content.Intent; import android.os.Bundle; +// 用于在组件间传递数据,例如在Activity、Service之间传递参数等,以键值对的形式存储数据 import android.os.IBinder; +// GTaskSyncService继承自Service类,是一个用于处理与GTask相关的同步操作的服务类, +// 比如启动同步、取消同步以及发送同步相关广播等功能 public class GTaskSyncService extends Service { + // 定义一个字符串常量,作为在Intent中传递同步操作类型的键,用于区分不同的同步相关动作 public final static String ACTION_STRING_NAME = "sync_action_type"; + // 定义一个整型常量,表示启动同步的操作类型,对应的值为0,用于在传递操作类型时使用 public final static int ACTION_START_SYNC = 0; + // 定义一个整型常量,表示取消同步的操作类型,对应的值为1,用于在传递操作类型时使用 public final static int ACTION_CANCEL_SYNC = 1; + // 定义一个整型常量,表示无效的操作类型,对应的值为2,用于在一些不符合预期的情况判断中使用 public final static int ACTION_INVALID = 2; + // 定义一个字符串常量,作为广播的Action名称,用于标识该服务发送的广播,其他组件可以通过监听这个Action来接收广播 public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; + // 定义一个字符串常量,作为广播中传递是否正在同步状态的键,用于在广播Intent中传递同步状态信息 public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; + // 定义一个字符串常量,作为广播中传递同步进度消息的键,用于在广播Intent中传递同步进度相关的文本信息 public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; + // 静态变量,用于保存当前正在执行的GTaskASyncTask实例,初始化为null,表示当前没有正在进行的同步任务 private static GTaskASyncTask mSyncTask = null; + // 静态变量,用于保存同步进度相关的消息内容,初始化为空字符串,后续会根据同步情况更新该内容并通过广播发送出去 private static String mSyncProgress = ""; + // 私有方法,用于启动同步任务 private void startSync() { + // 判断当前是否没有正在执行的同步任务(mSyncTask为null),如果是则创建一个新的GTaskASyncTask实例来执行同步操作 if (mSyncTask == null) { + // 创建GTaskASyncTask实例,传入当前服务的上下文(this)以及一个实现了OnCompleteListener接口的匿名内部类对象 mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + // 实现OnCompleteListener接口的onComplete方法,当同步任务完成时会被调用 public void onComplete() { + // 将mSyncTask置为null,表示同步任务已结束 mSyncTask = null; + // 发送一个空消息的广播,可能用于通知其他组件同步已完成等情况 sendBroadcast(""); + // 停止当前服务,因为同步任务已经完成,服务不再需要继续运行 stopSelf(); } }); + // 发送一个空消息的广播,可能用于通知其他组件即将开始同步等情况 sendBroadcast(""); + // 执行GTaskASyncTask实例的execute方法,启动异步任务开始执行同步操作 mSyncTask.execute(); } } + // 私有方法,用于取消正在进行的同步任务 private void cancelSync() { - if (mSyncTask != null) { + // 判断如果当前存在正在执行的同步任务(mSyncTask不为null),则调用GTaskASyncTask的cancelSync方法取消同步 + if (mSyncTask!= null) { mSyncTask.cancelSync(); } } + // 重写Service的onCreate方法,该方法在服务创建时被调用,这里将mSyncTask初始化为null, + // 确保每次服务启动时都处于没有正在执行同步任务的初始状态 @Override public void onCreate() { mSyncTask = null; } + // 重写Service的onStartCommand方法,该方法在每次服务接收到启动请求(通过startService方法启动服务时)被调用, + // 在这里根据传入的Intent中的参数来决定执行启动同步还是取消同步等操作,并返回服务的启动模式相关标识 @Override public int onStartCommand(Intent intent, int flags, int startId) { + // 从传入的Intent中获取携带的额外数据(以Bundle形式存储),这些数据可能包含了同步操作类型等信息 Bundle bundle = intent.getExtras(); - if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { + // 判断获取到的Bundle不为null并且其中包含了用于标识同步操作类型的键(ACTION_STRING_NAME) + if (bundle!= null && bundle.containsKey(ACTION_STRING_NAME)) { + // 根据获取到的同步操作类型的值进行不同的操作,通过switch语句进行判断 switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + // 如果操作类型是启动同步(ACTION_START_SYNC) case ACTION_START_SYNC: + // 调用startSync方法启动同步任务 startSync(); break; + // 如果操作类型是取消同步(ACTION_CANCEL_SYNC) case ACTION_CANCEL_SYNC: + // 调用cancelSync方法取消正在进行的同步任务 cancelSync(); break; default: + // 如果是其他未定义的操作类型,不做任何处理,直接跳出switch语句 break; } + // 返回START_STICKY,表示服务在被系统强制关闭后(例如内存不足等情况),会尝试重新创建并启动, + // 但不会重新传递上次的Intent,而是以空Intent启动,服务需要自行处理这种情况来恢复到合适的状态 return START_STICKY; } + // 如果传入的Intent不符合预期(没有包含操作类型相关参数等情况),则调用父类的onStartCommand方法进行默认处理 return super.onStartCommand(intent, flags, startId); } + // 重写Service的onLowMemory方法,该方法在系统内存不足时被调用,在这里用于取消正在进行的同步任务, + // 以释放内存资源,避免服务占用过多内存导致系统出现问题 @Override public void onLowMemory() { - if (mSyncTask != null) { + if (mSyncTask!= null) { mSyncTask.cancelSync(); } } + // 重写Service的onBind方法,用于处理服务的绑定操作,这里返回null,表示该服务不支持绑定操作, + // 即其他组件不能通过bindService方法来绑定这个服务获取IBinder对象进行交互 public IBinder onBind(Intent intent) { return null; } + // 用于发送同步相关的广播,广播中包含了是否正在同步的状态以及同步进度消息等信息 public void sendBroadcast(String msg) { + // 更新同步进度消息内容,将传入的msg赋值给mSyncProgress变量 mSyncProgress = msg; + // 创建一个Intent对象,设置其Action为之前定义的广播Action名称(GTASK_SERVICE_BROADCAST_NAME), + // 用于标识这个广播是由该服务发出的同步相关广播 Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + // 在Intent中添加额外数据,通过键(GTASK_SERVICE_BROADCAST_IS_SYNCING)来传递当前是否正在同步的状态, + // 根据mSyncTask是否为null来判断,null表示没有正在进行的同步任务,非null则表示正在同步 + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask!= null); + // 在Intent中添加额外数据,通过键(GTASK_SERVICE_BROADCAST_PROGRESS_MSG)来传递同步进度消息内容 intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + // 使用服务的上下文发送广播,将包含同步相关信息的Intent广播出去,其他组件可以通过注册监听相应Action来接收广播 sendBroadcast(intent); } + // 静态方法,用于在Activity中启动同步服务来执行同步操作, + // 首先设置GTaskManager中的Activity上下文,然后构建启动服务的Intent并传递启动同步的操作类型参数,最后启动服务 public static void startSync(Activity activity) { GTaskManager.getInstance().setActivityContext(activity); Intent intent = new Intent(activity, GTaskSyncService.class); @@ -112,17 +166,21 @@ public class GTaskSyncService extends Service { activity.startService(intent); } + // 静态方法,用于在给定的上下文(Context)中启动服务来取消同步操作, + // 构建启动服务的Intent并传递取消同步的操作类型参数,最后启动服务 public static void cancelSync(Context context) { Intent intent = new Intent(context, GTaskSyncService.class); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); context.startService(intent); } + // 静态方法,用于判断当前是否正在进行同步操作,通过判断mSyncTask是否为null来返回相应的布尔值结果 public static boolean isSyncing() { - return mSyncTask != null; + return mSyncTask!= null; } + // 静态方法,用于获取当前的同步进度消息内容,直接返回保存同步进度消息的mSyncProgress变量的值 public static String getProgressString() { return mSyncProgress; } -} +} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/model/Note.java b/app/src/main/java/net/micode/notes/model/Note.java index 3fdd9f8..d457492 100644 --- a/app/src/main/java/net/micode/notes/model/Note.java +++ b/app/src/main/java/net/micode/notes/model/Note.java @@ -1,114 +1,176 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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. */ +// 包声明,表明该类所在的包名为net.micode.notes.model,通常用于存放笔记相关的数据模型等相关类定义 package net.micode.notes.model; +// 用于构建ContentProvider操作相关的数据结构,比如插入、更新、删除等操作的数据封装,以便批量应用到ContentResolver上 import android.content.ContentProviderOperation; +// 用于获取ContentProvider操作执行后的结果集,比如批量更新、插入等操作完成后返回的结果信息 import android.content.ContentProviderResult; +// 用于根据给定的基础Uri和一个ID值构建一个新的Uri,方便对特定资源进行操作(比如对某个具体笔记的相关操作对应的Uri) import android.content.ContentUris; +// 用于存储键值对形式的数据,通常用于向ContentProvider插入、更新数据时传递具体的数据内容 import android.content.ContentValues; import android.content.Context; +// 用于处理ContentProvider操作应用时可能出现的异常情况,比如批量操作部分失败等异常处理 import android.content.OperationApplicationException; +// 用于表示一个资源的统一资源标识符(Uri),在Android中常用于定位ContentProvider中的数据资源等操作 import android.net.Uri; +// 用于处理在跨进程调用ContentProvider等操作时可能出现的远程异常情况 import android.os.RemoteException; import android.util.Log; +// 导入笔记相关的数据类,可能包含了笔记的各种属性、类型等定义以及不同类型笔记的数据结构相关类 import net.micode.notes.data.Notes; +// 导入笔记中呼叫记录相关的内部类,可能用于处理特定类型笔记(呼叫记录类型笔记)的数据结构和操作 import net.micode.notes.data.Notes.CallNote; +// 导入笔记中数据列相关的内部类,可能定义了笔记数据在存储时各个列的名称、类型等相关常量 import net.micode.notes.data.Notes.DataColumns; +// 导入笔记中普通笔记相关的列定义的内部类,可能定义了普通笔记在数据库存储时各个字段对应的列名等信息 import net.micode.notes.data.Notes.NoteColumns; +// 导入笔记中文本笔记相关的内部类,可能用于处理文本类型笔记的数据结构和操作 import net.micode.notes.data.Notes.TextNote; +// 导入用于存储列表等数据结构的集合类,这里主要用于存储ContentProviderOperation对象列表,以便批量操作 import java.util.ArrayList; +// Note类,应该是代表笔记的数据模型类,用于处理笔记相关的数据操作,比如创建笔记、更新笔记以及与ContentProvider交互等操作 public class Note { - private ContentValues mNoteDiffValues; // 用于存储笔记变化的ContentValues - private NoteData mNoteData; // 存储笔记数据的内部类 - private static final String TAG = "Note"; // 日志标签 + // 用于存储笔记的差异数据(可能是自上次同步或修改后发生变化的数据),以ContentValues形式存储,方便后续更新操作 + private ContentValues mNoteDiffValues; + // 用于存储笔记的详细数据(包含文本数据、呼叫数据等不同类型的数据),是一个自定义的NoteData类型对象 + private NoteData mNoteData; + // 定义一个日志标签,用于在Log输出时标识是该类中的相关日志信息,方便调试和查看日志记录 + private static final String TAG = "Note"; /** - * 创建一个新的笔记ID + * Create a new note id for adding a new note to databases + * 创建一个新的笔记ID,用于向数据库中添加新笔记,通过向ContentProvider插入一条新的笔记记录来获取新生成的笔记ID */ public static synchronized long getNewNoteId(Context context, long folderId) { - // 创建一个新的笔记 + // 创建一个新的ContentValues对象,用于存储要插入到数据库中的笔记初始数据 ContentValues values = new ContentValues(); + // 获取当前系统时间的时间戳,作为笔记的创建时间,单位为毫秒 long createdTime = System.currentTimeMillis(); + // 将创建时间设置到ContentValues中,对应笔记记录的创建日期字段(NoteColumns.CREATED_DATE) values.put(NoteColumns.CREATED_DATE, createdTime); + // 将创建时间也设置为修改时间,因为新创建的笔记初始时修改时间和创建时间相同,对应修改日期字段(NoteColumns.MODIFIED_DATE) values.put(NoteColumns.MODIFIED_DATE, createdTime); + // 设置笔记的类型,这里设置为普通笔记类型(Notes.TYPE_NOTE),可能有不同类型的笔记区分 values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + // 将本地修改标志设置为1,表示该笔记在本地有过修改(初始创建也算一种本地修改情况),对应本地修改字段(NoteColumns.LOCAL_MODIFIED) values.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置笔记的父文件夹ID,用于表示笔记所属的文件夹,对应父ID字段(NoteColumns.PARENT_ID) values.put(NoteColumns.PARENT_ID, folderId); + // 通过ContentResolver向指定的笔记内容Uri(Notes.CONTENT_NOTE_URI)插入新的笔记记录,返回插入后生成的Uri Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); long noteId = 0; try { + // 从插入后生成的Uri中获取路径段(通常Uri的路径部分可以按段分割,比如最后一段可能是新生成的资源ID),获取第二个路径段(索引为1)作为笔记ID noteId = Long.valueOf(uri.getPathSegments().get(1)); } catch (NumberFormatException e) { + // 如果在转换为长整型笔记ID时出现格式异常(比如路径段内容不是合法的数字格式),记录错误日志并将笔记ID设置为0 Log.e(TAG, "Get note id error :" + e.toString()); noteId = 0; } if (noteId == -1) { + // 如果获取到的笔记ID为 -1,说明出现了不合理的情况,抛出IllegalStateException异常,表示笔记ID错误 throw new IllegalStateException("Wrong note id:" + noteId); } return noteId; } + // 无参构造函数,用于初始化Note对象,创建一个新的ContentValues用于存储笔记差异数据,以及一个新的NoteData对象用于存储详细笔记数据 public Note() { mNoteDiffValues = new ContentValues(); mNoteData = new NoteData(); } + // 设置笔记的某个值(可能是笔记的属性值等),将给定的键值对添加到笔记差异数据ContentValues中, + // 同时更新本地修改标志和修改日期,以记录笔记数据的变化情况 public void setNoteValue(String key, String value) { mNoteDiffValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + // 设置笔记的文本数据,调用NoteData对象的相应方法来设置文本数据,将键值对存储到NoteData中的文本数据相关ContentValues中 public void setTextData(String key, String value) { mNoteData.setTextData(key, value); } + // 设置笔记的文本数据ID,调用NoteData对象的相应方法来设置文本数据ID,传入的ID值会被存储到NoteData对象中 public void setTextDataId(long id) { mNoteData.setTextDataId(id); } + // 获取笔记的文本数据ID,通过访问NoteData对象中的相应属性来返回文本数据ID public long getTextDataId() { return mNoteData.mTextDataId; } + // 设置笔记的呼叫数据ID,调用NoteData对象的相应方法来设置呼叫数据ID,传入的ID值会被存储到NoteData对象中,同时会进行参数合法性检查 public void setCallDataId(long id) { mNoteData.setCallDataId(id); } + // 设置笔记的呼叫数据,调用NoteData对象的相应方法来设置呼叫数据,将键值对存储到NoteData中的呼叫数据相关ContentValues中, + // 同时更新本地修改标志和修改日期,以记录笔记数据的变化情况 public void setCallData(String key, String value) { mNoteData.setCallData(key, value); } + // 判断笔记是否在本地有过修改,通过检查笔记差异数据ContentValues的大小(即是否有数据变化)以及NoteData对象是否有本地修改来综合判断 public boolean isLocalModified() { return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); } + // 同步笔记数据到ContentProvider(比如更新到数据库等存储介质中),根据笔记是否有本地修改以及更新操作的结果来返回同步是否成功 public boolean syncNote(Context context, long noteId) { if (noteId <= 0) { + // 如果传入的笔记ID小于等于0,说明是不合理的笔记ID,抛出IllegalArgumentException异常,表示笔记ID错误 throw new IllegalArgumentException("Wrong note id:" + noteId); } if (!isLocalModified()) { + // 如果笔记没有本地修改,说明不需要进行同步操作,直接返回true表示同步成功(实际上没有进行实际的更新操作) return true; } - // 更新笔记 + /** + * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and + * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the + * note data info + * 理论上,一旦数据发生变化,笔记应该在{@link NoteColumns#LOCAL_MODIFIED}和{@link NoteColumns#MODIFIED_DATE}字段上进行更新。 + * 为了数据安全,即使更新笔记失败,我们也要更新笔记数据信息。 + */ + // 通过ContentResolver尝试更新指定笔记ID对应的笔记记录,传入笔记差异数据ContentValues进行更新操作, + // 如果更新操作影响的行数为0(即没有实际更新到任何数据,可能更新失败),记录错误日志,但不立即返回,继续执行后续操作 if (context.getContentResolver().update( ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, null) == 0) { Log.e(TAG, "Update note error, should not happen"); // Do not return, fall through } + // 清除笔记差异数据ContentValues中的内容,因为已经尝试进行了更新操作,无论成功与否都先清空,准备下次记录新的差异数据 mNoteDiffValues.clear(); - // 同步笔记数据 + // 如果NoteData对象有本地修改,并且将NoteData中的数据推送到ContentResolver(即更新相关数据到存储介质)操作返回null(可能推送失败),则返回false表示同步失败 if (mNoteData.isLocalModified() && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { return false; @@ -117,14 +179,21 @@ public class Note { return true; } - // 内部类,用于存储笔记的文本数据和通话记录数据 + // NoteData内部类,用于封装笔记的详细数据(包含文本数据和呼叫数据相关的ContentValues以及对应的ID等信息), + // 处理与这些详细数据相关的操作,比如设置数据、判断是否有本地修改以及将数据推送到ContentResolver等操作 private class NoteData { + // 存储文本数据的唯一标识符(ID),初始化为0 private long mTextDataId; + // 用于存储文本数据相关的ContentValues,以键值对形式存储文本数据的具体内容等信息,初始化为一个新的ContentValues对象 private ContentValues mTextDataValues; + // 存储呼叫数据的唯一标识符(ID),初始化为0 private long mCallDataId; + // 用于存储呼叫数据相关的ContentValues,以键值对形式存储呼叫数据的具体内容等信息,初始化为一个新的ContentValues对象 private ContentValues mCallDataValues; + // 定义一个日志标签,用于在Log输出时标识是该内部类中的相关日志信息,方便调试和查看日志记录 private static final String TAG = "NoteData"; + // 构造函数,用于初始化NoteData对象,创建新的文本数据和呼叫数据相关的ContentValues对象,并将文本数据和呼叫数据的ID初始化为0 public NoteData() { mTextDataValues = new ContentValues(); mCallDataValues = new ContentValues(); @@ -132,17 +201,20 @@ public class Note { mCallDataId = 0; } + // 判断NoteData对象中的文本数据或呼叫数据是否有本地修改,通过检查对应的ContentValues的大小(即是否有数据变化)来判断 boolean isLocalModified() { return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; } + // 设置文本数据ID,进行参数合法性检查,如果传入的ID小于等于0,则抛出IllegalArgumentException异常,否则更新文本数据ID void setTextDataId(long id) { - if(id <= 0) { + if (id <= 0) { throw new IllegalArgumentException("Text data id should larger than 0"); } mTextDataId = id; } + // 设置呼叫数据ID,进行参数合法性检查,如果传入的ID小于等于0,则抛出IllegalArgumentException异常,否则更新呼叫数据ID void setCallDataId(long id) { if (id <= 0) { throw new IllegalArgumentException("Call data id should larger than 0"); @@ -150,82 +222,54 @@ public class Note { mCallDataId = id; } + // 设置呼叫数据,将给定的键值对添加到呼叫数据相关的ContentValues中,同时更新笔记的本地修改标志和修改日期(通过外部的Note对象相关字段来更新) void setCallData(String key, String value) { mCallDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + // 设置文本数据,将给定的键值对添加到文本数据相关的ContentValues中,同时更新笔记的本地修改标志和修改日期(通过外部的Note对象相关字段来更新) void setTextData(String key, String value) { mTextDataValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } + // 将NoteData中的数据推送到ContentResolver(比如更新到数据库等存储介质中),根据文本数据和呼叫数据的情况进行相应的插入、更新操作, + // 并处理操作过程中可能出现的异常情况,返回操作结果对应的Uri(如果成功)或null(如果失败) Uri pushIntoContentResolver(Context context, long noteId) { - // 将笔记数据推送到内容解析器 + /** + * Check for safety + */ + if (noteId <= 0) { + // 如果传入的笔记ID小于等于0,进行参数合法性检查,抛出IllegalArgumentException异常,表示笔记ID错误 + throw new IllegalArgumentException("Wrong note id:" + noteId); + } + + // 创建一个ArrayList,用于存储ContentProviderOperation对象,以便后续批量应用到ContentResolver上进行操作 ArrayList operationList = new ArrayList(); + // 创建一个ContentProviderOperation的构建器对象,初始化为null,后续根据具体情况创建相应的更新或插入操作构建器 ContentProviderOperation.Builder builder = null; - if(mTextDataValues.size() > 0) { + if (mTextDataValues.size() > 0) { + // 如果文本数据相关的ContentValues中有数据(即有文本数据需要处理),将笔记ID设置到文本数据的ContentValues中,对应笔记ID字段(DataColumns.NOTE_ID) mTextDataValues.put(DataColumns.NOTE_ID, noteId); if (mTextDataId == 0) { + // 如果文本数据ID为0,说明是新的文本数据,需要进行插入操作,设置文本数据的MIME类型为文本笔记的内容类型(TextNote.CONTENT_ITEM_TYPE) mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); + // 通过ContentResolver向指定的笔记数据内容Uri(Notes.CONTENT_DATA_URI)插入新的文本数据记录,返回插入后生成的Uri Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues); try { + // 尝试从插入后生成的Uri中获取路径段,获取第二个路径段(索引为1)作为新生成的文本数据ID,并设置到文本数据ID属性中 setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); } catch (NumberFormatException e) { + // 如果在转换为长整型文本数据ID时出现格式异常,记录错误日志,清除文本数据相关的ContentValues内容,并返回null表示插入失败 Log.e(TAG, "Insert new text data fail with noteId" + noteId); mTextDataValues.clear(); return null; } } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mTextDataId)); - builder.withValues(mTextDataValues); - operationList.add(builder.build()); - } - mTextDataValues.clear(); - } - - if(mCallDataValues.size() > 0) { - mCallDataValues.put(DataColumns.NOTE_ID, noteId); - if (mCallDataId == 0) { - mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); - Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, - mCallDataValues); - try { - setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); - } catch (NumberFormatException e) { - Log.e(TAG, "Insert new call data fail with noteId" + noteId); - mCallDataValues.clear(); - return null; - } - } else { - builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mCallDataId)); - builder.withValues(mCallDataValues); - operationList.add(builder.build()); - } - mCallDataValues.clear(); - } - - if (operationList.size() > 0) { - try { - ContentProviderResult[] results = context.getContentResolver().applyBatch( - Notes.AUTHORITY, operationList); - return (results == null || results.length == 0 || results[0] == null) ? null - : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); - } catch (RemoteException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - return null; - } catch (OperationApplicationException e) { - Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); - return null; - } - } - return null; - } - } -} \ No newline at end of file + // 如果文本数据ID不为0,说明是已有文本数据的更新操作,创建一个ContentProviderOperation的更新操作构建器, + // 根据文本数据ID对应的Uri(通过ContentUris.withAppendedId构建)来指定要更新的 \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/model/WorkingNote.java b/app/src/main/java/net/micode/notes/model/WorkingNote.java index ce2d218..f92e4aa 100644 --- a/app/src/main/java/net/micode/notes/model/WorkingNote.java +++ b/app/src/main/java/net/micode/notes/model/WorkingNote.java @@ -1,45 +1,87 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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. */ +// 包声明,表明该类所在的包名为net.micode.notes.model,通常用于存放和笔记相关的数据模型及操作逻辑等相关类 package net.micode.notes.model; +// 用于管理桌面小部件相关操作,例如获取小部件ID、更新小部件等操作,和Android桌面小部件功能交互相关 import android.appwidget.AppWidgetManager; +// 用于根据给定的基础Uri和一个ID值构建一个新的Uri,方便对特定资源进行操作(比如对某个具体笔记的相关操作对应的Uri) import android.content.ContentUris; +// 提供对Android设备上各种数据存储(如数据库等)进行查询、插入、更新、删除等操作的接口,通过它与Content Provider进行交互 import android.content.Context; +// 用于在数据库查询操作后获取结果集,以游标形式遍历查询返回的数据行,可从中获取具体的列数据 import android.database.Cursor; +// 用于处理字符串相关的工具方法,比如判断字符串是否为空、比较字符串内容是否相等之类的操作 import android.text.TextUtils; import android.util.Log; +// 导入笔记相关的数据类,可能包含了笔记的各种属性、类型等定义以及不同类型笔记的数据结构相关类 import net.micode.notes.data.Notes; +// 导入笔记中呼叫记录相关的内部类,可能用于处理特定类型笔记(呼叫记录类型笔记)的数据结构和操作 import net.micode.notes.data.Notes.CallNote; +// 导入笔记中数据列相关的内部类,可能定义了笔记数据在存储时各个列的名称、类型等相关常量 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.Notes.TextNote; +// 导入用于解析资源相关的工具类中的笔记背景资源相关的内部类,可能用于获取笔记背景相关的资源ID等操作 import net.micode.notes.tool.ResourceParser.NoteBgResources; +// WorkingNote类,应该是代表正在操作(编辑、修改等)的笔记的数据模型类,封装了笔记的各种属性以及相关操作方法 public class WorkingNote { - // 笔记成员变量 - private Note mNote; // 笔记对象 - private long mNoteId; // 笔记ID - private String mContent; // 笔记内容 - private int mMode; // 笔记模式 - - private long mAlertDate; // 闹钟日期 - private long mModifiedDate; // 修改日期 - private int mBgColorId; // 背景颜色ID - private int mWidgetId; // 小部件ID - private int mWidgetType; // 小部件类型 - private long mFolderId; // 文件夹ID - private Context mContext; // 上下文对象 - private static final String TAG = "WorkingNote"; // 日志标签 - private boolean mIsDeleted; // 是否删除 - private NoteSettingChangedListener mNoteSettingStatusListener; // 笔记设置变化监听器 - - // 数据投影数组 - public static final String[] DATA_PROJECTION = new String[]{ + // 用于存储关联的Note对象,Note类可能是更基础的笔记数据模型类,这里的WorkingNote可能是在其基础上进行更多业务相关操作的封装 + // Note for the working note + private Note mNote; + // 用于存储笔记的唯一标识符(ID),代表当前正在操作的笔记在数据库等存储介质中的标识 + // Note Id + private long mNoteId; + // 用于存储笔记的内容文本,比如用户输入的具体笔记文字内容等 + // Note content + private String mContent; + // 用于存储笔记的模式相关信息,具体含义可能根据业务逻辑而定,例如可能是不同的编辑模式等情况 + // Note mode + private int mMode; + + // 用于存储笔记设置的提醒日期时间戳,以毫秒为单位,用于表示笔记的提醒时间相关设置 + private long mAlertDate; + // 用于存储笔记最后修改的日期时间戳,以毫秒为单位,用于记录笔记最近一次被修改的时间 + private long mModifiedDate; + // 用于存储笔记背景颜色的资源ID,通过这个ID可以获取到对应的背景颜色资源,用于设置笔记的显示背景等 + private int mBgColorId; + // 用于存储笔记关联的桌面小部件的ID,用于标识该笔记与哪个桌面小部件相关联(如果有的话) + private int mWidgetId; + // 用于存储笔记关联的桌面小部件的类型,可能有不同类型的小部件对应不同的展示或功能,具体类型由业务定义 + private int mWidgetType; + // 用于存储笔记所属的文件夹的ID,用于表示笔记在文件系统中的分类归属,方便管理和查找笔记 + private long mFolderId; + // 用于存储当前的上下文环境(Context),通过它可以访问Android系统的各种资源、服务等,方便与系统进行交互操作 + private Context mContext; + // 定义一个日志标签,用于在Log输出时标识是该类中的相关日志信息,方便调试和查看日志记录 + private static final String TAG = "WorkingNote"; + // 用于标记当前笔记是否已被删除,true表示已删除,false表示未删除,方便在业务逻辑中判断笔记的删除状态 + private boolean mIsDeleted; + // 用于存储一个实现了NoteSettingChangedListener接口的对象,以便在笔记相关设置发生变化时通知对应的监听器进行相应处理 + private NoteSettingChangedListener mNoteSettingStatusListener; + + // 定义一个字符串数组常量,用于指定查询笔记数据时要获取的列名列表,主要涉及笔记数据相关的一些通用列信息,用于后续数据库查询操作 + public static final String[] DATA_PROJECTION = new String[] { DataColumns.ID, DataColumns.CONTENT, DataColumns.MIME_TYPE, @@ -49,8 +91,8 @@ public class WorkingNote { DataColumns.DATA4, }; - // 笔记投影数组 - public static final String[] NOTE_PROJECTION = new String[]{ + // 定义一个字符串数组常量,用于指定查询笔记基本信息时要获取的列名列表,主要涉及笔记自身属性相关的一些列信息,用于后续数据库查询操作 + public static final String[] NOTE_PROJECTION = new String[] { NoteColumns.PARENT_ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, @@ -59,7 +101,29 @@ public class WorkingNote { NoteColumns.MODIFIED_DATE }; - // 构造函数 + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记数据ID列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_ID_COLUMN = 0; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记内容列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_CONTENT_COLUMN = 1; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记MIME类型列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_MIME_TYPE_COLUMN = 2; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记模式相关列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_MODE_COLUMN = 3; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记父文件夹ID列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_PARENT_ID_COLUMN = 0; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记提醒日期列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记背景颜色ID列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记小部件ID列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_WIDGET_ID_COLUMN = 3; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记小部件类型列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记修改日期列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + + // 私有构造函数,用于创建一个新的空白笔记(尚未保存到数据库等存储介质中),初始化一些基本属性,如创建时间、所属文件夹等信息 + // New note construct private WorkingNote(Context context, long folderId) { mContext = context; mAlertDate = 0; @@ -72,7 +136,8 @@ public class WorkingNote { mWidgetType = Notes.TYPE_WIDGET_INVALIDE; } - // 构造函数 + // 私有构造函数,用于创建一个基于已有笔记ID的WorkingNote对象,通过从数据库等存储介质中加载已有笔记的信息来初始化对象属性 + // Existing note construct private WorkingNote(Context context, long noteId, long folderId) { mContext = context; mNoteId = noteId; @@ -82,17 +147,74 @@ public class WorkingNote { loadNote(); } - // 加载笔记 + // 私有方法,用于从数据库等存储介质中加载笔记的基本信息(如文件夹ID、背景颜色ID、小部件相关信息等),通过ContentResolver进行查询操作获取数据 private void loadNote() { - // 从数据库加载笔记信息 + // 使用ContentResolver查询指定笔记ID对应的笔记基本信息,传入构建好的笔记内容Uri(通过ContentUris.withAppendedId根据笔记ID生成)以及要查询的列名列表(NOTE_PROJECTION)等参数 + Cursor cursor = mContext.getContentResolver().query( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + + if (cursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则从游标中获取相应列的数据并赋值给对应的对象属性 + if (cursor.moveToFirst()) { + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); + mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); + mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); + } + // 关闭游标,释放相关资源,因为已经获取完需要的数据了 + cursor.close(); + } else { + // 如果游标为null,说明查询出现问题,没有找到对应的笔记,记录错误日志并抛出IllegalArgumentException异常,表示无法找到指定ID的笔记 + Log.e(TAG, "No note with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note with id " + mNoteId); + } + // 调用loadNoteData方法加载笔记的详细数据(如内容、类型等信息) + loadNoteData(); } - // 加载笔记数据 + // 私有方法,用于从数据库等存储介质中加载笔记的详细数据(如内容、类型等信息),通过ContentResolver进行查询操作获取数据,并根据数据类型进行相应的处理 private void loadNoteData() { - // 从数据库加载笔记数据 + // 使用ContentResolver查询指定笔记ID对应的笔记数据信息,传入笔记数据内容的Uri(Notes.CONTENT_DATA_URI)以及要查询的列名列表(DATA_PROJECTION)等参数, + // 同时通过条件筛选只获取当前笔记ID对应的笔记数据(DataColumns.NOTE_ID + "=?" 及对应的笔记ID参数) + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null); + + if (cursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则进入循环遍历游标中的每一行数据 + if (cursor.moveToFirst()) { + do { + // 从游标中获取笔记数据的MIME类型列的数据(表示数据的格式类型,比如文本、呼叫记录等类型) + String type = cursor.getString(DATA_MIME_TYPE_COLUMN); + if (DataConstants.NOTE.equals(type)) { + // 如果类型是普通笔记类型(DataConstants.NOTE),则从游标中获取笔记内容列的数据赋值给mContent属性, + // 获取笔记模式列的数据赋值给mMode属性,并将笔记数据ID设置到关联的Note对象中(通过调用Note对象的setTextDataId方法) + mContent = cursor.getString(DATA_CONTENT_COLUMN); + mMode = cursor.getInt(DATA_MODE_COLUMN); + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + } else if (DataConstants.CALL_NOTE.equals(type)) { + // 如果类型是呼叫记录笔记类型(DataConstants.CALL_NOTE),则将笔记数据ID设置到关联的Note对象的呼叫数据相关属性中(通过调用Note对象的setCallDataId方法) + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + } else { + // 如果是其他未知的类型,则记录调试日志,提示出现了错误的笔记类型 + Log.d(TAG, "Wrong note type with type:" + type); + } + } while (cursor.moveToNext()); + } + // 关闭游标,释放相关资源,因为已经获取完需要的数据了 + cursor.close(); + } else { + // 如果游标为null,说明查询出现问题,没有找到对应的笔记数据,记录错误日志并抛出IllegalArgumentException异常,表示无法找到指定ID的笔记数据 + Log.e(TAG, "No data with id:" + mNoteId); + throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); + } } - // 创建空笔记 + // 静态工厂方法,用于创建一个新的空白笔记对象,并设置一些初始属性(如背景颜色ID、小部件ID、小部件类型等),方便后续编辑等操作 public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, int widgetType, int defaultBgColorId) { WorkingNote note = new WorkingNote(context, folderId); @@ -102,131 +224,47 @@ public class WorkingNote { return note; } - // 加载笔记 + // 静态工厂方法,用于根据给定的笔记ID从数据库等存储介质中加载已有笔记信息并创建对应的WorkingNote对象,方便后续操作 public static WorkingNote load(Context context, long id) { return new WorkingNote(context, id, 0); } - // 保存笔记 + // 同步方法,用于保存当前笔记的信息到数据库等存储介质中,如果笔记值得保存(根据一定的业务规则判断),则进行保存操作并返回保存结果(成功或失败) public synchronized boolean saveNote() { - // 保存笔记到数据库 + if (isWorthSaving()) { + // 判断笔记是否已经存在于数据库中,如果不存在 + if (!existInDatabase()) { + // 通过调用Note类的静态方法获取一个新的笔记ID,如果获取失败(返回0),记录错误日志并返回false表示保存失败 + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + // 调用关联的Note对象的syncNote方法将笔记数据同步到数据库等存储介质中,进行实际的保存操作 + mNote.syncNote(mContext, mNoteId); + + /** + * Update widget content if there exist any widget of this note + * 如果当前笔记关联了桌面小部件(小部件ID有效且小部件类型有效)并且设置了NoteSettingChangedListener监听器, + * 则调用监听器的onWidgetChanged方法通知小部件内容需要更新(可能是笔记内容变化后小部件展示也需要相应更新等情况) + */ + if (mWidgetId!= AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType!= Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener!= null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + return true; + } else { + return false; + } } - // 判断笔记是否存在于数据库 + // 用于判断笔记是否已经存在于数据库等存储介质中,通过检查笔记ID是否大于0来判断(通常大于0表示已经有对应的存储记录) public boolean existInDatabase() { return mNoteId > 0; } - // 设置笔记设置变化监听器 - public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { - mNoteSettingStatusListener = l; - } - - // 设置闹钟日期 - public void setAlertDate(long date, boolean set) { - // 设置闹钟日期 - } - - // 标记笔记为删除 - public void markDeleted(boolean mark) { - mIsDeleted = mark; - } - - // 设置背景颜色ID - public void setBgColorId(int id) { - // 设置背景颜色ID - } - - // 设置检查列表模式 - public void setCheckListMode(int mode) { - // 设置检查列表模式 - } - - // 设置小部件类型 - public void setWidgetType(int type) { - // 设置小部件类型 - } - - // 设置小部件ID - public void setWidgetId(int id) { - // 设置小部件ID - } - - // 设置笔记内容 - public void setWorkingText(String text) { - // 设置笔记内容 - } - - // 将笔记转换为通话记录 - public void convertToCallNote(String phoneNumber, long callDate) { - // 将笔记转换为通话记录 - } - - // 判断是否有闹钟提醒 - public boolean hasClockAlert() { - return (mAlertDate > 0 ? true : false); - } - - // 获取笔记内容 - public String getContent() { - return mContent; - } - - // 获取闹钟日期 - public long getAlertDate() { - return mAlertDate; - } - - // 获取修改日期 - public long getModifiedDate() { - return mModifiedDate; - } - - // 获取背景颜色资源ID - public int getBgColorResId() { - return NoteBgResources.getNoteBgResource(mBgColorId); - } - - // 获取背景颜色ID - public int getBgColorId() { - return mBgColorId; - } - - // 获取标题背景颜色资源ID - public int getTitleBgResId() { - return NoteBgResources.getNoteTitleBgResource(mBgColorId); - } - - // 获取检查列表模式 - public int getCheckListMode() { - return mMode; - } - - // 获取笔记ID - public long getNoteId() { - return mNoteId; - } - - // 获取文件夹ID - public long getFolderId() { - return mFolderId; - } - - // 获取小部件ID - public int getWidgetId() { - return mWidgetId; - } - - // 获取小部件类型 - public int getWidgetType() { - return mWidgetType; - } - - // 笔记设置变化监听器接口 - public interface NoteSettingChangedListener { - void onBackgroundColorChanged(); - void onClockAlertChanged(long date, boolean set); - void onWidgetChanged(); - void onCheckListModeChanged(int oldMode, int newMode); - } -} \ No newline at end of file + // 私有方法,用于根据一定的业务规则判断笔记是否值得保存,比如笔记已被删除、不存在且内容为空、存在但没有本地修改等情况则不值得保存,返回相应的布尔值结果 + private boolean isWorthSaving() { + if (mIsDeleted \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/tool/BackupUtils.java b/app/src/main/java/net/micode/notes/tool/BackupUtils.java index e739593..df68f63 100644 --- a/app/src/main/java/net/micode/notes/tool/BackupUtils.java +++ b/app/src/main/java/net/micode/notes/tool/BackupUtils.java @@ -1,35 +1,65 @@ -/* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 - */ +//* +* 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.tool; +// 包声明,表明该类所在的包名为net.micode.notes.tool,通常用于存放和笔记应用相关的工具类,这里的BackupUtils应该是和备份相关的工具类 + package net.micode.notes.tool; +// 用于获取Android应用的上下文环境,通过它可以访问系统资源、服务等,是Android开发中很多操作的基础入口 import android.content.Context; +// 用于在数据库查询操作后获取结果集,以游标形式遍历查询返回的数据行,可从中获取具体的列数据 import android.database.Cursor; +// 用于获取Android设备外部存储(如SD卡等)的状态信息,判断是否可读写等情况 import android.os.Environment; +// 用于处理字符串相关的工具方法,比如判断字符串是否为空、格式化字符串等操作 import android.text.TextUtils; +// 用于格式化日期、时间相关的文本展示格式,方便将时间戳等数据转换为符合特定格式的字符串 import android.text.format.DateFormat; import android.util.Log; +// 导入应用资源相关的R类,通过它可以获取到应用中定义的各种资源(如字符串、布局、图片资源等)的ID,用于在代码中使用这些资源 import net.micode.notes.R; +// 导入笔记相关的数据类,可能包含了笔记的各种属性、类型等定义以及不同类型笔记的数据结构相关类 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; +// 导入Java中文件操作相关的类,用于创建、读取、写入文件等操作 import java.io.File; +// 用于在文件操作中表示找不到指定文件的异常情况,当尝试访问不存在的文件时会抛出该异常 import java.io.FileNotFoundException; +// 用于创建文件输出流,将数据写入到文件中,是进行文件写入操作的关键类之一 import java.io.FileOutputStream; +// 用于处理文件读写过程中出现的一般性IO异常情况,比如读写文件出错、权限不足等问题时抛出该异常 import java.io.IOException; +// 用于将格式化后的文本数据输出到指定的输出流(比如文件输出流、控制台输出流等),方便进行文本内容的输出操作 import java.io.PrintStream; +// BackupUtils类,是一个用于备份相关功能的工具类,可能涉及将笔记数据备份到文件等操作,采用了单例模式设计 public class BackupUtils { + // 定义一个日志标签,用于在Log输出时标识是该类中的相关日志信息,方便调试和查看日志记录 private static final String TAG = "BackupUtils"; - // 单例模式 + // 单例模式相关,用于保存唯一的BackupUtils实例对象,初始化为null,后续通过单例方法获取实例时进行初始化 + // Singleton stuff private static BackupUtils sInstance; - // 获取BackupUtils实例 + // 静态同步方法,用于获取BackupUtils的单例实例,如果实例还未创建,则创建一个新的实例并返回,保证整个应用中只有一个该类的实例存在 public static synchronized BackupUtils getInstance(Context context) { if (sInstance == null) { sInstance = new BackupUtils(context); @@ -37,42 +67,58 @@ public class BackupUtils { return sInstance; } - // 备份和恢复状态常量 + /** + * Following states are signs to represents backup or restore + * status + * 以下这些状态常量用于表示备份或恢复操作的状态情况 + */ + // 表示当前SD卡(外部存储设备)未挂载,不可进行读写操作,对应备份或恢复操作可能无法进行的一种状态 + // Currently, the sdcard is not mounted public static final int STATE_SD_CARD_UNMOUONTED = 0; + // 表示备份文件不存在,可能是还未进行过备份或者备份文件被误删除等情况,用于在检查备份相关情况时判断 + // The backup file not exist public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // 表示数据格式不正确,可能被其他程序修改导致不符合预期的格式,影响备份或恢复操作的正常进行,用于异常情况判断 + // The data is not well formated, may be changed by other programs public static final int STATE_DATA_DESTROIED = 2; + // 表示出现了一些运行时异常,导致备份或恢复操作失败,比如内存不足、程序崩溃等异常情况,用于捕获和标识异常状态 + // Some run-time exception which causes restore or backup fails public static final int STATE_SYSTEM_ERROR = 3; + // 表示备份或恢复操作成功完成,用于标识操作正常结束的状态情况 + // Backup or restore success public static final int STATE_SUCCESS = 4; + // 用于文本导出相关操作的对象,可能负责将笔记数据转换为文本格式并进行导出等具体功能,通过构造函数初始化 private TextExport mTextExport; - // 构造函数 + // 私有构造函数,用于初始化BackupUtils对象,创建一个TextExport对象用于后续的文本导出相关操作,保证外部不能随意创建该类实例,符合单例模式要求 private BackupUtils(Context context) { mTextExport = new TextExport(context); } - // 检查外部存储是否可用 + // 静态方法,用于判断外部存储(如SD卡等)是否可用,通过检查外部存储的挂载状态是否为已挂载(MEDIA_MOUNTED)来返回相应的布尔值结果 private static boolean externalStorageAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } - // 导出笔记到文本 + // 调用TextExport对象的exportToText方法进行文本导出操作,并返回相应的结果(可能是表示导出操作状态的状态码等) public int exportToText() { return mTextExport.exportToText(); } - // 获取导出的文本文件名 + // 获取通过TextExport对象导出的文本文件的文件名,实际是调用TextExport对象的相应属性来返回文件名 public String getExportedTextFileName() { return mTextExport.mFileName; } - // 获取导出的文本文件目录 + // 获取通过TextExport对象导出的文本文件所在的目录路径,实际是调用TextExport对象的相应属性来返回文件目录路径 public String getExportedTextFileDir() { return mTextExport.mFileDirectory; } - // 文本导出内部类 + // TextExport内部类,主要负责将笔记相关数据转换为文本格式并输出到指定位置(如文件)的具体操作,封装了相关的数据查询、格式转换等逻辑 private static class TextExport { + // 定义一个字符串数组常量,用于指定查询笔记基本信息时要获取的列名列表,主要涉及笔记自身属性相关的一些列信息,用于后续数据库查询操作 private static final String[] NOTE_PROJECTION = { NoteColumns.ID, NoteColumns.MODIFIED_DATE, @@ -80,6 +126,14 @@ public class BackupUtils { NoteColumns.TYPE }; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记ID列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_COLUMN_ID = 0; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记修改日期列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_COLUMN_MODIFIED_DATE = 1; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记摘要列的索引位置,方便从游标中获取对应的数据 + private static final int NOTE_COLUMN_SNIPPET = 2; + + // 定义一个字符串数组常量,用于指定查询笔记数据时要获取的列名列表,主要涉及笔记数据相关的一些通用列信息,用于后续数据库查询操作 private static final String[] DATA_PROJECTION = { DataColumns.CONTENT, DataColumns.MIME_TYPE, @@ -89,12 +143,32 @@ public class BackupUtils { DataColumns.DATA4, }; - private final String[] TEXT_FORMAT; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记数据内容列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_COLUMN_CONTENT = 0; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记数据MIME类型列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_COLUMN_MIME_TYPE = 1; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记数据呼叫日期列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_COLUMN_CALL_DATE = 2; + // 定义一个整型常量,用于表示在查询结果游标(Cursor)中笔记数据电话号码列的索引位置,方便从游标中获取对应的数据 + private static final int DATA_COLUMN_PHONE_NUMBER = 4; + + // 定义一个字符串数组,用于存储文本格式相关的模板字符串,不同索引位置对应不同用途的格式模板,后续会根据索引获取相应格式来格式化输出文本内容 + private final String [] TEXT_FORMAT; + // 定义一个整型常量,用于表示在TEXT_FORMAT数组中文件夹名称格式模板的索引位置,方便获取对应格式字符串 + private static final int FORMAT_FOLDER_NAME = 0; + // 定义一个整型常量,用于表示在TEXT_FORMAT数组中笔记日期格式模板的索引位置,方便获取对应格式字符串 + private static final int FORMAT_NOTE_DATE = 1; + // 定义一个整型常量,用于表示在TEXT_FORMAT数组中笔记内容格式模板的索引位置,方便获取对应格式字符串 + private static final int FORMAT_NOTE_CONTENT = 2; + + // 用于存储当前的上下文环境(Context),通过它可以访问Android系统的各种资源、服务等,方便与系统进行交互操作,在构造函数中初始化 private Context mContext; + // 用于存储导出的文本文件的文件名,初始化为空字符串,后续会根据实际情况赋值 private String mFileName; + // 用于存储导出的文本文件所在的目录路径,初始化为空字符串,后续会根据实际情况赋值 private String mFileDirectory; - // 构造函数 + // 构造函数,用于初始化TextExport对象,从资源中获取文本格式模板字符串数组,同时初始化上下文、文件名和文件目录等属性 public TextExport(Context context) { TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); mContext = context; @@ -102,104 +176,276 @@ public class BackupUtils { mFileDirectory = ""; } - // 获取格式化字符串 + // 根据给定的索引ID获取对应的文本格式模板字符串,用于后续格式化输出文本内容,实际就是从TEXT_FORMAT数组中根据索引获取相应元素 private String getFormat(int id) { return TEXT_FORMAT[id]; } - // 导出文件夹到文本 + /** + * Export the folder identified by folder id to text + * 将由文件夹ID标识的文件夹中的笔记数据导出为文本格式,通过查询该文件夹下的笔记及对应的数据,然后按照一定格式输出到指定的输出流(PrintStream)中 + */ private void exportFolderToText(String folderId, PrintStream ps) { - // 查询属于该文件夹的笔记 - } + // 使用ContentResolver查询属于该文件夹的所有笔记信息,传入笔记内容的Uri(Notes.CONTENT_NOTE_URI)、要查询的列名列表(NOTE_PROJECTION)以及通过文件夹ID筛选的条件(NoteColumns.PARENT_ID + "=?" 及对应的文件夹ID参数)等参数 + Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { + folderId + }, null); - // 导出笔记到文本 - private void exportNoteToText(String noteId, PrintStream ps) { - // 查询属于该笔记的数据 + if (notesCursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则进入循环遍历游标中的每一行数据 + if (notesCursor.moveToFirst()) { + do { + // 使用指定的日期格式模板格式化笔记的最后修改日期,并输出到指定的输出流(PrintStream)中,通过String.format方法结合获取到的格式模板和格式化后的日期数据进行输出 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 获取当前笔记的ID,用于后续查询该笔记对应的详细数据信息 + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + // 调用exportNoteToText方法将该笔记的详细数据信息导出为文本格式并输出到指定的输出流(PrintStream)中 + exportNoteToText(noteId, ps); + } while (notesCursor.moveToNext()); + } + // 关闭游标,释放相关资源,因为已经获取完需要的数据了 + notesCursor.close(); + } } - // 导出笔记数据到文本 - public int exportToText() { - // 检查外部存储是否可用 - if (!externalStorageAvailable()) { - return STATE_SD_CARD_UNMOUONTED; - } + /** + * Export note identified by id to a print stream + * 将由笔记ID标识的笔记数据导出为文本格式,并输出到指定的输出流(PrintStream)中,通过查询该笔记对应的详细数据信息,然后按照一定格式进行输出 + */ + private void exportNoteToText(String noteId, PrintStream ps) { + // 使用ContentResolver查询属于该笔记的所有数据信息,传入笔记数据内容的Uri(Notes.CONTENT_DATA_URI)、要查询的列名列表(DATA_PROJECTION)以及通过笔记ID筛选的条件(DataColumns.NOTE_ID + "=?" 及对应的笔记ID参数)等参数 + Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, + DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { + noteId + }, null); - PrintStream ps = getExportToTextPrintStream(); - if (ps == null) { - return STATE_SYSTEM_ERROR; - } - // 导出文件夹和笔记 - Cursor folderCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " - + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " - + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); - - if (folderCursor != null) { - if (folderCursor.moveToFirst()) { + if (dataCursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则进入循环遍历游标中的每一行数据 + if (dataCursor.moveToFirst()) { do { - String folderName = ""; - if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { - folderName = mContext.getString(R.string.call_record_folder_name); - } else { - folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); - } - if (!TextUtils.isEmpty(folderName)) { - ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); + // 从游标中获取笔记数据的MIME类型列的数据(表示数据的格式类型,比如文本、呼叫记录等类型) + String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); + if (DataConstants.CALL_NOTE.equals(mimeType)) { + // 如果类型是呼叫记录笔记类型(DataConstants.CALL_NOTE),则从游标中获取电话号码列的数据,并输出到指定的输出流(PrintStream)中, + // 使用指定的笔记内容格式模板进行格式化输出,前提是电话号码不为空 + String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); + long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); + String location = dataCursor.getString(DATA_COLUMN_CONTENT); + + if (!TextUtils.isEmpty(phoneNumber)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + phoneNumber)); + } + // 从游标中获取呼叫日期列的数据,并输出到指定的输出流(PrintStream)中, + // 使用指定的笔记内容格式模板进行格式化输出 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // 从游标中获取呼叫附件位置列的数据(如果有),并输出到指定的输出流(PrintStream)中, + // 使用指定的笔记内容格式模板进行格式化输出,前提是该位置信息不为空 + if (!TextUtils.isEmpty(location)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + location)); + } + } else if (DataConstants.NOTE.equals(mimeType)) { + // 如果类型是普通笔记类型(DataConstants.NOTE),则从游标中获取笔记内容列的数据,并输出到指定的输出流(PrintStream)中, + // 使用指定的笔记内容格式模板进行格式化输出,前提是笔记内容不为空 + String content = dataCursor.getString(DATA_COLUMN_CONTENT); + if (!TextUtils.isEmpty(content)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), + content)); + } } - String folderId = folderCursor.getString(NOTE_COLUMN_ID); - exportFolderToText(folderId, ps); - } while (folderCursor.moveToNext()); + } while (dataCursor.moveToNext()); } - folderCursor.close(); + // 关闭游标,释放相关资源,因为已经获取完需要的数据了 + dataCursor.close(); } + } + } +} + } while (dataCursor.moveToNext()); + } + // 关闭游标,释放相关资源,因为已经获取完当前笔记对应的数据信息了 + dataCursor.close(); + } + // print a line separator between note + // 尝试向输出流(PrintStream)中写入换行分隔符(通过写入对应字符的字节形式),用于在不同笔记内容之间进行分隔,使导出的文本更易读 + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER +}); + } catch (IOException e) { + // 如果在写入换行分隔符时出现IO异常,记录错误日志(将异常信息输出到日志中,方便排查问题) + Log.e(TAG, e.toString()); + } + } - Cursor noteCursor = mContext.getContentResolver().query( - Notes.CONTENT_NOTE_URI, - NOTE_PROJECTION, - NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID - + "=0", null, null); +/** + * Note will be exported as text which is user readable + * 将笔记导出为用户可读的文本格式,在这个方法中完成整个导出流程,包括检查外部存储是否可用、获取输出流、查询并导出不同类型笔记等操作,并返回导出操作的状态码 + */ +public int exportToText() { + // 调用externalStorageAvailable方法判断外部存储(如SD卡等)是否可用,如果不可用 + if (!externalStorageAvailable()) { + // 记录调试日志,提示媒体(外部存储设备)未挂载情况 + Log.d(TAG, "Media was not mounted"); + // 返回表示外部存储未挂载的状态码,表明当前无法进行导出操作,因为没有可用的存储位置 + return STATE_SD_CARD_UNMOUONTED; + } - if (noteCursor != null) { - if (noteCursor.moveToFirst()) { - do { - ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( - mContext.getString(R.string.format_datetime_mdhm), - noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); - String noteId = noteCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); - } while (noteCursor.moveToNext()); - } - noteCursor.close(); - } - ps.close(); + // 调用getExportToTextPrintStream方法获取用于将笔记数据输出为文本的打印流(PrintStream)对象,如果获取失败(返回null) + PrintStream ps = getExportToTextPrintStream(); + if (ps == null) { + // 记录错误日志,提示获取打印流出现错误情况 + Log.e(TAG, "get print stream error"); + // 返回表示系统错误的状态码,说明在获取输出流这个环节出现问题,导致导出操作无法正常进行 + return STATE_SYSTEM_ERROR; + } + // First export folder and its notes + // 使用ContentResolver查询需要导出的文件夹及其中笔记的信息,筛选条件比较复杂,主要是获取特定类型的文件夹(普通文件夹且非回收站文件夹,以及呼叫记录文件夹)及其包含的笔记信息 + Cursor folderCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " + + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); - return STATE_SUCCESS; + if (folderCursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则进入循环遍历游标中的每一行数据 + if (folderCursor.moveToFirst()) { + do { + // 初始化文件夹名称为空字符串,后续根据不同情况获取并赋值实际的文件夹名称 + String folderName = ""; + // 如果当前文件夹的ID等于呼叫记录文件夹的ID(Notes.ID_CALL_RECORD_FOLDER),则从资源中获取对应的字符串资源(呼叫记录文件夹名称)赋值给folderName变量 + if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { + folderName = mContext.getString(R.string.call_record_folder_name); + } else { + // 否则,从游标中获取文件夹摘要列的数据作为文件夹名称(一般情况的文件夹名称获取方式) + folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); + } + // 判断文件夹名称不为空字符串时,使用指定的文件夹名称格式模板格式化文件夹名称,并输出到打印流(PrintStream)中 + if (!TextUtils.isEmpty(folderName)) { + ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); + } + // 获取当前文件夹的ID,用于后续调用exportFolderToText方法导出该文件夹下的笔记数据 + String folderId = folderCursor.getString(NOTE_COLUMN_ID); + exportFolderToText(folderId, ps); + } while (folderCursor.moveToNext()); } + // 关闭游标,释放相关资源,因为已经获取完需要的文件夹及笔记相关数据了 + folderCursor.close(); + } - // 获取导出到文本的打印流 - private PrintStream getExportToTextPrintStream() { - File file = generateFileMountedOnSDcard(mContext, R.string.file_path, - R.string.file_name_txt_format); - if (file == null) { - return null; - } - mFileName = file.getName(); - mFileDirectory = mContext.getString(R.string.file_path); - PrintStream ps = null; - try { - FileOutputStream fos = new FileOutputStream(file); - ps = new PrintStream(fos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (NullPointerException e) { - e.printStackTrace(); - } - return ps; + // Export notes in root's folder + // 使用ContentResolver查询根文件夹下的笔记信息,筛选条件是类型为普通笔记(Notes.TYPE_NOTE)且父文件夹ID为0(表示根文件夹下)的笔记 + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + + "=0", null, null); + + if (noteCursor!= null) { + // 判断游标是否有数据,如果游标可以移动到第一条数据(即有查询到的数据),则进入循环遍历游标中的每一行数据 + if (noteCursor.moveToFirst()) { + do { + // 使用指定的笔记日期格式模板格式化笔记的最后修改日期,并输出到打印流(PrintStream)中 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 获取当前笔记的ID,用于后续调用exportNoteToText方法导出该笔记的详细数据信息 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); } + // 关闭游标,释放相关资源,因为已经获取完需要的根文件夹下笔记相关数据了 + noteCursor.close(); + } + // 关闭打印流,释放相关资源,完成整个笔记数据导出到文本文件的操作 + ps.close(); + + // 返回表示导出操作成功的状态码,说明整个导出流程顺利完成,笔记数据已成功导出为文本格式 + return STATE_SUCCESS; +} + +/** + * Get a print stream pointed to the file {@generateExportedTextFile} + * 获取一个指向由{@generateExportedTextFile}方法生成的文件的打印流(PrintStream)对象,用于后续向该文件中写入导出的笔记文本数据,如果获取失败则返回null + */ +private PrintStream getExportToTextPrintStream() { + // 调用generateFileMountedOnSDcard方法在外部存储(SD卡等)上生成用于存储导出文本数据的文件对象,如果生成失败(返回null) + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + if (file == null) { + // 记录错误日志,提示创建用于导出的文件失败情况 + Log.e(TAG, "create file to exported failed"); + return null; + } + // 将生成的文件的名称赋值给mFileName属性,用于后续可能的获取文件名相关操作 + mFileName = file.getName(); + // 将文件所在的目录路径(从资源中获取的固定路径字符串)赋值给mFileDirectory属性,用于后续可能的获取文件目录相关操作 + mFileDirectory = mContext.getString(R.string.file_path); + PrintStream ps = null; + try { + // 创建一个基于生成的文件对象的文件输出流(FileOutputStream),用于后续向文件中写入数据 + FileOutputStream fos = new FileOutputStream(file); + // 使用文件输出流创建一个打印流(PrintStream)对象,通过这个对象可以方便地将格式化后的文本数据写入到文件中 + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + // 如果在创建文件输出流时出现文件不存在的异常(比如文件路径不可写、文件不存在且无法创建等原因),打印异常堆栈信息,方便排查问题,并返回null表示获取打印流失败 + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + // 如果出现空指针异常(比如传入的文件对象为null等情况),打印异常堆栈信息,方便排查问题,并返回null表示获取打印流失败 + e.printStackTrace(); + return null; } + return ps; +} + } + +/** + * Generate the text file to store imported data + * 在外部存储(SD卡等)上生成用于存储导入数据的文本文件,包括创建文件所在的目录(如果不存在)以及文件本身(如果不存在),并返回生成的文件对象,如果生成失败则返回null + */ +private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + // 在StringBuilder中添加外部存储的根目录路径(通过Environment.getExternalStorageDirectory获取) + sb.append(Environment.getExternalStorageDirectory()); + // 接着添加从资源中获取的文件路径字符串,拼接出完整的文件目录路径 + sb.append(context.getString(filePathResId)); + // 根据拼接好的路径字符串创建一个File对象,表示文件所在的目录对象 + File filedir = new File(sb.toString()); + // 在StringBuilder中继续添加文件名相关内容,文件名通过资源中获取的格式化字符串结合当前系统时间进行格式化生成(使用DateFormat.format按照指定格式生成包含日期的文件名部分) + sb.append(context.getString( + fileNameFormatResId, + DateFormat.format(context.getString(R.string.format_date_ymd), + System.currentTimeMillis()))); + // 根据最终拼接好的完整路径字符串创建一个File对象,表示要生成的文件对象 + File file = new File(sb.toString()); - // 在SD卡上生成用于存储导入数据的文本文件 - private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { - // ... + try { + // 判断文件所在的目录是否不存在,如果不存在则创建该目录 + if (!filedir.exists()) { + filedir.mkdir(); + } + // 判断文件是否不存在,如果不存在则创建新的文件 + if (!file.exists()) { + file.createNewFile(); + } + // 返回生成的文件对象,用于后续操作(如获取输出流向文件中写入数据等) + return file; + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; } -} \ No newline at end of file +} + + diff --git a/app/src/main/java/net/micode/notes/tool/DataUtils.java b/app/src/main/java/net/micode/notes/tool/DataUtils.java index 20e9458..2a14982 100644 --- a/app/src/main/java/net/micode/notes/tool/DataUtils.java +++ b/app/src/main/java/net/micode/notes/tool/DataUtils.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.tool; @@ -23,19 +34,20 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import java.util.ArrayList; import java.util.HashSet; -public class DataUtils { - public static final String TAG = "DataUtils"; // 日志标签 - // 批量删除笔记 +public class DataUtils { + public static final String TAG = "DataUtils"; public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { - // 如果id集合为空或大小为0,返回true - if (ids == null || ids.size() == 0) { - Log.d(TAG, "the ids is null or empty"); + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); return true; } - // 创建操作列表 - ArrayList operationList = new ArrayList<>(); + ArrayList operationList = new ArrayList(); for (long id : ids) { if(id == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Don't delete system folder root"); @@ -46,7 +58,6 @@ public class DataUtils { operationList.add(builder.build()); } try { - // 执行批量操作 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); if (results == null || results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); @@ -61,7 +72,6 @@ public class DataUtils { return false; } - // 将笔记移动到指定文件夹 public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { ContentValues values = new ContentValues(); values.put(NoteColumns.PARENT_ID, desFolderId); @@ -70,16 +80,14 @@ public class DataUtils { resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); } - // 批量将笔记移动到指定文件夹 - public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, long folderId) { - // 如果id集合为空,返回true + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, + long folderId) { if (ids == null) { Log.d(TAG, "the ids is null"); return true; } - // 创建操作列表 - ArrayList operationList = new ArrayList<>(); + ArrayList operationList = new ArrayList(); for (long id : ids) { ContentProviderOperation.Builder builder = ContentProviderOperation .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); @@ -89,10 +97,9 @@ public class DataUtils { } try { - // 执行批量操作 ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); if (results == null || results.length == 0 || results[0] == null) { - Log.d(TAG, "move notes to folder failed, ids:" + ids.toString()); + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; } return true; @@ -104,16 +111,19 @@ public class DataUtils { return false; } - // 获取用户文件夹数量(不包括系统文件夹) + /** + * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} + */ public static int getUserFolderCount(ContentResolver resolver) { - Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, new String[] { "COUNT(*)" }, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, null); + int count = 0; - if (cursor != null) { - if (cursor.moveToFirst()) { + if(cursor != null) { + if(cursor.moveToFirst()) { try { count = cursor.getInt(0); } catch (IndexOutOfBoundsException e) { @@ -126,13 +136,13 @@ public class DataUtils { return count; } - // 检查笔记在数据库中是否可见(不是垃圾箱中的笔记) public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, new String [] {String.valueOf(type)}, null); + boolean exist = false; if (cursor != null) { if (cursor.getCount() > 0) { @@ -143,10 +153,10 @@ public class DataUtils { return exist; } - // 检查笔记是否存在于数据库中 public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null, null, null, null); + boolean exist = false; if (cursor != null) { if (cursor.getCount() > 0) { @@ -157,10 +167,10 @@ public class DataUtils { return exist; } - // 检查数据是否存在于数据库中 public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null, null, null, null); + boolean exist = false; if (cursor != null) { if (cursor.getCount() > 0) { @@ -171,16 +181,15 @@ public class DataUtils { return exist; } - // 检查文件夹名称是否已存在 public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.SNIPPET + "=?", + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", new String[] { name }, null); boolean exist = false; - if (cursor != null) { - if (cursor.getCount() > 0) { + if(cursor != null) { + if(cursor.getCount() > 0) { exist = true; } cursor.close(); @@ -188,13 +197,13 @@ public class DataUtils { return exist; } - // 获取文件夹中笔记的小部件属性 public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, NoteColumns.PARENT_ID + "=?", new String[] { String.valueOf(folderId) }, null); + HashSet set = null; if (c != null) { if (c.moveToFirst()) { @@ -215,13 +224,13 @@ public class DataUtils { return set; } - // 根据笔记ID获取通话记录号码 public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, new String [] { CallNote.PHONE_NUMBER }, CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, null); + if (cursor != null && cursor.moveToFirst()) { try { return cursor.getString(0); @@ -234,4 +243,53 @@ public class DataUtils { return ""; } -// 根据电话号码 \ No newline at end of file + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.NOTE_ID }, + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + } + } + cursor.close(); + } + return 0; + } + + public static String getSnippetById(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String [] { NoteColumns.SNIPPET }, + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); + return snippet; + } + throw new IllegalArgumentException("Note is not found with id: " + noteId); + } + + public static String getFormattedSnippet(String snippet) { + if (snippet != null) { + snippet = snippet.trim(); + int index = snippet.indexOf('\n'); + if (index != -1) { + snippet = snippet.substring(0, index); + } + } + return snippet; + } +} diff --git a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java index 71934db..666b729 100644 --- a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java +++ b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java @@ -1,69 +1,113 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.tool; public class GTaskStringUtils { - // Google Tasks API中使用的JSON字段常量 - // 动作ID public final static String GTASK_JSON_ACTION_ID = "action_id"; - // 动作列表 + public final static String GTASK_JSON_ACTION_LIST = "action_list"; - // 动作类型 + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; - // 创建动作 + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; - // 获取所有动作 + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; - // 移动动作 + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; - // 更新动作 + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; - // 创建者ID + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; - // 子实体 + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; - // 客户端版本 + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; - // 完成状态 + public final static String GTASK_JSON_COMPLETED = "completed"; - // 当前列表ID + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; - // 默认列表ID + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; - // 已删除标记 + public final static String GTASK_JSON_DELETED = "deleted"; - // 目标列表 + public final static String GTASK_JSON_DEST_LIST = "dest_list"; - // 目标父实体 + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; - // 目标父实体类型 + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; - // 实体变化 + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; - // 实体类型 + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; - // 获取已删除任务 + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; - // ID + public final static String GTASK_JSON_ID = "id"; - // 索引 + public final static String GTASK_JSON_INDEX = "index"; - // 最后修改时间 + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; - // 最后同步点 + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; - // 列表ID + public final static String GTASK_JSON_LIST_ID = "list_id"; - // 列表数组 + public final static String GTASK_JSON_LISTS = "lists"; - // 名称 + public final static String GTASK_JSON_NAME = "name"; - // 新ID + public final static String GTASK_JSON_NEW_ID = "new_id"; - // 笔记 + public final static String GTASK_JSON_NOTES = "notes"; -// 父ID \ No newline at end of file + + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + + public final static String GTASK_JSON_RESULTS = "results"; + + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + + public final static String GTASK_JSON_TASKS = "tasks"; + + public final static String GTASK_JSON_TYPE = "type"; + + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + + public final static String GTASK_JSON_USER = "user"; + + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + + public final static String FOLDER_DEFAULT = "Default"; + + public final static String FOLDER_CALL_NOTE = "Call_Note"; + + public final static String FOLDER_META = "METADATA"; + + public final static String META_HEAD_GTASK_ID = "meta_gid"; + + public final static String META_HEAD_NOTE = "meta_note"; + + public final static String META_HEAD_DATA = "meta_data"; + + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; + +} diff --git a/app/src/main/java/net/micode/notes/tool/ResourceParser.java b/app/src/main/java/net/micode/notes/tool/ResourceParser.java index 1242010..1ad3ad6 100644 --- a/app/src/main/java/net/micode/notes/tool/ResourceParser.java +++ b/app/src/main/java/net/micode/notes/tool/ResourceParser.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package net.micode.notes.tool; import android.content.Context; @@ -21,83 +22,49 @@ import android.preference.PreferenceManager; import net.micode.notes.R; import net.micode.notes.ui.NotesPreferenceActivity; -/** - * ResourceParser类用于管理应用程序中的资源,包括背景颜色、文本大小等。 - */ public class ResourceParser { - /** - * 定义颜色常量。 - */ public static final int YELLOW = 0; public static final int BLUE = 1; public static final int WHITE = 2; public static final int GREEN = 3; public static final int RED = 4; - /** - * 默认背景颜色。 - */ public static final int BG_DEFAULT_COLOR = YELLOW; - /** - * 定义文本大小常量。 - */ public static final int TEXT_SMALL = 0; public static final int TEXT_MEDIUM = 1; public static final int TEXT_LARGE = 2; public static final int TEXT_SUPER = 3; - /** - * 默认文本大小。 - */ public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; - /** - * NoteBgResources内部类用于管理笔记背景资源。 - */ public static class NoteBgResources { - /** - * 编辑模式下不同颜色的背景资源ID。 - */ private final static int [] BG_EDIT_RESOURCES = new int [] { - R.drawable.edit_yellow, - R.drawable.edit_blue, - R.drawable.edit_white, - R.drawable.edit_green, - R.drawable.edit_red + R.drawable.edit_yellow, + R.drawable.edit_blue, + R.drawable.edit_white, + R.drawable.edit_green, + R.drawable.edit_red }; - /** - * 编辑模式下不同颜色的标题背景资源ID。 - */ private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { - R.drawable.edit_title_yellow, - R.drawable.edit_title_blue, - R.drawable.edit_title_white, - R.drawable.edit_title_green, - R.drawable.edit_title_red + R.drawable.edit_title_yellow, + R.drawable.edit_title_blue, + R.drawable.edit_title_white, + R.drawable.edit_title_green, + R.drawable.edit_title_red }; - /** - * 根据ID返回编辑模式下的背景资源ID。 - */ public static int getNoteBgResource(int id) { return BG_EDIT_RESOURCES[id]; } - /** - * 根据ID返回编辑模式下的标题背景资源ID。 - */ public static int getNoteTitleBgResource(int id) { return BG_EDIT_TITLE_RESOURCES[id]; } } - /** - * 根据用户在偏好设置中的选择返回默认的背景颜色ID。 - * 如果用户设置了背景颜色,则随机返回一个背景颜色ID;否则返回默认背景颜色ID。 - */ public static int getDefaultBgId(Context context) { if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { @@ -107,148 +74,108 @@ public class ResourceParser { } } - /** - * NoteItemBgResources内部类用于管理笔记项背景资源。 - */ public static class NoteItemBgResources { - /** - * 列表中不同位置的背景资源ID。 - */ private final static int [] BG_FIRST_RESOURCES = new int [] { - R.drawable.list_yellow_up, - R.drawable.list_blue_up, - R.drawable.list_white_up, - R.drawable.list_green_up, - R.drawable.list_red_up + R.drawable.list_yellow_up, + R.drawable.list_blue_up, + R.drawable.list_white_up, + R.drawable.list_green_up, + R.drawable.list_red_up }; + private final static int [] BG_NORMAL_RESOURCES = new int [] { - R.drawable.list_yellow_middle, - R.drawable.list_blue_middle, - R.drawable.list_white_middle, - R.drawable.list_green_middle, - R.drawable.list_red_middle + R.drawable.list_yellow_middle, + R.drawable.list_blue_middle, + R.drawable.list_white_middle, + R.drawable.list_green_middle, + R.drawable.list_red_middle }; + private final static int [] BG_LAST_RESOURCES = new int [] { - R.drawable.list_yellow_down, - R.drawable.list_blue_down, - R.drawable.list_white_down, - R.drawable.list_green_down, - R.drawable.list_red_down, + R.drawable.list_yellow_down, + R.drawable.list_blue_down, + R.drawable.list_white_down, + R.drawable.list_green_down, + R.drawable.list_red_down, }; + private final static int [] BG_SINGLE_RESOURCES = new int [] { - R.drawable.list_yellow_single, - R.drawable.list_blue_single, - R.drawable.list_white_single, - R.drawable.list_green_single, - R.drawable.list_red_single + R.drawable.list_yellow_single, + R.drawable.list_blue_single, + R.drawable.list_white_single, + R.drawable.list_green_single, + R.drawable.list_red_single }; - /** - * 根据ID返回列表中第一项的背景资源ID。 - */ public static int getNoteBgFirstRes(int id) { return BG_FIRST_RESOURCES[id]; } - /** - * 根据ID返回列表中最后一项的背景资源ID。 - */ public static int getNoteBgLastRes(int id) { return BG_LAST_RESOURCES[id]; } - /** - * 根据ID返回列表中单项的背景资源ID。 - */ public static int getNoteBgSingleRes(int id) { return BG_SINGLE_RESOURCES[id]; } - /** - * 根据ID返回列表中普通项的背景资源ID。 - */ public static int getNoteBgNormalRes(int id) { return BG_NORMAL_RESOURCES[id]; } - /** - * 返回文件夹背景资源ID。 - */ public static int getFolderBgRes() { return R.drawable.list_folder; } } - /** - * WidgetBgResources内部类用于管理小部件背景资源。 - */ public static class WidgetBgResources { - /** - * 2x小部件不同颜色的背景资源ID。 - */ private final static int [] BG_2X_RESOURCES = new int [] { - R.drawable.widget_2x_yellow, - R.drawable.widget_2x_blue, - R.drawable.widget_2x_white, - R.drawable.widget_2x_green, - R.drawable.widget_2x_red, + R.drawable.widget_2x_yellow, + R.drawable.widget_2x_blue, + R.drawable.widget_2x_white, + R.drawable.widget_2x_green, + R.drawable.widget_2x_red, }; - /** - * 根据ID返回2x小部件的背景资源ID。 - */ public static int getWidget2xBgResource(int id) { return BG_2X_RESOURCES[id]; } - /** - * 4x小部件不同颜色的背景资源ID。 - */ private final static int [] BG_4X_RESOURCES = new int [] { - R.drawable.widget_4x_yellow, - R.drawable.widget_4x_blue, - R.drawable.widget_4x_white, - R.drawable.widget_4x_green, - R.drawable.widget_4x_red + R.drawable.widget_4x_yellow, + R.drawable.widget_4x_blue, + R.drawable.widget_4x_white, + R.drawable.widget_4x_green, + R.drawable.widget_4x_red }; - /** - * 根据ID返回4x小部件的背景资源ID。 - */ public static int getWidget4xBgResource(int id) { return BG_4X_RESOURCES[id]; } } - /** - * TextAppearanceResources内部类用于管理文本外观资源。 - */ public static class TextAppearanceResources { - /** - * 不同大小的文本样式资源ID。 - */ private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { - R.style.TextAppearanceNormal, - R.style.TextAppearanceMedium, - R.style.TextAppearanceLarge, - R.style.TextAppearanceSuper + R.style.TextAppearanceNormal, + R.style.TextAppearanceMedium, + R.style.TextAppearanceLarge, + R.style.TextAppearanceSuper }; - /** - * 根据ID返回文本样式资源ID。如果ID超出范围,返回默认文本大小ID。 - */ public static int getTexAppearanceResource(int id) { + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ if (id >= TEXTAPPEARANCE_RESOURCES.length) { return BG_DEFAULT_FONT_SIZE; } return TEXTAPPEARANCE_RESOURCES[id]; } - /** - * 返回文本样式资源数组的长度。 - */ public static int getResourcesSize() { return TEXTAPPEARANCE_RESOURCES.length; } } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java index 074417e..85723be 100644 --- a/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java +++ b/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -1,25 +1,56 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; -// 导入所需的Android类和接口 +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; + +import java.io.IOException; + public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { - // 类成员变量 - private long mNoteId; // 笔记ID - private String mSnippet; // 笔记摘要 - private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要的最大长度 - MediaPlayer mPlayer; // 用于播放声音的MediaPlayer对象 + private long mNoteId; + private String mSnippet; + private static final int SNIPPET_PREW_MAX_LEN = 60; + MediaPlayer mPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题栏的窗口特性 + requestWindowFeature(Window.FEATURE_NO_TITLE); - // 设置窗口参数,确保提醒时屏幕是亮的 final Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); @@ -30,13 +61,11 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); } - // 获取启动Activity的Intent Intent intent = getIntent(); try { - mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 获取笔记ID - mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 获取笔记摘要 - // 如果摘要超过最大长度,则截断并添加提示 + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) : mSnippet; @@ -45,26 +74,23 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD return; } - mPlayer = new MediaPlayer(); // 初始化MediaPlayer对象 - // 如果数据库中存在该笔记,则显示操作对话框并播放提醒声音 + mPlayer = new MediaPlayer(); if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { showActionDialog(); playAlarmSound(); } else { - finish(); // 如果不存在,则结束Activity + finish(); } } - // 检查屏幕是否亮着 private boolean isScreenOn() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); return pm.isScreenOn(); } - // 播放提醒声音 private void playAlarmSound() { Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); - // 设置MediaPlayer的声音流类型 + int silentModeStreams = Settings.System.getInt(getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); @@ -74,38 +100,40 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } try { - mPlayer.setDataSource(this, url); // 设置数据源 - mPlayer.prepare(); // 准备播放 - mPlayer.setLooping(true); // 设置循环播放 - mPlayer.start(); // 开始播放 + mPlayer.setDataSource(this, url); + mPlayer.prepare(); + mPlayer.setLooping(true); + mPlayer.start(); } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { + // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { + // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { + // TODO Auto-generated catch block e.printStackTrace(); } } - // 显示操作对话框 private void showActionDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); - dialog.setTitle(R.string.app_name); // 设置对话框标题 - dialog.setMessage(mSnippet); // 设置对话框消息 - dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮 + dialog.setTitle(R.string.app_name); + dialog.setMessage(mSnippet); + dialog.setPositiveButton(R.string.notealert_ok, this); if (isScreenOn()) { - dialog.setNegativeButton(R.string.notealert_enter, this); // 设置进入按钮 + dialog.setNegativeButton(R.string.notealert_enter, this); } - dialog.show().setOnDismissListener(this); // 显示对话框并设置消失监听器 + dialog.show().setOnDismissListener(this); } - // 实现OnClickListener接口的方法,处理按钮点击事件 public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_NEGATIVE: - Intent intent = new Intent(this, NoteEditActivity.class); // 进入编辑笔记的Activity + Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, mNoteId); startActivity(intent); @@ -115,18 +143,16 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD } } - // 实现OnDismissListener接口的方法,处理对话框消失事件 public void onDismiss(DialogInterface dialog) { - stopAlarmSound(); // 停止提醒声音 - finish(); // 结束Activity + stopAlarmSound(); + finish(); } - // 停止提醒声音 private void stopAlarmSound() { if (mPlayer != null) { - mPlayer.stop(); // 停止播放 - mPlayer.release(); // 释放资源 + mPlayer.stop(); + mPlayer.release(); mPlayer = null; } } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java index 8fe640e..f221202 100644 --- a/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java +++ b/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -16,53 +27,39 @@ import android.database.Cursor; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; + public class AlarmInitReceiver extends BroadcastReceiver { - // 定义查询数据库时需要的列 private static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE + NoteColumns.ID, + NoteColumns.ALERTED_DATE }; - // 定义列索引 private static final int COLUMN_ID = 0; private static final int COLUMN_ALERTED_DATE = 1; - // 当接收到广播时触发的方法 @Override public void onReceive(Context context, Intent intent) { - // 获取当前日期时间 long currentDate = System.currentTimeMillis(); - // 查询数据库中所有未提醒且类型为笔记的记录 Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, new String[] { String.valueOf(currentDate) }, null); - // 如果查询结果不为空 if (c != null) { - // 如果查询结果至少有一条记录 if (c.moveToFirst()) { - // 遍历查询结果 do { - // 获取提醒日期 long alertDate = c.getLong(COLUMN_ALERTED_DATE); - // 创建意图,用于触发AlarmReceiver Intent sender = new Intent(context, AlarmReceiver.class); - // 设置数据URI,传递笔记ID sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); - // 创建PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - // 获取AlarmManager服务 AlarmManager alermManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); - // 设置闹钟,使用RTC_WAKEUP模式 alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); } while (c.moveToNext()); } - // 关闭游标 c.close(); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java index 056573a..54e503b 100644 --- a/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java +++ b/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -10,14 +21,10 @@ import android.content.Context; import android.content.Intent; public class AlarmReceiver extends BroadcastReceiver { - // 当接收到广播时触发的方法 @Override public void onReceive(Context context, Intent intent) { - // 设置意图,指定启动AlarmAlertActivity intent.setClass(context, AlarmAlertActivity.class); - // 为意图添加FLAG_ACTIVITY_NEW_TASK标志,允许在没有栈的情况下启动活动 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - // 使用context启动AlarmAlertActivity context.startActivity(intent); } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java b/app/src/main/java/net/micode/notes/ui/DateTimePicker.java index 66f72ec..496b0cd 100644 --- a/app/src/main/java/net/micode/notes/ui/DateTimePicker.java +++ b/app/src/main/java/net/micode/notes/ui/DateTimePicker.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -10,6 +21,7 @@ import java.util.Calendar; import net.micode.notes.R; + import android.content.Context; import android.text.format.DateFormat; import android.view.View; @@ -17,32 +29,140 @@ import android.widget.FrameLayout; import android.widget.NumberPicker; public class DateTimePicker extends FrameLayout { - // 类成员变量和常量定义 - private final NumberPicker mDateSpinner; // 日期选择器 - private final NumberPicker mHourSpinner; // 小时选择器 - private final NumberPicker mMinuteSpinner; // 分钟选择器 - private final NumberPicker mAmPmSpinner; // 上下午选择器 - private Calendar mDate; // 日期和时间的Calendar实例 + private static final boolean DEFAULT_ENABLE_STATE = true; + + private static final int HOURS_IN_HALF_DAY = 12; + private static final int HOURS_IN_ALL_DAY = 24; + private static final int DAYS_IN_ALL_WEEK = 7; + private static final int DATE_SPINNER_MIN_VAL = 0; + private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; + private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; + private static final int MINUT_SPINNER_MIN_VAL = 0; + private static final int MINUT_SPINNER_MAX_VAL = 59; + private static final int AMPM_SPINNER_MIN_VAL = 0; + private static final int AMPM_SPINNER_MAX_VAL = 1; - // 各种选择器的显示值数组 + private final NumberPicker mDateSpinner; + private final NumberPicker mHourSpinner; + private final NumberPicker mMinuteSpinner; + private final NumberPicker mAmPmSpinner; + private Calendar mDate; private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; - private boolean mIsAm; // 标记是否为上午 - private boolean mIs24HourView; // 标记是否为24小时制视图 - private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 标记组件是否启用 - private boolean mInitialising; // 标记组件是否在初始化中 + private boolean mIsAm; + + private boolean mIs24HourView; + + private boolean mIsEnabled = DEFAULT_ENABLE_STATE; + + private boolean mInitialising; + + private OnDateTimeChangedListener mOnDateTimeChangedListener; + + private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); + updateDateControl(); + onDateTimeChanged(); + } + }; + + private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + boolean isDateChanged = false; + Calendar cal = Calendar.getInstance(); + if (!mIs24HourView) { + if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || + oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + mIsAm = !mIsAm; + updateAmPmControl(); + } + } else { + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + } + int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); + mDate.set(Calendar.HOUR_OF_DAY, newHour); + onDateTimeChanged(); + if (isDateChanged) { + setCurrentYear(cal.get(Calendar.YEAR)); + setCurrentMonth(cal.get(Calendar.MONTH)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + int minValue = mMinuteSpinner.getMinValue(); + int maxValue = mMinuteSpinner.getMaxValue(); + int offset = 0; + if (oldVal == maxValue && newVal == minValue) { + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + offset -= 1; + } + if (offset != 0) { + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl(); + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + updateAmPmControl(); + } else { + mIsAm = true; + updateAmPmControl(); + } + } + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + }; - // 内部接口,用于通知日期时间改变的监听器 + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; public interface OnDateTimeChangedListener { void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute); + int dayOfMonth, int hourOfDay, int minute); } - // 构造函数和初始化代码 - public DateTimePicker(Context context) { this(context, System.currentTimeMillis()); } @@ -53,41 +173,313 @@ public class DateTimePicker extends FrameLayout { public DateTimePicker(Context context, long date, boolean is24HourView) { super(context); - // 初始化代码... + mDate = Calendar.getInstance(); + mInitialising = true; + mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + inflate(context, R.layout.datetime_picker, this); + + mDateSpinner = (NumberPicker) findViewById(R.id.date); + mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); + mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); + mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + + mHourSpinner = (NumberPicker) findViewById(R.id.hour); + mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); + mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); + mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); + mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); + mMinuteSpinner.setOnLongPressUpdateInterval(100); + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + + String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); + mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); + mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); + mAmPmSpinner.setDisplayedValues(stringsForAmPm); + mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); + + // update controls to initial state + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + set24HourView(is24HourView); + + // set to current time + setCurrentDate(date); + + setEnabled(isEnabled()); + + // set the content descriptions + mInitialising = false; + } + + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) { + return; + } + super.setEnabled(enabled); + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + mIsEnabled = enabled; } - // 设置和获取日期时间的方法 + @Override + public boolean isEnabled() { + return mIsEnabled; + } + /** + * Get the current date in millis + * + * @return the current date in millis + */ public long getCurrentDateInTimeMillis() { return mDate.getTimeInMillis(); } + /** + * Set the current date + * + * @param date The current date in millis + */ public void setCurrentDate(long date) { - // 设置当前日期时间... + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(date); + setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), + cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); + } + + /** + * Set the current date + * + * @param year The current year + * @param month The current month + * @param dayOfMonth The current dayOfMonth + * @param hourOfDay The current hourOfDay + * @param minute The current minute + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * Get current year + * + * @return The current year + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * Set current year + * + * @param year The current year + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * Set current month in the year + * + * @param month The month in the year + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } } - // 其他设置和获取年、月、日、小时、分钟的方法 + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * Set current minute + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } - // 更新选择器显示的方法 + /** + * @return true if this is in 24 hour view else false. + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * Set whether in 24 hour or AM/PM mode. + * + * @param is24HourView True for 24 hour mode. False for AM/PM mode. + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + int hour = getCurrentHourOfDay(); + updateHourControl(); + setCurrentHour(hour); + updateAmPmControl(); + } private void updateDateControl() { - // 更新日期选择器显示... + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); + mDateSpinner.setDisplayedValues(null); + for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { + cal.add(Calendar.DAY_OF_YEAR, 1); + mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); + } + mDateSpinner.setDisplayedValues(mDateDisplayValues); + mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); + mDateSpinner.invalidate(); } private void updateAmPmControl() { - // 更新上下午选择器显示... + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } } private void updateHourControl() { - // 更新小时选择器显示... + if (mIs24HourView) { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + } } - // 内部方法,当日期时间改变时调用 + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } private void onDateTimeChanged() { if (mOnDateTimeChangedListener != null) { - mOnDateTimeChangedListener.onDateTimeChange(this, getCurrentYear(), + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java index da698e4..2c47ba4 100644 --- a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java +++ b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -20,74 +31,60 @@ import android.text.format.DateUtils; public class DateTimePickerDialog extends AlertDialog implements OnClickListener { - private Calendar mDate = Calendar.getInstance(); // 当前日期时间 - private boolean mIs24HourView; // 是否为24小时制视图 - private OnDateTimeSetListener mOnDateTimeSetListener; // 日期时间设置回调 - private DateTimePicker mDateTimePicker; // 日期时间选择器实例 + private Calendar mDate = Calendar.getInstance(); + private boolean mIs24HourView; + private OnDateTimeSetListener mOnDateTimeSetListener; + private DateTimePicker mDateTimePicker; - // 回调接口,用于通知日期时间设置 public interface OnDateTimeSetListener { - void OnDateTimeSet(AlertDialog dialog, long date); // 设置日期时间的方法 + void OnDateTimeSet(AlertDialog dialog, long date); } - // 构造函数,初始化对话框 public DateTimePickerDialog(Context context, long date) { super(context); - mDateTimePicker = new DateTimePicker(context); // 创建日期时间选择器 - setView(mDateTimePicker); // 设置对话框视图为日期时间选择器 - - // 设置日期时间改变的监听器 + mDateTimePicker = new DateTimePicker(context); + setView(mDateTimePicker); mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { public void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute) { - // 更新当前日期时间 + int dayOfMonth, int hourOfDay, int minute) { mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, month); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MINUTE, minute); - updateTitle(mDate.getTimeInMillis()); // 更新对话框标题 + updateTitle(mDate.getTimeInMillis()); } }); - - // 设置初始日期时间 mDate.setTimeInMillis(date); mDate.set(Calendar.SECOND, 0); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); - - // 设置对话框按钮 setButton(context.getString(R.string.datetime_dialog_ok), this); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); - - // 设置24小时制视图 set24HourView(DateFormat.is24HourFormat(this.getContext())); - updateTitle(mDate.getTimeInMillis()); // 初始化对话框标题 + updateTitle(mDate.getTimeInMillis()); } - // 设置24小时制视图 public void set24HourView(boolean is24HourView) { mIs24HourView = is24HourView; } - // 设置日期时间设置的回调 public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mOnDateTimeSetListener = callBack; } - // 更新对话框标题 private void updateTitle(long date) { int flag = - DateUtils.FORMAT_SHOW_YEAR | - DateUtils.FORMAT_SHOW_DATE | - DateUtils.FORMAT_SHOW_TIME; - flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; // 根据24小时制设置标志 - setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); // 格式化并设置标题 + DateUtils.FORMAT_SHOW_YEAR | + DateUtils.FORMAT_SHOW_DATE | + DateUtils.FORMAT_SHOW_TIME; + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); } - // 按钮点击事件处理 public void onClick(DialogInterface arg0, int arg1) { if (mOnDateTimeSetListener != null) { - mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); // 调用回调方法 + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); } } + } \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java index ae333e0..613dc74 100644 --- a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java +++ b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -17,38 +28,34 @@ import android.widget.PopupMenu.OnMenuItemClickListener; import net.micode.notes.R; public class DropdownMenu { - private Button mButton; // 用于触发下拉菜单的按钮 - private PopupMenu mPopupMenu; // 下拉菜单对象 - private Menu mMenu; // 菜单项集合 + private Button mButton; + private PopupMenu mPopupMenu; + private Menu mMenu; - // 构造函数,初始化下拉菜单 public DropdownMenu(Context context, Button button, int menuId) { mButton = button; - mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮背景为下拉图标 - mPopupMenu = new PopupMenu(context, mButton); // 创建PopupMenu实例 - mMenu = mPopupMenu.getMenu(); // 获取菜单 - mPopupMenu.getMenuInflater().inflate(menuId, mMenu); // 填充菜单项 - mButton.setOnClickListener(new OnClickListener() { // 设置按钮点击事件 + mButton.setBackgroundResource(R.drawable.dropdown_icon); + mPopupMenu = new PopupMenu(context, mButton); + mMenu = mPopupMenu.getMenu(); + mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { - mPopupMenu.show(); // 显示下拉菜单 + mPopupMenu.show(); } }); } - // 设置下拉菜单项点击事件的监听器 public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { if (mPopupMenu != null) { - mPopupMenu.setOnMenuItemClickListener(listener); // 设置监听器 + mPopupMenu.setOnMenuItemClickListener(listener); } } - // 根据ID查找菜单项 public MenuItem findItem(int id) { return mMenu.findItem(id); } - // 设置触发下拉菜单的按钮的标题 public void setTitle(CharSequence title) { mButton.setText(title); } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java index c122d0e..96b77da 100644 --- a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java +++ b/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -17,30 +28,26 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; + public class FoldersListAdapter extends CursorAdapter { - // 定义查询数据库时需要的列 public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET + NoteColumns.ID, + NoteColumns.SNIPPET }; - // 定义列索引 public static final int ID_COLUMN = 0; public static final int NAME_COLUMN = 1; - // 构造函数,初始化适配器 public FoldersListAdapter(Context context, Cursor c) { super(context, c); // TODO Auto-generated constructor stub } - // 创建新的列表项视图 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new FolderListItem(context); } - // 绑定数据到列表项视图 @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof FolderListItem) { @@ -50,14 +57,12 @@ public class FoldersListAdapter extends CursorAdapter { } } - // 获取文件夹名称 public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); } - // 内部类,定义列表项的布局和行为 private class FolderListItem extends LinearLayout { private TextView mName; @@ -71,4 +76,5 @@ public class FoldersListAdapter extends CursorAdapter { mName.setText(name); } } -} \ No newline at end of file + +} diff --git a/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java index 8ce9225..0bbc25d 100644 --- a/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java +++ b/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java @@ -1,99 +1,878 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; -// 导入所需的类和接口 +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class NoteEditActivity extends Activity implements OnClickListener, NoteSettingChangedListener, OnTextViewChangeListener { - // 内部类,用于持有笔记头部视图的引用 private class HeadViewHolder { public TextView tvModified; + public ImageView ivAlertIcon; + public TextView tvAlertDate; + public ImageView ibSetBgColor; } - // 静态代码块,用于初始化背景和字体大小选择器的映射关系 private static final Map sBgSelectorBtnsMap = new HashMap(); static { - // 初始化背景选择器按钮映射 + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); } private static final Map sBgSelectorSelectionMap = new HashMap(); static { - // 初始化背景选择器选中状态映射 + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); } private static final Map sFontSizeBtnsMap = new HashMap(); static { - // 初始化字体大小选择器按钮映射 + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); } private static final Map sFontSelectorSelectionMap = new HashMap(); static { - // 初始化字体大小选择器选中状态映射 + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); } - // 类成员变量 + private static final String TAG = "NoteEditActivity"; + private HeadViewHolder mNoteHeaderHolder; + private View mHeadViewPanel; + private View mNoteBgColorSelector; + private View mFontSizeSelector; + private EditText mNoteEditor; + private View mNoteEditorPanel; + private WorkingNote mWorkingNote; + private SharedPreferences mSharedPrefs; private int mFontSizeId; - // Activity生命周期方法 + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; + + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; + + public static final String TAG_CHECKED = String.valueOf('\u221A'); + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); + + private LinearLayout mEditTextList; + + private String mUserQuery; + private Pattern mPattern; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.note_edit); - // 初始化Activity状态 + this.setContentView(R.layout.note_edit); + + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); } + /** + * Current activity may be killed when the memory is low. Once it is killed, for another time + * user load this activity, we should restore the former state + */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); - // 恢复Activity状态 + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + private boolean initActivityState(Intent intent) { + /** + * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, + * then jump to the NotesListActivity + */ + mWorkingNote = null; + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * Starting from the searched result + */ + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + return false; + } + } + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // New note + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // Parse call-record note + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + @Override + protected void onResume() { + super.onResume(); + initNoteScreen(); + } + + private void initNoteScreen() { + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + /** + * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker + * is not ready + */ + showAlertHeader(); + } + + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + /** + * For new note without note id, we should firstly save it to + * generate a id. If the editing note is not worth saving, there + * is no id which is equivalent to create new note + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + if (mFontSizeSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return super.dispatchTouchEvent(ev); + } + + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1]; + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; } - // 初始化资源和视图 private void initResources() { - // 初始化头部视图、编辑器、选择器等 + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + + mFontSizeSelector = findViewById(R.id.font_size_selector); + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + }; + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + } + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); + } + + @Override + protected void onPause() { + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); + } + clearSettingState(); + } + + private void updateWidget() { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + mWorkingNote.getWidgetId() + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_set_bg_color) { + mNoteBgColorSelector.setVisibility(View.VISIBLE); + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + - View.VISIBLE); + } else if (sBgSelectorBtnsMap.containsKey(id)) { + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE); + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + mNoteBgColorSelector.setVisibility(View.GONE); + } else if (sFontSizeBtnsMap.containsKey(id)) { + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + mFontSizeId = sFontSizeBtnsMap.get(id); + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); + } } - // 处理返回键事件 @Override public void onBackPressed() { - // 处理返回键,保存笔记 + if(clearSettingState()) { + return; + } + + saveNote(); + super.onBackPressed(); + } + + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + public void onBackgroundColorChanged() { + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) { + return true; + } + clearSettingState(); + menu.clear(); + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_note_edit, menu); + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); + } + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + if (mWorkingNote.hasClockAlert()) { + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; } - // 处理选项菜单项点击事件 @Override public boolean onOptionsItemSelected(MenuItem item) { - // 处理菜单项点击,如新建笔记、删除笔记、设置提醒等 + switch (item.getItemId()) { + case R.id.menu_new_note: + createNewNote(); + break; + case R.id.menu_delete: + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_note)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteCurrentNote(); + finish(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.menu_font_size: + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + break; + case R.id.menu_list_mode: + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share: + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + break; + case R.id.menu_send_to_desktop: + sendToDesktop(); + break; + case R.id.menu_alert: + setReminder(); + break; + case R.id.menu_delete_remind: + mWorkingNote.setAlertDate(0, false); + break; + default: + break; + } + return true; } - // 设置提醒 private void setReminder() { - // 显示日期时间选择对话框,设置提醒 + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date , true); + } + }); + d.show(); } - // 发送到桌面 - private void sendToDesktop() { - // 将笔记发送到桌面,创建快捷方式 + /** + * Share note to apps that support {@link Intent#ACTION_SEND} action + * and {@text/plain} type + */ + private void sendTo(Context context, String info) { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); + context.startActivity(intent); + } + + private void createNewNote() { + // Firstly, save current editing notes + saveNote(); + + // For safety, start a new NoteEditActivity + finish(); + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + } + mWorkingNote.markDeleted(true); + } + + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + public void onClockAlertChanged(long date, boolean set) { + /** + * User could set clock to an unsaved note, so before setting the + * alert clock, we should save the note first + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) { + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); + if(!set) { + alarmManager.cancel(pendingIntent); + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); + } + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + public void onWidgetChanged() { + updateWidget(); + } + + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { + return; + } + + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); + NoteEditText edit = null; + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); + edit.requestFocus(); + edit.setSelection(length); + } + + public void onEditTextEnter(int index, String text) { + /** + * Should not happen, check for debug + */ + if(index > mEditTextList.getChildCount()) { + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); + mEditTextList.addView(view, index); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + private void switchToListMode(String text) { + mEditTextList.removeAllViews(); + String[] items = text.split("\n"); + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); + index++; + } + } + mEditTextList.addView(getListItem("", index)); + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); + + mNoteEditor.setVisibility(View.GONE); + mEditTextList.setVisibility(View.VISIBLE); + } + + private Spannable getHighlightQueryResult(String fullText, String userQuery) { + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(fullText); + int start = 0; + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + private View getListItem(String item, int index) { + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + } + } + }); + + if (item.startsWith(TAG_CHECKED)) { + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); + } + + edit.setOnTextViewChangeListener(this); + edit.setIndex(index); + edit.setText(getHighlightQueryResult(item, mUserQuery)); + return view; + } + + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) { + Log.e(TAG, "Wrong index, should not happen"); + return; + } + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + public void onCheckListModeChanged(int oldMode, int newMode) { + if (newMode == TextNote.MODE_CHECK_LIST) { + switchToListMode(mNoteEditor.getText().toString()); + } else { + if (!getWorkingText()) { + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); + mNoteEditor.setVisibility(View.VISIBLE); + } + } + + private boolean getWorkingText() { + boolean hasChecked = false; + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); + } + return hasChecked; } - // 保存笔记 private boolean saveNote() { - // 保存当前编辑的笔记 + getWorkingText(); + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * There are two modes from List view to edit view, open one note, + * create/edit a node. Opening node requires to the original + * position in the list when back from edit view, while creating a + * new node requires to the top of the list. This code + * {@link #RESULT_OK} is used to identify the create/edit state + */ + setResult(RESULT_OK); + } + return saved; + } + + private void sendToDesktop() { + /** + * Before send message to home, we should make sure that current + * editing note is exists in databases. So, for new note, firstly + * save it + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + if (mWorkingNote.getNoteId() > 0) { + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); + sender.putExtra("duplicate", true); + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + showToast(R.string.info_note_enter_desktop); + sendBroadcast(sender); + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + private String makeShortcutIconTitle(String content) { + content = content.replace(TAG_CHECKED, ""); + content = content.replace(TAG_UNCHECKED, ""); + return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, + SHORTCUT_ICON_TITLE_MAX_LEN) : content; + } + + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + } + + private void showToast(int resId, int duration) { + Toast.makeText(this, resId, duration).show(); } + - // 其他方法,如处理文本变化、列表模式切换等 -} \ No newline at end of file + public void OnOpenMenu(View view) { + openOptionsMenu(); + } +} diff --git a/app/src/main/java/net/micode/notes/ui/NoteEditText.java b/app/src/main/java/net/micode/notes/ui/NoteEditText.java index 23bc0c1..2afe2a8 100644 --- a/app/src/main/java/net/micode/notes/ui/NoteEditText.java +++ b/app/src/main/java/net/micode/notes/ui/NoteEditText.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -28,15 +39,13 @@ import java.util.Map; public class NoteEditText extends EditText { private static final String TAG = "NoteEditText"; - private int mIndex; // 索引,用于标识文本编辑的位置 - private int mSelectionStartBeforeDelete; // 删除前的选择起始位置 + private int mIndex; + private int mSelectionStartBeforeDelete; - // 定义不同的链接协议 - private static final String SCHEME_TEL = "tel:"; - private static final String SCHEME_HTTP = "http:"; - private static final String SCHEME_EMAIL = "mailto:"; + private static final String SCHEME_TEL = "tel:" ; + private static final String SCHEME_HTTP = "http:" ; + private static final String SCHEME_EMAIL = "mailto:" ; - // 定义链接协议与动作资源的映射 private static final Map sSchemaActionResMap = new HashMap(); static { sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); @@ -44,71 +53,165 @@ public class NoteEditText extends EditText { sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); } - // 回调接口,用于处理文本编辑事件 + /** + * Call by the {@link NoteEditActivity} to delete or add edit text + */ public interface OnTextViewChangeListener { + /** + * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens + * and the text is null + */ void onEditTextDelete(int index, String text); + + /** + * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} + * happen + */ void onEditTextEnter(int index, String text); + + /** + * Hide or show item option when text change + */ void onTextChange(int index, boolean hasText); } private OnTextViewChangeListener mOnTextViewChangeListener; - // 构造函数 public NoteEditText(Context context) { super(context, null); mIndex = 0; } - // 设置索引 public void setIndex(int index) { mIndex = index; } - // 设置文本编辑事件的监听器 public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener; } - // 其他构造函数 public NoteEditText(Context context, AttributeSet attrs) { super(context, attrs, android.R.attr.editTextStyle); } public NoteEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); + // TODO Auto-generated constructor stub } - // 处理触摸事件,用于选择文本 @Override public boolean onTouchEvent(MotionEvent event) { - // 处理触摸事件,更新光标位置 + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + Selection.setSelection(getText(), off); + break; + } + return super.onTouchEvent(event); } - // 处理按键事件,特别是删除和回车键 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - // 处理按下删除键的事件 + switch (keyCode) { + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + return false; + } + break; + case KeyEvent.KEYCODE_DEL: + mSelectionStartBeforeDelete = getSelectionStart(); + break; + default: + break; + } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - // 处理抬起删除键和回车键的事件 + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: + if (mOnTextViewChangeListener != null) { + if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + int selectionStart = getSelectionStart(); + String text = getText().subSequence(selectionStart, length()).toString(); + setText(getText().subSequence(0, selectionStart)); + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } return super.onKeyUp(keyCode, event); } - // 处理焦点变化事件,用于更新文本编辑状态 @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { - // 处理焦点变化,更新文本编辑状态 + if (mOnTextViewChangeListener != null) { + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } super.onFocusChanged(focused, direction, previouslyFocusedRect); } - // 创建上下文菜单,用于处理链接点击事件 @Override protected void onCreateContextMenu(ContextMenu menu) { - // 创建上下文菜单,处理链接点击事件 + if (getText() instanceof Spanned) { + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + + int min = Math.min(selStart, selEnd); + int max = Math.max(selStart, selEnd); + + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { + int defaultResId = 0; + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; + } + + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + // goto a new intent + urls[0].onClick(NoteEditText.this); + return true; + } + }); + } + } super.onCreateContextMenu(menu); } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/app/src/main/java/net/micode/notes/ui/NoteItemData.java index 23bc0c1..0f5a878 100644 --- a/app/src/main/java/net/micode/notes/ui/NoteItemData.java +++ b/app/src/main/java/net/micode/notes/ui/NoteItemData.java @@ -1,114 +1,224 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; import android.content.Context; -import android.graphics.Rect; -import android.text.Layout; -import android.text.Selection; -import android.text.Spanned; +import android.database.Cursor; import android.text.TextUtils; -import android.text.style.URLSpan; -import android.util.AttributeSet; -import android.util.Log; -import android.view.ContextMenu; -import android.view.KeyEvent; -import android.view.MenuItem; -import android.view.MenuItem.OnMenuItemClickListener; -import android.view.MotionEvent; -import android.widget.EditText; -import net.micode.notes.R; +import net.micode.notes.data.Contact; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.DataUtils; + + +public class NoteItemData { + static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE, + NoteColumns.BG_COLOR_ID, + NoteColumns.CREATED_DATE, + NoteColumns.HAS_ATTACHMENT, + NoteColumns.MODIFIED_DATE, + NoteColumns.NOTES_COUNT, + NoteColumns.PARENT_ID, + NoteColumns.SNIPPET, + NoteColumns.TYPE, + NoteColumns.WIDGET_ID, + NoteColumns.WIDGET_TYPE, + }; + + private static final int ID_COLUMN = 0; + private static final int ALERTED_DATE_COLUMN = 1; + private static final int BG_COLOR_ID_COLUMN = 2; + private static final int CREATED_DATE_COLUMN = 3; + private static final int HAS_ATTACHMENT_COLUMN = 4; + private static final int MODIFIED_DATE_COLUMN = 5; + private static final int NOTES_COUNT_COLUMN = 6; + private static final int PARENT_ID_COLUMN = 7; + private static final int SNIPPET_COLUMN = 8; + private static final int TYPE_COLUMN = 9; + private static final int WIDGET_ID_COLUMN = 10; + private static final int WIDGET_TYPE_COLUMN = 11; + + private long mId; + private long mAlertDate; + private int mBgColorId; + private long mCreatedDate; + private boolean mHasAttachment; + private long mModifiedDate; + private int mNotesCount; + private long mParentId; + private String mSnippet; + private int mType; + private int mWidgetId; + private int mWidgetType; + private String mName; + private String mPhoneNumber; + + private boolean mIsLastItem; + private boolean mIsFirstItem; + private boolean mIsOnlyOneItem; + private boolean mIsOneNoteFollowingFolder; + private boolean mIsMultiNotesFollowingFolder; + + public NoteItemData(Context context, Cursor cursor) { + mId = cursor.getLong(ID_COLUMN); + mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); + mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); + mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); + mParentId = cursor.getLong(PARENT_ID_COLUMN); + mSnippet = cursor.getString(SNIPPET_COLUMN); + mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( + NoteEditActivity.TAG_UNCHECKED, ""); + mType = cursor.getInt(TYPE_COLUMN); + mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); + mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); + + mPhoneNumber = ""; + if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { + mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); + if (!TextUtils.isEmpty(mPhoneNumber)) { + mName = Contact.getContact(context, mPhoneNumber); + if (mName == null) { + mName = mPhoneNumber; + } + } + } + + if (mName == null) { + mName = ""; + } + checkPostion(cursor); + } + + private void checkPostion(Cursor cursor) { + mIsLastItem = cursor.isLast() ? true : false; + mIsFirstItem = cursor.isFirst() ? true : false; + mIsOnlyOneItem = (cursor.getCount() == 1); + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + if (cursor.moveToPrevious()) { + if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { + if (cursor.getCount() > (position + 1)) { + mIsMultiNotesFollowingFolder = true; + } else { + mIsOneNoteFollowingFolder = true; + } + } + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; + } -import java.util.HashMap; -import java.util.Map; + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; + } -public class NoteEditText extends EditText { - private static final String TAG = "NoteEditText"; - private int mIndex; // 索引,用于标识文本编辑的位置 - private int mSelectionStartBeforeDelete; // 删除前的选择起始位置 + public boolean isLast() { + return mIsLastItem; + } - // 定义不同的链接协议 - private static final String SCHEME_TEL = "tel:"; - private static final String SCHEME_HTTP = "http:"; - private static final String SCHEME_EMAIL = "mailto:"; + public String getCallName() { + return mName; + } + + public boolean isFirst() { + return mIsFirstItem; + } - // 定义链接协议与动作资源的映射 - private static final Map sSchemaActionResMap = new HashMap(); - static { - sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); - sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); - sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); + public boolean isSingle() { + return mIsOnlyOneItem; } - // 回调接口,用于处理文本编辑事件 - public interface OnTextViewChangeListener { - void onEditTextDelete(int index, String text); - void onEditTextEnter(int index, String text); - void onTextChange(int index, boolean hasText); + public long getId() { + return mId; } - private OnTextViewChangeListener mOnTextViewChangeListener; + public long getAlertDate() { + return mAlertDate; + } + + public long getCreatedDate() { + return mCreatedDate; + } + + public boolean hasAttachment() { + return mHasAttachment; + } + + public long getModifiedDate() { + return mModifiedDate; + } + + public int getBgColorId() { + return mBgColorId; + } - // 构造函数 - public NoteEditText(Context context) { - super(context, null); - mIndex = 0; + public long getParentId() { + return mParentId; } - // 设置索引 - public void setIndex(int index) { - mIndex = index; + public int getNotesCount() { + return mNotesCount; } - // 设置文本编辑事件的监听器 - public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { - mOnTextViewChangeListener = listener; + public long getFolderId () { + return mParentId; } - // 其他构造函数 - public NoteEditText(Context context, AttributeSet attrs) { - super(context, attrs, android.R.attr.editTextStyle); + public int getType() { + return mType; } - public NoteEditText(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); + public int getWidgetType() { + return mWidgetType; } - // 处理触摸事件,用于选择文本 - @Override - public boolean onTouchEvent(MotionEvent event) { - // 处理触摸事件,更新光标位置 - return super.onTouchEvent(event); + public int getWidgetId() { + return mWidgetId; } - // 处理按键事件,特别是删除和回车键 - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - // 处理按下删除键的事件 - return super.onKeyDown(keyCode, event); + public String getSnippet() { + return mSnippet; } - @Override - public boolean onKeyUp(int keyCode, KeyEvent event) { - // 处理抬起删除键和回车键的事件 - return super.onKeyUp(keyCode, event); + public boolean hasAlert() { + return (mAlertDate > 0); } - // 处理焦点变化事件,用于更新文本编辑状态 - @Override - protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { - // 处理焦点变化,更新文本编辑状态 - super.onFocusChanged(focused, direction, previouslyFocusedRect); + public boolean isCallRecord() { + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); } - // 创建上下文菜单,用于处理链接点击事件 - @Override - protected void onCreateContextMenu(ContextMenu menu) { - // 创建上下文菜单,处理链接点击事件 - super.onCreateContextMenu(menu); + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/NotesListActivity.java b/app/src/main/java/net/micode/notes/ui/NotesListActivity.java index 7b0abac..2fa42ce 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesListActivity.java +++ b/app/src/main/java/net/micode/notes/ui/NotesListActivity.java @@ -1,188 +1,992 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; -// 导入所需的类和接口 +import android.R.menu; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { - // 类成员变量和常量定义 - private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; + private static final int FOLDER_LIST_QUERY_TOKEN = 1; + private static final int MENU_FOLDER_DELETE = 0; + private static final int MENU_FOLDER_VIEW = 1; + private static final int MENU_FOLDER_CHANGE_NAME = 2; + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; - // 枚举,定义列表编辑状态 private enum ListEditState { NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER }; - private ListEditState mState; // 当前列表编辑状态 - private BackgroundQueryHandler mBackgroundQueryHandler; // 后台查询处理器 - private NotesListAdapter mNotesListAdapter; // 笔记列表适配器 - private ListView mNotesListView; // 笔记列表视图 - private Button mAddNewNote; // 新建笔记按钮 - private Button mMenuSet; // 设置按钮 - private boolean mDispatch; // 是否分发事件 - private int mOriginY; // 原始Y坐标 - private int mDispatchY; // 分发Y坐标 - private TextView mTitleBar; // 标题栏 - private long mCurrentFolderId; // 当前文件夹ID - private ContentResolver mContentResolver; // 内容解析器 - private ModeCallback mModeCallBack; // 模式回调 - private static final String TAG = "NotesListActivity"; // 日志标签 - private NoteItemData mFocusNoteDataItem; // 焦点笔记数据项 - - // Activity生命周期方法 + private ListEditState mState; + + private BackgroundQueryHandler mBackgroundQueryHandler; + + private NotesListAdapter mNotesListAdapter; + + private ListView mNotesListView; + + private Button mAddNewNote; + private Button mMenuSet; + + private boolean mDispatch; + + private int mOriginY; + + private int mDispatchY; + + private TextView mTitleBar; + + private long mCurrentFolderId; + + private ContentResolver mContentResolver; + + private ModeCallback mModeCallBack; + + private static final String TAG = "NotesListActivity"; + + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; + + private NoteItemData mFocusNoteDataItem; + + private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; + + private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + + NoteColumns.NOTES_COUNT + ">0)"; + + private final static int REQUEST_CODE_OPEN_NODE = 102; + private final static int REQUEST_CODE_NEW_NODE = 103; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_list); initResources(); + + /** + * Insert an introduction when user firstly use this application + */ setAppInfoFromRawRes(); } - // 初始化资源 - private void initResources() { - // 初始化内容解析器、后台查询处理器、笔记列表适配器、笔记列表视图等 + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK + && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { + mNotesListAdapter.changeCursor(null); + } else { + super.onActivityResult(requestCode, resultCode, data); + } } - // 设置应用信息 private void setAppInfoFromRawRes() { - // 从raw资源文件中读取介绍信息,并显示 + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { + StringBuilder sb = new StringBuilder(); + InputStream in = null; + try { + in = getResources().openRawResource(R.raw.introduction); + if (in != null) { + InputStreamReader isr = new InputStreamReader(in); + BufferedReader br = new BufferedReader(isr); + char [] buf = new char[1024]; + int len = 0; + while ((len = br.read(buf)) > 0) { + sb.append(buf, 0, len); + } + } else { + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + e.printStackTrace(); + return; + } finally { + if(in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, + AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, + ResourceParser.RED); + note.setWorkingText(sb.toString()); + if (note.saveNote()) { + sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); + } else { + Log.e(TAG, "Save introduction note error"); + return; + } + } + } + + @Override + protected void onStart() { + super.onStart(); + startAsyncNotesListQuery(); + } + + private void initResources() { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mNotesListView = (ListView) findViewById(R.id.notes_list); + mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), + null, false); + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + mNotesListView.setOnItemLongClickListener(this); + mNotesListAdapter = new NotesListAdapter(this); + mNotesListView.setAdapter(mNotesListAdapter); + mAddNewNote = (Button) findViewById(R.id.btn_new_note); + mAddNewNote.setOnClickListener(this); + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); + mMenuSet = (Button) findViewById(R.id.btn_set); + mDispatch = false; + mDispatchY = 0; + mOriginY = 0; + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mState = ListEditState.NOTE_LIST; + mModeCallBack = new ModeCallback(); } - // 启动后台笔记列表查询 + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + private DropdownMenu mDropDownMenu; + private ActionMode mActionMode; + private Menu menu; + private MenuItem mMoveMenu; + + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + getMenuInflater().inflate(R.menu.note_list_options, menu); + this.menu = menu; + menu.findItem(R.id.delete).setOnMenuItemClickListener(this); + mMoveMenu = menu.findItem(R.id.move); + if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER + || DataUtils.getUserFolderCount(mContentResolver) == 0) { + mMoveMenu.setVisible(false); + } else { + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); + mNotesListView.setLongClickable(false); + mAddNewNote.setVisibility(View.GONE); + mMenuSet.setVisibility(View.GONE); + + View customView = LayoutInflater.from(NotesListActivity.this).inflate( + R.layout.note_list_dropdown_menu, null); + mode.setCustomView(customView); + mDropDownMenu = new DropdownMenu(NotesListActivity.this, + (Button) customView.findViewById(R.id.selection_menu), + R.menu.note_list_dropdown); + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + public boolean onMenuItemClick(MenuItem item) { + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); + return true; + } + + }); + return true; + } + + private void updateMenu() { + int selectedCount = mNotesListAdapter.getSelectedCount(); + // Update dropdown menu + String format = getResources().getString(R.string.menu_select_title, selectedCount); + mDropDownMenu.setTitle(format); + MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); + if (item != null) { + if (mNotesListAdapter.isAllSelected()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + // TODO Auto-generated method stub + return false; + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + // TODO Auto-generated method stub + return false; + } + + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); + mNotesListView.clearChoices(); + mNotesListView.setItemChecked(0,true); + mNotesListView.setItemChecked(0,false); + + mNotesListView.setLongClickable(true); + System.out.println("-----------------onDestroyActionMode------------------"); + mNotesListAdapter.notifyDataSetChanged(); +// closeOptionsMenu(); +// mNotesListView.invalidate(); + mAddNewNote.setVisibility(View.VISIBLE); + mMenuSet.setVisibility(View.VISIBLE); + + + +// mNotesListView.setChoiceMode(ListView.CHOICE_MODE_NONE); + +// menu.clear(); +// menu.close(); + } + + + + public void finishActionMode() { + mActionMode.finish(); + mActionMode = null; + mNotesListAdapter.setChoiceMode(false); + mNotesListView.setLongClickable(true); + } + + + + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, + boolean checked) { + mNotesListAdapter.setCheckedItem(position, checked); + updateMenu(); + } + + public boolean onMenuItemClick(MenuItem item) { + if (mNotesListAdapter.getSelectedCount() == 0) { + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), + Toast.LENGTH_SHORT).show(); + return true; + } + + switch (item.getItemId()) { + case R.id.delete: + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_notes, + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.move: + startQueryDestinationFolders(); + break; + default: + return false; + } + return true; + } + } + + + private class NewNoteOnTouchListener implements OnTouchListener { + + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: { + Display display = getWindowManager().getDefaultDisplay(); + int screenHeight = display.getHeight(); + int newNoteViewHeight = mAddNewNote.getHeight(); + int start = screenHeight - newNoteViewHeight; + int eventY = start + (int) event.getY(); + /** + * Minus TitleBar's height + */ + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + /** + * HACKME:When click the transparent part of "New Note" button, dispatch + * the event to the list view behind this button. The transparent part of + * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) + * and the line top of the button. The coordinate based on left of the "New + * Note" button. The 94 represents maximum height of the transparent part. + * Notice that, if the background of the button changes, the formula should + * also change. This is very bad, just for the UI designer's strong requirement. + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); + mDispatchY = eventY; + event.setLocation(event.getX(), mDispatchY); + mDispatch = true; + return mNotesListView.dispatchTouchEvent(event); + } + } + break; + } + case MotionEvent.ACTION_MOVE: { + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; + event.setLocation(event.getX(), mDispatchY); + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + default: { + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + private void startAsyncNotesListQuery() { - // 根据当前文件夹ID启动后台笔记列表查询 + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION + : NORMAL_SELECTION; + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) + }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); + } + + private final class BackgroundQueryHandler extends AsyncQueryHandler { + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: + mNotesListAdapter.changeCursor(cursor); + break; + case FOLDER_LIST_QUERY_TOKEN: + if (cursor != null && cursor.getCount() > 0) { + showFolderListMenu(cursor); + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } } - // 显示文件夹列表菜单 private void showFolderListMenu(Cursor cursor) { - // 显示文件夹列表菜单,用于移动笔记 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); + } + }); + builder.show(); } - // 创建新建笔记 private void createNewNote() { - // 创建并启动新建笔记的Intent + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); } - // 批量删除笔记 private void batchDelete() { - // 批量删除选中的笔记 + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + HashSet widgets = mNotesListAdapter.getSelectedWidget(); + if (!isSyncMode()) { + // if not synced, delete notes directly + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { + // in sync mode, we'll move the deleted note into the trash + // folder + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter + .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; + } + + @Override + protected void onPostExecute(HashSet widgets) { + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + mModeCallBack.finishActionMode(); + } + }.execute(); } - // 删除文件夹 private void deleteFolder(long folderId) { - // 删除指定的文件夹 + if (folderId == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Wrong folder id, should not happen " + folderId); + return; + } + + HashSet ids = new HashSet(); + ids.add(folderId); + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); + if (!isSyncMode()) { + // if not synced, delete folder directly + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { + // in sync mode, we'll move the deleted folder into the trash folder + DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); + } + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } } - // 打开笔记节点 private void openNode(NoteItemData data) { - // 打开并编辑指定的笔记 + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); } - // 打开文件夹 private void openFolder(NoteItemData data) { - // 打开指定的文件夹 + mCurrentFolderId = data.getId(); + startAsyncNotesListQuery(); + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mState = ListEditState.CALL_RECORD_FOLDER; + mAddNewNote.setVisibility(View.GONE); + mMenuSet.setVisibility(View.GONE); + } else { + mState = ListEditState.SUB_FOLDER; + } + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mTitleBar.setText(R.string.call_record_folder_name); + } else { + mTitleBar.setText(data.getSnippet()); + } + mTitleBar.setVisibility(View.VISIBLE); } - // 处理按钮点击事件 public void onClick(View v) { - // 处理新建笔记按钮点击事件 + switch (v.getId()) { + case R.id.btn_new_note: + createNewNote(); + break; + default: + break; + } } - // 显示软键盘 private void showSoftInput() { - // 显示软键盘 + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } } - // 隐藏软键盘 private void hideSoftInput(View view) { - // 隐藏软键盘 + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } - // 显示创建或修改文件夹对话框 private void showCreateOrModifyFolderDialog(final boolean create) { - // 显示创建或修改文件夹的对话框 + final AlertDialog.Builder builder = new AlertDialog.Builder(this); + View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); + final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); + showSoftInput(); + if (!create) { + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); + builder.setTitle(getString(R.string.menu_folder_change_name)); + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + builder.setPositiveButton(android.R.string.ok, null); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + hideSoftInput(etName); + } + }); + + final Dialog dialog = builder.setView(view).show(); + final Button positive = (Button)dialog.findViewById(android.R.id.button1); + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + hideSoftInput(etName); + String name = etName.getText().toString(); + if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { + Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), + Toast.LENGTH_LONG).show(); + etName.setSelection(0, etName.length()); + return; + } + if (!create) { + if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) + }); + } + } else if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); + } + dialog.dismiss(); + } + }); + + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } + /** + * When the name edit text is null, disable the positive button + */ + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // TODO Auto-generated method stub + + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } else { + positive.setEnabled(true); + } + } + + public void afterTextChanged(Editable s) { + // TODO Auto-generated method stub + + } + }); } - // 处理返回键事件 @Override public void onBackPressed() { - // 根据当前状态处理返回键事件 + + System.out.println("-------onBackPressed---00000"); + switch (mState) { + case SUB_FOLDER: + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + startAsyncNotesListQuery(); + mTitleBar.setVisibility(View.GONE); + break; + case CALL_RECORD_FOLDER: + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + mAddNewNote.setVisibility(View.VISIBLE); + mMenuSet.setVisibility(View.VISIBLE); + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); + break; + case NOTE_LIST: + System.out.println("-------onBackPressed---"); + super.onBackPressed(); + break; + default: + break; + } } - // 更新Widget private void updateWidget(int appWidgetId, int appWidgetType) { - // 更新Widget + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + if (appWidgetType == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + appWidgetId + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); } - // 创建上下文菜单 private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - // 创建文件夹上下文菜单 + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); + } } }; - // 处理上下文菜单项点击事件 + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + mNotesListView.setOnCreateContextMenuListener(null); + } + super.onContextMenuClosed(menu); + } + @Override public boolean onContextItemSelected(MenuItem item) { - // 处理文件夹上下文菜单项点击事件 + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + switch (item.getItemId()) { + case MENU_FOLDER_VIEW: + openFolder(mFocusNoteDataItem); + break; + case MENU_FOLDER_DELETE: + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.alert_title_delete)); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(getString(R.string.alert_message_delete_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case MENU_FOLDER_CHANGE_NAME: + showCreateOrModifyFolderDialog(false); + break; + default: + break; + } + + return true; } - // 准备选项菜单 @Override public boolean onPrepareOptionsMenu(Menu menu) { - // 根据当前状态准备选项菜单 + menu.clear(); + if (mState == ListEditState.NOTE_LIST) { + getMenuInflater().inflate(R.menu.note_list, menu); + // set sync or sync_cancel + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + return true; } - // 处理选项菜单项点击事件 @Override public boolean onOptionsItemSelected(MenuItem item) { - // 处理选项菜单项点击事件 + switch (item.getItemId()) { + case R.id.menu_new_folder: { + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: { + exportNoteToText(); + break; + } + case R.id.menu_sync: { + if (isSyncMode()) { + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { + GTaskSyncService.startSync(this); + } else { + GTaskSyncService.cancelSync(this); + } + } else { + startPreferenceActivity(); + } + break; + } + case R.id.menu_setting: { + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: { + createNewNote(); + break; + } + case R.id.menu_search: + onSearchRequested(); + break; + default: + break; + } + return true; } - // 处理搜索请求 @Override public boolean onSearchRequested() { - // 处理搜索请求 + startSearch(null, false, null /* appData */, false); + return true; } - // 导出笔记到文本 private void exportNoteToText() { - // 导出笔记到文本文件 + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); + new AsyncTask() { + + @Override + protected Integer doInBackground(Void... unused) { + return backup.exportToText(); + } + + @Override + protected void onPostExecute(Integer result) { + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export)); + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } + } + + }.execute(); } - // 检查是否处于同步模式 private boolean isSyncMode() { - // 检查是否处于同步模式 + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; } - // 启动偏好设置活动 private void startPreferenceActivity() { - // 启动偏好设置活动 + Activity from = getParent() != null ? getParent() : this; + Intent intent = new Intent(from, NotesPreferenceActivity.class); + from.startActivityIfNeeded(intent, -1); } - // 列表项点击事件监听器 private class OnListItemClickListener implements OnItemClickListener { + public void onItemClick(AdapterView parent, View view, int position, long id) { - // 处理列表项点击事件 + if (view instanceof NotesListItem) { + NoteItemData item = ((NotesListItem) view).getItemData(); + if (mNotesListAdapter.isInChoiceMode()) { + if (item.getType() == Notes.TYPE_NOTE) { + position = position - mNotesListView.getHeaderViewsCount(); + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); + } + return; + } + + switch (mState) { + case NOTE_LIST: + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item); + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: + case CALL_RECORD_FOLDER: + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + default: + break; + } + } } + } - // 启动查询目标文件夹 private void startQueryDestinationFolders() { - // 查询目标文件夹 + String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; + selection = (mState == ListEditState.NOTE_LIST) ? selection: + "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + + mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, + null, + Notes.CONTENT_NOTE_URI, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLER), + String.valueOf(mCurrentFolderId) + }, + NoteColumns.MODIFIED_DATE + " DESC"); } - // 处理长按事件 public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - // 处理列表项长按事件 + if (view instanceof NotesListItem) { + mFocusNoteDataItem = ((NotesListItem) view).getItemData(); + if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { + if (mNotesListView.startActionMode(mModeCallBack) != null) { + mModeCallBack.onItemCheckedStateChanged(null, position, id, true); + mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + } else { + Log.e(TAG, "startActionMode fails"); + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); + } + } + return false; } -} \ No newline at end of file + + public void OnOpenMenu(View view) { + openOptionsMenu(); + } +} diff --git a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java index f32254f..51c9cb9 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java +++ b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -19,21 +30,19 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; + public class NotesListAdapter extends CursorAdapter { - // 类成员变量 private static final String TAG = "NotesListAdapter"; - private Context mContext; // 上下文对象 - private HashMap mSelectedIndex; // 选中状态的索引映射 - private int mNotesCount; // 笔记计数 - private boolean mChoiceMode; // 选择模式 + private Context mContext; + private HashMap mSelectedIndex; + private int mNotesCount; + private boolean mChoiceMode; - // AppWidgetAttribute内部类,用于存储与AppWidget相关的属性 public static class AppWidgetAttribute { public int widgetId; public int widgetType; }; - // 构造函数 public NotesListAdapter(Context context) { super(context, null); mSelectedIndex = new HashMap(); @@ -41,39 +50,34 @@ public class NotesListAdapter extends CursorAdapter { mNotesCount = 0; } - // 创建新的列表项视图 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new NotesListItem(context); } - // 绑定数据到列表项视图 @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof NotesListItem) { NoteItemData itemData = new NoteItemData(context, cursor); - ((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); + ((NotesListItem) view).bind(context, itemData, mChoiceMode, + isSelectedItem(cursor.getPosition())); } } - // 设置列表项的选中状态 public void setCheckedItem(final int position, final boolean checked) { mSelectedIndex.put(position, checked); notifyDataSetChanged(); } - // 获取选择模式状态 public boolean isInChoiceMode() { return mChoiceMode; } - // 设置选择模式 public void setChoiceMode(boolean mode) { mSelectedIndex.clear(); mChoiceMode = mode; } - // 选中或取消选中所有项 public void selectAll(boolean checked) { Cursor cursor = getCursor(); for (int i = 0; i < getCount(); i++) { @@ -85,7 +89,6 @@ public class NotesListAdapter extends CursorAdapter { } } - // 获取选中的笔记ID集合 public HashSet getSelectedItemIds() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { @@ -98,10 +101,10 @@ public class NotesListAdapter extends CursorAdapter { } } } + return itemSet; } - // 获取选中的AppWidget属性集合 public HashSet getSelectedWidget() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { @@ -113,6 +116,9 @@ public class NotesListAdapter extends CursorAdapter { widget.widgetId = item.getWidgetId(); widget.widgetType = item.getWidgetType(); itemSet.add(widget); + /** + * Don't close cursor here, only the adapter could close it + */ } else { Log.e(TAG, "Invalid cursor"); return null; @@ -122,7 +128,6 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } - // 获取选中的计数 public int getSelectedCount() { Collection values = mSelectedIndex.values(); if (null == values) { @@ -138,13 +143,11 @@ public class NotesListAdapter extends CursorAdapter { return count; } - // 检查是否全部选中 public boolean isAllSelected() { int checkedCount = getSelectedCount(); return (checkedCount != 0 && checkedCount == mNotesCount); } - // 检查指定位置的项是否选中 public boolean isSelectedItem(final int position) { if (null == mSelectedIndex.get(position)) { return false; @@ -152,21 +155,18 @@ public class NotesListAdapter extends CursorAdapter { return mSelectedIndex.get(position); } - // 当内容变化时调用 @Override protected void onContentChanged() { super.onContentChanged(); calcNotesCount(); } - // 当游标变化时调用 @Override public void changeCursor(Cursor cursor) { super.changeCursor(cursor); calcNotesCount(); } - // 计算笔记计数 private void calcNotesCount() { mNotesCount = 0; for (int i = 0; i < getCount(); i++) { @@ -181,4 +181,4 @@ public class NotesListAdapter extends CursorAdapter { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/NotesListItem.java b/app/src/main/java/net/micode/notes/ui/NotesListItem.java index 0a27983..1221e80 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesListItem.java +++ b/app/src/main/java/net/micode/notes/ui/NotesListItem.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -18,29 +29,26 @@ import net.micode.notes.data.Notes; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + public class NotesListItem extends LinearLayout { - // 类成员变量,用于显示笔记列表项的各个部分 - private ImageView mAlert; // 用于显示提醒图标 - private TextView mTitle; // 用于显示笔记标题 - private TextView mTime; // 用于显示笔记修改时间 - private TextView mCallName; // 用于显示通话记录名称 - private NoteItemData mItemData; // 笔记项数据 - private CheckBox mCheckBox; // 用于选择模式时的复选框 + private ImageView mAlert; + private TextView mTitle; + private TextView mTime; + private TextView mCallName; + private NoteItemData mItemData; + private CheckBox mCheckBox; - // 构造函数,初始化笔记列表项视图 public NotesListItem(Context context) { super(context); - inflate(context, R.layout.note_item, this); // 将note_item布局文件加载到此LinearLayout中 - mAlert = (ImageView) findViewById(R.id.iv_alert_icon); // 初始化提醒图标 - mTitle = (TextView) findViewById(R.id.tv_title); // 初始化标题 - mTime = (TextView) findViewById(R.id.tv_time); // 初始化时间 - mCallName = (TextView) findViewById(R.id.tv_name); // 初始化通话记录名称 - mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); // 初始化复选框 + inflate(context, R.layout.note_item, this); + mAlert = (ImageView) findViewById(R.id.iv_alert_icon); + mTitle = (TextView) findViewById(R.id.tv_title); + mTime = (TextView) findViewById(R.id.tv_time); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); } - // 绑定笔记数据到视图 public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { - // 根据是否处于选择模式和笔记类型设置复选框的可见性和选中状态 if (choiceMode && data.getType() == Notes.TYPE_NOTE) { mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setChecked(checked); @@ -48,10 +56,8 @@ public class NotesListItem extends LinearLayout { mCheckBox.setVisibility(View.GONE); } - mItemData = data; // 设置笔记项数据 - // 根据笔记项数据的类型和属性设置视图的显示内容 + mItemData = data; if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { - // 特殊处理通话记录文件夹 mCallName.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); @@ -59,7 +65,6 @@ public class NotesListItem extends LinearLayout { + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setImageResource(R.drawable.call_record); } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { - // 处理通话记录下的笔记项 mCallName.setVisibility(View.VISIBLE); mCallName.setText(data.getCallName()); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); @@ -71,13 +76,13 @@ public class NotesListItem extends LinearLayout { mAlert.setVisibility(View.GONE); } } else { - // 处理普通笔记项 mCallName.setVisibility(View.GONE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + if (data.getType() == Notes.TYPE_FOLDER) { mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, - data.getNotesCount())); + data.getNotesCount())); mAlert.setVisibility(View.GONE); } else { mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); @@ -89,13 +94,12 @@ public class NotesListItem extends LinearLayout { } } } - mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); // 设置修改时间 - setBackground(data); // 设置背景 + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + setBackground(data); } - // 设置背景 private void setBackground(NoteItemData data) { - // 根据笔记项数据的类型和属性设置背景资源 int id = data.getBgColorId(); if (data.getType() == Notes.TYPE_NOTE) { if (data.isSingle() || data.isOneFollowingFolder()) { @@ -112,8 +116,7 @@ public class NotesListItem extends LinearLayout { } } - // 获取笔记项数据 public NoteItemData getItemData() { return mItemData; } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java index 258696a..07c5f7e 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * 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.ui; @@ -36,45 +47,53 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.gtask.remote.GTaskSyncService; + public class NotesPreferenceActivity extends PreferenceActivity { - // 偏好设置的文件名和键值 public static final String PREFERENCE_NAME = "notes_preferences"; + public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; + public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; + public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; + private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; + private static final String AUTHORITIES_FILTER_KEY = "authorities"; - private PreferenceCategory mAccountCategory; // 账号设置的分类 - private GTaskReceiver mReceiver; // 用于接收同步状态广播的接收器 - private Account[] mOriAccounts; // 原始账号数组 - private boolean mHasAddedAccount; // 是否添加了新账号 + private PreferenceCategory mAccountCategory; + + private GTaskReceiver mReceiver; + + private Account[] mOriAccounts; + + private boolean mHasAddedAccount; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); - // 使用应用图标作为导航 + /* using the app icon for navigation */ getActionBar().setDisplayHomeAsUpEnabled(true); - // 从XML文件中添加偏好设置 addPreferencesFromResource(R.xml.preferences); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mReceiver = new GTaskReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); - registerReceiver(mReceiver, filter); // 注册广播接收器 + registerReceiver(mReceiver, filter); mOriAccounts = null; View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); - getListView().addHeaderView(header, null, true); // 在列表视图中添加头部 + getListView().addHeaderView(header, null, true); } @Override protected void onResume() { super.onResume(); - // 如果用户添加了新账号,需要自动设置同步账号 + // need to set sync account automatically if user has added a new + // account if (mHasAddedAccount) { Account[] accounts = getGoogleAccounts(); if (mOriAccounts != null && accounts.length > mOriAccounts.length) { @@ -94,18 +113,17 @@ public class NotesPreferenceActivity extends PreferenceActivity { } } - refreshUI(); // 刷新用户界面 + refreshUI(); } @Override protected void onDestroy() { if (mReceiver != null) { - unregisterReceiver(mReceiver); // 注销广播接收器 + unregisterReceiver(mReceiver); } super.onDestroy(); } - // 加载账号偏好设置 private void loadAccountPreference() { mAccountCategory.removeAll(); @@ -117,10 +135,11 @@ public class NotesPreferenceActivity extends PreferenceActivity { public boolean onPreferenceClick(Preference preference) { if (!GTaskSyncService.isSyncing()) { if (TextUtils.isEmpty(defaultAccount)) { - // 第一次设置账号 + // the first time to set account showSelectAccountAlertDialog(); } else { - // 如果账号已经设置,需要提示用户风险 + // if the account has already been set, we need to promp + // user about the risk showChangeAccountConfirmAlertDialog(); } } else { @@ -135,12 +154,11 @@ public class NotesPreferenceActivity extends PreferenceActivity { mAccountCategory.addPreference(accountPref); } - // 加载同步按钮 private void loadSyncButton() { Button syncButton = (Button) findViewById(R.id.preference_sync_button); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); - // 设置按钮状态 + // set button state if (GTaskSyncService.isSyncing()) { syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setOnClickListener(new View.OnClickListener() { @@ -158,7 +176,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { } syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); - // 设置最后同步时间 + // set last sync time if (GTaskSyncService.isSyncing()) { lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setVisibility(View.VISIBLE); @@ -175,13 +193,11 @@ public class NotesPreferenceActivity extends PreferenceActivity { } } - // 刷新用户界面 private void refreshUI() { loadAccountPreference(); loadSyncButton(); } - // 显示选择账号的对话框 private void showSelectAccountAlertDialog() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); @@ -230,7 +246,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { mHasAddedAccount = true; Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { - "gmail-ls" + "gmail-ls" }); startActivityForResult(intent, -1); dialog.dismiss(); @@ -238,7 +254,6 @@ public class NotesPreferenceActivity extends PreferenceActivity { }); } - // 显示更改账号确认对话框 private void showChangeAccountConfirmAlertDialog() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); @@ -258,7 +273,8 @@ public class NotesPreferenceActivity extends PreferenceActivity { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { - showSelectAccountAlertDialog(); } else if (which == 1) { + showSelectAccountAlertDialog(); + } else if (which == 1) { removeSyncAccount(); refreshUI(); } @@ -267,13 +283,11 @@ public class NotesPreferenceActivity extends PreferenceActivity { dialogBuilder.show(); } - // 获取Google账号 private Account[] getGoogleAccounts() { AccountManager accountManager = AccountManager.get(this); return accountManager.getAccountsByType("com.google"); } - // 设置同步账号 private void setSyncAccount(String account) { if (!getSyncAccountName(this).equals(account)) { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); @@ -285,10 +299,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { } editor.commit(); - // 清除上次同步时间 + // clean up last sync time setLastSyncTime(this, 0); - // 清除本地gtask相关信息 + // clean up local gtask related info new Thread(new Runnable() { public void run() { ContentValues values = new ContentValues(); @@ -304,7 +318,6 @@ public class NotesPreferenceActivity extends PreferenceActivity { } } - // 移除同步账号 private void removeSyncAccount() { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); @@ -316,7 +329,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { } editor.commit(); - // 清除本地gtask相关信息 + // clean up local gtask related info new Thread(new Runnable() { public void run() { ContentValues values = new ContentValues(); @@ -327,14 +340,12 @@ public class NotesPreferenceActivity extends PreferenceActivity { }).start(); } - // 获取同步账号名称 public static String getSyncAccountName(Context context) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); } - // 设置最后同步时间 public static void setLastSyncTime(Context context, long time) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); @@ -343,15 +354,14 @@ public class NotesPreferenceActivity extends PreferenceActivity { editor.commit(); } - // 获取最后同步时间 public static long getLastSyncTime(Context context) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); } - // 广播接收器,用于接收同步状态的变化 private class GTaskReceiver extends BroadcastReceiver { + @Override public void onReceive(Context context, Intent intent) { refreshUI(); @@ -360,10 +370,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { syncStatus.setText(intent .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); } + } } - // 处理选项菜单项点击事件 public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: @@ -374,4 +384,5 @@ public class NotesPreferenceActivity extends PreferenceActivity { default: return false; } - } \ No newline at end of file + } +} diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java index 29cc099..ec6f819 100644 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java +++ b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java @@ -1,10 +1,20 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package net.micode.notes.widget; - import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; @@ -23,24 +33,20 @@ import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NotesListActivity; public abstract class NoteWidgetProvider extends AppWidgetProvider { - // 定义查询数据库时需要的列 public static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.BG_COLOR_ID, - NoteColumns.SNIPPET + NoteColumns.ID, + NoteColumns.BG_COLOR_ID, + NoteColumns.SNIPPET }; - // 定义列索引 public static final int COLUMN_ID = 0; public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_SNIPPET = 2; - private static final String TAG = "NoteWidgetProvider"; // 日志标签 + private static final String TAG = "NoteWidgetProvider"; - // 当小部件被删除时调用 @Override public void onDeleted(Context context, int[] appWidgetIds) { - // 更新数据库,将删除的小部件的WIDGET_ID设置为无效 ContentValues values = new ContentValues(); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); for (int i = 0; i < appWidgetIds.length; i++) { @@ -51,23 +57,20 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { } } - // 获取小部件的笔记信息 private Cursor getNoteWidgetInfo(Context context, int widgetId) { return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, - NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>", + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, null); } - // 更新小部件 protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { update(context, appWidgetManager, appWidgetIds, false); } - // 更新小部件,可以指定是否处于隐私模式 private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, - boolean privacyMode) { + boolean privacyMode) { for (int i = 0; i < appWidgetIds.length; i++) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { int bgId = ResourceParser.getDefaultBgId(context); @@ -97,12 +100,12 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { c.close(); } - // 创建RemoteViews对象,用于更新小部件视图 RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); - - // 生成PendingIntent,用于小部件点击事件 + /** + * Generate the pending intent to start host for the widget + */ PendingIntent pendingIntent = null; if (privacyMode) { rv.setTextViewText(R.id.widget_text, @@ -121,12 +124,9 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { } } - // 获取背景资源ID的抽象方法 protected abstract int getBgResourceId(int bgId); - // 获取布局ID的抽象方法 protected abstract int getLayoutId(); - // 获取小部件类型的抽象方法 protected abstract int getWidgetType(); -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java index 9470d13..adcb2f7 100644 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java +++ b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package net.micode.notes.widget; @@ -12,33 +23,25 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.ResourceParser; -// 继承自NoteWidgetProvider,并实现2x2网格大小的笔记小部件 + public class NoteWidgetProvider_2x extends NoteWidgetProvider { - // 当小部件需要更新时调用 @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - // 调用父类的更新方法 super.update(context, appWidgetManager, appWidgetIds); } - // 获取小部件的布局ID @Override protected int getLayoutId() { - // 返回2x2网格小部件的布局资源ID return R.layout.widget_2x; } - // 获取背景资源ID @Override protected int getBgResourceId(int bgId) { - // 根据传入的背景ID,返回对应的2x2网格小部件背景资源ID return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); } - // 获取小部件类型 @Override protected int getWidgetType() { - // 返回小部件的类型,这里是2x2网格 return Notes.TYPE_WIDGET_2X; } -} \ No newline at end of file +} diff --git a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java index 060f9b7..c12a02e 100644 --- a/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java +++ b/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java @@ -1,6 +1,17 @@ /* - * 版权声明,表明这段代码是由MiCode开源社区拥有,并在Apache License 2.0下授权。 - * 许可证的具体内容可以在http://www.apache.org/licenses/LICENSE-2.0 查看。 + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package net.micode.notes.widget; @@ -12,33 +23,24 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.ResourceParser; -// 继承自NoteWidgetProvider,并实现4x4网格大小的笔记小部件 + public class NoteWidgetProvider_4x extends NoteWidgetProvider { - // 当小部件需要更新时调用 @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - // 调用父类的更新方法 super.update(context, appWidgetManager, appWidgetIds); } - // 获取小部件的布局ID - @Override protected int getLayoutId() { - // 返回4x4网格小部件的布局资源ID return R.layout.widget_4x; } - // 获取背景资源ID @Override protected int getBgResourceId(int bgId) { - // 根据传入的背景ID,返回对应的4x4网格小部件背景资源ID return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); } - // 获取小部件类型 @Override protected int getWidgetType() { - // 返回小部件的类型,这里是4x4网格 return Notes.TYPE_WIDGET_4X; } -} \ No newline at end of file +} diff --git a/app/src/main/res/layout/account_dialog_title.xml b/app/src/main/res/layout/account_dialog_title.xml index d4e4fc2..7717112 100644 --- a/app/src/main/res/layout/account_dialog_title.xml +++ b/app/src/main/res/layout/account_dialog_title.xml @@ -1,49 +1,43 @@ - + +--> - - + - - + android:id="@+id/account_dialog_title" + style="?android:attr/textAppearanceMedium" + android:singleLine="true" + android:ellipsize="end" + android:gravity="center" + android:layout_marginTop="-2.7dip" + android:layout_marginBottom="-2.7dip" + android:layout_width="fill_parent" + android:layout_height="wrap_content"/> - - + android:id="@+id/account_dialog_subtitle" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_marginTop="5dip" + android:layout_marginBottom="1dip" + android:gravity="center"/> + \ No newline at end of file diff --git a/app/src/main/res/layout/add_account_text.xml b/app/src/main/res/layout/add_account_text.xml index dbc0f4e..c799178 100644 --- a/app/src/main/res/layout/add_account_text.xml +++ b/app/src/main/res/layout/add_account_text.xml @@ -1,43 +1,32 @@ - + + +--> + - - - - - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:minHeight="50dip" + android:gravity="center_vertical" + android:orientation="vertical"> + - - - - - + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center" + android:textAppearance="?android:attr/textAppearanceMedium" + android:text="@string/preferences_add_account" /> \ No newline at end of file diff --git a/app/src/main/res/layout/datetime_picker.xml b/app/src/main/res/layout/datetime_picker.xml index 63c2677..f10d592 100644 --- a/app/src/main/res/layout/datetime_picker.xml +++ b/app/src/main/res/layout/datetime_picker.xml @@ -1,77 +1,56 @@ - - - +--> + android:orientation="horizontal" + android:layout_gravity="center_horizontal" + android:layout_width="wrap_content" + android:layout_height="wrap_content"> + android:id="@+id/date" + android:layout_width="120dip" + android:layout_height="wrap_content" + android:focusable="true" + android:focusableInTouchMode="true" + /> + android:id="@+id/hour" + android:layout_width="50dip" + android:layout_height="wrap_content" + android:layout_marginLeft="5dip" + android:focusable="true" + android:focusableInTouchMode="true" + /> + android:id="@+id/minute" + android:layout_width="50dip" + android:layout_height="wrap_content" + android:layout_marginLeft="5dip" + android:focusable="true" + android:focusableInTouchMode="true" + /> - - - - - - - - - - - - - - + android:id="@+id/amPm" + android:layout_width="50dip" + android:layout_height="wrap_content" + android:layout_marginLeft="5dip" + android:focusable="true" + android:focusableInTouchMode="true" + /> + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_edit_text.xml b/app/src/main/res/layout/dialog_edit_text.xml index 0057b52..361b39a 100644 --- a/app/src/main/res/layout/dialog_edit_text.xml +++ b/app/src/main/res/layout/dialog_edit_text.xml @@ -1,33 +1,23 @@ - +--> - - - - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/et_foler_name" + android:layout_width="fill_parent" + android:hint="@string/hint_foler_name" + android:layout_height="fill_parent" /> \ No newline at end of file diff --git a/app/src/main/res/layout/folder_list_item.xml b/app/src/main/res/layout/folder_list_item.xml index 6bd3167..77e8148 100644 --- a/app/src/main/res/layout/folder_list_item.xml +++ b/app/src/main/res/layout/folder_list_item.xml @@ -1,52 +1,29 @@ - + - - - - - android:minHeight="50dip" - - - - - + 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. +--> - - - - - + - \ No newline at end of file + + \ No newline at end of file diff --git a/app/src/main/res/layout/note_edit.xml b/app/src/main/res/layout/note_edit.xml index c08e24a..3f0c279 100644 --- a/app/src/main/res/layout/note_edit.xml +++ b/app/src/main/res/layout/note_edit.xml @@ -16,704 +16,395 @@ --> + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:background="@drawable/list_background" + xmlns:android="http://schemas.android.com/apk/res/android"> + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="vertical"> + android:id="@+id/note_title" + android:layout_width="fill_parent" + android:layout_height="wrap_content"> + android:id="@+id/tv_modified_date" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1" + android:layout_gravity="left|center_vertical" + android:layout_marginRight="8dip" + android:textAppearance="@style/TextAppearanceSecondaryItem" /> + android:id="@+id/iv_alert_icon" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:background="@drawable/title_alert" /> - + android:id="@+id/tv_alert_date" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:layout_marginLeft="2dip" + android:layout_marginRight="8dip" + android:textAppearance="@style/TextAppearanceSecondaryItem" /> + + android:id="@+id/menu_more" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center" + android:onClick="OnOpenMenu" + android:background="@drawable/ic_menu_more_dark" /> + android:id="@+id/btn_set_bg_color" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:padding="10dp" + android:layout_gravity="center" + android:background="@drawable/bg_btn_set_color" /> + android:id="@+id/sv_note_edit" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="vertical"> + android:layout_width="fill_parent" + android:layout_height="7dip" + android:background="@drawable/bg_color_btn_mask" /> + android:layout_width="fill_parent" + android:layout_height="0dip" + android:layout_weight="1" + android:scrollbars="none" + android:overScrollMode="never" + android:layout_gravity="left|top" + android:fadingEdgeLength="0dip"> + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="vertical"> + android:id="@+id/note_edit_view" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:gravity="left|top" + android:background="@null" + android:autoLink="all" + android:linksClickable="false" + android:minLines="12" + android:textAppearance="@style/TextAppearancePrimaryItem" + android:lineSpacingMultiplier="1.2" /> + android:id="@+id/note_edit_list" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:layout_marginLeft="-10dip" + android:visibility="gone" /> + android:layout_width="fill_parent" + android:layout_height="7dip" + android:background="@drawable/bg_color_btn_mask" /> + android:layout_height="43dip" + android:layout_width="wrap_content" + android:background="@drawable/bg_color_btn_mask" + android:layout_gravity="top|right" /> + android:id="@+id/note_bg_color_selector" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:background="@drawable/note_edit_color_selector_panel" + android:layout_marginTop="30dip" + android:layout_marginRight="8dip" + android:layout_gravity="top|right" + android:visibility="gone"> + android:layout_width="0dip" + android:layout_height="match_parent" + android:layout_weight="1"> + android:id="@+id/iv_bg_yellow" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + android:id="@+id/iv_bg_yellow_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:layout_marginRight="5dip" + android:focusable="false" + android:visibility="gone" + android:src="@drawable/selected" /> + android:layout_width="0dip" + android:layout_height="match_parent" + android:layout_weight="1"> + android:id="@+id/iv_bg_blue" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + android:id="@+id/iv_bg_blue_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:layout_marginRight="3dip" + android:src="@drawable/selected" /> + android:layout_width="0dip" + android:layout_height="match_parent" + android:layout_weight="1"> + android:id="@+id/iv_bg_white" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + android:id="@+id/iv_bg_white_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:layout_marginRight="2dip" + android:src="@drawable/selected" /> + android:layout_width="0dip" + android:layout_height="match_parent" + android:layout_weight="1"> + android:id="@+id/iv_bg_green" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + android:id="@+id/iv_bg_green_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:src="@drawable/selected" /> + android:layout_width="0dip" + android:layout_height="match_parent" + android:layout_weight="1"> + android:id="@+id/iv_bg_red" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + android:id="@+id/iv_bg_red_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:src="@drawable/selected" /> + android:id="@+id/font_size_selector" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:background="@drawable/font_size_selector_bg" + android:layout_gravity="bottom" + android:visibility="gone"> + android:id="@+id/ll_font_small" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:layout_gravity="center" + android:gravity="center"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/font_small" + android:layout_marginBottom="5dip" /> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/menu_font_small" + android:textAppearance="@style/TextAppearanceUnderMenuIcon" /> + android:id="@+id/iv_small_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:layout_marginRight="6dip" + android:layout_marginBottom="-7dip" + android:focusable="false" + android:visibility="gone" + android:src="@drawable/selected" /> + android:id="@+id/ll_font_normal" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:layout_gravity="center" + android:gravity="center"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/font_normal" + android:layout_marginBottom="5dip" /> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/menu_font_normal" + android:textAppearance="@style/TextAppearanceUnderMenuIcon" /> + android:id="@+id/iv_medium_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:layout_marginRight="6dip" + android:layout_marginBottom="-7dip" + android:src="@drawable/selected" /> + android:id="@+id/ll_font_large" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:layout_gravity="center" + android:gravity="center"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/font_large" + android:layout_marginBottom="5dip" /> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/menu_font_large" + android:textAppearance="@style/TextAppearanceUnderMenuIcon" /> + android:id="@+id/iv_large_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:layout_marginRight="6dip" + android:layout_marginBottom="-7dip" + android:src="@drawable/selected" /> + android:id="@+id/ll_font_super" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:layout_gravity="center" + android:gravity="center"> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/font_super" + android:layout_marginBottom="5dip" /> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/menu_font_super" + android:textAppearance="@style/TextAppearanceUnderMenuIcon" /> + android:id="@+id/iv_super_select" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="bottom|right" + android:focusable="false" + android:visibility="gone" + android:layout_marginRight="6dip" + android:layout_marginBottom="-7dip" + android:src="@drawable/selected" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/layout/note_edit_list_item.xml b/app/src/main/res/layout/note_edit_list_item.xml index 57a8fb0..a885f9c 100644 --- a/app/src/main/res/layout/note_edit_list_item.xml +++ b/app/src/main/res/layout/note_edit_list_item.xml @@ -1,66 +1,39 @@ - + - - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="wrap_content"> - - - - - - - + android:id="@+id/cb_edit_item" + android:layout_width="wrap_content" + android:layout_height="28dip" + android:checked="false" + android:focusable="false" + android:layout_gravity="top|left" /> - - - - - - - - + android:id="@+id/et_edit_text" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:lineSpacingMultiplier="1.2" + android:layout_gravity="center_vertical" + android:textAppearance="@style/TextAppearancePrimaryItem" + android:background="@null" /> - \ No newline at end of file diff --git a/app/src/main/res/layout/note_item.xml b/app/src/main/res/layout/note_item.xml index 85d7d40..d541f6a 100644 --- a/app/src/main/res/layout/note_item.xml +++ b/app/src/main/res/layout/note_item.xml @@ -1,133 +1,78 @@ - +--> - - - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/note_item" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> - - - - + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:gravity="center_vertical"> - - - - - + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> - - - - - - + android:id="@+id/tv_name" + android:layout_width="wrap_content" + android:layout_height="0dip" + android:layout_weight="1" + android:textAppearance="@style/TextAppearancePrimaryItem" + android:visibility="gone" /> - - - + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical"> - - - - - + android:id="@+id/tv_title" + android:layout_width="0dip" + android:layout_height="wrap_content" + android:layout_weight="1" + android:singleLine="true" /> - - - - - + android:id="@+id/tv_time" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearanceSecondaryItem" /> + android:id="@android:id/checkbox" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:focusable="false" + android:clickable="false" + android:visibility="gone" /> - - - - - - + android:id="@+id/iv_alert_icon" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="top|right"/> - - - - diff --git a/app/src/main/res/layout/note_list.xml b/app/src/main/res/layout/note_list.xml index 9c89da3..b62a661 100644 --- a/app/src/main/res/layout/note_list.xml +++ b/app/src/main/res/layout/note_list.xml @@ -1,117 +1,69 @@ - + - - - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:background="@drawable/list_background"> - - - + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="vertical"> - - - - - - - - - + android:id="@+id/tv_title_bar" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:background="@drawable/title_bar_bg" + android:visibility="gone" + android:gravity="center_vertical" + android:singleLine="true" + android:textColor="#FFEAD1AE" + android:textSize="@dimen/text_font_size_medium" /> + android:id="@+id/notes_list" + android:layout_width="fill_parent" + android:layout_height="0dip" + android:layout_weight="1" + android:cacheColorHint="@null" + android:listSelector="@android:color/transparent" + android:divider="@null" + android:fadingEdge="@null" /> - - - - - - -