Compare commits

..

43 Commits

Author SHA1 Message Date
zhangqing a47e5924c3 1
1 week ago
zhangqing bb65bcadad 1
3 weeks ago
zhangqing 8b31f5f248 1
3 weeks ago
zhangqing 14c079710e 1
3 weeks ago
zhangqing 16c437cc47 1
3 weeks ago
zhangqing da6f4022fe 1
3 weeks ago
zhangqing 8af82dd3d9 1
3 weeks ago
zhangqing a485982f05 1
3 weeks ago
zhangqing 8ab652dfbe 1
3 weeks ago
zhangqing 9050d31519 1
3 weeks ago
zhangqing c7d0138c60 1
3 weeks ago
zhangqing 22fdfec7d2 1
3 weeks ago
zhangqing 3a30d87e4d 1
3 weeks ago
zhangqing bd61291b63 1
3 weeks ago
zhangqing 98a1123ad8 1
3 weeks ago
zhangqing c717dc8cd6 1
3 weeks ago
zhangqing 5d7861efca 1
3 weeks ago
zhangqing efddb74a19 1
3 weeks ago
zhangqing 4892c33aab 1
3 weeks ago
zhangqing 3b0bf51ff7 1
3 weeks ago
zhangqing 459fc3c707 1
3 weeks ago
zhangqing 5c9b6e705d 1
3 weeks ago
zhangqing ec667998ff 1
3 weeks ago
zhangqing 1b7764a848 1
3 weeks ago
zhangqing f4a1eb2f2b 1
3 weeks ago
zhangqing 41d99251dd 1
3 weeks ago
zhangqing dc47c8bdf3 修改
1 month ago
zhangqing 51e9953203 1
1 month ago
zhangqing 11d4eb7cf6 修改
1 month ago
p4bog53jv 16a9607336 报告新版
1 month ago
zhangqing 6ee1db494f 报告新版
1 month ago
p4bog53jv 5a32137102 报告完整版
1 month ago
zhangqing 0af70798dc 报告完整版
1 month ago
p4bog53jv 7d5f3dc6b6 报告完整版
1 month ago
zhangqing 7690398fe0 报告完整版
1 month ago
p4bog53jv 818464c518 报告完整版
1 month ago
zhangqing e0d0ebff59 更新报告
1 month ago
p4bog53jv a4471d0096 更新报告
2 months ago
zhangqing 4ecb33a8f4 更新报告
2 months ago
p4bog53jv b6bb460151 更新报告
2 months ago
zhangqing 5482add6e2 更新报告
2 months ago
p4bog53jv 2089613de2 合并基本功能报告
2 months ago
zhangqing b11cb30b4c 列出小米标签基本功能
2 months ago

Binary file not shown.

@ -14,60 +14,88 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data; // 包声明
import android.content.Context; import android.content.Context; // 导入上下文类
import android.database.Cursor; import android.database.Cursor; // 导入数据库游标类
import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Phone; // 导入联系人电话相关类
import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Data; // 导入联系人数据相关类
import android.telephony.PhoneNumberUtils; import android.telephony.PhoneNumberUtils; // 导入电话号码工具类
import android.util.Log; import android.util.Log; // 导入日志类
import java.util.HashMap; import java.util.HashMap; // 导入HashMap类用于缓存联系人信息
/**
*
*
*/
public class Contact { public class Contact {
// 联系人缓存使用HashMap存储电话号码到联系人姓名的映射提高查询效率
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact"; 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 + "'" * ID
+ " AND " + Data.RAW_CONTACT_ID + " IN " *
+ "(SELECT raw_contact_id " * 使PHONE_NUMBERS_EQUAL
+ " FROM phone_lookup" */
+ " WHERE min_match = '+')"; private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER // 电话号码相等比较
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" // MIME类型为电话类型
+ " AND " + Data.RAW_CONTACT_ID + " IN " // 原始联系人ID在子查询中
+ "(SELECT raw_contact_id " // 子查询开始
+ " FROM phone_lookup" // 从电话查找表
+ " WHERE min_match = '+')"; // 最小匹配条件
/**
*
*
* @param context 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 如果缓存为空,则初始化缓存
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>(); // 创建新的HashMap
} }
// 先从缓存中查找,如果找到则直接返回
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber); // 返回缓存中的姓名
} }
String selection = CALLER_ID_SELECTION.replace("+", // 构建查询条件:替换选择语句中的'+'为最小匹配数
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); // PhoneNumberUtils.toCallerIDMinMatch将电话号码转换为最小匹配格式
String selection = CALLER_ID_SELECTION.replace("+", // 替换占位符
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); // 获取电话号码的最小匹配格式
// 查询联系人数据库
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI, // 查询URI联系人数据URI
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME }, // 要返回的列:显示名称
selection, selection, // 选择条件
new String[] { phoneNumber }, new String[] { phoneNumber }, // 选择参数:电话号码
null); null); // 排序方式(无)
if (cursor != null && cursor.moveToFirst()) { // 处理查询结果
if (cursor != null && cursor.moveToFirst()) { // 如果游标不为空且有数据
try { try {
String name = cursor.getString(0); String name = cursor.getString(0); // 获取第一列的显示名称索引0
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name); // 将结果存入缓存
return name; return name; // 返回姓名
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); // 处理数组越界异常
return null; Log.e(TAG, " Cursor get string error " + e.toString()); // 记录错误日志
return null; // 发生异常时返回null
} finally { } finally {
cursor.close(); cursor.close(); // 确保关闭游标,释放资源
} }
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); // 没有找到匹配的联系人
return null; Log.d(TAG, "No contact matched with number:" + phoneNumber); // 记录调试日志
return null; // 返回null
} }
} }
} }

@ -16,264 +16,292 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri; // 导入Android URI类用于定义内容提供者的URI
/**
*
* URI
*/
public class Notes { public class Notes {
// 内容提供者的授权标识用于ContentProvider的authority属性
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes";
// 日志标签,用于调试输出
public static final String TAG = "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; 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_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER}
*/ */
public static final int ID_ROOT_FOLDER = 0; public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // Intent额外数据键名常量用于在不同组件间传递数据
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0; // 小部件类型常量
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x大小的小部件
public static final int TYPE_WIDGET_4X = 1; // 4x大小的小部件
/**
*
* MIME
*/
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记MIME类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话笔记MIME类型
} }
/** /**
* Uri to query all notes and folders * URI
* URI访
*/ */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/** /**
* Uri to query data * URI
* URI访
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
*
*
*/
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id"; // 主键ID字段名
/** /**
* The parent's id for note or folder * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id"; // 父文件夹ID字段名
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date"; // 创建日期字段名
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date"; // 修改日期字段名
/** /**
* Alert date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date"; // 提醒日期字段名
/** /**
* Folder's name or text content of note *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet"; // 摘要字段名
/** /**
* Note's widget id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id"; // 小部件ID字段名
/** /**
* Note's widget type *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type"; // 小部件类型字段名
/** /**
* Note's background color's id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色ID字段名
/** /**
* For text note, it doesn't has attachment, for multi-media *
* note, it has at least one attachment * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment"; // 是否有附件字段名
/** /**
* Folder's count of notes *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count"; // 笔记数量字段名
/** /**
* The file type: folder or note *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type"; // 类型字段名
/** /**
* The last sync id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id"; // 同步ID字段名
/** /**
* Sign to indicate local modified or not *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified"; // 本地修改标记字段名
/** /**
* Original parent id before moving into temporary folder * ID
* <P> Type : INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 原始父文件夹ID字段名
/** /**
* The gtask id * GoogleID
* <P> Type : TEXT </P> * <P> : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id"; // Google任务ID字段名
/** /**
* The version code *
* <P> Type : INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version"; // 版本号字段名
} }
/**
*
*
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id"; // 主键ID字段名
/** /**
* The MIME type of the item represented by this row. * MIME
* <P> Type: Text </P> * <P> : Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type"; // MIME类型字段名
/** /**
* The reference id to note that this data belongs to * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id"; // 笔记ID字段名
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date"; // 创建日期字段名
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date"; // 修改日期字段名
/** /**
* Data's content *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String CONTENT = "content"; public static final String CONTENT = "content"; // 内容字段名
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* integer data type * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static final String DATA1 = "data1"; // 通用数据字段1
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* integer data type * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static final String DATA2 = "data2"; // 通用数据字段2
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static final String DATA3 = "data3"; // 通用数据字段3
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA4 = "data4"; // 通用数据字段4
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5"; // 通用数据字段5
} }
/**
*
*
*/
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not *
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <P> : Integer 1: 0: </P>
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1; // 模式字段使用DATA1列
public static final int MODE_CHECK_LIST = 1; public static final int MODE_CHECK_LIST = 1; // 清单模式常量
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 内容类型常量用于ContentProvider
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 String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 单项目类型
// 文本笔记的URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
} }
/**
*
*
*/
public static final class CallNote implements DataColumns { public static final class CallNote implements DataColumns {
/** /**
* Call date for this record *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1; // 通话日期字段使用DATA1列
/** /**
* Phone number for this record *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3; // 电话号码字段使用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"; // 内容类型常量用于ContentProvider
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"; // 单项目类型
// 通话笔记的URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
} }
} }

@ -26,198 +26,246 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
*
* SQLiteOpenHelper
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称常量
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
// 数据库版本常量,用于数据库升级
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
/**
*
*
*/
public interface TABLE { public interface TABLE {
// 笔记表名
public static final String NOTE = "note"; public static final String NOTE = "note";
// 数据表名
public static final String DATA = "data"; public static final String DATA = "data";
} }
// 日志标签,用于调试
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
// 单例实例
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
/**
* SQL
*
*/
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" + // 创建笔记表
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父文件夹ID
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景颜色ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建时间
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改时间
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量(用于文件夹)
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 内容摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型(笔记/文件夹/系统)
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 小部件ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标志
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父文件夹ID
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号
")"; ")";
/**
* SQL
*
*/
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" + // 创建数据表
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建时间
NoteColumns.MODIFIED_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.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容
DataColumns.DATA1 + " INTEGER," + DataColumns.DATA1 + " INTEGER," + // 通用数据字段1整数
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," + // 通用数据字段2整数
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 通用数据字段3文本
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 通用数据字段4文本
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 通用数据字段5文本
")"; ")";
/**
* SQL
* note_id
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " + // 创建索引
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; // 在note_id字段上创建索引
/** /**
* Increase folder's note count when move note to the folder *
* ID
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+ // 创建触发器
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + // 在PARENT_ID更新后触发
" BEGIN " + " BEGIN " + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + // 笔记计数加1
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + // 更新新父文件夹
" END"; " END"; // 触发器结束
/** /**
* Decrease folder's note count when move note from folder *
* ID
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " + "CREATE TRIGGER decrease_folder_count_on_update " + // 创建触发器
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + // 在PARENT_ID更新后触发
" BEGIN " + " BEGIN " + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + // 笔记计数减1
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + // 更新原父文件夹
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + // 确保计数不小于0
" END"; " END"; // 触发器结束
/** /**
* Increase folder's note count when insert new note to the folder *
*
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " + // 创建触发器
" AFTER INSERT ON " + TABLE.NOTE + " AFTER INSERT ON " + TABLE.NOTE + // 在插入笔记后触发
" BEGIN " + " BEGIN " + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + // 笔记计数加1
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + // 更新父文件夹
" END"; " END"; // 触发器结束
/** /**
* Decrease folder's note count when delete note from the folder *
*
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " + // 创建触发器
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE + // 在删除笔记后触发
" BEGIN " + " BEGIN " + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + // 笔记计数减1
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + // 更新原父文件夹
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " AND " + NoteColumns.NOTES_COUNT + ">0;" + // 确保计数不小于0
" END"; " END"; // 触发器结束
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} *
* NOTE
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " + // 创建触发器
" AFTER INSERT ON " + TABLE.DATA + " AFTER INSERT ON " + TABLE.DATA + // 在插入数据后触发
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + // 仅当MIME类型为NOTE时
" BEGIN" + " BEGIN" + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + // 设置摘要为内容
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + // 更新对应的笔记
" END"; " END"; // 触发器结束
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed *
* NOTE
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " + // 创建触发器
" AFTER UPDATE ON " + TABLE.DATA + " AFTER UPDATE ON " + TABLE.DATA + // 在更新数据后触发
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + // 仅当MIME类型为NOTE时
" BEGIN" + " BEGIN" + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + // 设置摘要为内容
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + // 更新对应的笔记
" END"; " END"; // 触发器结束
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted *
* NOTE
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " + "CREATE TRIGGER update_note_content_on_delete " + // 创建触发器
" AFTER delete ON " + TABLE.DATA + " AFTER delete ON " + TABLE.DATA + // 在删除数据后触发
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + // 仅当MIME类型为NOTE时
" BEGIN" + " BEGIN" + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.SNIPPET + "=''" + " SET " + NoteColumns.SNIPPET + "=''" + // 清空摘要
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + // 更新对应的笔记
" END"; " END"; // 触发器结束
/** /**
* Delete datas belong to note which has been deleted *
*
*/ */
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " + // 创建触发器
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE + // 在删除笔记后触发
" BEGIN" + " BEGIN" + // 触发器开始
" DELETE FROM " + TABLE.DATA + " DELETE FROM " + TABLE.DATA + // 从数据表删除
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + // 删除笔记ID对应的数据
" END"; " END"; // 触发器结束
/** /**
* Delete notes belong to folder which has been deleted *
*
*/ */
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " + // 创建触发器
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE + // 在删除笔记后触发
" BEGIN" + " BEGIN" + // 触发器开始
" DELETE FROM " + TABLE.NOTE + " DELETE FROM " + TABLE.NOTE + // 从笔记表删除
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + // 删除父文件夹ID为被删除ID的笔记
" END"; " END"; // 触发器结束
/** /**
* Move notes belong to folder which has been moved to trash folder *
*
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " + // 创建触发器
" AFTER UPDATE ON " + TABLE.NOTE + " AFTER UPDATE ON " + TABLE.NOTE + // 在更新笔记后触发
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + // 仅当新父文件夹是回收站时
" BEGIN" + " BEGIN" + // 触发器开始
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE + // 更新笔记表
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + // 设置父文件夹为回收站
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + // 更新原文件夹下的所有笔记
" END"; " END"; // 触发器结束
/**
*
* @param context
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION); // 调用父类构造函数
} }
/**
*
* @param db SQLite
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行创建笔记表的SQL语句
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db); // 重新创建笔记表的触发器
createSystemFolder(db); createSystemFolder(db); // 创建系统文件夹
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created"); // 日志记录
} }
/**
*
* @param db SQLite
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); 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_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -225,7 +273,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); 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_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 重新创建触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -234,129 +283,187 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
* @param db SQLite
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues(); // 创建内容值对象
/** /**
* call record foler for call notes *
*
*/ */
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); // 设置ID为通话记录文件夹ID
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置类型为系统类型
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入数据
/** /**
* root folder which is default folder *
*
*/ */
values.clear(); values.clear(); // 清空内容值
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); // 设置ID为根文件夹ID
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置类型为系统类型
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入数据
/** /**
* temporary folder which is used for moving note *
*
*/ */
values.clear(); values.clear(); // 清空内容值
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); // 设置ID为临时文件夹ID
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置类型为系统类型
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入数据
/** /**
* create trash folder *
*
*/ */
values.clear(); values.clear(); // 清空内容值
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); // 设置ID为回收站文件夹ID
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置类型为系统类型
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入数据
} }
/**
*
* @param db SQLite
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL); // 执行创建数据表的SQL语句
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db); // 重新创建数据表的触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建数据表索引
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created"); // 日志记录
} }
/**
*
* @param db SQLite
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) { 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_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); 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_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/**
*
* 使
* @param context
* @return
*/
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) { // 如果实例为空
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context); // 创建新实例
} }
return mInstance; return mInstance; // 返回实例
} }
/**
*
*
* @param db SQLite
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db); // 创建笔记表
createDataTable(db); createDataTable(db); // 创建数据表
} }
/**
*
*
* @param db SQLite
* @param oldVersion
* @param newVersion
*/
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false; // 是否需要重新创建触发器
boolean skipV2 = false; boolean skipV2 = false; // 是否跳过V2升级
// 从版本1升级到版本2
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db); // 执行V2升级
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // 这个升级包含了从V2到V3的升级
oldVersion++; oldVersion++; // 增加版本号
} }
// 从版本2升级到版本3如果没有跳过
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db); // 执行V3升级
reCreateTriggers = true; reCreateTriggers = true; // 需要重新创建触发器
oldVersion++; oldVersion++; // 增加版本号
} }
// 从版本3升级到版本4
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db); // 执行V4升级
oldVersion++; oldVersion++; // 增加版本号
} }
// 如果需要重新创建触发器
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db); // 重新创建笔记表触发器
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db); // 重新创建数据表触发器
} }
// 如果升级后版本号不匹配,抛出异常
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + "fails");
} }
} }
/**
* V2
*
* @param db SQLite
*/
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); // 删除已存在的note表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); // 删除已存在的data表
createNoteTable(db); createNoteTable(db); // 重新创建note表
createDataTable(db); createDataTable(db); // 重新创建data表
} }
/**
* V3
* GoogleID
* @param db SQLite
*/
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // 删除未使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 添加Google任务ID字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
ContentValues values = new ContentValues(); // 添加回收站系统文件夹
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); ContentValues values = new ContentValues(); // 创建内容值对象
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); // 设置ID为回收站文件夹ID
db.insert(TABLE.NOTE, null, values); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置类型为系统类型
db.insert(TABLE.NOTE, null, values); // 插入数据
} }
/**
* V4
*
* @param db SQLite
*/
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0"); // 添加版本号字段
} }
} }

