Compare commits

...

43 Commits
main ... master

Author SHA1 Message Date
zhangqing a47e5924c3 1
7 days 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.
*/
package net.micode.notes.data;
package net.micode.notes.data; // 包声明
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.content.Context; // 导入上下文类
import android.database.Cursor; // 导入数据库游标类
import android.provider.ContactsContract.CommonDataKinds.Phone; // 导入联系人电话相关类
import android.provider.ContactsContract.Data; // 导入联系人数据相关类
import android.telephony.PhoneNumberUtils; // 导入电话号码工具类
import android.util.Log; // 导入日志类
import java.util.HashMap;
import java.util.HashMap; // 导入HashMap类用于缓存联系人信息
/**
*
*
*/
public class Contact {
// 联系人缓存使用HashMap存储电话号码到联系人姓名的映射提高查询效率
private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact";
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
* ID
*
* 使PHONE_NUMBERS_EQUAL
*/
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) {
// 如果缓存为空,则初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
sContactCache = new HashMap<String, String>(); // 创建新的HashMap
}
// 先从缓存中查找,如果找到则直接返回
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(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
Data.CONTENT_URI, // 查询URI联系人数据URI
new String [] { Phone.DISPLAY_NAME }, // 要返回的列:显示名称
selection, // 选择条件
new String[] { phoneNumber }, // 选择参数:电话号码
null); // 排序方式(无)
if (cursor != null && cursor.moveToFirst()) {
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) { // 如果游标不为空且有数据
try {
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
return name;
String name = cursor.getString(0); // 获取第一列的显示名称索引0
sContactCache.put(phoneNumber, name); // 将结果存入缓存
return name; // 返回姓名
} 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 {
cursor.close();
cursor.close(); // 确保关闭游标,释放资源
}
} 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;
import android.net.Uri;
import android.net.Uri; // 导入Android URI类用于定义内容提供者的URI
/**
*
* URI
*/
public class Notes {
// 内容提供者的授权标识用于ContentProvider的authority属性
public static final String AUTHORITY = "micode_notes";
// 日志标签,用于调试输出
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
// 笔记类型常量定义
public static final int TYPE_NOTE = 0; // 普通笔记类型
public static final int TYPE_FOLDER = 1; // 文件夹类型
public static final int TYPE_SYSTEM = 2; // 系统文件夹类型
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*
* {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
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 ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID
// Intent额外数据键名常量用于在不同组件间传递数据
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
// 小部件类型常量
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x大小的小部件
public static final int TYPE_WIDGET_4X = 1; // 4x大小的小部件
/**
*
* MIME
*/
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记MIME类型
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");
/**
* Uri to query data
* URI
* URI访
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
*
*
*/
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <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
* <P> Type: INTEGER (long) </P>
* ID
* <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
* <P> Type: INTEGER (long) </P>
* ID
* <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
* <P> Type: INTEGER (long) </P>
* ID
* <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> Type: INTEGER </P>
*
* <P> : 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
* <P> Type: INTEGER (long) </P>
* ID
* <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
* <P> Type : INTEGER </P>
* ID
* <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
* <P> Type : TEXT </P>
* GoogleID
* <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 {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <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.
* <P> Type: Text </P>
* MIME
* <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
* <P> Type: INTEGER (long) </P>
* ID
* <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
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : 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
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : 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
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : 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
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : 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
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA5 = "data5";
public static final String DATA5 = "data5"; // 通用数据字段5
}
/**
*
*
*/
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <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";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/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"; // 单项目类型
// 文本笔记的URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
*
*
*/
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 CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String PHONE_NUMBER = DATA3; // 电话号码字段使用DATA3列
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");
}
}
}

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

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

