Compare commits

..

No commits in common. 'master' and 'develop' have entirely different histories.

Binary file not shown.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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