@ -14,292 +14,364 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data; // 包声明
import android.app.SearchManager; // 导入搜索管理器类
import android.content.ContentProvider; // 导入内容提供者基类
import android.content.ContentUris; // 导入内容URI工具类
import android.content.ContentValues; // 导入内容值类
import android.content.Intent; // 导入意图类
import android.content.UriMatcher; // 导入URI匹配器类
import android.database.Cursor; // 导入数据库游标类
import android.database.sqlite.SQLiteDatabase; // 导入SQLite数据库类
import android.net.Uri; // 导入URI类
import android.text.TextUtils; // 导入文本工具类
import android.util.Log; // 导入日志类
import android.app.SearchManager; import net.micode.notes.R; // 导入资源类
import android.content.ContentProvider; import net.micode.notes.data.Notes.DataColumns; // 导入数据列接口
import android.content.ContentUris; import net.micode.notes.data.Notes.NoteColumns; // 导入笔记列接口
import android.content.ContentValues; import net.micode.notes.data.NotesDatabaseHelper.TABLE; // 导入表名接口
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;
/**
*
* ContentProviderCRUD
*
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// URI匹配器用于匹配不同的URI请求
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
// 数据库帮助类实例
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
// 日志标签
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
// URI匹配码常量
private static final int URI_NOTE = 1; // 笔记表
private static final int URI_NOTE_ITEM = 2; // 单个笔记项
private static final int URI_DATA = 3; // 数据表
private static final int URI_DATA_ITEM = 4; // 单个数据项
private static final int URI_SEARCH = 5; // 搜索
private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议
private static final int URI_NOTE = 1; // 静态代码块初始化URI匹配器
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 创建URI匹配器
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配笔记表
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单个笔记,#表示数字ID
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配数据表
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 匹配单个数据
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); 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.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. * x'0A' SQLite'\n'
* '\n'
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," // 笔记ID
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + 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_1 + "," // 建议文本1移除换行符
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," // 建议文本2移除换行符
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," // 建议图标使用资源ID
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," // 建议意图动作
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; // 建议意图数据
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; */
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION // 选择搜索投影
+ " FROM " + TABLE.NOTE // 从笔记表
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" // 条件摘要LIKE参数
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // 且不在回收站中
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 且类型为笔记
/**
*
*
* @return true
*/
@Override @Override
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext()); // 获取数据库帮助类实例(单例)
return true; return true; // 返回true表示创建成功
} }
/**
*
* URI
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return
*/
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null; // 游标变量
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取可读数据库
String id = null; String id = null; // ID变量
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) { // 根据URI匹配码进行分支
case URI_NOTE: case URI_NOTE: // 查询笔记表
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder); // 执行查询
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 查询单个笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取URI路径段中的ID第二个段
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder); // 执行带ID的查询
break; break;
case URI_DATA: case URI_DATA: // 查询数据表
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder); // 执行查询
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 查询单个数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取URI路径段中的ID
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder); // 执行带ID的查询
break; break;
case URI_SEARCH: case URI_SEARCH: // 搜索
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST: // 搜索建议
// 搜索和搜索建议不支持自定义排序和投影
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
String searchString = null; String searchString = null; // 搜索字符串
// 获取搜索字符串
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 从URI路径段获取搜索建议查询词
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1); // 获取查询词
} }
} else { } else {
searchString = uri.getQueryParameter("pattern"); // 从查询参数获取搜索模式
searchString = uri.getQueryParameter("pattern"); // 获取pattern参数
} }
if (TextUtils.isEmpty(searchString)) { if (TextUtils.isEmpty(searchString)) { // 如果搜索字符串为空
return null; return null; // 返回null
} }
try { try {
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString); // 格式化为LIKE模式%keyword%
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString }); // 执行原始查询
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString()); Log.e(TAG, "got exception: " + ex.toString()); // 记录异常
} }
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri); // 未知URI异常
} }
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri); // 设置通知URI用于数据变化通知
} }
return c; return c; // 返回游标
} }
/**
*
* URI
* @param uri URI
* @param values
* @return URI
*/
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0; // 插入的ID
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 插入笔记
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values); // 插入笔记返回ID
break; break;
case URI_DATA: case URI_DATA: // 插入数据
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID); // 获取关联的笔记ID
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values.toString()); Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 记录警告
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values); // 插入数据返回ID
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri); // 未知URI异常
} }
// Notify the note uri // 通知笔记URI变化
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); // 通知笔记URI变化
} }
// Notify the data uri // 通知数据URI变化
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); // 通知数据URI变化
} }
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId); // 返回新插入项的URI
} }
/**
*
* URI
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0; int count = 0; // 删除计数
String id = null; String id = null; // ID变量
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
boolean deleteData = false; boolean deleteData = false; // 是否删除数据标志
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 删除笔记
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 系统文件夹不允许删除ID小于等于0
count = db.delete(TABLE.NOTE, selection, selectionArgs); selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 添加ID>0条件
count = db.delete(TABLE.NOTE, selection, selectionArgs); // 执行删除
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 删除单个笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取ID
/** long noteId = Long.valueOf(id); // 转换为长整型
* ID that smaller than 0 is system folder which is not allowed to if (noteId <= 0) { // 系统文件夹不允许删除
* trash
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break; break;
} }
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 执行带ID的删除
break; break;
case URI_DATA: case URI_DATA: // 删除数据
count = db.delete(TABLE.DATA, selection, selectionArgs); count = db.delete(TABLE.DATA, selection, selectionArgs); // 执行删除
deleteData = true; deleteData = true; // 标记为删除数据
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 删除单个数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取ID
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 执行带ID的删除
deleteData = true; deleteData = true; // 标记为删除数据
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri); // 未知URI异常
} }
if (count > 0) { if (count > 0) { // 如果删除了数据
if (deleteData) { if (deleteData) { // 如果是删除数据
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI变化
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null); // 通知当前URI变化
} }
return count; return count; // 返回删除计数
} }
/**
*
* URI
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0; // 更新计数
String id = null; String id = null; // ID变量
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
boolean updateData = false; boolean updateData = false; // 是否更新数据标志
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 更新笔记
increaseNoteVersion(-1, selection, selectionArgs); increaseNoteVersion(-1, selection, selectionArgs); // 增加笔记版本
count = db.update(TABLE.NOTE, values, selection, selectionArgs); count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 执行更新
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 更新单个笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取ID
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加笔记版本
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs); // 执行带ID的更新
break; break;
case URI_DATA: case URI_DATA: // 更新数据
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs); // 执行更新
updateData = true; updateData = true; // 标记为更新数据
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 更新单个数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取ID
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs); // 执行带ID的更新
updateData = true; updateData = true; // 标记为更新数据
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri); // 未知URI异常
} }
if (count > 0) { if (count > 0) { // 如果更新了数据
if (updateData) { if (updateData) { // 如果是更新数据
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI变化
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null); // 通知当前URI变化
} }
return count; return count; // 返回更新计数
} }
/**
*
* AND
* @param selection
* @return
*/
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); // 如果不为空则添加AND和括号
} }
/**
*
*
* @param id ID-1使
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120); // 构建SQL语句
sql.append("UPDATE "); sql.append("UPDATE "); // UPDATE关键字
sql.append(TABLE.NOTE); sql.append(TABLE.NOTE); // 表名
sql.append(" SET "); sql.append(" SET "); // SET关键字
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION); // 版本字段
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号加1
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) { // 如果有条件
sql.append(" WHERE "); sql.append(" WHERE "); // WHERE关键字
} }
if (id > 0) { if (id > 0) { // 如果有指定ID
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); sql.append(NoteColumns.ID + "=" + String.valueOf(id)); // ID条件
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) { // 如果有选择语句
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection; // 解析选择语句
// 替换参数占位符
for (String args : selectionArgs) { for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args); selectString = selectString.replaceFirst("\\?", args); // 替换问号为实际参数
} }
sql.append(selectString); sql.append(selectString); // 添加选择条件
} }
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL
} }
/**
* MIME
* null
* @param uri URI
* @return MIME
*/
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null; // 暂未实现
} }
}
}

@ -25,58 +25,64 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class MetaData extends Task { public class MetaData extends Task { // 元数据类继承自Task
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName(); // 日志标签
private String mRelatedGid = null; private String mRelatedGid = null; // 关联的Google任务ID
// 设置元数据
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); // 在元数据中添加Google任务ID
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid"); // 添加失败
} }
setNotes(metaInfo.toString()); setNotes(metaInfo.toString()); // 将元数据JSON字符串设为备注
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME); // 设置名称为元数据笔记名称
} }
// 获取关联的Google任务ID
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
// 重写:检查是否值得保存(只要有备注就值得保存)
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null; // 只要有备注就值得保存
} }
// 重写从远程JSON设置内容
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js); // 调用父类方法
if (getNotes() != null) { if (getNotes() != null) { // 如果有备注
try { try {
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim()); // 解析备注为JSON
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); // 获取关联的Google任务ID
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid"); // 获取失败
mRelatedGid = null; mRelatedGid = null; // 设为null
} }
} }
} }
// 重写从本地JSON设置内容不应该被调用
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called // 这个函数不应该被调用
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); // 抛出异常
} }
// 重写从内容生成本地JSON不应该被调用
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); // 抛出异常
} }
// 重写:获取同步操作(不应该被调用)
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called"); // 抛出异常
} }
}
}

@ -20,82 +20,86 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
public abstract class Node { public abstract class Node { // 抽象节点类,所有数据节点的基类
public static final int SYNC_ACTION_NONE = 0; // 同步操作类型常量
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_LOCAL = 4; // 从本地删除
public static final int SYNC_ACTION_DEL_REMOTE = 3; public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 更新远程
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 更新本地
public static final int SYNC_ACTION_DEL_LOCAL = 4; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 更新冲突
public static final int SYNC_ACTION_ERROR = 8; // 同步错误
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
private String mGid; // Google任务ID
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; private String mName; // 节点名称
private long mLastModified; // 最后修改时间
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; private boolean mDeleted; // 删除标记
public static final int SYNC_ACTION_ERROR = 8; // 构造函数
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
public Node() { public Node() {
mGid = null; mGid = null; // Google任务ID为空
mName = ""; mName = ""; // 名称为空字符串
mLastModified = 0; mLastModified = 0; // 最后修改时间为0
mDeleted = false; mDeleted = false; // 未删除
} }
// 抽象方法获取创建操作的JSON对象
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();
// 抽象方法:根据游标获取同步操作类型
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
// 设置Google任务ID
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
// 设置节点名称
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
// 设置最后修改时间
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
// 设置删除标记
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
// 获取Google任务ID
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
// 获取节点名称
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
// 获取最后修改时间
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
// 获取删除标记
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
}
}

@ -36,136 +36,133 @@ import org.json.JSONObject;
public class SqlData { public class SqlData {
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName(); // 日志标签,使用类名
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999; // 无效ID标识
// 查询数据库时使用的列投影(需要查询的列)
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0; // ID列在游标中的索引
public static final int DATA_MIME_TYPE_COLUMN = 1; // MIME类型列索引
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; // DATA1列索引
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_DATA_3_COLUMN = 4; // DATA3列索引
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; private ContentResolver mContentResolver; // 内容解析器,用于数据库操作
private boolean mIsCreate; // 是否为新建数据记录
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; private long mDataId; // 数据记录ID
private String mDataMimeType; // MIME类型
private ContentResolver mContentResolver; private String mDataContent; // 数据内容
private long mDataContentData1; // 数据字段1长整型
private boolean mIsCreate; private String mDataContentData3; // 数据字段3字符串
private ContentValues mDiffDataValues; // 存储需要更新的字段差异值
private long mDataId;
// 构造函数创建新的SqlData对象未存入数据库
private String mDataMimeType;
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = true; mIsCreate = true; // 标记为新创建
mDataId = INVALID_ID; mDataId = INVALID_ID; // 初始化为无效ID
mDataMimeType = DataConstants.NOTE; mDataMimeType = DataConstants.NOTE; // 默认MIME类型为笔记
mDataContent = ""; mDataContent = ""; // 内容初始化为空
mDataContentData1 = 0; mDataContentData1 = 0; // 数据字段1初始化为0
mDataContentData3 = ""; mDataContentData3 = ""; // 数据字段3初始化为空
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues(); // 初始化差异值容器
} }
// 构造函数从数据库游标创建SqlData对象
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; mIsCreate = false; // 标记为已存在数据库
loadFromCursor(c); loadFromCursor(c); // 从游标加载数据
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues(); // 初始化差异值容器
} }
// 从数据库游标加载数据到对象字段
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN); // 获取ID
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); // 获取MIME类型
mDataContent = c.getString(DATA_CONTENT_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN); // 获取内容
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); // 获取DATA1
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); // 获取DATA3
} }
// 从JSON对象设置数据内容并记录差异值
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) { // 如果是新建或ID不同
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId); // 记录ID差异
} }
mDataId = dataId; mDataId = dataId; // 更新当前ID
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { // 如果是新建或MIME类型不同
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); // 记录MIME类型差异
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType; // 更新MIME类型
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) { // 如果是新建或内容不同
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent); // 记录内容差异
} }
mDataContent = dataContent; mDataContent = dataContent; // 更新内容
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) { // 如果是新建或DATA1不同
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1); // 记录DATA1差异
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1; // 更新DATA1
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { // 如果是新建或DATA3不同
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3); // 记录DATA3差异
} }
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3; // 更新DATA3
} }
// 将对象内容转换为JSON格式
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) { // 如果对象是新建的(未保存到数据库)
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
return null; return null; // 返回null因为数据不存在
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
js.put(DataColumns.ID, mDataId); js.put(DataColumns.ID, mDataId); // 添加ID字段
js.put(DataColumns.MIME_TYPE, mDataMimeType); js.put(DataColumns.MIME_TYPE, mDataMimeType); // 添加MIME类型字段
js.put(DataColumns.CONTENT, mDataContent); js.put(DataColumns.CONTENT, mDataContent); // 添加内容字段
js.put(DataColumns.DATA1, mDataContentData1); js.put(DataColumns.DATA1, mDataContentData1); // 添加DATA1字段
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3); // 添加DATA3字段
return js; return js; // 返回JSON对象
} }
// 提交数据到数据库(插入或更新)
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { // 如果是新建数据
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID); // 移除无效ID
} }
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId); // 添加笔记ID
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); // 插入数据库
try { try {
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1)); // 从URI获取新生成的ID
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed"); // 抛出异常
} }
} else { } else { // 如果是更新数据
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) { // 如果有需要更新的字段
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) { // 如果不验证版本
// 直接更新数据
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else { // 如果需要验证版本
// 带版本控制的更新(防止同步冲突)
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
@ -173,17 +170,18 @@ public class SqlData {
String.valueOf(noteId), String.valueOf(version) String.valueOf(noteId), String.valueOf(version)
}); });
} }
if (result == 0) { if (result == 0) { // 如果没有更新任何行
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
} }
mDiffDataValues.clear(); mDiffDataValues.clear(); // 清空差异值
mIsCreate = false; mIsCreate = false; // 标记为已创建
} }
// 获取数据ID
public long getId() { public long getId() {
return mDataId; return mDataId;
} }
} }