@ -25,58 +25,64 @@ import org.json.JSONException;
import org.json.JSONObject;
public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName();
public class MetaData extends Task { // 元数据类继承自Task
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) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); // 在元数据中添加Google任务ID
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
Log.e(TAG, "failed to put related gid"); // 添加失败
}
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
setNotes(metaInfo.toString()); // 将元数据JSON字符串设为备注
setName(GTaskStringUtils.META_NOTE_NAME); // 设置名称为元数据笔记名称
}
// 获取关联的Google任务ID
public String getRelatedGid() {
return mRelatedGid;
}
// 重写:检查是否值得保存(只要有备注就值得保存)
@Override
public boolean isWorthSaving() {
return getNotes() != null;
return getNotes() != null; // 只要有备注就值得保存
}
// 重写从远程JSON设置内容
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
super.setContentByRemoteJSON(js); // 调用父类方法
if (getNotes() != null) { // 如果有备注
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
JSONObject metaInfo = new JSONObject(getNotes().trim()); // 解析备注为JSON
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); // 获取关联的Google任务ID
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
Log.w(TAG, "failed to get related gid"); // 获取失败
mRelatedGid = null; // 设为null
}
}
}
// 重写从本地JSON设置内容不应该被调用
@Override
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
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); // 抛出异常
}
// 重写:获取同步操作(不应该被调用)
@Override
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;
public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_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_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
public abstract class Node { // 抽象节点类,所有数据节点的基类
// 同步操作类型常量
public static final int SYNC_ACTION_NONE = 0; // 无需同步
public static final int SYNC_ACTION_ADD_REMOTE = 1; // 添加到远程
public static final int SYNC_ACTION_ADD_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_UPDATE_REMOTE = 5; // 更新远程
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 更新本地
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 更新冲突
public static final int SYNC_ACTION_ERROR = 8; // 同步错误
private String mGid; // Google任务ID
private String mName; // 节点名称
private long mLastModified; // 最后修改时间
private boolean mDeleted; // 删除标记
// 构造函数
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
mGid = null; // Google任务ID为空
mName = ""; // 名称为空字符串
mLastModified = 0; // 最后修改时间为0
mDeleted = false; // 未删除
}
// 抽象方法获取创建操作的JSON对象
public abstract JSONObject getCreateAction(int actionId);
// 抽象方法获取更新操作的JSON对象
public abstract JSONObject getUpdateAction(int actionId);
// 抽象方法从远程JSON设置内容
public abstract void setContentByRemoteJSON(JSONObject js);
// 抽象方法从本地JSON设置内容
public abstract void setContentByLocalJSON(JSONObject js);
// 抽象方法从内容生成本地JSON
public abstract JSONObject getLocalJSONFromContent();
// 抽象方法:根据游标获取同步操作类型
public abstract int getSyncAction(Cursor c);
// 设置Google任务ID
public void setGid(String gid) {
this.mGid = gid;
}
// 设置节点名称
public void setName(String name) {
this.mName = name;
}
// 设置最后修改时间
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
// 设置删除标记
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
// 获取Google任务ID
public String getGid() {
return this.mGid;
}
// 获取节点名称
public String getName() {
return this.mName;
}
// 获取最后修改时间
public long getLastModified() {
return this.mLastModified;
}
// 获取删除标记
public boolean getDeleted() {
return this.mDeleted;
}
}
}

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

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

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

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

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

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

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

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

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