@ -39,10 +39,11 @@ import java.util.ArrayList;
public class SqlNote { public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999; // 无效ID标识
// 笔记查询的列投影
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,208 +53,183 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
// 各列在游标中的索引
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
private Context mContext; private Context mContext; // 上下文
private ContentResolver mContentResolver; // 内容解析器
private ContentResolver mContentResolver; private boolean mIsCreate; // 是否为新建笔记
private long mId; // 笔记ID
private boolean mIsCreate; private long mAlertDate; // 提醒日期
private int mBgColorId; // 背景颜色ID
private long mId; private long mCreatedDate; // 创建日期
private int mHasAttachment; // 是否有附件
private long mAlertDate; private long mModifiedDate; // 修改日期
private long mParentId; // 父笔记ID
private int mBgColorId; private String mSnippet; // 内容摘要
private int mType; // 笔记类型(笔记/文件夹/系统)
private long mCreatedDate; private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
private int mHasAttachment; private long mOriginParent; // 原始父笔记ID
private long mVersion; // 版本号
private long mModifiedDate; private ContentValues mDiffNoteValues; // 笔记差异值
private ArrayList<SqlData> mDataList; // 笔记关联的数据列表
private long mParentId;
// 构造函数:创建新笔记
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true; // 标记为新创建
mId = INVALID_ID; mId = INVALID_ID; // 初始化为无效ID
mAlertDate = 0; mAlertDate = 0; // 提醒日期为0
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context); // 获取默认背景颜色
mCreatedDate = System.currentTimeMillis(); mCreatedDate = System.currentTimeMillis(); // 创建时间为当前时间
mHasAttachment = 0; mHasAttachment = 0; // 默认无附件
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis(); // 修改时间为当前时间
mParentId = 0; mParentId = 0; // 父笔记ID为0根目录
mSnippet = ""; mSnippet = ""; // 摘要为空
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE; // 类型为普通笔记
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 小部件ID无效
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 小部件类型无效
mOriginParent = 0; mOriginParent = 0; // 原始父笔记ID为0
mVersion = 0; mVersion = 0; // 版本号为0
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化差异值容器
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化数据列表
} }
// 构造函数:从数据库游标创建笔记对象
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false; // 标记为已存在
loadFromCursor(c); loadFromCursor(c); // 从游标加载笔记信息
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化数据列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果是普通笔记类型
loadDataContent(); loadDataContent(); // 加载关联的数据内容
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化差异值容器
} }
// 构造函数从笔记ID创建笔记对象
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false; // 标记为已存在
loadFromCursor(id); loadFromCursor(id); // 从ID加载笔记信息
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化数据列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果是普通笔记类型
loadDataContent(); loadDataContent(); // 加载关联的数据内容
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化差异值容器
} }
// 从笔记ID加载笔记信息
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
// 查询指定ID的笔记
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] { String.valueOf(id) }, null);
String.valueOf(id)
}, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext(); // 移动到第一行
loadFromCursor(c); loadFromCursor(c); // 从游标加载数据
} else { } else {
Log.w(TAG, "loadFromCursor: cursor = null"); Log.w(TAG, "loadFromCursor: cursor = null");
} }
} finally { } finally {
if (c != null) if (c != null)
c.close(); c.close(); // 关闭游标
} }
} }
// 从数据库游标加载笔记信息到对象字段
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN); // 获取笔记ID
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); // 获取提醒日期
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); // 获取背景颜色ID
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); mCreatedDate = c.getLong(CREATED_DATE_COLUMN); // 获取创建日期
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); // 获取附件标记
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); // 获取修改日期
mParentId = c.getLong(PARENT_ID_COLUMN); mParentId = c.getLong(PARENT_ID_COLUMN); // 获取父笔记ID
mSnippet = c.getString(SNIPPET_COLUMN); mSnippet = c.getString(SNIPPET_COLUMN); // 获取内容摘要
mType = c.getInt(TYPE_COLUMN); mType = c.getInt(TYPE_COLUMN); // 获取笔记类型
mWidgetId = c.getInt(WIDGET_ID_COLUMN); mWidgetId = c.getInt(WIDGET_ID_COLUMN); // 获取小部件ID
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); // 获取小部件类型
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN); // 获取版本号
} }
// 加载笔记关联的数据内容
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear(); // 清空数据列表
try { try {
// 查询该笔记的所有关联数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] { String.valueOf(mId) }, null);
String.valueOf(mId)
}, null);
if (c != null) { if (c != null) {
if (c.getCount() == 0) { if (c.getCount() == 0) { // 如果没有数据
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");
return; return;
} }
while (c.moveToNext()) { while (c.moveToNext()) { // 遍历所有数据行
SqlData data = new SqlData(mContext, c); SqlData data = new SqlData(mContext, c); // 创建SqlData对象
mDataList.add(data); mDataList.add(data); // 添加到列表
} }
} else { } else {
Log.w(TAG, "loadDataContent: cursor = null"); Log.w(TAG, "loadDataContent: cursor = null");
} }
} finally { } finally {
if (c != null) if (c != null)
c.close(); c.close(); // 关闭游标
} }
} }
// 从JSON对象设置笔记内容
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记元数据
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { // 如果是系统文件夹
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder"); // 系统文件夹不能修改
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { // 如果是普通文件夹
// for folder we can only update the snnipet and type // 对于文件夹,只能更新摘要和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) { // 如果是新建或摘要不同
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); // 记录摘要差异
} }
mSnippet = snippet; mSnippet = snippet; // 更新摘要
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) { // 如果是新建或类型不同
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type); // 记录类型差异
} }
mType = type; mType = type; // 更新类型
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { // 如果是普通笔记
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取数据数组
// 更新笔记ID
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id); mDiffNoteValues.put(NoteColumns.ID, id);
} }
mId = id; mId = id;
// 更新提醒日期
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0; .getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
@ -261,6 +237,7 @@ public class SqlNote {
} }
mAlertDate = alertDate; mAlertDate = alertDate;
// 更新背景颜色ID
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) { if (mIsCreate || mBgColorId != bgColorId) {
@ -268,6 +245,7 @@ public class SqlNote {
} }
mBgColorId = bgColorId; mBgColorId = bgColorId;
// 更新创建日期
long createDate = note.has(NoteColumns.CREATED_DATE) ? note long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) { if (mIsCreate || mCreatedDate != createDate) {
@ -275,6 +253,7 @@ public class SqlNote {
} }
mCreatedDate = createDate; mCreatedDate = createDate;
// 更新附件标记
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0; .getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) { if (mIsCreate || mHasAttachment != hasAttachment) {
@ -282,6 +261,7 @@ public class SqlNote {
} }
mHasAttachment = hasAttachment; mHasAttachment = hasAttachment;
// 更新修改日期
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) { if (mIsCreate || mModifiedDate != modifiedDate) {
@ -289,6 +269,7 @@ public class SqlNote {
} }
mModifiedDate = modifiedDate; mModifiedDate = modifiedDate;
// 更新父笔记ID
long parentId = note.has(NoteColumns.PARENT_ID) ? note long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0; .getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) { if (mIsCreate || mParentId != parentId) {
@ -296,6 +277,7 @@ public class SqlNote {
} }
mParentId = parentId; mParentId = parentId;
// 更新内容摘要
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
@ -303,6 +285,7 @@ public class SqlNote {
} }
mSnippet = snippet; mSnippet = snippet;
// 更新笔记类型
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
@ -310,6 +293,7 @@ public class SqlNote {
} }
mType = type; mType = type;
// 更新小部件ID
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID; : AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) { if (mIsCreate || mWidgetId != widgetId) {
@ -317,6 +301,7 @@ public class SqlNote {
} }
mWidgetId = widgetId; mWidgetId = widgetId;
// 更新小部件类型
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) { if (mIsCreate || mWidgetType != widgetType) {
@ -324,6 +309,7 @@ public class SqlNote {
} }
mWidgetType = widgetType; mWidgetType = widgetType;
// 更新原始父笔记ID
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) { if (mIsCreate || mOriginParent != originParent) {
@ -331,45 +317,50 @@ public class SqlNote {
} }
mOriginParent = originParent; mOriginParent = originParent;
// 处理关联的数据内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i); // 获取单个数据对象
SqlData sqlData = null; SqlData sqlData = null;
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) { // 如果数据有ID
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
// 在现有数据列表中查找匹配的数据
for (SqlData temp : mDataList) { for (SqlData temp : mDataList) {
if (dataId == temp.getId()) { if (dataId == temp.getId()) {
sqlData = temp; sqlData = temp; // 找到匹配的数据
break;
} }
} }
} }
if (sqlData == null) { if (sqlData == null) { // 如果没有找到匹配的数据
sqlData = new SqlData(mContext); sqlData = new SqlData(mContext); // 创建新数据对象
mDataList.add(sqlData); mDataList.add(sqlData); // 添加到数据列表
} }
sqlData.setContent(data); sqlData.setContent(data); // 设置数据内容
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false; // 返回失败
} }
return true; return true; // 返回成功
} }
// 将笔记内容转换为JSON格式
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
if (mIsCreate) { if (mIsCreate) { // 如果是新建笔记(未保存)
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
return null; return null; // 返回null
} }
JSONObject note = new JSONObject(); JSONObject note = new JSONObject(); // 创建笔记对象
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果是普通笔记
// 添加所有笔记字段到JSON
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
@ -382,124 +373,134 @@ public class SqlNote {
note.put(NoteColumns.WIDGET_ID, mWidgetId); note.put(NoteColumns.WIDGET_ID, mWidgetId);
note.put(NoteColumns.WIDGET_TYPE, mWidgetType); note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 添加笔记元数据
JSONArray dataArray = new JSONArray(); // 处理关联的数据
for (SqlData sqlData : mDataList) { JSONArray dataArray = new JSONArray(); // 创建数据数组
JSONObject data = sqlData.getContent(); for (SqlData sqlData : mDataList) { // 遍历所有关联数据
if (data != null) { JSONObject data = sqlData.getContent(); // 获取数据JSON
dataArray.put(data); if (data != null) { // 如果数据不为空
dataArray.put(data); // 添加到数组
} }
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 添加数据数组
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { // 如果是文件夹
// 文件夹只有ID、类型和摘要字段
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 添加笔记元数据
} }
return js; return js; // 返回JSON对象
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
return null; return null; // 返回null
} }
// 设置父笔记ID
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id; // 更新父笔记ID
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id); // 记录差异
} }
// 设置Google任务ID
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); // 记录Google任务ID差异
} }
// 设置同步ID
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); // 记录同步ID差异
} }
// 重置本地修改标记
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); // 将本地修改标记设为0
} }
// 获取笔记ID
public long getId() { public long getId() {
return mId; return mId;
} }
// 获取父笔记ID
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
// 获取内容摘要
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
// 检查是否为普通笔记类型
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
// 提交笔记到数据库(插入或更新)
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) { // 如果是新建笔记
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID); // 移除无效ID
} }
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); // 插入数据库
try { try {
mId = Long.valueOf(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1)); // 从URI获取新生成的ID
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed"); // 抛出异常
} }
if (mId == 0) { if (mId == 0) { // 如果ID为0创建失败
throw new IllegalStateException("Create thread id failed"); throw new IllegalStateException("Create thread id failed"); // 抛出异常
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果是普通笔记
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) { // 遍历所有关联数据
sqlData.commit(mId, false, -1); sqlData.commit(mId, false, -1); // 提交数据到数据库
} }
} }
} else { } else { // 如果是更新笔记
// 验证笔记ID有效性
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note"); Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id"); throw new IllegalStateException("Try to update note with invalid id"); // 抛出异常
} }
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) { // 如果有需要更新的字段
mVersion ++; mVersion++; // 增加版本号
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) { // 如果不验证版本
// 直接更新笔记
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] { String.valueOf(mId) });
String.valueOf(mId) } else { // 如果需要验证版本
}); // 带版本控制的更新(防止同步冲突)
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] { String.valueOf(mId), String.valueOf(mVersion) });
String.valueOf(mId), String.valueOf(mVersion)
});
} }
if (result == 0) { if (result == 0) { // 如果没有更新任何行
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果是普通笔记
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) { // 遍历所有关联数据
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion); // 提交数据到数据库
} }
} }
} }
// refresh local info // 刷新本地信息
loadFromCursor(mId); loadFromCursor(mId); // 重新加载笔记信息
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果是普通笔记
loadDataContent(); loadDataContent(); // 重新加载关联数据
mDiffNoteValues.clear(); mDiffNoteValues.clear(); // 清空差异值
mIsCreate = false; mIsCreate = false; // 标记为已创建
} }
} }

@ -33,63 +33,61 @@ import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName(); // 日志标签
private boolean mCompleted; private boolean mCompleted; // 任务是否完成
private String mNotes; // 任务备注
private String mNotes; private JSONObject mMetaInfo; // 元数据信息(存储笔记的完整信息)
private Task mPriorSibling; // 前一个兄弟任务(用于排序)
private JSONObject mMetaInfo; private TaskList mParent; // 父任务列表
private Task mPriorSibling;
private TaskList mParent;
// 构造函数
public Task() { public Task() {
super(); super(); // 调用父类构造函数
mCompleted = false; mCompleted = false; // 默认未完成
mNotes = null; mNotes = null; // 备注为空
mPriorSibling = null; mPriorSibling = null; // 前兄弟任务为空
mParent = null; mParent = null; // 父任务列表为空
mMetaInfo = null; mMetaInfo = null; // 元数据为空
} }
// 获取创建任务的JSON操作对象
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
try { try {
// action_type // 设置操作类型为创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // 设置任务在列表中的索引位置
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// entity_delta // 创建实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK); GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型为任务
if (getNotes() != null) { if (getNotes() != null) { // 如果有备注
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 添加备注
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 添加实体数据
// parent_id // 设置父任务列表ID
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// dest_parent_type // 设置目标父类型为组(任务列表)
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id // 设置列表ID
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// prior_sibling_id // 如果有前兄弟任务设置前兄弟任务ID
if (mPriorSibling != null) { if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
} }
@ -97,103 +95,108 @@ public class Task extends Node {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject"); throw new ActionFailureException("fail to generate task-create jsonobject"); // 抛出异常
} }
return js; return js; // 返回JSON对象
} }
// 获取更新任务的JSON操作对象
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
try { try {
// action_type // 设置操作类型为更新
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // 设置任务ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // 创建实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
if (getNotes() != null) { if (getNotes() != null) { // 如果有备注
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 添加备注
} }
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 添加实体数据
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject"); // 抛出异常
} }
return js; return js; // 返回JSON对象
} }
// 从远程JSON设置任务内容从Google Tasks API获取的数据
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // 设置任务ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // 设置最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // 设置任务名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
// notes // 设置任务备注
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
} }
// deleted // 设置删除状态
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// completed // 设置完成状态
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject"); throw new ActionFailureException("fail to get task content from jsonobject"); // 抛出异常
} }
} }
} }
// 从本地JSON设置任务内容从数据库获取的数据
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); // 没有可用数据
return;
} }
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记元数据
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取数据数组
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { // 如果不是普通笔记类型
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");
return; return;
} }
// 遍历数据数组找到类型为NOTE的数据作为任务名称
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT)); // 设置任务名称
break; break;
} }
} }
@ -204,103 +207,102 @@ public class Task extends Node {
} }
} }
// 从任务内容生成本地JSON用于保存到数据库
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName(); // 获取任务名称
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) { // 如果没有元数据信息(从网页创建的新任务)
// new task created from web if (name == null) { // 如果名称为空
if (name == null) {
Log.w(TAG, "the note seems to be an empty one"); Log.w(TAG, "the note seems to be an empty one");
return null; return null; // 返回null
} }
// 创建新的JSON结构
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name); data.put(DataColumns.CONTENT, name); // 设置内容为任务名称
dataArray.put(data); dataArray.put(data); // 添加数据到数组
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 添加数据数组
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置类型为笔记
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 添加笔记元数据
return js; return js; // 返回JSON对象
} else { } else { // 如果已有元数据信息(已同步的任务)
// synced task JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记元数据
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取数据数组
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新数据数组中的任务名称
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName()); data.put(DataColumns.CONTENT, getName()); // 更新任务名称
break; break;
} }
} }
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 确保类型为笔记
return mMetaInfo; return mMetaInfo; // 返回更新后的元数据
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return null; return null; // 返回null
} }
} }
// 设置元数据信息
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes()); // 从备注解析JSON
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, e.toString()); Log.w(TAG, e.toString());
mMetaInfo = null; mMetaInfo = null; // 解析失败则设为null
} }
} }
} }
// 根据数据库游标确定同步操作类型
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记信息
} }
if (noteInfo == null) { if (noteInfo == null) { // 如果没有笔记信息
Log.w(TAG, "it seems that note meta has been deleted"); Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE; // 需要更新远程
} }
if (!noteInfo.has(NoteColumns.ID)) { if (!noteInfo.has(NoteColumns.ID)) { // 如果没有笔记ID
Log.w(TAG, "remote note id seems to be deleted"); Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL; // 需要更新本地
} }
// validate the note id now // 验证笔记ID是否匹配
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL; // ID不匹配需要更新本地
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // 如果本地没有修改
// there is no local update if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果同步ID等于最后修改时间
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { return SYNC_ACTION_NONE; // 无需同步
// no update both side
return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local return SYNC_ACTION_UPDATE_LOCAL; // 需要更新本地
return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else { // 如果本地有修改
// validate gtask id // 验证Google任务ID是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // ID不匹配返回错误
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果同步ID等于最后修改时间
// local modification only return SYNC_ACTION_UPDATE_REMOTE; // 只需要更新远程
return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT; // 有冲突
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -308,44 +310,52 @@ public class Task extends Node {
e.printStackTrace(); e.printStackTrace();
} }
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // 返回错误
} }
// 检查任务是否值得保存(有名称或备注)
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
// 设置任务完成状态
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
// 设置任务备注
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
// 设置前兄弟任务
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
// 设置父任务列表
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
// 获取任务完成状态
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
// 获取任务备注
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
// 获取前兄弟任务
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }
// 获取父任务列表
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
}
}

@ -30,93 +30,96 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
public class TaskList extends Node { public class TaskList extends Node { // 任务列表类继承自Node
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName(); // 日志标签
private int mIndex; private int mIndex; // 列表索引
private ArrayList<Task> mChildren; // 子任务列表
private ArrayList<Task> mChildren;
// 构造函数
public TaskList() { public TaskList() {
super(); super(); // 调用父类构造函数
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>(); // 初始化子任务列表
mIndex = 1; mIndex = 1; // 默认索引为1
} }
// 获取创建任务列表的JSON操作对象
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
try { try {
// action_type // 设置操作类型为创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // 设置列表索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta // 创建实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型为组
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 添加实体数据
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject"); throw new ActionFailureException("fail to generate tasklist-create jsonobject"); // 抛出异常
} }
return js; return js; // 返回JSON对象
} }
// 获取更新任务列表的JSON操作对象
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
try { try {
// action_type // 设置操作类型为更新
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // 设置任务列表ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // 创建实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 添加实体数据
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); throw new ActionFailureException("fail to generate tasklist-update jsonobject"); // 抛出异常
} }
return js; return js; // 返回JSON对象
} }
// 从远程JSON设置任务列表内容
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // 设置任务列表ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // 设置最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // 设置任务列表名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
@ -124,32 +127,34 @@ public class TaskList extends Node {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject"); throw new ActionFailureException("fail to get tasklist content from jsonobject"); // 抛出异常
} }
} }
} }
// 从本地JSON设置任务列表内容
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); // 没有可用数据
return;
} }
try { try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取文件夹信息
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { // 如果是普通文件夹
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET); // 获取文件夹名称
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); // 添加MIUI前缀
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { // 如果是系统文件夹
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) // 根文件夹
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) // 通话记录文件夹
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE); + GTaskStringUtils.FOLDER_CALL_NOTE);
else else
Log.e(TAG, "invalid system folder"); Log.e(TAG, "invalid system folder"); // 无效的系统文件夹
} else { } else {
Log.e(TAG, "error type"); Log.e(TAG, "error type"); // 错误的类型
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -157,54 +162,52 @@ public class TaskList extends Node {
} }
} }
// 从任务列表内容生成本地JSON
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建JSON对象
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject(); // 创建文件夹对象
String folderName = getName(); String folderName = getName(); // 获取文件夹名称
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) // 如果以MIUI前缀开头
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length()); // 去除前缀
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName); // 设置文件夹摘要
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) // 默认文件夹
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) // 通话记录文件夹
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 类型为系统文件夹
else else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 类型为普通文件夹
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); js.put(GTaskStringUtils.META_HEAD_NOTE, folder); // 添加文件夹信息
return js; return js; // 返回JSON对象
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return null; return null; // 返回null
} }
} }
// 根据数据库游标确定同步操作类型
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // 如果本地没有修改
// there is no local update if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果同步ID等于最后修改时间
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { return SYNC_ACTION_NONE; // 无需同步
// no update both side
return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local return SYNC_ACTION_UPDATE_LOCAL; // 需要更新本地
return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else { // 如果本地有修改
// validate gtask id // 验证Google任务ID是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // ID不匹配返回错误
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果同步ID等于最后修改时间
// local modification only return SYNC_ACTION_UPDATE_REMOTE; // 只需要更新远程
return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// for folder conflicts, just apply local modification // 对于文件夹冲突,直接应用本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
@ -213,131 +216,142 @@ public class TaskList extends Node {
e.printStackTrace(); e.printStackTrace();
} }
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // 返回错误
} }
// 获取子任务数量
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
// 添加子任务到列表末尾
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) { // 如果任务不为空且不在列表中
ret = mChildren.add(task); ret = mChildren.add(task); // 添加到列表
if (ret) { if (ret) {
// need to set prior sibling and parent // 需要设置前兄弟任务和父任务列表
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1)); // 前兄弟任务为列表最后一个
task.setParent(this); task.setParent(this); // 父任务列表为当前列表
} }
} }
return ret; return ret;
} }
// 在指定位置添加子任务
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) { // 检查索引有效性
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task); // 获取任务位置
if (task != null && pos == -1) { if (task != null && pos == -1) { // 如果任务不为空且不在列表中
mChildren.add(index, task); mChildren.add(index, task); // 在指定位置添加
// update the task list // 更新任务列表关系
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0) // 如果不是第一个
preTask = mChildren.get(index - 1); preTask = mChildren.get(index - 1); // 前一个任务
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1) // 如果不是最后一个
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1); // 后一个任务
task.setPriorSibling(preTask); task.setPriorSibling(preTask); // 设置前兄弟任务
if (afterTask != null) if (afterTask != null) // 如果有后一个任务
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task); // 更新后一个任务的前兄弟任务
} }
return true; return true;
} }
// 移除子任务
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task); // 获取任务索引
if (index != -1) { if (index != -1) { // 如果任务在列表中
ret = mChildren.remove(task); ret = mChildren.remove(task); // 移除任务
if (ret) { if (ret) {
// reset prior sibling and parent // 重置前兄弟任务和父任务列表
task.setPriorSibling(null); task.setPriorSibling(null); // 前兄弟任务设为null
task.setParent(null); task.setParent(null); // 父任务列表设为null
// update the task list // 更新任务列表
if (index != mChildren.size()) { if (index != mChildren.size()) { // 如果不是最后一个
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1)); // 更新前兄弟任务
} }
} }
} }
return ret; return ret;
} }
// 移动子任务到新位置
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { // 检查索引有效性
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task); // 获取任务当前位置
if (pos == -1) { if (pos == -1) { // 如果任务不在列表中
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list");
return false; return false;
} }
if (pos == index) if (pos == index) // 如果位置相同
return true; return true;
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index)); // 先移除再添加
} }
// 根据Google任务ID查找子任务
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
if (t.getGid().equals(gid)) { if (t.getGid().equals(gid)) { // 如果ID匹配
return t; return t; // 返回任务
} }
} }
return null; return null; // 没找到返回null
} }
// 获取子任务在列表中的索引
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task); // 返回任务索引
} }
// 根据索引获取子任务
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) { // 检查索引有效性
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
return null; return null; // 返回null
} }
return mChildren.get(index); return mChildren.get(index); // 返回任务
} }
// 根据Google任务ID获取子任务
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) { // 遍历所有任务
if (task.getGid().equals(gid)) if (task.getGid().equals(gid)) // 如果ID匹配
return task; return task; // 返回任务
} }
return null; return null; // 没找到返回null
} }
// 获取子任务列表
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren;
} }
// 设置列表索引
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
// 获取列表索引
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }
} }