@ -31,37 +31,42 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
*
*
*/
public class WorkingNote {
// Note for the working note
// 内部Note对象用于处理数据层操作
private Note mNote;
// Note Id
// 笔记ID0表示新笔记
private long mNoteId;
// Note content
// 笔记内容
private String mContent;
// Note mode
// 笔记模式(如待办事项模式)
private int mMode;
// 提醒日期
private long mAlertDate;
// 修改日期
private long mModifiedDate;
// 背景颜色ID
private int mBgColorId;
// 关联的小部件ID
private int mWidgetId;
// 小部件类型
private int mWidgetType;
// 所属文件夹ID
private long mFolderId;
// 应用上下文
private Context mContext;
// 日志标签
private static final String TAG = "WorkingNote";
// 是否标记为删除
private boolean mIsDeleted;
// 笔记设置变化监听器
private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据表查询字段投影
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +77,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
// 笔记表查询字段投影
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -81,56 +87,64 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
// 数据表字段索引常量
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
// 笔记表字段索引常量
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
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_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
/**
* -
* @param context
* @param folderId ID
*/
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();
mAlertDate = 0; // 初始无提醒
mModifiedDate = System.currentTimeMillis(); // 设置当前时间为修改时间
mFolderId = folderId;
mNote = new Note();
mNoteId = 0;
mNote = new Note(); // 创建新的Note对象
mNoteId = 0; // 新笔记ID为0
mIsDeleted = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mMode = 0; // 默认模式
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效的小部件类型
}
// Existing note construct
/**
* -
* @param context
* @param noteId ID
* @param folderId ID
*/
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
loadNote(); // 从数据库加载笔记数据
}
/**
*
*/
private void loadNote() {
// 查询笔记表获取基本信息
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
// 从游标读取字段值
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -143,10 +157,14 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
loadNoteData(); // 加载笔记内容数据
}
/**
*
*/
private void loadNoteData() {
// 查询数据表获取笔记内容
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
@ -157,10 +175,12 @@ public class WorkingNote {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
// 普通笔记类型
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 通话记录笔记类型
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
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,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,12 +212,24 @@ public class WorkingNote {
return note;
}
/**
*
* @param context
* @param id ID
* @return WorkingNote
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
*
* @return
*/
public synchronized boolean saveNote() {
// 检查是否值得保存
if (isWorthSaving()) {
// 如果是新笔记,先创建数据库记录
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
@ -196,11 +237,10 @@ public class WorkingNote {
}
}
// 同步数据到数据库
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
*/
// 如果有关联的小部件,通知更新
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
@ -212,10 +252,19 @@ public class WorkingNote {
}
}
/**
*
* @return
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
*
*
* @return
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +274,19 @@ public class WorkingNote {
}
}
/**
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,14 +297,23 @@ public class WorkingNote {
}
}
/**
*
* @param mark
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
// 如果有小部件,通知更新
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}
/**
* ID
* @param id ID
*/
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -257,6 +324,10 @@ public class WorkingNote {
}
}
/**
*
* @param mode
*/
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -267,6 +338,10 @@ public class WorkingNote {
}
}
/**
*
* @param type
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +349,10 @@ public class WorkingNote {
}
}
/**
* ID
* @param id ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +360,10 @@ public class WorkingNote {
}
}
/**
*
* @param text
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,81 +371,141 @@ public class WorkingNote {
}
}
/**
*
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
/**
*
* @return
*/
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
// 以下为获取各种属性的方法
/**
*
* @return
*/
public String getContent() {
return mContent;
}
/**
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
* @return ID
*/
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
/**
* ID
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
* @return ID
*/
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
/**
*
* @return
*/
public int getCheckListMode() {
return mMode;
}
/**
* ID
* @return ID
*/
public long getNoteId() {
return mNoteId;
}
/**
* ID
* @return ID
*/
public long getFolderId() {
return mFolderId;
}
/**
* ID
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
*
*/
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
*
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*
* @param date
* @param set
*/
void onClockAlertChanged(long date, boolean set);
/**
* Call when user create note from widget
*
*/
void onWidgetChanged();
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*
* @param oldMode
* @param 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)
* 2010-2011MiCode
*
* 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 obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
*
* limitations under the License.
*
*/
// 包声明:工具类包
package net.micode.notes.tool;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
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.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
// 导入Android相关类
import android.content.Context; // 上下文类,用于访问应用资源
import android.database.Cursor; // 数据库游标,用于查询结果
import android.os.Environment; // 环境类,用于访问外部存储
import android.text.TextUtils; // 文本工具类
import android.text.format.DateFormat; // 日期格式化类
import android.util.Log; // 日志工具类
// 导入应用内部资源
import net.micode.notes.R; // R资源文件
import net.micode.notes.data.Notes; // 笔记数据类
import net.micode.notes.data.Notes.DataColumns; // 数据列定义
import net.micode.notes.data.Notes.DataConstants; // 数据常量定义
import net.micode.notes.data.Notes.NoteColumns; // 笔记列定义
// 导入Java IO类
import java.io.File; // 文件类
import java.io.FileNotFoundException; // 文件未找到异常
import java.io.FileOutputStream; // 文件输出流
import java.io.IOException; // IO异常
import java.io.PrintStream; // 打印流
// 备份工具类:负责将笔记数据导出为文本文件
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static BackupUtils sInstance;
private static final String TAG = "BackupUtils"; // 日志标签
// 单例模式相关
private static BackupUtils sInstance; // 静态单例实例
// 获取单例实例的静态方法使用synchronized确保线程安全
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
if (sInstance == null) { // 如果实例为空
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;
// The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
// 状态常量定义
public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD卡未挂载状态
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在状态
public static final int STATE_DATA_DESTROIED = 2; // 数据被破坏状态
public static final int STATE_SYSTEM_ERROR = 3; // 系统错误状态
public static final int STATE_SUCCESS = 4; // 成功状态
private TextExport mTextExport; // 文本导出器实例
// 私有构造函数,外部不能直接实例化
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
mTextExport = new TextExport(context); // 创建文本导出器
}
// 检查外部存储是否可用的静态方法
private static boolean externalStorageAvailable() {
// 判断外部存储状态是否为已挂载
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出数据到文本文件的公共方法
public int exportToText() {
return mTextExport.exportToText();
return mTextExport.exportToText(); // 调用文本导出器的导出方法
}
// 获取导出的文本文件名
public String getExportedTextFileName() {
return mTextExport.mFileName;
return mTextExport.mFileName; // 返回文件名
}
// 获取导出的文本文件目录
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
return mTextExport.mFileDirectory; // 返回文件目录
}
// 内部类:文本导出器,实现具体的导出逻辑
private static class TextExport {
// 笔记表查询字段数组,定义需要查询的列
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 笔记ID列
NoteColumns.MODIFIED_DATE, // 修改日期列
NoteColumns.SNIPPET, // 内容摘要列
NoteColumns.TYPE // 类型列
};
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
// 笔记列索引常量
private static final int NOTE_COLUMN_ID = 0; // ID列索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; // 修改日期列索引
private static final int NOTE_COLUMN_SNIPPET = 2; // 内容摘要列索引
// 数据表查询字段数组
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
DataColumns.CONTENT, // 内容列
DataColumns.MIME_TYPE, // MIME类型列
DataColumns.DATA1, // 数据1列
DataColumns.DATA2, // 数据2列
DataColumns.DATA3, // 数据3列
DataColumns.DATA4, // 数据4列
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 数据列索引常量
private static final int DATA_COLUMN_CONTENT = 0; // 内容列索引
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_PHONE_NUMBER = 4; // 电话号码列索引
// 文本格式化字符串数组,从资源文件中读取
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_NOTE_CONTENT = 2;
// 格式化索引常量
private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式索引
private static final int FORMAT_NOTE_DATE = 1; // 笔记日期格式索引
private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式索引
private Context mContext;
private String mFileName;
private String mFileDirectory;
private Context mContext; // 上下文对象
private String mFileName; // 文件名
private String mFileDirectory; // 文件目录
// 构造函数
public TextExport(Context context) {
// 从资源文件获取文本格式化数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
mContext = context; // 保存上下文
mFileName = ""; // 初始化文件名为空
mFileDirectory = ""; // 初始化文件目录为空
}
// 获取指定索引的格式化字符串
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) {
// Query notes belong to this folder
// 查询属于该文件夹的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
NOTE_PROJECTION, // 查询的列
NoteColumns.PARENT_ID + "=?", // 查询条件父ID等于指定文件夹ID
new String[] { folderId }, // 查询参数
null); // 排序方式(无)
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
if (notesCursor != null) { // 如果游标不为空
if (notesCursor.moveToFirst()) { // 如果游标移动到第一行
do {
// Print note's last modified date
// 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
mContext.getString(R.string.format_datetime_mdhm), // 日期时间格式
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // 修改日期
// 查询属于该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID); // 获取笔记ID
exportNoteToText(noteId, ps); // 导出该笔记的内容
} 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) {
// 查询属于该笔记的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
DATA_PROJECTION, // 查询的列
DataColumns.NOTE_ID + "=?", // 查询条件笔记ID等于指定笔记ID
new String[] { noteId }, // 查询参数
null); // 排序方式(无)
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
if (dataCursor != null) { // 如果游标不为空
if (dataCursor.moveToFirst()) { // 如果游标移动到第一行
do {
// 获取MIME类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
if (DataConstants.CALL_NOTE.equals(mimeType)) { // 如果是通话笔记类型
// 获取通话笔记的各个字段
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) {
if (!TextUtils.isEmpty(phoneNumber)) { // 如果电话号码不为空
// 打印电话号码
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
if (!TextUtils.isEmpty(location)) {
// 打印通话附件位置
if (!TextUtils.isEmpty(location)) { // 如果位置信息不为空
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
} else if (DataConstants.NOTE.equals(mimeType)) { // 如果是普通笔记类型
String content = dataCursor.getString(DATA_COLUMN_CONTENT); // 获取内容
if (!TextUtils.isEmpty(content)) { // 如果内容不为空
// 打印内容
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
} while (dataCursor.moveToNext());
} while (dataCursor.moveToNext()); // 移动到下一行
}
dataCursor.close();
dataCursor.close(); // 关闭游标
}
// print a line separator between note
// 在笔记之间打印分隔符
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
ps.write(new byte[] { // 写入字节数组
Character.LINE_SEPARATOR, // 行分隔符
Character.LETTER_NUMBER // 字母数字字符
});
} catch (IOException e) {
Log.e(TAG, e.toString());
} catch (IOException e) { // 捕获IO异常
Log.e(TAG, e.toString()); // 记录错误日志
}
}
/**
* Note will be exported as text which is user readable
*
* @return
*/
public int exportToText() {
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
if (!externalStorageAvailable()) { // 检查外部存储是否可用
Log.d(TAG, "Media was not mounted"); // 记录调试日志
return STATE_SD_CARD_UNMOUONTED; // 返回SD卡未挂载状态
}
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
PrintStream ps = getExportToTextPrintStream(); // 获取打印流
if (ps == null) { // 如果打印流为空
Log.e(TAG, "get print stream error"); // 记录错误日志
return STATE_SYSTEM_ERROR; // 返回系统错误状态
}
// First export folder and its notes
// 首先导出文件夹及其笔记
// 查询所有文件夹(排除垃圾箱)和通话记录文件夹
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, // 查询条件
null, // 查询参数
null); // 排序方式
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
if (folderCursor != null) { // 如果游标不为空
if (folderCursor.moveToFirst()) { // 如果游标移动到第一行
do {
// Print folder's name
String folderName = "";
// 打印文件夹名称
String folderName = ""; // 初始化文件夹名称为空
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
// 如果是通话记录文件夹
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
// 普通文件夹
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {
if (!TextUtils.isEmpty(folderName)) { // 如果文件夹名称不为空
// 打印文件夹名称
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
String folderId = folderCursor.getString(NOTE_COLUMN_ID); // 获取文件夹ID
exportFolderToText(folderId, ps); // 导出该文件夹下的笔记
} while (folderCursor.moveToNext()); // 移动到下一行
}
folderCursor.close();
folderCursor.close(); // 关闭游标
}
// Export notes in root's folder
// 导出根目录下的笔记父ID为0的笔记
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
+ "=0", // 查询条件类型为笔记且父ID为0
null, // 查询参数
null); // 排序方式
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
if (noteCursor != null) { // 如果游标不为空
if (noteCursor.moveToFirst()) { // 如果游标移动到第一行
do {
// 打印笔记的修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
mContext.getString(R.string.format_datetime_mdhm), // 日期格式
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // 修改日期
// 查询属于该笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID); // 获取笔记ID
exportNoteToText(noteId, ps); // 导出该笔记的内容
} 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() {
// 生成文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
if (file == null) { // 如果文件为空
Log.e(TAG, "create file to exported failed"); // 记录错误日志
return null; // 返回null
}
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
mFileName = file.getName(); // 保存文件名
mFileDirectory = mContext.getString(R.string.file_path); // 保存文件目录
PrintStream ps = null; // 初始化打印流
try {
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (NullPointerException e) {
e.printStackTrace();
return null;
FileOutputStream fos = new FileOutputStream(file); // 创建文件输出流
ps = new PrintStream(fos); // 创建打印流
} catch (FileNotFoundException e) { // 捕获文件未找到异常
e.printStackTrace(); // 打印异常堆栈
return null; // 返回null
} catch (NullPointerException e) { // 捕获空指针异常
e.printStackTrace(); // 打印异常堆栈
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) {
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
File file = new File(sb.toString());
StringBuilder sb = new StringBuilder(); // 创建字符串构建器
sb.append(Environment.getExternalStorageDirectory()); // 添加外部存储目录
sb.append(context.getString(filePathResId)); // 添加文件路径
File filedir = new File(sb.toString()); // 创建目录文件对象
sb.append(context.getString( // 添加文件名
fileNameFormatResId, // 文件名格式资源ID
DateFormat.format(context.getString(R.string.format_date_ymd), // 日期格式
System.currentTimeMillis()))); // 当前时间
File file = new File(sb.toString()); // 创建文件对象
try {
if (!filedir.exists()) {
filedir.mkdir();
if (!filedir.exists()) { // 如果目录不存在
filedir.mkdir(); // 创建目录
}
if (!file.exists()) {
file.createNewFile();
if (!file.exists()) { // 如果文件不存在
file.createNewFile(); // 创建新文件
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return file; // 返回文件对象
} catch (SecurityException e) { // 捕获安全异常
e.printStackTrace(); // 打印异常堆栈
} catch (IOException e) { // 捕获IO异常
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)
* 2010-2011MiCode
*
* 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 obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
*
* limitations under the License.
*
*/
// 包声明:工具类包
package net.micode.notes.tool;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;
// 导入Android相关类
import android.content.ContentProviderOperation; // 内容提供器操作类
import android.content.ContentProviderResult; // 内容提供器结果类
import android.content.ContentResolver; // 内容解析器类
import android.content.ContentUris; // 内容URI工具类
import android.content.ContentValues; // 内容值类
import android.content.OperationApplicationException; // 操作应用异常类
import android.database.Cursor; // 数据库游标类
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.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
// 导入应用内部类
import net.micode.notes.data.Notes; // 笔记数据类
import net.micode.notes.data.Notes.CallNote; // 通话笔记类
import net.micode.notes.data.Notes.NoteColumns; // 笔记列定义
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; // 小部件属性类
// 导入Java集合类
import java.util.ArrayList; // 动态数组类
import java.util.HashSet; // 哈希集合类
// 数据库工具类,提供对笔记数据的各种操作
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) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
if (ids == null) { // 如果ID集合为空
Log.d(TAG, "the ids is null"); // 记录调试日志
return true; // 返回成功(无需删除)
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
if (ids.size() == 0) { // 如果ID集合大小为0
Log.d(TAG, "no id is in the hashset"); // 记录调试日志
return true; // 返回成功(无需删除)
}
// 创建内容提供器操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
for (long id : ids) { // 遍历ID集合
if(id == Notes.ID_ROOT_FOLDER) { // 如果是根文件夹ID
Log.e(TAG, "Don't delete system folder root"); // 记录错误日志
continue; // 跳过,不删除系统根文件夹
}
// 创建删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
operationList.add(builder.build()); // 添加到操作列表
}
try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
// 如果结果为空或无效
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 记录调试日志
return false; // 返回失败
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return true; // 返回成功
} catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} catch (OperationApplicationException e) { // 捕获操作应用异常
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) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
ContentValues values = new ContentValues(); // 创建内容值对象
values.put(NoteColumns.PARENT_ID, desFolderId); // 设置父文件夹ID为目标文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置原始父文件夹ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 设置本地修改标志为1已修改
// 更新笔记
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,
long folderId) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
if (ids == null) { // 如果ID集合为空
Log.d(TAG, "the ids is null"); // 记录调试日志
return true; // 返回成功(无需移动)
}
// 创建内容提供器操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
for (long id : ids) { // 遍历ID集合
// 创建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置父文件夹ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 设置本地修改标志
operationList.add(builder.build()); // 添加到操作列表
}
try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
// 如果结果为空或无效
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); // 记录调试日志
return false; // 返回失败
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return true; // 返回成功
} catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录错误日志
} catch (OperationApplicationException e) { // 捕获操作应用异常
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) {
// 查询用户文件夹数量
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
new String[] { "COUNT(*)" }, // 查询计数
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, // 参数
null); // 排序方式
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
int count = 0; // 初始化计数
if(cursor != null) { // 如果游标不为空
if(cursor.moveToFirst()) { // 如果游标移动到第一行
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
count = cursor.getInt(0); // 获取计数值
} catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "get folder count failed:" + e.toString()); // 记录错误日志
} finally {
cursor.close();
cursor.close(); // 关闭游标
}
}
}
return count;
return count; // 返回计数
}
// 检查指定类型的笔记是否在数据库中可见(不在垃圾箱中)
// 参数resolver - 内容解析器noteId - 笔记IDtype - 笔记类型
// 返回值boolean - 是否可见
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询指定ID和类型的笔记
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);
null, // 所有列
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, // 条件
new String [] {String.valueOf(type)}, // 参数
null); // 排序
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
boolean exist = false; // 初始化存在标志
if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; // 设置存在标志为true
}
cursor.close();
cursor.close(); // 关闭游标
}
return exist;
return exist; // 返回存在标志
}
// 检查笔记是否存在于笔记数据库中
// 参数resolver - 内容解析器noteId - 笔记ID
// 返回值boolean - 是否存在
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询指定ID的笔记
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
null, // 所有列
null, // 无条件
null, // 无参数
null); // 无排序
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
boolean exist = false; // 初始化存在标志
if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; // 设置存在标志为true
}
cursor.close();
cursor.close(); // 关闭游标
}
return exist;
return exist; // 返回存在标志
}
// 检查数据是否存在于数据数据库中
// 参数resolver - 内容解析器dataId - 数据ID
// 返回值boolean - 是否存在
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询指定ID的数据
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
null, // 所有列
null, // 无条件
null, // 无参数
null); // 无排序
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
boolean exist = false; // 初始化存在标志
if (cursor != null) { // 如果游标不为空
if (cursor.getCount() > 0) { // 如果结果数大于0
exist = true; // 设置存在标志为true
}
cursor.close();
cursor.close(); // 关闭游标
}
return exist;
return exist; // 返回存在标志
}
// 检查可见文件夹名称是否已存在
// 参数resolver - 内容解析器name - 文件夹名称
// 返回值boolean - 是否存在
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询指定名称的文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + // 类型为文件夹
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + // 不在垃圾箱
" AND " + NoteColumns.SNIPPET + "=?", // 名称匹配
new String[] { name }, // 参数
null); // 排序
boolean exist = false; // 初始化存在标志
if(cursor != null) { // 如果游标不为空
if(cursor.getCount() > 0) { // 如果结果数大于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) {
// 查询文件夹中的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, // 查询小部件ID和类型
NoteColumns.PARENT_ID + "=?", // 父文件夹ID条件
new String[] { String.valueOf(folderId) }, // 参数
null); // 排序
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
HashSet<AppWidgetAttribute> set = null; // 初始化小部件属性集合
if (c != null) { // 如果游标不为空
if (c.moveToFirst()) { // 如果游标移动到第一行
set = new HashSet<AppWidgetAttribute>(); // 创建集合
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建小部件属性对象
widget.widgetId = c.getInt(0); // 获取小部件ID
widget.widgetType = c.getInt(1); // 获取小部件类型
set.add(widget); // 添加到集合
} catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
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) {
// 查询通话笔记的电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
new String [] { CallNote.PHONE_NUMBER }, // 查询电话号码列
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", // 条件
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, // 参数
null); // 排序
if (cursor != null && cursor.moveToFirst()) {
if (cursor != null && cursor.moveToFirst()) { // 如果游标不为空且移动到第一行
try {
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
return cursor.getString(0); // 返回电话号码
} catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "Get call number fails " + e.toString()); // 记录错误日志
} finally {
cursor.close();
cursor.close(); // 关闭游标
}
}
return "";
return ""; // 返回空字符串
}
// 根据电话号码和通话日期获取笔记ID
// 参数resolver - 内容解析器phoneNumber - 电话号码callDate - 通话日期
// 返回值long - 笔记ID如果不存在返回0
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询通话笔记的笔记ID
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.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
+ CallNote.PHONE_NUMBER + ",?)", // 条件(包含电话号码相等函数)
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, // 参数
null); // 排序
if (cursor != null) {
if (cursor.moveToFirst()) {
if (cursor != null) { // 如果游标不为空
if (cursor.moveToFirst()) { // 如果游标移动到第一行
try {
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
return cursor.getLong(0); // 返回笔记ID
} catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
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) {
// 查询笔记的内容摘要
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
new String [] { NoteColumns.SNIPPET }, // 查询内容摘要列
NoteColumns.ID + "=?", // 条件
new String [] { String.valueOf(noteId)}, // 参数
null); // 排序
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
if (cursor != null) { // 如果游标不为空
String snippet = ""; // 初始化内容摘要
if (cursor.moveToFirst()) { // 如果游标移动到第一行
snippet = cursor.getString(0); // 获取内容摘要
}
cursor.close();
return snippet;
cursor.close(); // 关闭游标
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) {
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);
if (snippet != null) { // 如果内容摘要不为空
snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n'); // 查找第一个换行符位置
if (index != -1) { // 如果找到换行符
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)
* 2010-2011MiCode
*
* 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 obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
*
* limitations under the License.
*
*/
// 包声明:工具类包
package net.micode.notes.tool;
// Google Task相关JSON字段和常量的工具类
public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id";
public final static String GTASK_JSON_ACTION_LIST = "action_list";
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
public final static String GTASK_JSON_COMPLETED = "completed";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
public final static String GTASK_JSON_DELETED = "deleted";
public final static String GTASK_JSON_DEST_LIST = "dest_list";
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
public final static String GTASK_JSON_ID = "id";
public final static String GTASK_JSON_INDEX = "index";
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
public final static String GTASK_JSON_LIST_ID = "list_id";
public final static String GTASK_JSON_LISTS = "lists";
public final static String GTASK_JSON_NAME = "name";
public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PARENT_ID = "parent_id";
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
public final static String GTASK_JSON_RESULTS = "results";
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
public final static String GTASK_JSON_TASKS = "tasks";
public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_TYPE_TASK = "TASK";
public final static String GTASK_JSON_USER = "user";
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
public final static String FOLDER_DEFAULT = "Default";
public final static String FOLDER_CALL_NOTE = "Call_Note";
public final static String FOLDER_META = "METADATA";
public final static String META_HEAD_GTASK_ID = "meta_gid";
public final static String META_HEAD_NOTE = "meta_note";
public final static String META_HEAD_DATA = "meta_data";
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
// JSON字段名常量定义
// 动作相关字段
public final static String GTASK_JSON_ACTION_ID = "action_id"; // 动作ID字段
public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 动作列表字段
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; // 动作类型字段
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建动作类型
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取全部动作类型
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动动作类型
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新动作类型
// 创建者相关字段
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者ID字段
// 实体相关字段
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_TYPE_GROUP = "GROUP"; // 组类型
public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型
// 客户端版本字段
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; // 客户端版本字段
// 完成状态字段
public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态字段
// 列表相关字段
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_LIST = "dest_list"; // 目标列表字段
public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表ID字段
public final static String GTASK_JSON_LISTS = "lists"; // 列表集合字段
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表字段
// 删除相关字段
public final static String GTASK_JSON_DELETED = "deleted"; // 删除状态字段
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; // 获取删除项字段
// 父级相关字段
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_PARENT_ID = "parent_id"; // 父级ID字段
// 通用字段
public final static String GTASK_JSON_ID = "id"; // ID字段
public final static String GTASK_JSON_INDEX = "index"; // 索引字段
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间字段
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; // 最新同步点字段
public final static String GTASK_JSON_NAME = "name"; // 名称字段
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_PRIOR_SIBLING_ID = "prior_sibling_id"; // 前兄弟ID字段
public final static String GTASK_JSON_RESULTS = "results"; // 结果字段
public final static String GTASK_JSON_TASKS = "tasks"; // 任务字段
public final static String GTASK_JSON_TYPE = "type"; // 类型字段
public final static String GTASK_JSON_USER = "user"; // 用户字段
// MIUI文件夹前缀
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; // MIUI笔记文件夹前缀
// 文件夹名称常量
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"; // 元数据GTask ID头部
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)
* 2010-2011MiCode
*
* 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 obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
* "原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
*
* limitations under the License.
*
*/
// 包声明:工具类包
package net.micode.notes.tool;
import android.content.Context;
import android.preference.PreferenceManager;
// 导入Android相关类
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 static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
// 背景颜色常量定义(使用整型常量表示不同颜色)
public static final int YELLOW = 0; // 黄色背景
public static final int BLUE = 1; // 蓝色背景
public static final int WHITE = 2; // 白色背景
public static final int GREEN = 3; // 绿色背景
public static final int RED = 4; // 红色背景
public static final int BG_DEFAULT_COLOR = YELLOW;
// 默认背景颜色
public static final int BG_DEFAULT_COLOR = YELLOW; // 默认背景颜色为黄色
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
// 字体大小常量定义
public static final int TEXT_SMALL = 0; // 小字体
public static final int TEXT_MEDIUM = 1; // 中等字体
public static final int TEXT_LARGE = 2; // 大字体
public static final int TEXT_SUPER = 3; // 超大字体
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 默认字体大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小为中等
// 笔记背景资源类:处理编辑界面的背景资源
public static class NoteBgResources {
// 编辑背景资源数组,对应不同颜色的背景图片
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
R.drawable.edit_yellow, // 黄色编辑背景资源ID
R.drawable.edit_blue, // 蓝色编辑背景资源ID
R.drawable.edit_white, // 白色编辑背景资源ID
R.drawable.edit_green, // 绿色编辑背景资源ID
R.drawable.edit_red // 红色编辑背景资源ID
};
// 编辑标题背景资源数组,对应不同颜色的标题背景图片
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
R.drawable.edit_title_yellow, // 黄色标题背景资源ID
R.drawable.edit_title_blue, // 蓝色标题背景资源ID
R.drawable.edit_title_white, // 白色标题背景资源ID
R.drawable.edit_title_green, // 绿色标题背景资源ID
R.drawable.edit_title_red // 红色标题背景资源ID
};
// 获取笔记背景资源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) {
return BG_EDIT_TITLE_RESOURCES[id];
return BG_EDIT_TITLE_RESOURCES[id]; // 返回指定ID的标题背景资源
}
}
// 获取默认背景ID的方法
public static int getDefaultBgId(Context context) {
// 检查偏好设置中是否启用了随机背景颜色
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 如果启用了随机背景颜色,则随机选择一个背景颜色
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 否则使用默认背景颜色
return BG_DEFAULT_COLOR;
}
}
// 笔记列表项背景资源类:处理列表界面的背景资源
public static class NoteItemBgResources {
// 第一个列表项背景资源数组(列表顶部项)
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
R.drawable.list_yellow_up, // 黄色顶部背景
R.drawable.list_blue_up, // 蓝色顶部背景
R.drawable.list_white_up, // 白色顶部背景
R.drawable.list_green_up, // 绿色顶部背景
R.drawable.list_red_up // 红色顶部背景
};
// 中间列表项背景资源数组(列表中间项)
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
R.drawable.list_yellow_middle, // 黄色中间背景
R.drawable.list_blue_middle, // 蓝色中间背景
R.drawable.list_white_middle, // 白色中间背景
R.drawable.list_green_middle, // 绿色中间背景
R.drawable.list_red_middle // 红色中间背景
};
// 最后一个列表项背景资源数组(列表底部项)
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
R.drawable.list_yellow_down, // 黄色底部背景
R.drawable.list_blue_down, // 蓝色底部背景
R.drawable.list_white_down, // 白色底部背景
R.drawable.list_green_down, // 绿色底部背景
R.drawable.list_red_down, // 红色底部背景
};
// 单个列表项背景资源数组(列表只有一项时)
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
R.drawable.list_yellow_single, // 黄色单个背景
R.drawable.list_blue_single, // 蓝色单个背景
R.drawable.list_white_single, // 白色单个背景
R.drawable.list_green_single, // 绿色单个背景
R.drawable.list_red_single // 红色单个背景
};
// 获取第一个列表项背景资源的方法
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
return BG_FIRST_RESOURCES[id]; // 返回指定ID的第一个列表项背景资源
}
// 获取最后一个列表项背景资源的方法
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
return BG_LAST_RESOURCES[id]; // 返回指定ID的最后一个列表项背景资源
}
// 获取单个列表项背景资源的方法
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
return BG_SINGLE_RESOURCES[id]; // 返回指定ID的单个列表项背景资源
}
// 获取中间列表项背景资源的方法
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
return BG_NORMAL_RESOURCES[id]; // 返回指定ID的中间列表项背景资源
}
// 获取文件夹背景资源的方法
public static int getFolderBgRes() {
return R.drawable.list_folder;
return R.drawable.list_folder; // 返回文件夹背景资源ID
}
}
// 小部件背景资源类:处理桌面小部件的背景资源
public static class WidgetBgResources {
// 2x小部件背景资源数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
R.drawable.widget_2x_yellow, // 黄色2x小部件背景
R.drawable.widget_2x_blue, // 蓝色2x小部件背景
R.drawable.widget_2x_white, // 白色2x小部件背景
R.drawable.widget_2x_green, // 绿色2x小部件背景
R.drawable.widget_2x_red, // 红色2x小部件背景
};
// 获取2x小部件背景资源的方法
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 [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
R.drawable.widget_4x_yellow, // 黄色4x小部件背景
R.drawable.widget_4x_blue, // 蓝色4x小部件背景
R.drawable.widget_4x_white, // 白色4x小部件背景
R.drawable.widget_4x_green, // 绿色4x小部件背景
R.drawable.widget_4x_red // 红色4x小部件背景
};
// 获取4x小部件背景资源的方法
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
return BG_4X_RESOURCES[id]; // 返回指定ID的4x小部件背景资源
}
}
// 文本外观资源类:处理文本样式资源
public static class TextAppearanceResources {
// 文本外观资源数组,对应不同的字体大小样式
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
R.style.TextAppearanceNormal, // 正常文本外观
R.style.TextAppearanceMedium, // 中等文本外观
R.style.TextAppearanceLarge, // 大文本外观
R.style.TextAppearanceSuper // 超大文本外观
};
// 获取文本外观资源的方法
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
* HACKME: SharedPreferenceIDbug
* ID
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
// 如果ID超出范围返回默认字体大小
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
return TEXTAPPEARANCE_RESOURCES[id]; // 返回指定ID的文本外观资源
}
// 获取资源数组大小的方法
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
return TEXTAPPEARANCE_RESOURCES.length; // 返回文本外观资源数组的长度
}
}
}
[file content end]
Loading…
Cancel
Save