@ -16,18 +16,53 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* ActionFailureException
* Google Tasks
*
* RuntimeException
*
*
*
* 1. Google Task
* 2. JSON
* 3.
* 4.
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
/**
* UID
*
*/
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/**
*
* ActionFailureException
*/
public ActionFailureException() { public ActionFailureException() {
super(); super(); // 调用父类RuntimeException的无参构造函数
} }
/**
*
* ActionFailureException
*
* @param paramString
*/
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString); // 调用父类RuntimeException的带消息构造函数
} }
/**
*
* ActionFailureException
*
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable); // 调用父类RuntimeException的带消息和原因的构造函数
} }
} }

@ -16,18 +16,55 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* NetworkFailureException
* Google Tasks
*
* Exception
*
*
*
* 1.
* 2. 404500
* 3. SSL/TLS
* 4.
* 5.
*/
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
/**
* UID
*
*/
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
/**
*
* NetworkFailureException
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super(); // 调用父类Exception的无参构造函数
} }
/**
*
* NetworkFailureException
*
* @param paramString
* "网络连接失败""服务器无响应"
*/
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString); // 调用父类Exception的带消息构造函数
} }
/**
*
* NetworkFailureException
*
*
* @param paramString
* @param paramThrowable IOException
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable); // 调用父类Exception的带消息和原因的构造函数
} }
} }

@ -1,4 +1,3 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
@ -30,94 +29,112 @@ import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 同步通知的ID确保唯一性
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 同步完成回调接口
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete(); // 同步完成时调用
} }
private Context mContext; private Context mContext; // 上下文对象
private NotificationManager mNotifiManager; // 通知管理器
private NotificationManager mNotifiManager; private GTaskManager mTaskManager; // 任务管理器
private OnCompleteListener mOnCompleteListener; // 完成监听器
private GTaskManager mTaskManager;
private OnCompleteListener mOnCompleteListener;
// 构造函数
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context; // 保存上下文
mOnCompleteListener = listener; mOnCompleteListener = listener; // 保存完成监听器
mNotifiManager = (NotificationManager) mContext mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE); .getSystemService(Context.NOTIFICATION_SERVICE); // 获取通知管理器服务
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance(); // 获取任务管理器单例
} }
// 取消同步操作
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync(); // 委托给任务管理器取消同步
} }
// 发布同步进度
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message // 发布单个进度消息
}); });
} }
// 显示通知
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
// 创建通知对象
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis()); // 设置图标、文本和时间戳
notification.defaults = Notification.DEFAULT_LIGHTS; notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光效果
notification.flags = Notification.FLAG_AUTO_CANCEL; notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置点击后自动取消
PendingIntent pendingIntent; PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
// 如果不是成功状态,点击通知跳转到设置页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
} else { } else {
// 如果是成功状态,点击通知跳转到笔记列表页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0);
} }
// 设置通知的详细信息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); pendingIntent); // 设置标题、内容和点击意图
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // 显示通知
} }
// 后台执行同步任务
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
// 发布登录进度
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext))); // 显示正在登录指定账户的进度
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this); // 执行同步操作并返回结果状态
} }
// 更新同步进度
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
// 如果上下文是同步服务,发送广播通知进度
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
// 同步完成后处理结果
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
// 根据同步结果显示不同的通知
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
// 同步成功
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount())); // 显示成功通知
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); // 更新最后同步时间
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); // 网络错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); // 显示网络错误通知
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); // 内部错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); // 显示内部错误通知
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
// 同步被取消
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled)); // 显示取消通知
} }
// 通知监听器同步已完成
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete(); // 在新线程中调用完成回调
} }
}).start(); }).start();
} }
} }
} }

@ -62,524 +62,533 @@ import java.util.zip.InflaterInputStream;
public class GTaskClient { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName(); // 日志标签
// Google Tasks API URL常量
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; // 获取数据URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; // 提交数据URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; private static GTaskClient mInstance = null; // 单例实例
private static GTaskClient mInstance = null; // HTTP客户端和相关参数
private DefaultHttpClient mHttpClient; // HTTP客户端实例
private DefaultHttpClient mHttpClient; private String mGetUrl; // 动态生成的GET URL
private String mPostUrl; // 动态生成的POST URL
private String mGetUrl; private long mClientVersion; // 客户端版本号,从服务器获取
private boolean mLoggedin; // 登录状态标志
private String mPostUrl; private long mLastLoginTime; // 上次登录时间
private int mActionId; // 操作ID计数器用于生成唯一的操作ID
private long mClientVersion; private Account mAccount; // 当前登录的Google账户
private JSONArray mUpdateArray; // 批量更新操作的JSON数组
private boolean mLoggedin;
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
private JSONArray mUpdateArray;
private GTaskClient() { private GTaskClient() {
// 初始化所有成员变量
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL; // 默认GET URL
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL; // 默认POST URL
mClientVersion = -1; mClientVersion = -1; // 未初始化的版本号
mLoggedin = false; mLoggedin = false; // 初始状态为未登录
mLastLoginTime = 0; mLastLoginTime = 0; // 初始登录时间为0
mActionId = 1; mActionId = 1; // 操作ID从1开始
mAccount = null; mAccount = null; // 初始账户为空
mUpdateArray = null; mUpdateArray = null; // 初始更新数组为空
} }
// 获取单例实例
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient(); // 第一次调用时创建实例
} }
return mInstance; return mInstance;
} }
// 登录方法,返回登录是否成功
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 检查Cookie是否过期假设5分钟后过期
// then we need to re-login final long interval = 1000 * 60 * 5; // 5分钟的毫秒数
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false; // 如果超过5分钟标记为未登录
} }
// need to re-login after account switch // 检查账户是否切换,需要重新登录
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false; // 账户已切换,需要重新登录
} }
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in"); // 已经登录,直接返回
return true; return true;
} }
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis(); // 更新最后登录时间
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false); // 获取Google账户授权令牌
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed"); // 获取授权令牌失败
return false; return false;
} }
// login with custom domain if necessary // 如果不是gmail.com或googlemail.com账户尝试使用自定义域名登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); // 构建自定义域名URL
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1; // 找到@符号位置
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index); // 提取域名后缀
url.append(suffix + "/"); url.append(suffix + "/"); // 添加域名后缀
mGetUrl = url.toString() + "ig"; mGetUrl = url.toString() + "ig"; // 设置自定义GET URL
mPostUrl = url.toString() + "r/ig"; mPostUrl = url.toString() + "r/ig"; // 设置自定义POST URL
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) { // 尝试使用自定义域名登录
mLoggedin = true; mLoggedin = true; // 登录成功
} }
} }
// try to login with google official url // 如果自定义域名登录失败尝试使用Google官方URL登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL; // 重置为默认GET URL
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL; // 重置为默认POST URL
if (!tryToLoginGtask(activity, authToken)) { if (!tryToLoginGtask(activity, authToken)) { // 尝试使用官方URL登录
return false; return false; // 登录失败
} }
} }
mLoggedin = true; mLoggedin = true; // 标记为已登录
return true; return true; // 登录成功
} }
// 登录Google账户并获取授权令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity); // 获取账户管理器
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取所有Google账户
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account"); // 没有可用的Google账户
return null; return null;
} }
// 获取设置中配置的同步账户名
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
for (Account a : accounts) { for (Account a : accounts) {
if (a.name.equals(accountName)) { if (a.name.equals(accountName)) { // 查找匹配的账户
account = a; account = a;
break; break;
} }
} }
if (account != null) { if (account != null) {
mAccount = account; mAccount = account; // 设置当前账户
} else { } else {
Log.e(TAG, "unable to get an account with the same name in the settings"); Log.e(TAG, "unable to get an account with the same name in the settings"); // 未找到匹配账户
return null; return null;
} }
// get the token now // 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null); // 请求授权令牌
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取结果
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); // 提取授权令牌
if (invalidateToken) { if (invalidateToken) { // 如果需要使令牌失效
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken); // 使当前令牌失效
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false); // 重新获取令牌
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "get auth token failed"); Log.e(TAG, "get auth token failed"); // 获取授权令牌失败
authToken = null; authToken = null;
} }
return authToken; return authToken; // 返回授权令牌
} }
// 尝试登录Google Tasks
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(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); // 重新获取授权令牌
authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed"); // 重新获取令牌失败
return false; return false;
} }
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) { // 使用新令牌再次尝试登录
Log.e(TAG, "login gtask failed"); Log.e(TAG, "login gtask failed"); // 登录失败
return false; return false;
} }
} }
return true; return true; // 登录成功
} }
// 实际的Google Tasks登录逻辑
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000; // 连接超时时间10秒
int timeoutSocket = 15000; int timeoutSocket = 15000; // Socket超时时间15秒
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams(); // 创建HTTP参数
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 设置Socket超时
mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient = new DefaultHttpClient(httpParameters); // 创建HTTP客户端
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore(); // 创建Cookie存储
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore); // 设置Cookie存储
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 禁用Expect-Continue
// login gtask // 登录Google Tasks
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken; // 构建登录URL
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl); // 创建GET请求
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet); // 执行HTTP请求
// get the cookie now // 检查Cookie中是否包含认证信息
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); // 获取所有Cookie
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) { if (cookie.getName().contains("GTL")) { // 查找包含"GTL"的CookieGoogle Tasks认证
hasAuthCookie = true; hasAuthCookie = true;
} }
} }
if (!hasAuthCookie) { if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie"); // 警告未找到认证Cookie
} }
// get the client version // 从响应中提取客户端版本号
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity()); // 获取响应内容
String jsBegin = "_setup("; String jsBegin = "_setup("; // JavaScript响应开始标记
String jsEnd = ")}</script>"; String jsEnd = ")}</script>"; // JavaScript响应结束标记
int begin = resString.indexOf(jsBegin); int begin = resString.indexOf(jsBegin); // 查找开始位置
int end = resString.lastIndexOf(jsEnd); int end = resString.lastIndexOf(jsEnd); // 查找结束位置
String jsString = null; String jsString = null;
if (begin != -1 && end != -1 && begin < end) { if (begin != -1 && end != -1 && begin < end) { // 确保找到有效位置
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end); // 提取JavaScript字符串
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString); // 解析为JSON对象
mClientVersion = js.getLong("v"); mClientVersion = js.getLong("v"); // 获取客户端版本号
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions // 捕获所有其他异常
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed"); // HTTP GET请求失败
return false; return false;
} }
return true; return true; // 登录成功
} }
// 获取下一个操作ID
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++; // 返回当前操作ID并递增
} }
// 创建HTTP POST请求对象
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl); // 创建POST请求
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // 设置内容类型
httpPost.setHeader("AT", "1"); httpPost.setHeader("AT", "1"); // 设置AT头部认证令牌
return httpPost; return httpPost;
} }
// 从HTTP实体获取响应内容支持GZIP和Deflate压缩
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue(); // 获取内容编码
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding); // 记录编码类型
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent(); // 获取输入流
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent()); // 如果是GZIP编码使用GZIP输入流
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true); // 创建Inflater对象
input = new InflaterInputStream(entity.getContent(), inflater); input = new InflaterInputStream(entity.getContent(), inflater); // 使用Inflater输入流
} }
try { try {
InputStreamReader isr = new InputStreamReader(input); InputStreamReader isr = new InputStreamReader(input); // 创建输入流读取器
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr); // 创建缓冲读取器
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); // 创建字符串构建器
while (true) { while (true) {
String buff = br.readLine(); String buff = br.readLine(); // 读取一行
if (buff == null) { if (buff == null) {
return sb.toString(); return sb.toString(); // 读取完成,返回内容
} }
sb = sb.append(buff); sb = sb.append(buff); // 添加到字符串构建器
} }
} finally { } finally {
input.close(); input.close(); // 确保关闭输入流
} }
} }
// 发送POST请求到Google Tasks API
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first"); // 未登录错误
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost(); // 创建POST请求
try { try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); // 创建参数列表
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString())); // 添加JSON参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); // 创建URL编码实体
httpPost.setEntity(entity); httpPost.setEntity(entity); // 设置请求实体
// execute the post // 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost); // 执行请求
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity()); // 获取响应内容
return new JSONObject(jsString); return new JSONObject(jsString); // 解析为JSON对象并返回
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // HTTP协议异常
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("postRequest failed");
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // IO异常
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject"); throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 其他异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("error occurs when posting request");
} }
} }
// 创建任务
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交之前的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建操作列表
// action_list // 添加创建任务的操作
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId())); // 获取任务的创建操作
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表
// client_version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 发送请求
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost); // 发送POST请求
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取结果数组的第一个元素
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务的GID
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("create task: handing jsonobject failed");
} }
} }
// 创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交之前的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建操作列表
// action_list // 添加创建任务列表的操作
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId())); // 获取任务列表的创建操作
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表
// client version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 发送请求
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost); // 发送POST请求
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取结果数组的第一个元素
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务列表的GID
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("create tasklist: handing jsonobject failed");
} }
} }
// 提交批量更新
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) { // 如果有待提交的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
// action_list // 添加操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost); // 发送请求
mUpdateArray = null; mUpdateArray = null; // 清空更新数组
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed"); throw new ActionFailureException("commit update: handing jsonobject failed");
} }
} }
} }
// 添加节点到更新数组
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // 如果更新数组过大超过10个先提交当前更新
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate(); // 提交当前更新
} }
if (mUpdateArray == null) if (mUpdateArray == null) // 如果更新数组为空,创建新数组
mUpdateArray = new JSONArray(); mUpdateArray = new JSONArray();
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId())); // 添加节点的更新操作
} }
} }
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交之前的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建操作列表
JSONObject action = new JSONObject(); JSONObject action = new JSONObject(); // 创建移动操作
// action_list // 构建移动操作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); // 设置操作类型为移动
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作ID
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 设置任务ID
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // 如果是在同一个任务列表中移动且任务不是第一个设置前一个兄弟节点的ID
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 设置源列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 设置目标父节点ID
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // 如果是在不同任务列表之间移动设置目标列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action); // 将操作添加到操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表到请求
// client_version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost); // 发送请求
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed");
} }
} }
// 删除节点
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交之前的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建操作列表
// action_list // 添加删除操作
node.setDeleted(true); node.setDeleted(true); // 标记节点为已删除
actionList.put(node.getUpdateAction(getActionId())); actionList.put(node.getUpdateAction(getActionId())); // 获取节点的更新操作(包含删除标记)
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表
// client_version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost); // 发送请求
mUpdateArray = null; mUpdateArray = null; // 清空更新数组
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed"); throw new ActionFailureException("delete node: handing jsonobject failed");
} }
} }
// 获取所有任务列表
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first"); // 未登录错误
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
try { try {
HttpGet httpGet = new HttpGet(mGetUrl); HttpGet httpGet = new HttpGet(mGetUrl); // 创建GET请求
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet); // 执行请求
// get the task list // 从响应中提取任务列表数据
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity()); // 获取响应内容
String jsBegin = "_setup("; String jsBegin = "_setup("; // JavaScript响应开始标记
String jsEnd = ")}</script>"; String jsEnd = ")}</script>"; // JavaScript响应结束标记
int begin = resString.indexOf(jsBegin); int begin = resString.indexOf(jsBegin); // 查找开始位置
int end = resString.lastIndexOf(jsEnd); int end = resString.lastIndexOf(jsEnd); // 查找结束位置
String jsString = null; String jsString = null;
if (begin != -1 && end != -1 && begin < end) { if (begin != -1 && end != -1 && begin < end) { // 确保找到有效位置
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end); // 提取JavaScript字符串
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString); // 解析为JSON对象
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); // 返回任务列表数组
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // HTTP协议异常
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // IO异常
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed"); throw new ActionFailureException("get task lists: handing jasonobject failed");
} }
} }
// 获取特定任务列表的所有任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交之前的更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建操作列表
JSONObject action = new JSONObject(); JSONObject action = new JSONObject(); // 创建获取所有任务的操作
// action_list // 构建获取所有任务的操作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); // 设置操作类型为获取所有
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作ID
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 设置任务列表ID
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 设置不获取已删除的任务
actionList.put(action); actionList.put(action); // 将操作添加到操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表到请求
// client_version // 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost); // 发送请求
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 返回任务数组
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed"); throw new ActionFailureException("get task list: handing jsonobject failed");
} }
} }
// 获取当前同步账户
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
// 重置更新数组
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }
} }

@ -24,105 +24,112 @@ import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type"; // 同步操作类型常量
public final static String ACTION_STRING_NAME = "sync_action_type"; // Intent中操作类型的键名
public final static int ACTION_START_SYNC = 0;
// 同步操作类型值
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_START_SYNC = 0; // 开始同步
public final static int ACTION_CANCEL_SYNC = 1; // 取消同步
public final static int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2; // 无效操作
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; // 广播相关常量
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; // 广播名称
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; // 是否正在同步的广播键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; // 进度消息的广播键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private static GTaskASyncTask mSyncTask = null; // 同步任务实例
private static GTaskASyncTask mSyncTask = null; private static String mSyncProgress = ""; // 同步进度消息
private static String mSyncProgress = ""; // 开始同步方法
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) { // 如果没有正在进行的同步任务
// 创建新的同步任务,并设置完成监听器
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() { public void onComplete() {
mSyncTask = null; mSyncTask = null; // 同步完成,清空任务引用
sendBroadcast(""); sendBroadcast(""); // 发送空广播通知同步完成
stopSelf(); stopSelf(); // 停止服务
} }
}); });
sendBroadcast(""); sendBroadcast(""); // 发送广播通知开始同步
mSyncTask.execute(); mSyncTask.execute(); // 执行同步任务
} }
} }
// 取消同步方法
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) { // 如果有正在进行的同步任务
mSyncTask.cancelSync(); mSyncTask.cancelSync(); // 取消同步
} }
} }
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null; // 服务创建时初始化同步任务为空
} }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras(); // 获取Intent中的附加数据
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { // 如果包含操作类型
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { // 根据操作类型执行相应操作
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync(); // 开始同步
break; break;
case ACTION_CANCEL_SYNC: case ACTION_CANCEL_SYNC:
cancelSync(); cancelSync(); // 取消同步
break; break;
default: default:
break; break; // 无效操作,不做任何处理
} }
return START_STICKY; return START_STICKY; // 返回粘性服务标志,系统会在服务被杀死后尝试重新创建
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId); // 默认处理
} }
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) { // 在低内存情况下
mSyncTask.cancelSync(); mSyncTask.cancelSync(); // 取消同步任务以释放资源
} }
} }
// 服务绑定方法(未实现)
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null; // 不提供绑定服务功能
} }
// 发送广播方法
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg; // 更新同步进度消息
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); // 创建广播Intent
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); // 添加是否正在同步的附加信息
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); // 添加进度消息
sendBroadcast(intent); sendBroadcast(intent); // 发送广播
} }
// 静态方法从Activity启动同步
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity); // 设置活动上下文
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class); // 创建启动服务的Intent
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); // 设置操作为开始同步
activity.startService(intent); activity.startService(intent); // 启动服务
} }
// 静态方法:取消同步
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class); // 创建启动服务的Intent
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); // 设置操作为取消同步
context.startService(intent); context.startService(intent); // 启动服务
} }
// 静态方法:检查是否正在同步
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null; // 根据同步任务是否存在判断是否正在同步
} }
// 静态方法:获取当前同步进度消息
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress; // 返回同步进度消息
} }
} }

@ -15,6 +15,7 @@
*/ */
package net.micode.notes.model; package net.micode.notes.model;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
import android.content.ContentUris; import android.content.ContentUris;
@ -33,27 +34,40 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
/**
* Note
*
*/
public class Note { public class Note {
// 笔记表的差异值(需要更新的字段)
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
// 笔记数据对象,处理内容数据
private NoteData mNoteData; private NoteData mNoteData;
// 日志标签
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * ID
* @param context
* @param folderId ID
* @return ID0
*/ */
public static synchronized long getNewNoteId(Context context, long folderId) { public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database // 创建新的笔记记录
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis(); long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime); values.put(NoteColumns.CREATED_DATE, createdTime); // 创建时间
values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime); // 修改时间
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 笔记类型
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId); // 父文件夹ID
// 插入数据库
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0; long noteId = 0;
try { try {
// 从URI中解析出笔记ID
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
@ -65,63 +79,106 @@ public class Note {
return noteId; return noteId;
} }
/**
*
*/
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
} }
/**
*
* @param key
* @param value
*/
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
// 设置本地修改标志和修改时间
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
*
* @param key
* @param value
*/
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
/**
* ID
* @param id ID
*/
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
/**
* ID
* @return ID
*/
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }
/**
* ID
* @param id ID
*/
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }
/**
*
* @param key
* @param value
*/
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
/**
*
* @return
*/
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
/**
*
* @param context
* @param noteId ID
* @return
*/
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
// 如果没有本地修改,直接返回成功
if (!isLocalModified()) { if (!isLocalModified()) {
return true; return true;
} }
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * {@link NoteColumns#LOCAL_MODIFIED}
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}使
* note data info *
*/ */
if (context.getContentResolver().update( if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) { null) == 0) {
Log.e(TAG, "Update note error, should not happen"); Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through // 不返回,继续执行
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear(); // 清空差异值
// 同步笔记数据
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
@ -130,28 +187,43 @@ public class Note {
return true; return true;
} }
/**
*
*/
private class NoteData { private class NoteData {
// 文本数据ID
private long mTextDataId; private long mTextDataId;
// 文本数据的差异值
private ContentValues mTextDataValues; private ContentValues mTextDataValues;
// 通话数据ID
private long mCallDataId; private long mCallDataId;
// 通话数据的差异值
private ContentValues mCallDataValues; private ContentValues mCallDataValues;
// 日志标签
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
/**
*
*/
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
mTextDataId = 0; mTextDataId = 0; // 0表示新数据
mCallDataId = 0; mCallDataId = 0; // 0表示新数据
} }
/**
*
* @return
*/
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
/**
* ID
* @param id ID
*/
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +231,10 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
/**
* ID
* @param id ID
*/
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,21 +242,39 @@ public class Note {
mCallDataId = id; mCallDataId = id;
} }
/**
*
* @param key
* @param value
*/
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
// 标记笔记为已修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
*
* @param key
* @param value
*/
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
// 标记笔记为已修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
* ContentResolver
* @param context
* @param noteId ID
* @return URInull
*/
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety *
*/ */
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -189,13 +283,16 @@ public class Note {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
// 处理文本数据
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 设置笔记ID
if (mTextDataId == 0) { if (mTextDataId == 0) {
// 新数据,执行插入操作
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
try { try {
// 从URI中获取新插入的数据ID
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId); Log.e(TAG, "Insert new text data fail with noteId" + noteId);
@ -203,21 +300,25 @@ public class Note {
return null; return null;
} }
} else { } else {
// 现有数据,执行更新操作
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues);
operationList.add(builder.build()); operationList.add(builder.build());
} }
mTextDataValues.clear(); mTextDataValues.clear(); // 清空已处理的数据
} }
// 处理通话数据
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId); // 设置笔记ID
if (mCallDataId == 0) { if (mCallDataId == 0) {
// 新数据,执行插入操作
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues); mCallDataValues);
try { try {
// 从URI中获取新插入的数据ID
setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId); Log.e(TAG, "Insert new call data fail with noteId" + noteId);
@ -225,18 +326,21 @@ public class Note {
return null; return null;
} }
} else { } else {
// 现有数据,执行更新操作
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId)); Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues); builder.withValues(mCallDataValues);
operationList.add(builder.build()); operationList.add(builder.build());
} }
mCallDataValues.clear(); mCallDataValues.clear(); // 清空已处理的数据
} }
// 执行批量操作
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); Notes.AUTHORITY, operationList);
// 返回操作结果
return (results == null || results.length == 0 || results[0] == null) ? null return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { } catch (RemoteException e) {
@ -250,4 +354,4 @@ public class Note {
return null; return null;
} }
} }
} }

@ -31,37 +31,42 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
*
*
*/
public class WorkingNote { public class WorkingNote {
// Note for the working note // 内部Note对象用于处理数据层操作
private Note mNote; private Note mNote;
// Note Id // 笔记ID0表示新笔记
private long mNoteId; private long mNoteId;
// Note content // 笔记内容
private String mContent; private String mContent;
// Note mode // 笔记模式(如待办事项模式)
private int mMode; private int mMode;
// 提醒日期
private long mAlertDate; private long mAlertDate;
// 修改日期
private long mModifiedDate; private long mModifiedDate;
// 背景颜色ID
private int mBgColorId; private int mBgColorId;
// 关联的小部件ID
private int mWidgetId; private int mWidgetId;
// 小部件类型
private int mWidgetType; private int mWidgetType;
// 所属文件夹ID
private long mFolderId; private long mFolderId;
// 应用上下文
private Context mContext; private Context mContext;
// 日志标签
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
// 是否标记为删除
private boolean mIsDeleted; private boolean mIsDeleted;
// 笔记设置变化监听器
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据表查询字段投影
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -72,6 +77,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 笔记表查询字段投影
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -81,56 +87,64 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
// 数据表字段索引常量
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
// 笔记表字段索引常量
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct /**
* -
* @param context
* @param folderId ID
*/
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0; // 初始无提醒
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis(); // 设置当前时间为修改时间
mFolderId = folderId; mFolderId = folderId;
mNote = new Note(); mNote = new Note(); // 创建新的Note对象
mNoteId = 0; mNoteId = 0; // 新笔记ID为0
mIsDeleted = false; mIsDeleted = false;
mMode = 0; mMode = 0; // 默认模式
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效的小部件类型
} }
// Existing note construct /**
* -
* @param context
* @param noteId ID
* @param folderId ID
*/
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
mFolderId = folderId; mFolderId = folderId;
mIsDeleted = false; mIsDeleted = false;
mNote = new Note(); mNote = new Note();
loadNote(); loadNote(); // 从数据库加载笔记数据
} }
/**
*
*/
private void loadNote() { private void loadNote() {
// 查询笔记表获取基本信息
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
// 从游标读取字段值
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -143,10 +157,14 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
} }
loadNoteData(); loadNoteData(); // 加载笔记内容数据
} }
/**
*
*/
private void loadNoteData() { private void loadNoteData() {
// 查询数据表获取笔记内容
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
@ -157,10 +175,12 @@ public class WorkingNote {
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
// 普通笔记类型
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) { } else if (DataConstants.CALL_NOTE.equals(type)) {
// 通话记录笔记类型
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +194,15 @@ public class WorkingNote {
} }
} }
/**
*
* @param context
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
* @return WorkingNote
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,12 +212,24 @@ public class WorkingNote {
return note; return note;
} }
/**
*
* @param context
* @param id ID
* @return WorkingNote
*/
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
/**
*
* @return
*/
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
// 检查是否值得保存
if (isWorthSaving()) { if (isWorthSaving()) {
// 如果是新笔记,先创建数据库记录
if (!existInDatabase()) { if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
@ -196,11 +237,10 @@ public class WorkingNote {
} }
} }
// 同步数据到数据库
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** // 如果有关联的小部件,通知更新
* Update widget content if there exist any widget of this note
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
@ -212,10 +252,19 @@ public class WorkingNote {
} }
} }
/**
*
* @return
*/
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
/**
*
*
* @return
*/
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +274,19 @@ public class WorkingNote {
} }
} }
/**
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
/**
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -239,14 +297,23 @@ public class WorkingNote {
} }
} }
/**
*
* @param mark
*/
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
// 如果有小部件,通知更新
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
} }
/**
* ID
* @param id ID
*/
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
@ -257,6 +324,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param mode
*/
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
@ -267,6 +338,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param type
*/
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -274,6 +349,10 @@ public class WorkingNote {
} }
} }
/**
* ID
* @param id ID
*/
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -281,6 +360,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param text
*/
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
@ -288,81 +371,141 @@ public class WorkingNote {
} }
} }
/**
*
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
/**
*
* @return
*/
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
// 以下为获取各种属性的方法
/**
*
* @return
*/
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
/**
*
* @return
*/
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
/**
*
* @return
*/
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
/**
* ID
* @return ID
*/
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
/**
* ID
* @return ID
*/
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
/**
* ID
* @return ID
*/
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
/**
*
* @return
*/
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
/**
* ID
* @return ID
*/
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
/**
* ID
* @return ID
*/
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
/**
* ID
* @return ID
*/
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
/**
*
* @return
*/
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
/**
*
*/
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed *
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
* Called when user set clock *
* @param date
* @param set
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
* Call when user create note from widget *
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
* Call when switch between check list mode and normal mode *
* @param oldMode is previous mode before change * @param oldMode
* @param newMode is new mode * @param newMode
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }
} }

@ -1,344 +1,393 @@
[file name]: BackupUtils.java
[file content begin]
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* 2010-2011MiCode
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* Apache License 2.0
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* 使
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
*
* limitations under the License. * limitations under the License.
*
*/ */
// 包声明:工具类包
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; // 导入Android相关类
import android.database.Cursor; import android.content.Context; // 上下文类,用于访问应用资源
import android.os.Environment; import android.database.Cursor; // 数据库游标,用于查询结果
import android.text.TextUtils; import android.os.Environment; // 环境类,用于访问外部存储
import android.text.format.DateFormat; import android.text.TextUtils; // 文本工具类
import android.util.Log; import android.text.format.DateFormat; // 日期格式化类
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.R; // R资源文件
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes; // 笔记数据类
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.DataColumns; // 数据列定义
import net.micode.notes.data.Notes.DataConstants; // 数据常量定义
import java.io.File; import net.micode.notes.data.Notes.NoteColumns; // 笔记列定义
import java.io.FileNotFoundException;
import java.io.FileOutputStream; // 导入Java IO类
import java.io.IOException; import java.io.File; // 文件类
import java.io.PrintStream; import java.io.FileNotFoundException; // 文件未找到异常
import java.io.FileOutputStream; // 文件输出流
import java.io.IOException; // IO异常
import java.io.PrintStream; // 打印流
// 备份工具类:负责将笔记数据导出为文本文件
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils"; // 日志标签
// Singleton stuff // 单例模式相关
private static BackupUtils sInstance; private static BackupUtils sInstance; // 静态单例实例
// 获取单例实例的静态方法使用synchronized确保线程安全
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) { // 如果实例为空
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context); // 创建新实例
} }
return sInstance; return sInstance; // 返回实例
} }
/** /**
* Following states are signs to represents backup or restore *
* status
*/ */
// Currently, the sdcard is not mounted // 状态常量定义
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD卡未挂载状态
// The backup file not exist public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在状态
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_DATA_DESTROIED = 2; // 数据被破坏状态
// The data is not well formated, may be changed by other programs public static final int STATE_SYSTEM_ERROR = 3; // 系统错误状态
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_SUCCESS = 4; // 成功状态
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3; private TextExport mTextExport; // 文本导出器实例
// Backup or restore success
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
// 私有构造函数,外部不能直接实例化
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context); // 创建文本导出器
} }
// 检查外部存储是否可用的静态方法
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
// 判断外部存储状态是否为已挂载
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
// 导出数据到文本文件的公共方法
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText(); // 调用文本导出器的导出方法
} }
// 获取导出的文本文件名
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName; // 返回文件名
} }
// 获取导出的文本文件目录
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory; // 返回文件目录
} }
// 内部类:文本导出器,实现具体的导出逻辑
private static class TextExport { private static class TextExport {
// 笔记表查询字段数组,定义需要查询的列
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, NoteColumns.ID, // 笔记ID列
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE, // 修改日期列
NoteColumns.SNIPPET, NoteColumns.SNIPPET, // 内容摘要列
NoteColumns.TYPE NoteColumns.TYPE // 类型列
}; };
private static final int NOTE_COLUMN_ID = 0; // 笔记列索引常量
private static final int NOTE_COLUMN_ID = 0; // ID列索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int NOTE_COLUMN_MODIFIED_DATE = 1; // 修改日期列索引
private static final int NOTE_COLUMN_SNIPPET = 2; // 内容摘要列索引
private static final int NOTE_COLUMN_SNIPPET = 2;
// 数据表查询字段数组
private static final String[] DATA_PROJECTION = { private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, DataColumns.CONTENT, // 内容列
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE, // MIME类型列
DataColumns.DATA1, DataColumns.DATA1, // 数据1列
DataColumns.DATA2, DataColumns.DATA2, // 数据2列
DataColumns.DATA3, DataColumns.DATA3, // 数据3列
DataColumns.DATA4, DataColumns.DATA4, // 数据4列
}; };
private static final int DATA_COLUMN_CONTENT = 0; // 数据列索引常量
private static final int DATA_COLUMN_CONTENT = 0; // 内容列索引
private static final int DATA_COLUMN_MIME_TYPE = 1; private static final int DATA_COLUMN_MIME_TYPE = 1; // MIME类型列索引
private static final int DATA_COLUMN_CALL_DATE = 2; // 通话日期列索引
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_PHONE_NUMBER = 4; // 电话号码列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式化字符串数组,从资源文件中读取
private final String [] TEXT_FORMAT; private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0; // 格式化索引常量
private static final int FORMAT_NOTE_DATE = 1; private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式索引
private static final int FORMAT_NOTE_CONTENT = 2; private static final int FORMAT_NOTE_DATE = 1; // 笔记日期格式索引
private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式索引
private Context mContext; private Context mContext; // 上下文对象
private String mFileName; private String mFileName; // 文件名
private String mFileDirectory; private String mFileDirectory; // 文件目录
// 构造函数
public TextExport(Context context) { public TextExport(Context context) {
// 从资源文件获取文本格式化数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context; // 保存上下文
mFileName = ""; mFileName = ""; // 初始化文件名为空
mFileDirectory = ""; mFileDirectory = ""; // 初始化文件目录为空
} }
// 获取指定索引的格式化字符串
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id]; // 返回格式化字符串
} }
/** /**
* Export the folder identified by folder id to text *
* @param folderId ID
* @param ps
*/ */
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // 查询属于该文件夹的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, // 查询的列
folderId NoteColumns.PARENT_ID + "=?", // 查询条件父ID等于指定文件夹ID
}, null); new String[] { folderId }, // 查询参数
null); // 排序方式(无)
if (notesCursor != null) { if (notesCursor != null) { // 如果游标不为空
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) { // 如果游标移动到第一行
do { do {
// Print note's last modified date // 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm), // 日期时间格式
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // 修改日期
// Query data belong to this note // 查询属于该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID); // 获取笔记ID
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps); // 导出该笔记的内容
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext()); // 移动到下一行
} }
notesCursor.close(); notesCursor.close(); // 关闭游标
} }
} }
/** /**
* Export note identified by id to a print stream *
* @param noteId ID
* @param ps
*/ */
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
// 查询属于该笔记的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, // 查询的列
noteId DataColumns.NOTE_ID + "=?", // 查询条件笔记ID等于指定笔记ID
}, null); new String[] { noteId }, // 查询参数
null); // 排序方式(无)
if (dataCursor != null) { if (dataCursor != null) { // 如果游标不为空
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) { // 如果游标移动到第一行
do { do {
// 获取MIME类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) { // 如果是通话笔记类型
// Print phone number // 获取通话笔记的各个字段
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) { if (!TextUtils.isEmpty(phoneNumber)) { // 如果电话号码不为空
// 打印电话号码
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
} }
// Print call date // 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), .format(mContext.getString(R.string.format_datetime_mdhm),
callDate))); callDate)));
// Print call attachment location // 打印通话附件位置
if (!TextUtils.isEmpty(location)) { if (!TextUtils.isEmpty(location)) { // 如果位置信息不为空
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location)); location));
} }
} else if (DataConstants.NOTE.equals(mimeType)) { } else if (DataConstants.NOTE.equals(mimeType)) { // 如果是普通笔记类型
String content = dataCursor.getString(DATA_COLUMN_CONTENT); String content = dataCursor.getString(DATA_COLUMN_CONTENT); // 获取内容
if (!TextUtils.isEmpty(content)) { if (!TextUtils.isEmpty(content)) { // 如果内容不为空
// 打印内容
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content)); content));
} }
} }
} while (dataCursor.moveToNext()); } while (dataCursor.moveToNext()); // 移动到下一行
} }
dataCursor.close(); dataCursor.close(); // 关闭游标
} }
// print a line separator between note // 在笔记之间打印分隔符
try { try {
ps.write(new byte[] { ps.write(new byte[] { // 写入字节数组
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, // 行分隔符
Character.LETTER_NUMBER // 字母数字字符
}); });
} catch (IOException e) { } catch (IOException e) { // 捕获IO异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
} }
} }
/** /**
* Note will be exported as text which is user readable *
* @return
*/ */
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) { // 检查外部存储是否可用
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted"); // 记录调试日志
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED; // 返回SD卡未挂载状态
} }
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream(); // 获取打印流
if (ps == null) { if (ps == null) { // 如果打印流为空
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error"); // 记录错误日志
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR; // 返回系统错误状态
} }
// First export folder and its notes
// 首先导出文件夹及其笔记
// 查询所有文件夹(排除垃圾箱)和通话记录文件夹
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, // 查询条件
null, // 查询参数
null); // 排序方式
if (folderCursor != null) { if (folderCursor != null) { // 如果游标不为空
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) { // 如果游标移动到第一行
do { do {
// Print folder's name // 打印文件夹名称
String folderName = ""; String folderName = ""; // 初始化文件夹名称为空
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
// 如果是通话记录文件夹
folderName = mContext.getString(R.string.call_record_folder_name); folderName = mContext.getString(R.string.call_record_folder_name);
} else { } else {
// 普通文件夹
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
} }
if (!TextUtils.isEmpty(folderName)) { if (!TextUtils.isEmpty(folderName)) { // 如果文件夹名称不为空
// 打印文件夹名称
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
} }
String folderId = folderCursor.getString(NOTE_COLUMN_ID); String folderId = folderCursor.getString(NOTE_COLUMN_ID); // 获取文件夹ID
exportFolderToText(folderId, ps); exportFolderToText(folderId, ps); // 导出该文件夹下的笔记
} while (folderCursor.moveToNext()); } while (folderCursor.moveToNext()); // 移动到下一行
} }
folderCursor.close(); folderCursor.close(); // 关闭游标
} }
// Export notes in root's folder // 导出根目录下的笔记父ID为0的笔记
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null); + "=0", // 查询条件类型为笔记且父ID为0
null, // 查询参数
null); // 排序方式
if (noteCursor != null) { if (noteCursor != null) { // 如果游标不为空
if (noteCursor.moveToFirst()) { if (noteCursor.moveToFirst()) { // 如果游标移动到第一行
do { do {
// 打印笔记的修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm), // 日期格式
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // 修改日期
// Query data belong to this note // 查询属于该笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID); String noteId = noteCursor.getString(NOTE_COLUMN_ID); // 获取笔记ID
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps); // 导出该笔记的内容
} while (noteCursor.moveToNext()); } while (noteCursor.moveToNext()); // 移动到下一行
} }
noteCursor.close(); noteCursor.close(); // 关闭游标
} }
ps.close(); ps.close(); // 关闭打印流
return STATE_SUCCESS; return STATE_SUCCESS; // 返回成功状态
} }
/** /**
* Get a print stream pointed to the file {@generateExportedTextFile} *
* @return null
*/ */
private PrintStream getExportToTextPrintStream() { private PrintStream getExportToTextPrintStream() {
// 生成文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format); R.string.file_name_txt_format);
if (file == null) { if (file == null) { // 如果文件为空
Log.e(TAG, "create file to exported failed"); Log.e(TAG, "create file to exported failed"); // 记录错误日志
return null; return null; // 返回null
} }
mFileName = file.getName(); mFileName = file.getName(); // 保存文件名
mFileDirectory = mContext.getString(R.string.file_path); mFileDirectory = mContext.getString(R.string.file_path); // 保存文件目录
PrintStream ps = null; PrintStream ps = null; // 初始化打印流
try { try {
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file); // 创建文件输出流
ps = new PrintStream(fos); ps = new PrintStream(fos); // 创建打印流
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) { // 捕获文件未找到异常
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈
return null; return null; // 返回null
} catch (NullPointerException e) { } catch (NullPointerException e) { // 捕获空指针异常
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈
return null; return null; // 返回null
} }
return ps; return ps; // 返回打印流
} }
} }
/** /**
* Generate the text file to store imported data * SD
* @param context
* @param filePathResId ID
* @param fileNameFormatResId ID
* @return Filenull
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); // 创建字符串构建器
sb.append(Environment.getExternalStorageDirectory()); sb.append(Environment.getExternalStorageDirectory()); // 添加外部存储目录
sb.append(context.getString(filePathResId)); sb.append(context.getString(filePathResId)); // 添加文件路径
File filedir = new File(sb.toString()); File filedir = new File(sb.toString()); // 创建目录文件对象
sb.append(context.getString( sb.append(context.getString( // 添加文件名
fileNameFormatResId, fileNameFormatResId, // 文件名格式资源ID
DateFormat.format(context.getString(R.string.format_date_ymd), DateFormat.format(context.getString(R.string.format_date_ymd), // 日期格式
System.currentTimeMillis()))); System.currentTimeMillis()))); // 当前时间
File file = new File(sb.toString()); File file = new File(sb.toString()); // 创建文件对象
try { try {
if (!filedir.exists()) { if (!filedir.exists()) { // 如果目录不存在
filedir.mkdir(); filedir.mkdir(); // 创建目录
} }
if (!file.exists()) { if (!file.exists()) { // 如果文件不存在
file.createNewFile(); file.createNewFile(); // 创建新文件
} }
return file; return file; // 返回文件对象
} catch (SecurityException e) { } catch (SecurityException e) { // 捕获安全异常
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈
} catch (IOException e) { } catch (IOException e) { // 捕获IO异常
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈
} }
return null; return null; // 如果失败返回null
} }
} }
[file content end]

@ -1,295 +1,374 @@
[file name]: DataUtils.java
[file content begin]
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* 2010-2011MiCode
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* Apache License 2.0
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* 使
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
*
* limitations under the License. * limitations under the License.
*
*/ */
// 包声明:工具类包
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; // 导入Android相关类
import android.content.ContentProviderResult; import android.content.ContentProviderOperation; // 内容提供器操作类
import android.content.ContentResolver; import android.content.ContentProviderResult; // 内容提供器结果类
import android.content.ContentUris; import android.content.ContentResolver; // 内容解析器类
import android.content.ContentValues; import android.content.ContentUris; // 内容URI工具类
import android.content.OperationApplicationException; import android.content.ContentValues; // 内容值类
import android.database.Cursor; import android.content.OperationApplicationException; // 操作应用异常类
import android.os.RemoteException; import android.database.Cursor; // 数据库游标类
import android.util.Log; 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; // 笔记数据类
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.CallNote; // 通话笔记类
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import net.micode.notes.data.Notes.NoteColumns; // 笔记列定义
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; // 小部件属性类
import java.util.ArrayList;
import java.util.HashSet;
// 导入Java集合类
import java.util.ArrayList; // 动态数组类
import java.util.HashSet; // 哈希集合类
// 数据库工具类,提供对笔记数据的各种操作
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils"; // 日志标签
// 批量删除笔记的方法
// 参数resolver - 内容解析器ids - 要删除的笔记ID集合
// 返回值boolean - 删除是否成功
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) { if (ids == null) { // 如果ID集合为空
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null"); // 记录调试日志
return true; return true; // 返回成功(无需删除)
} }
if (ids.size() == 0) { if (ids.size() == 0) { // 如果ID集合大小为0
Log.d(TAG, "no id is in the hashset"); Log.d(TAG, "no id is in the hashset"); // 记录调试日志
return true; return true; // 返回成功(无需删除)
} }
// 创建内容提供器操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) { // 遍历ID集合
if(id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) { // 如果是根文件夹ID
Log.e(TAG, "Don't delete system folder root"); Log.e(TAG, "Don't delete system folder root"); // 记录错误日志
continue; continue; // 跳过,不删除系统根文件夹
} }
// 创建删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build()); operationList.add(builder.build()); // 添加到操作列表
} }
try { try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 如果结果为空或无效
return false; Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 记录调试日志
return false; // 返回失败
} }
return true; return true; // 返回成功
} catch (RemoteException e) { } catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) { // 捕获操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} }
return false; return false; // 返回失败
} }
// 将笔记移动到其他文件夹的方法
// 参数resolver - 内容解析器id - 笔记IDsrcFolderId - 源文件夹IDdesFolderId - 目标文件夹ID
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues(); // 创建内容值对象
values.put(NoteColumns.PARENT_ID, desFolderId); values.put(NoteColumns.PARENT_ID, desFolderId); // 设置父文件夹ID为目标文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置原始父文件夹ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1); // 设置本地修改标志为1已修改
// 更新笔记
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
} }
// 批量移动笔记到指定文件夹的方法
// 参数resolver - 内容解析器ids - 笔记ID集合folderId - 目标文件夹ID
// 返回值boolean - 移动是否成功
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
if (ids == null) { if (ids == null) { // 如果ID集合为空
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null"); // 记录调试日志
return true; return true; // 返回成功(无需移动)
} }
// 创建内容提供器操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) { // 遍历ID集合
// 创建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId); builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置父文件夹ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 设置本地修改标志
operationList.add(builder.build()); operationList.add(builder.build()); // 添加到操作列表
} }
try { try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 如果结果为空或无效
return false; Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 记录调试日志
return false; // 返回失败
} }
return true; return true; // 返回成功
} catch (RemoteException e) { } catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) { // 捕获操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} }
return false; return false; // 返回失败
} }
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} *
* resolver -
* int -
*/ */
public static int getUserFolderCount(ContentResolver resolver) { 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(*)" }, new String[] { "COUNT(*)" }, // 查询计数
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, // 参数
null); null); // 排序方式
int count = 0; int count = 0; // 初始化计数
if(cursor != null) { if(cursor != null) { // 如果游标不为空
if(cursor.moveToFirst()) { if(cursor.moveToFirst()) { // 如果游标移动到第一行
try { try {
count = cursor.getInt(0); count = cursor.getInt(0); // 获取计数值
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "get folder count failed:" + e.toString()); Log.e(TAG, "get folder count failed:" + e.toString()); // 记录错误日志
} finally { } finally {
cursor.close(); cursor.close(); // 关闭游标
} }
} }
} }
return count; return count; // 返回计数
} }
// 检查指定类型的笔记是否在数据库中可见(不在垃圾箱中)
// 参数resolver - 内容解析器noteId - 笔记IDtype - 笔记类型
// 返回值boolean - 是否可见
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询指定ID和类型的笔记
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, // 所有列
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, // 条件
new String [] {String.valueOf(type)}, new String [] {String.valueOf(type)}, // 参数
null); null); // 排序
boolean exist = false; boolean exist = false; // 初始化存在标志
if (cursor != null) { if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; exist = true; // 设置存在标志为true
} }
cursor.close(); cursor.close(); // 关闭游标
} }
return exist; return exist; // 返回存在标志
} }
// 检查笔记是否存在于笔记数据库中
// 参数resolver - 内容解析器noteId - 笔记ID
// 返回值boolean - 是否存在
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询指定ID的笔记
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, // 所有列
null, // 无条件
null, // 无参数
null); // 无排序
boolean exist = false; boolean exist = false; // 初始化存在标志
if (cursor != null) { if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; exist = true; // 设置存在标志为true
} }
cursor.close(); cursor.close(); // 关闭游标
} }
return exist; return exist; // 返回存在标志
} }
// 检查数据是否存在于数据数据库中
// 参数resolver - 内容解析器dataId - 数据ID
// 返回值boolean - 是否存在
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询指定ID的数据
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, // 所有列
null, // 无条件
null, // 无参数
null); // 无排序
boolean exist = false; boolean exist = false; // 初始化存在标志
if (cursor != null) { if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; exist = true; // 设置存在标志为true
} }
cursor.close(); cursor.close(); // 关闭游标
} }
return exist; return exist; // 返回存在标志
} }
// 检查可见文件夹名称是否已存在
// 参数resolver - 内容解析器name - 文件夹名称
// 返回值boolean - 是否存在
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询指定名称的文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + // 类型为文件夹
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + // 不在垃圾箱
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?", // 名称匹配
new String[] { name }, null); new String[] { name }, // 参数
boolean exist = false; null); // 排序
if(cursor != null) { boolean exist = false; // 初始化存在标志
if(cursor.getCount() > 0) { if(cursor != null) { // 如果游标不为空
exist = true; if(cursor.getCount() > 0) { // 如果结果数大于0
exist = true; // 设置存在标志为true
} }
cursor.close(); cursor.close(); // 关闭游标
} }
return exist; return exist; // 返回存在标志
} }
// 获取文件夹中的笔记小部件属性
// 参数resolver - 内容解析器folderId - 文件夹ID
// 返回值HashSet<AppWidgetAttribute> - 小部件属性集合
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询文件夹中的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, // 查询小部件ID和类型
NoteColumns.PARENT_ID + "=?", NoteColumns.PARENT_ID + "=?", // 父文件夹ID条件
new String[] { String.valueOf(folderId) }, new String[] { String.valueOf(folderId) }, // 参数
null); null); // 排序
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null; // 初始化小部件属性集合
if (c != null) { if (c != null) { // 如果游标不为空
if (c.moveToFirst()) { if (c.moveToFirst()) { // 如果游标移动到第一行
set = new HashSet<AppWidgetAttribute>(); set = new HashSet<AppWidgetAttribute>(); // 创建集合
do { do {
try { try {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建小部件属性对象
widget.widgetId = c.getInt(0); widget.widgetId = c.getInt(0); // 获取小部件ID
widget.widgetType = c.getInt(1); widget.widgetType = c.getInt(1); // 获取小部件类型
set.add(widget); set.add(widget); // 添加到集合
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
} }
} while (c.moveToNext()); } while (c.moveToNext()); // 移动到下一行
} }
c.close(); c.close(); // 关闭游标
} }
return set; return set; // 返回集合
} }
// 根据笔记ID获取通话号码
// 参数resolver - 内容解析器noteId - 笔记ID
// 返回值String - 电话号码,如果不存在返回空字符串
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询通话笔记的电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER }, // 查询电话号码列
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", // 条件
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, // 参数
null); null); // 排序
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) { // 如果游标不为空且移动到第一行
try { try {
return cursor.getString(0); return cursor.getString(0); // 返回电话号码
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "Get call number fails " + e.toString()); Log.e(TAG, "Get call number fails " + e.toString()); // 记录错误日志
} finally { } finally {
cursor.close(); cursor.close(); // 关闭游标
} }
} }
return ""; return ""; // 返回空字符串
} }
// 根据电话号码和通话日期获取笔记ID
// 参数resolver - 内容解析器phoneNumber - 电话号码callDate - 通话日期
// 返回值long - 笔记ID如果不存在返回0
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询通话笔记的笔记ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID }, // 查询笔记ID列
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)", + CallNote.PHONE_NUMBER + ",?)", // 条件(包含电话号码相等函数)
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, // 参数
null); null); // 排序
if (cursor != null) { if (cursor != null) { // 如果游标不为空
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) { // 如果游标移动到第一行
try { try {
return cursor.getLong(0); return cursor.getLong(0); // 返回笔记ID
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "Get call note id fails " + e.toString()); Log.e(TAG, "Get call note id fails " + e.toString()); // 记录错误日志
} }
} }
cursor.close(); cursor.close(); // 关闭游标
} }
return 0; return 0; // 返回0表示不存在
} }
// 根据笔记ID获取内容摘要
// 参数resolver - 内容解析器noteId - 笔记ID
// 返回值String - 内容摘要,如果不存在抛出异常
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询笔记的内容摘要
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET }, // 查询内容摘要列
NoteColumns.ID + "=?", NoteColumns.ID + "=?", // 条件
new String [] { String.valueOf(noteId)}, new String [] { String.valueOf(noteId)}, // 参数
null); null); // 排序
if (cursor != null) { if (cursor != null) { // 如果游标不为空
String snippet = ""; String snippet = ""; // 初始化内容摘要
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) { // 如果游标移动到第一行
snippet = cursor.getString(0); snippet = cursor.getString(0); // 获取内容摘要
} }
cursor.close(); cursor.close(); // 关闭游标
return snippet; return snippet; // 返回内容摘要
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId); // 抛出异常
} }
// 格式化内容摘要(去除换行符和多余空格)
// 参数snippet - 原始内容摘要
// 返回值String - 格式化后的内容摘要
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) { // 如果内容摘要不为空
snippet = snippet.trim(); snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n'); int index = snippet.indexOf('\n'); // 查找第一个换行符位置
if (index != -1) { if (index != -1) { // 如果找到换行符
snippet = snippet.substring(0, index); snippet = snippet.substring(0, index); // 截取到换行符之前的内容
} }
} }
return snippet; return snippet; // 返回格式化后的内容摘要
} }
} }
[file content end]

@ -1,113 +1,109 @@
[file name]: GTaskStringUtils.java
[file content begin]
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* 2010-2011MiCode
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* Apache License 2.0
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* 使
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
*
* limitations under the License. * limitations under the License.
*
*/ */
// 包声明:工具类包
package net.micode.notes.tool; package net.micode.notes.tool;
// Google Task相关JSON字段和常量的工具类
public class GTaskStringUtils { public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id"; // JSON字段名常量定义
public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 动作相关字段
public final static String GTASK_JSON_ACTION_ID = "action_id"; // 动作ID字段
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; 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_CREATE = "create"; // 创建动作类型
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取全部动作类型
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"; // 更新动作类型
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// 创建者相关字段
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者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_CHILD_ENTITY = "child_entity"; 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_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; // 组类型
public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型
public final static String GTASK_JSON_COMPLETED = "completed";
// 客户端版本字段
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; // 客户端版本字段
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; // 完成状态字段
public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态字段
public final static String GTASK_JSON_DELETED = "deleted";
// 列表相关字段
public final static String GTASK_JSON_DEST_LIST = "dest_list"; 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"; // 默认列表ID字段
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_LIST = "dest_list"; // 目标列表字段
public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表ID字段
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_LISTS = "lists"; // 列表集合字段
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表字段
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_DELETED = "deleted"; // 删除状态字段
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; // 获取删除项字段
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// 父级相关字段
public final static String GTASK_JSON_ID = "id"; 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_INDEX = "index"; public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父级ID字段
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 通用字段
public final static String GTASK_JSON_ID = "id"; // ID字段
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; public final static String GTASK_JSON_INDEX = "index"; // 索引字段
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间字段
public final static String GTASK_JSON_LIST_ID = "list_id"; public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; // 最新同步点字段
public final static String GTASK_JSON_NAME = "name"; // 名称字段
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_NEW_ID = "new_id"; // 新ID字段
public final static String GTASK_JSON_NOTES = "notes"; // 笔记字段
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; // 前兄弟ID字段
public final static String GTASK_JSON_RESULTS = "results"; // 结果字段
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_TASKS = "tasks"; // 任务字段
public final static String GTASK_JSON_TYPE = "type"; // 类型字段
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_USER = "user"; // 用户字段
public final static String GTASK_JSON_PARENT_ID = "parent_id"; // MIUI文件夹前缀
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; // MIUI笔记文件夹前缀
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// 文件夹名称常量
public final static String GTASK_JSON_RESULTS = "results"; public final static String FOLDER_DEFAULT = "Default"; // 默认文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note"; // 通话笔记文件夹名称
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String FOLDER_META = "METADATA"; // 元数据文件夹名称
public final static String GTASK_JSON_TASKS = "tasks"; // 元数据头部信息
public final static String META_HEAD_GTASK_ID = "meta_gid"; // 元数据GTask ID头部
public final static String GTASK_JSON_TYPE = "type"; public final static String META_HEAD_NOTE = "meta_note"; // 元数据笔记头部
public final static String META_HEAD_DATA = "meta_data"; // 元数据数据头部
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// 元数据笔记名称(提示用户不要更新和删除)
public final static String GTASK_JSON_TYPE_TASK = "TASK"; public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; // 元数据笔记名称
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";
} }
[file content end]

@ -1,181 +1,229 @@
[file name]: ResourceParser.java
[file content begin]
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* 2010-2011MiCode
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* Apache License 2.0
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* 使
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
*
* limitations under the License. * limitations under the License.
*
*/ */
// 包声明:工具类包
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; // 导入Android相关类
import android.preference.PreferenceManager; import android.content.Context; // 上下文类
import android.preference.PreferenceManager; // 偏好设置管理器
import net.micode.notes.R; // 导入应用内部资源
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.R; // R资源文件
import net.micode.notes.ui.NotesPreferenceActivity; // 笔记偏好设置活动
// 资源解析器,用于处理笔记的背景颜色、字体大小等资源
public class ResourceParser { public class ResourceParser {
public static final int YELLOW = 0; // 背景颜色常量定义(使用整型常量表示不同颜色)
public static final int BLUE = 1; public static final int YELLOW = 0; // 黄色背景
public static final int WHITE = 2; public static final int BLUE = 1; // 蓝色背景
public static final int GREEN = 3; public static final int WHITE = 2; // 白色背景
public static final int RED = 4; public static final int GREEN = 3; // 绿色背景
public static final int RED = 4; // 红色背景
public static final int BG_DEFAULT_COLOR = YELLOW; // 默认背景颜色
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_SMALL = 0; // 小字体
public static final int TEXT_LARGE = 2; public static final int TEXT_MEDIUM = 1; // 中等字体
public static final int TEXT_SUPER = 3; public static final int TEXT_LARGE = 2; // 大字体
public static final int TEXT_SUPER = 3; // 超大字体
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小为中等
// 笔记背景资源类:处理编辑界面的背景资源
public static class NoteBgResources { public static class NoteBgResources {
// 编辑背景资源数组,对应不同颜色的背景图片
private final static int [] BG_EDIT_RESOURCES = new int [] { private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow, R.drawable.edit_yellow, // 黄色编辑背景资源ID
R.drawable.edit_blue, R.drawable.edit_blue, // 蓝色编辑背景资源ID
R.drawable.edit_white, R.drawable.edit_white, // 白色编辑背景资源ID
R.drawable.edit_green, R.drawable.edit_green, // 绿色编辑背景资源ID
R.drawable.edit_red R.drawable.edit_red // 红色编辑背景资源ID
}; };
// 编辑标题背景资源数组,对应不同颜色的标题背景图片
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow, R.drawable.edit_title_yellow, // 黄色标题背景资源ID
R.drawable.edit_title_blue, R.drawable.edit_title_blue, // 蓝色标题背景资源ID
R.drawable.edit_title_white, R.drawable.edit_title_white, // 白色标题背景资源ID
R.drawable.edit_title_green, R.drawable.edit_title_green, // 绿色标题背景资源ID
R.drawable.edit_title_red R.drawable.edit_title_red // 红色标题背景资源ID
}; };
// 获取笔记背景资源ID的方法
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id]; return BG_EDIT_RESOURCES[id]; // 返回指定ID的背景资源
} }
// 获取笔记标题背景资源ID的方法
public static int getNoteTitleBgResource(int id) { public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id]; // 返回指定ID的标题背景资源
} }
} }
// 获取默认背景ID的方法
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
// 检查偏好设置中是否启用了随机背景颜色
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 如果启用了随机背景颜色,则随机选择一个背景颜色
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else { } else {
// 否则使用默认背景颜色
return BG_DEFAULT_COLOR; return BG_DEFAULT_COLOR;
} }
} }
// 笔记列表项背景资源类:处理列表界面的背景资源
public static class NoteItemBgResources { public static class NoteItemBgResources {
// 第一个列表项背景资源数组(列表顶部项)
private final static int [] BG_FIRST_RESOURCES = new int [] { private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up, R.drawable.list_yellow_up, // 黄色顶部背景
R.drawable.list_blue_up, R.drawable.list_blue_up, // 蓝色顶部背景
R.drawable.list_white_up, R.drawable.list_white_up, // 白色顶部背景
R.drawable.list_green_up, R.drawable.list_green_up, // 绿色顶部背景
R.drawable.list_red_up R.drawable.list_red_up // 红色顶部背景
}; };
// 中间列表项背景资源数组(列表中间项)
private final static int [] BG_NORMAL_RESOURCES = new int [] { private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle, R.drawable.list_yellow_middle, // 黄色中间背景
R.drawable.list_blue_middle, R.drawable.list_blue_middle, // 蓝色中间背景
R.drawable.list_white_middle, R.drawable.list_white_middle, // 白色中间背景
R.drawable.list_green_middle, R.drawable.list_green_middle, // 绿色中间背景
R.drawable.list_red_middle R.drawable.list_red_middle // 红色中间背景
}; };
// 最后一个列表项背景资源数组(列表底部项)
private final static int [] BG_LAST_RESOURCES = new int [] { private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down, R.drawable.list_yellow_down, // 黄色底部背景
R.drawable.list_blue_down, R.drawable.list_blue_down, // 蓝色底部背景
R.drawable.list_white_down, R.drawable.list_white_down, // 白色底部背景
R.drawable.list_green_down, R.drawable.list_green_down, // 绿色底部背景
R.drawable.list_red_down, R.drawable.list_red_down, // 红色底部背景
}; };
// 单个列表项背景资源数组(列表只有一项时)
private final static int [] BG_SINGLE_RESOURCES = new int [] { private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single, R.drawable.list_yellow_single, // 黄色单个背景
R.drawable.list_blue_single, R.drawable.list_blue_single, // 蓝色单个背景
R.drawable.list_white_single, R.drawable.list_white_single, // 白色单个背景
R.drawable.list_green_single, R.drawable.list_green_single, // 绿色单个背景
R.drawable.list_red_single R.drawable.list_red_single // 红色单个背景
}; };
// 获取第一个列表项背景资源的方法
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id]; return BG_FIRST_RESOURCES[id]; // 返回指定ID的第一个列表项背景资源
} }
// 获取最后一个列表项背景资源的方法
public static int getNoteBgLastRes(int id) { public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id]; return BG_LAST_RESOURCES[id]; // 返回指定ID的最后一个列表项背景资源
} }
// 获取单个列表项背景资源的方法
public static int getNoteBgSingleRes(int id) { public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id]; return BG_SINGLE_RESOURCES[id]; // 返回指定ID的单个列表项背景资源
} }
// 获取中间列表项背景资源的方法
public static int getNoteBgNormalRes(int id) { public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id]; return BG_NORMAL_RESOURCES[id]; // 返回指定ID的中间列表项背景资源
} }
// 获取文件夹背景资源的方法
public static int getFolderBgRes() { public static int getFolderBgRes() {
return R.drawable.list_folder; return R.drawable.list_folder; // 返回文件夹背景资源ID
} }
} }
// 小部件背景资源类:处理桌面小部件的背景资源
public static class WidgetBgResources { public static class WidgetBgResources {
// 2x小部件背景资源数组
private final static int [] BG_2X_RESOURCES = new int [] { private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow, R.drawable.widget_2x_yellow, // 黄色2x小部件背景
R.drawable.widget_2x_blue, R.drawable.widget_2x_blue, // 蓝色2x小部件背景
R.drawable.widget_2x_white, R.drawable.widget_2x_white, // 白色2x小部件背景
R.drawable.widget_2x_green, R.drawable.widget_2x_green, // 绿色2x小部件背景
R.drawable.widget_2x_red, R.drawable.widget_2x_red, // 红色2x小部件背景
}; };
// 获取2x小部件背景资源的方法
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; return BG_2X_RESOURCES[id]; // 返回指定ID的2x小部件背景资源
} }
// 4x小部件背景资源数组
private final static int [] BG_4X_RESOURCES = new int [] { private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow, R.drawable.widget_4x_yellow, // 黄色4x小部件背景
R.drawable.widget_4x_blue, R.drawable.widget_4x_blue, // 蓝色4x小部件背景
R.drawable.widget_4x_white, R.drawable.widget_4x_white, // 白色4x小部件背景
R.drawable.widget_4x_green, R.drawable.widget_4x_green, // 绿色4x小部件背景
R.drawable.widget_4x_red R.drawable.widget_4x_red // 红色4x小部件背景
}; };
// 获取4x小部件背景资源的方法
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; return BG_4X_RESOURCES[id]; // 返回指定ID的4x小部件背景资源
} }
} }
// 文本外观资源类:处理文本样式资源
public static class TextAppearanceResources { public static class TextAppearanceResources {
// 文本外观资源数组,对应不同的字体大小样式
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal, R.style.TextAppearanceNormal, // 正常文本外观
R.style.TextAppearanceMedium, R.style.TextAppearanceMedium, // 中等文本外观
R.style.TextAppearanceLarge, R.style.TextAppearanceLarge, // 大文本外观
R.style.TextAppearanceSuper R.style.TextAppearanceSuper // 超大文本外观
}; };
// 获取文本外观资源的方法
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: SharedPreferenceIDbug
* The id may larger than the length of resources, in this case, * ID
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/ */
if (id >= TEXTAPPEARANCE_RESOURCES.length) { if (id >= TEXTAPPEARANCE_RESOURCES.length) {
// 如果ID超出范围返回默认字体大小
return BG_DEFAULT_FONT_SIZE; return BG_DEFAULT_FONT_SIZE;
} }
return TEXTAPPEARANCE_RESOURCES[id]; return TEXTAPPEARANCE_RESOURCES[id]; // 返回指定ID的文本外观资源
} }
// 获取资源数组大小的方法
public static int getResourcesSize() { public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length; return TEXTAPPEARANCE_RESOURCES.length; // 返回文本外观资源数组的长度
} }
} }
} }
[file content end]
Loading…
Cancel
Save