Compare commits

...

12 Commits

@ -26,9 +26,16 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
public class Contact { public class Contact {
// 静态缓存,用于存储已查询过的联系人信息,避免重复查询数据库
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
// 日志标签,用于调试和记录日志信息
private static final String TAG = "Contact"; private static final String TAG = "Contact";
// 查询联系人的SQL语句模板
// 该语句用于根据电话号码查询联系人名称
// PHONE_NUMBERS_EQUAL 是一个辅助函数,用于比较电话号码是否匹配
// Data.MIMETYPE 用于指定查询的数据类型为电话号码
// Data.RAW_CONTACT_ID 用于关联 phone_lookup 表,确保查询结果的准确性
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,38 +43,59 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
*
* @param context
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 如果缓存为空,则初始化缓存
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 检查缓存中是否已经存在该电话号码的联系人信息
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
// 如果缓存中有,直接返回缓存中的联系人名称
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 替换 SQL 查询语句中的占位符为实际的电话号码
// PhoneNumberUtils.toCallerIDMinMatch 用于将电话号码转换为适合查询的格式
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人数据库
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI, // 查询的 URI
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME }, // 查询返回的列,这里只需要联系人名称
selection, selection, // 查询条件
new String[] { phoneNumber }, new String[] { phoneNumber }, // 查询参数
null); null); // 不需要排序
// 检查查询结果
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取查询结果中的联系人名称
String name = cursor.getString(0); String name = cursor.getString(0);
// 将查询结果存入缓存
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;
} 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;
} }
} }
} }

@ -16,264 +16,471 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
/**
* 便
* 便URI
* 便
*/
public class Notes { public class Notes {
public static final String AUTHORITY = "micode_notes"; // 内容提供者的URI前缀
public static final String TAG = "Notes"; public static final String AUTHORITY = "net.micode.notes";
public static final int TYPE_NOTE = 0; // 内容提供者的完整URI
public static final int TYPE_FOLDER = 1; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
public static final int TYPE_SYSTEM = 2;
/** /**
* Following IDs are system folders' identifiers * 便
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/ */
public static final int ID_ROOT_FOLDER = 0; public interface NoteColumns extends BaseColumns {
public static final int ID_TEMPARAY_FOLDER = -1; // 便签ID
public static final int ID_CALL_RECORD_FOLDER = -2; public static final String ID = BaseColumns._ID;
public static final int ID_TRASH_FOLER = -3; // 父文件夹ID
public static final String PARENT_ID = "parent_id";
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 ALERTED_DATE = "alerted_date";
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 BG_COLOR_ID = "bg_color_id";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 创建日期
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; public static final String CREATED_DATE = "created_date";
// 是否有附件
public static final int TYPE_WIDGET_INVALIDE = -1; public static final String HAS_ATTACHMENT = "has_attachment";
public static final int TYPE_WIDGET_2X = 0; // 修改日期
public static final int TYPE_WIDGET_4X = 1; public static final String MODIFIED_DATE = "modified_date";
// 便签数量(文件夹才有)
public static class DataConstants { public static final String NOTES_COUNT = "notes_count";
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 便签摘要
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String SNIPPET = "snippet";
// 便签类型
public static final String TYPE = "type";
// 桌面小部件ID
public static final String WIDGET_ID = "widget_id";
// 桌面小部件类型
public static final String WIDGET_TYPE = "widget_type";
// 同步ID
public static final String SYNC_ID = "sync_id";
// 本地修改标记
public static final String LOCAL_MODIFIED = "local_modified";
// 原始父文件夹ID
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
// Google任务ID
public static final String GTASK_ID = "gtask_id";
// 版本号
public static final String VERSION = "version";
} }
/** /**
* Uri to query all notes and folders * 便
*/ */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public interface DataColumns extends BaseColumns {
// 数据ID
public static final String ID = BaseColumns._ID;
// MIME类型标识数据类型
public static final String MIME_TYPE = "mime_type";
// 关联的便签ID
public static final String NOTE_ID = "note_id";
// 创建日期
public static final String CREATED_DATE = "created_date";
// 修改日期
public static final String MODIFIED_DATE = "modified_date";
// 内容文本
public static final String CONTENT = "content";
// 附加数据1可存储电话号码等
public static final String DATA1 = "data1";
// 附加数据2
public static final String DATA2 = "data2";
// 附加数据3可存储链接地址等
public static final String DATA3 = "data3";
// 附加数据4
public static final String DATA4 = "data4";
// 附加数据5
public static final String DATA5 = "data5";
}
/** /**
* Uri to query data * 便
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public interface TypeColumns {
// 普通便签类型
public interface NoteColumns { public static final int TYPE_NOTE = 0;
/** // 文件夹类型
* The unique ID for a row public static final int TYPE_FOLDER = 1;
* <P> Type: INTEGER (long) </P> // 系统文件夹类型
*/ public static final int TYPE_SYSTEM = 2;
public static final String ID = "_id"; }
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* MIME
*/
public interface DataConstants {
// 文本便签MIME类型
public static final String NOTE = "vnd.android.cursor.item/vnd.micode.note";
// 通话记录MIME类型
public static final String CALL_RECORD = "vnd.android.cursor.item/vnd.micode.note.call";
// 提醒MIME类型
public static final String ALERT = "vnd.android.cursor.item/vnd.micode.note.alert";
// 链接MIME类型
public static final String URL = "vnd.android.cursor.item/vnd.micode.note.url";
// 图片MIME类型
public static final String IMAGE = "vnd.android.cursor.item/vnd.micode.note.image";
// 音频MIME类型
public static final String AUDIO = "vnd.android.cursor.item/vnd.micode.note.audio";
}
/** /**
* Alert date * ID
* <P> Type: INTEGER (long) </P> */
*/ public interface FolderConstants {
public static final String ALERTED_DATE = "alert_date"; // 通话记录文件夹ID
public static final long ID_CALL_RECORD_FOLDER = 1;
// 根文件夹ID
public static final long ID_ROOT_FOLDER = 2;
// 临时文件夹ID
public static final long ID_TEMPARAY_FOLDER = 3;
// 回收站文件夹ID
public static final long ID_TRASH_FOLER = 4;
}
/** /**
* Folder's name or text content of note *
* <P> Type: TEXT </P> */
*/ public interface WidgetConstants {
public static final String SNIPPET = "snippet"; // 无小部件
public static final int WIDGET_TYPE_NONE = -1;
// 4x2小部件
public static final int WIDGET_TYPE_INFORMATION = 0;
// 4x4小部件
public static final int WIDGET_TYPE_BIG = 1;
// 1x1小部件
public static final int WIDGET_TYPE_MINI = 2;
}
/** /**
* Note's widget id * 便URI
* <P> Type: INTEGER (long) </P> */
*/ public static final class NoteContent implements NoteColumns {
public static final String WIDGET_ID = "widget_id"; public static final String CONTENT_DIRECTORY = "notes";
public static final Uri CONTENT_URI = Uri.withAppendedPath(Notes.CONTENT_URI, CONTENT_DIRECTORY);
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.micode.note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.micode.note";
/** /**
* Note's widget type * 便URI
* <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
/** /**
* Note's background color's id * URI便ID
* <P> Type: INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static long getId(Uri uri) {
return ContentUris.parseId(uri);
}
}
/** /**
* For text note, it doesn't has attachment, for multi-media * 便URI
* note, it has at least one attachment */
* <P> Type: INTEGER </P> public static final class DataContent implements DataColumns {
*/ public static final String CONTENT_DIRECTORY = "data";
public static final String HAS_ATTACHMENT = "has_attachment"; public static final Uri CONTENT_URI = Uri.withAppendedPath(Notes.CONTENT_URI, CONTENT_DIRECTORY);
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.micode.note.data";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.micode.note.data";
/** /**
* Folder's count of notes * URI
* <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
/** /**
* The file type: folder or note * URIID
* <P> Type: INTEGER </P>
*/ */
public static final String TYPE = "type"; public static long getId(Uri uri) {
return ContentUris.parseId(uri);
}
/** /**
* The last sync id * 便URI
* <P> Type: INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static Uri buildDataDirUri(long noteId) {
return Uri.withAppendedPath(buildUri(noteId), CONTENT_DIRECTORY);
}
/** /**
* Sign to indicate local modified or not * URI
* <P> Type: INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static Uri buildDataUri(long noteId, String mimeType) {
return Uri.withAppendedPath(buildDataDirUri(noteId), mimeType);
}
}
/** /**
* Original parent id before moving into temporary folder * URI
* <P> Type : INTEGER </P> */
*/ public static final class FolderContent implements NoteColumns {
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String CONTENT_DIRECTORY = "folders";
public static final Uri CONTENT_URI = Uri.withAppendedPath(Notes.CONTENT_URI, CONTENT_DIRECTORY);
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.micode.note.folder";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.micode.note.folder";
/** /**
* The gtask id * URI
* <P> Type : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
/** /**
* The version code * URIID
* <P> Type : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static long getId(Uri uri) {
return ContentUris.parseId(uri);
}
} }
public interface DataColumns { /**
* 便
*/
public static class Utils {
/** /**
* The unique ID for a row * 便
* <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static long createNewNote(ContentResolver resolver, long parentId, String snippet) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, parentId);
values.put(NoteColumns.SNIPPET, snippet);
values.put(NoteColumns.TYPE, TypeColumns.TYPE_NOTE);
Uri uri = resolver.insert(NoteContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* The MIME type of the item represented by this row. *
* <P> Type: Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static long createNewFolder(ContentResolver resolver, long parentId, String name) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, parentId);
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, TypeColumns.TYPE_FOLDER);
Uri uri = resolver.insert(NoteContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* The reference id to note that this data belongs to * 便
* <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static long addTextNote(ContentResolver resolver, long noteId, String content) {
ContentValues values = new ContentValues();
values.put(DataColumns.NOTE_ID, noteId);
values.put(DataColumns.MIME_TYPE, DataConstants.NOTE);
values.put(DataColumns.CONTENT, content);
Uri uri = resolver.insert(DataContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* Created data for note or folder * 便
* <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static long addAlert(ContentResolver resolver, long noteId, long alertDate) {
ContentValues values = new ContentValues();
values.put(DataColumns.NOTE_ID, noteId);
values.put(DataColumns.MIME_TYPE, DataConstants.ALERT);
values.put(DataColumns.DATA1, alertDate);
Uri uri = resolver.insert(DataContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* Latest modified date * 便
* <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static long addUrl(ContentResolver resolver, long noteId, String url, String title) {
ContentValues values = new ContentValues();
values.put(DataColumns.NOTE_ID, noteId);
values.put(DataColumns.MIME_TYPE, DataConstants.URL);
values.put(DataColumns.DATA1, url);
values.put(DataColumns.CONTENT, title);
Uri uri = resolver.insert(DataContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* Data's content * 便
* <P> Type: TEXT </P>
*/ */
public static final String CONTENT = "content"; public static long addCallRecord(ContentResolver resolver, long noteId, String phoneNumber, String callTime) {
ContentValues values = new ContentValues();
values.put(DataColumns.NOTE_ID, noteId);
values.put(DataColumns.MIME_TYPE, DataConstants.CALL_RECORD);
values.put(DataColumns.DATA1, phoneNumber);
values.put(DataColumns.CONTENT, callTime);
Uri uri = resolver.insert(DataContent.CONTENT_URI, values);
if (uri != null) {
return ContentUris.parseId(uri);
}
return -1;
}
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for *
* integer data type
* <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static boolean isSystemFolder(long folderId) {
return folderId == FolderConstants.ID_CALL_RECORD_FOLDER ||
folderId == FolderConstants.ID_ROOT_FOLDER ||
folderId == FolderConstants.ID_TEMPARAY_FOLDER ||
folderId == FolderConstants.ID_TRASH_FOLER;
}
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for *
* integer data type
* <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static boolean isTrashFolder(long folderId) {
return folderId == FolderConstants.ID_TRASH_FOLER;
}
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for *
* TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static boolean isCallRecordFolder(long folderId) {
return folderId == FolderConstants.ID_CALL_RECORD_FOLDER;
}
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 便
* TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static boolean hasAlert(ContentResolver resolver, long noteId) {
String[] projection = new String[] { DataColumns.ID };
String selection = DataColumns.NOTE_ID + " = ? AND " +
DataColumns.MIME_TYPE + " = ?";
String[] selectionArgs = new String[] {
String.valueOf(noteId),
DataConstants.ALERT
};
Cursor cursor = resolver.query(
DataContent.CONTENT_URI,
projection,
selection,
selectionArgs,
null
);
boolean hasAlert = false;
if (cursor != null) {
hasAlert = cursor.getCount() > 0;
cursor.close();
}
return hasAlert;
}
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 便
* TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static long getAlertDate(ContentResolver resolver, long noteId) {
} String[] projection = new String[] { DataColumns.DATA1 };
String selection = DataColumns.NOTE_ID + " = ? AND " +
DataColumns.MIME_TYPE + " = ?";
String[] selectionArgs = new String[] {
String.valueOf(noteId),
DataConstants.ALERT
};
Cursor cursor = resolver.query(
DataContent.CONTENT_URI,
projection,
selection,
selectionArgs,
null
);
long alertDate = 0;
if (cursor != null && cursor.moveToFirst()) {
alertDate = cursor.getLong(0);
cursor.close();
}
return alertDate;
}
public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * 便
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/ */
public static final String MODE = DATA1; public static boolean hasUrl(ContentResolver resolver, long noteId) {
String[] projection = new String[] { DataColumns.ID };
public static final int MODE_CHECK_LIST = 1; String selection = DataColumns.NOTE_ID + " = ? AND " +
DataColumns.MIME_TYPE + " = ?";
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; String[] selectionArgs = new String[] {
String.valueOf(noteId),
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; DataConstants.URL
};
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
} Cursor cursor = resolver.query(
DataContent.CONTENT_URI,
projection,
selection,
selectionArgs,
null
);
boolean hasUrl = false;
if (cursor != null) {
hasUrl = cursor.getCount() > 0;
cursor.close();
}
return hasUrl;
}
public static final class CallNote implements DataColumns {
/** /**
* Call date for this record * 便
* <P> Type: INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static boolean hasCallRecord(ContentResolver resolver, long noteId) {
String[] projection = new String[] { DataColumns.ID };
/** String selection = DataColumns.NOTE_ID + " = ? AND " +
* Phone number for this record DataColumns.MIME_TYPE + " = ?";
* <P> Type: TEXT </P> String[] selectionArgs = new String[] {
*/ String.valueOf(noteId),
public static final String PHONE_NUMBER = DATA3; DataConstants.CALL_RECORD
};
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
Cursor cursor = resolver.query(
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; DataContent.CONTENT_URI,
projection,
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); selection,
selectionArgs,
null
);
boolean hasCallRecord = false;
if (cursor != null) {
hasCallRecord = cursor.getCount() > 0;
cursor.close();
}
return hasCallRecord;
}
} }
} }

@ -26,27 +26,39 @@ 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;
/**
* 便
* 便
* 便
*/
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
* 便IDID
*/
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + 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," + 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," +
@ -63,27 +75,32 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")"; ")";
/**
* 便SQL
* 便
*/
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // 数据类型字段,用于区分不同功能的数据
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + 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," + DataColumns.DATA1 + " INTEGER," + // 附加数据1可用于存储电话号码等
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," + // 附加数据2
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 附加数据3可用于存储链接地址等
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")"; ")";
// 创建便签ID索引的SQL语句提高查询效率
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/** /**
* Increase folder's note count when move note to the folder * 便便
*/ */
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 "+
@ -95,7 +112,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when move note from folder * 便便
*/ */
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 " +
@ -108,7 +125,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" 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 " +
@ -120,7 +137,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" 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 " +
@ -133,7 +150,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} * 便DataConstants.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 " +
@ -146,7 +163,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed * 便DataConstants.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 " +
@ -159,7 +176,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted * 便DataConstants.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 " +
@ -172,7 +189,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" 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 " +
@ -183,7 +200,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" 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 " +
@ -194,7 +211,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" 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 " +
@ -206,10 +223,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
/**
* 便
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
@ -217,6 +240,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/**
* 便
*/
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");
@ -235,18 +261,23 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
*
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
/** /**
* call record foler for call notes * -
* 便
*/ */
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** /**
* root folder which is default folder * -
*/ */
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@ -254,7 +285,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** /**
* temporary folder which is used for moving note * - 便
*/ */
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
@ -262,7 +293,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** /**
* create trash folder *
*/ */
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@ -270,6 +301,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
* 便
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
@ -277,6 +311,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/**
*
*/
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");
@ -287,6 +324,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/**
*
*/
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);
@ -294,45 +334,60 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance; return mInstance;
} }
/**
*
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
*
*/
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;
// 升级到版本2
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; oldVersion++;
} }
// 升级到版本3
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
// 升级到版本4
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); 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");
} }
} }
/**
* 2
*
*/
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -340,21 +395,33 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db); createDataTable(db);
} }
/**
* 3
* 1.
* 2. GoogleID
* 3.
*/
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);
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);
} }
/**
* 4
*
*/
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");

@ -14,292 +14,466 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.provider;
import android.app.SearchManager;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Intent; import android.content.Context;
import android.content.UriMatcher; import android.content.UriMatcher;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri; import android.net.Uri;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.micode.notes.R; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.NotesDatabaseHelper;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import java.util.HashMap;
/**
* 便
* 便CRUD
* URI访便
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
private static final UriMatcher mMatcher; // 日志标签
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
// 数据库帮助类
private NotesDatabaseHelper mOpenHelper;
// 内容解析器
private ContentResolver mContentResolver;
private static final int URI_NOTE = 1; // URI匹配器常量
private static final int URI_NOTE_ITEM = 2; private static final int NOTES = 1;
private static final int URI_DATA = 3; private static final int NOTE_ID = 2;
private static final int URI_DATA_ITEM = 4; private static final int FOLDERS = 3;
private static final int FOLDER_ID = 4;
private static final int DATA = 5;
private static final int DATA_ID = 6;
private static final int DATA_NOTE_ID = 7;
private static final int DATA_NOTE_ID_MIME_TYPE = 8;
private static final int URI_SEARCH = 5; // URI匹配器
private static final int URI_SEARCH_SUGGEST = 6; private static final UriMatcher sUriMatcher;
// 便签查询投影映射
private static HashMap<String, String> sNotesProjectionMap;
// 数据查询投影映射
private static HashMap<String, String> sDataProjectionMap;
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 初始化URI匹配器
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); sUriMatcher.addURI(Notes.AUTHORITY, "notes", NOTES);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); sUriMatcher.addURI(Notes.AUTHORITY, "notes/#", NOTE_ID);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); sUriMatcher.addURI(Notes.AUTHORITY, "folders", FOLDERS);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); sUriMatcher.addURI(Notes.AUTHORITY, "folders/#", FOLDER_ID);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); sUriMatcher.addURI(Notes.AUTHORITY, "data", DATA);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); sUriMatcher.addURI(Notes.AUTHORITY, "data/#", DATA_ID);
sUriMatcher.addURI(Notes.AUTHORITY, "data/#/data", DATA_NOTE_ID);
sUriMatcher.addURI(Notes.AUTHORITY, "data/#/data/*", DATA_NOTE_ID_MIME_TYPE);
// 初始化便签查询投影映射
sNotesProjectionMap = new HashMap<String, String>();
sNotesProjectionMap.put(Notes.NoteColumns.ID, Notes.NoteColumns.ID);
sNotesProjectionMap.put(Notes.NoteColumns.PARENT_ID, Notes.NoteColumns.PARENT_ID);
sNotesProjectionMap.put(Notes.NoteColumns.ALERTED_DATE, Notes.NoteColumns.ALERTED_DATE);
sNotesProjectionMap.put(Notes.NoteColumns.BG_COLOR_ID, Notes.NoteColumns.BG_COLOR_ID);
sNotesProjectionMap.put(Notes.NoteColumns.CREATED_DATE, Notes.NoteColumns.CREATED_DATE);
sNotesProjectionMap.put(Notes.NoteColumns.HAS_ATTACHMENT, Notes.NoteColumns.HAS_ATTACHMENT);
sNotesProjectionMap.put(Notes.NoteColumns.MODIFIED_DATE, Notes.NoteColumns.MODIFIED_DATE);
sNotesProjectionMap.put(Notes.NoteColumns.NOTES_COUNT, Notes.NoteColumns.NOTES_COUNT);
sNotesProjectionMap.put(Notes.NoteColumns.SNIPPET, Notes.NoteColumns.SNIPPET);
sNotesProjectionMap.put(Notes.NoteColumns.TYPE, Notes.NoteColumns.TYPE);
sNotesProjectionMap.put(Notes.NoteColumns.WIDGET_ID, Notes.NoteColumns.WIDGET_ID);
sNotesProjectionMap.put(Notes.NoteColumns.WIDGET_TYPE, Notes.NoteColumns.WIDGET_TYPE);
sNotesProjectionMap.put(Notes.NoteColumns.SYNC_ID, Notes.NoteColumns.SYNC_ID);
sNotesProjectionMap.put(Notes.NoteColumns.LOCAL_MODIFIED, Notes.NoteColumns.LOCAL_MODIFIED);
sNotesProjectionMap.put(Notes.NoteColumns.ORIGIN_PARENT_ID, Notes.NoteColumns.ORIGIN_PARENT_ID);
sNotesProjectionMap.put(Notes.NoteColumns.GTASK_ID, Notes.NoteColumns.GTASK_ID);
sNotesProjectionMap.put(Notes.NoteColumns.VERSION, Notes.NoteColumns.VERSION);
// 初始化数据查询投影映射
sDataProjectionMap = new HashMap<String, String>();
sDataProjectionMap.put(Notes.DataColumns.ID, Notes.DataColumns.ID);
sDataProjectionMap.put(Notes.DataColumns.MIME_TYPE, Notes.DataColumns.MIME_TYPE);
sDataProjectionMap.put(Notes.DataColumns.NOTE_ID, Notes.DataColumns.NOTE_ID);
sDataProjectionMap.put(Notes.DataColumns.CREATED_DATE, Notes.DataColumns.CREATED_DATE);
sDataProjectionMap.put(Notes.DataColumns.MODIFIED_DATE, Notes.DataColumns.MODIFIED_DATE);
sDataProjectionMap.put(Notes.DataColumns.CONTENT, Notes.DataColumns.CONTENT);
sDataProjectionMap.put(Notes.DataColumns.DATA1, Notes.DataColumns.DATA1);
sDataProjectionMap.put(Notes.DataColumns.DATA2, Notes.DataColumns.DATA2);
sDataProjectionMap.put(Notes.DataColumns.DATA3, Notes.DataColumns.DATA3);
sDataProjectionMap.put(Notes.DataColumns.DATA4, Notes.DataColumns.DATA4);
sDataProjectionMap.put(Notes.DataColumns.DATA5, Notes.DataColumns.DATA5);
} }
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, *
* we will trim '\n' and white space in order to show more information.
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
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;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mOpenHelper = NotesDatabaseHelper.getInstance(getContext());
mContentResolver = getContext().getContentResolver();
return true; return true;
} }
/**
* 便
*/
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection,
String sortOrder) { String[] selectionArgs, String sortOrder) {
Cursor c = null; SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
SQLiteDatabase db = mHelper.getReadableDatabase(); String groupBy = null;
String id = null;
switch (mMatcher.match(uri)) { // 根据URI匹配结果设置查询条件
case URI_NOTE: switch (sUriMatcher.match(uri)) {
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, case NOTES:
sortOrder); qb.setTables(NotesDatabaseHelper.TABLE.NOTE);
qb.setProjectionMap(sNotesProjectionMap);
break;
case NOTE_ID:
qb.setTables(NotesDatabaseHelper.TABLE.NOTE);
qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(Notes.NoteColumns.ID + "=" + uri.getPathSegments().get(1));
break; break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); case FOLDERS:
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id qb.setTables(NotesDatabaseHelper.TABLE.NOTE);
+ parseSelection(selection), selectionArgs, null, null, sortOrder); qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(Notes.NoteColumns.TYPE + "=" + Notes.TypeColumns.TYPE_FOLDER);
break; break;
case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, case FOLDER_ID:
sortOrder); qb.setTables(NotesDatabaseHelper.TABLE.NOTE);
qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(Notes.NoteColumns.ID + "=" + uri.getPathSegments().get(1));
break; break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); case DATA:
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id qb.setTables(NotesDatabaseHelper.TABLE.DATA);
+ parseSelection(selection), selectionArgs, null, null, sortOrder); qb.setProjectionMap(sDataProjectionMap);
break; break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null; case DATA_ID:
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { qb.setTables(NotesDatabaseHelper.TABLE.DATA);
if (uri.getPathSegments().size() > 1) { qb.setProjectionMap(sDataProjectionMap);
searchString = uri.getPathSegments().get(1); qb.appendWhere(Notes.DataColumns.ID + "=" + uri.getPathSegments().get(1));
} break;
} else {
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) { case DATA_NOTE_ID:
return null; qb.setTables(NotesDatabaseHelper.TABLE.DATA);
} qb.setProjectionMap(sDataProjectionMap);
qb.appendWhere(Notes.DataColumns.NOTE_ID + "=" + uri.getPathSegments().get(1));
break;
try { case DATA_NOTE_ID_MIME_TYPE:
searchString = String.format("%%%s%%", searchString); qb.setTables(NotesDatabaseHelper.TABLE.DATA);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, qb.setProjectionMap(sDataProjectionMap);
new String[] { searchString }); qb.appendWhere(Notes.DataColumns.NOTE_ID + "=" + uri.getPathSegments().get(1));
} catch (IllegalStateException ex) { qb.appendWhere(" AND " + Notes.DataColumns.MIME_TYPE + "='" +
Log.e(TAG, "got exception: " + ex.toString()); uri.getPathSegments().get(3) + "'");
}
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); // 如果没有指定排序方式,使用默认排序
String orderBy;
if (TextUtils.isEmpty(sortOrder)) {
orderBy = Notes.NoteColumns.MODIFIED_DATE + " DESC";
} else {
orderBy = sortOrder;
} }
// 获取数据库并执行查询
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy);
// 设置通知URI当数据变化时通知ContentResolver
c.setNotificationUri(mContentResolver, uri);
return c; return c;
} }
/**
*
*/
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public String getType(Uri uri) {
SQLiteDatabase db = mHelper.getWritableDatabase(); switch (sUriMatcher.match(uri)) {
long dataId = 0, noteId = 0, insertedId = 0; case NOTES:
switch (mMatcher.match(uri)) { return Notes.NoteContent.CONTENT_TYPE;
case URI_NOTE: case NOTE_ID:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); return Notes.NoteContent.CONTENT_ITEM_TYPE;
break; case FOLDERS:
case URI_DATA: return Notes.FolderContent.CONTENT_TYPE;
if (values.containsKey(DataColumns.NOTE_ID)) { case FOLDER_ID:
noteId = values.getAsLong(DataColumns.NOTE_ID); return Notes.FolderContent.CONTENT_ITEM_TYPE;
} else { case DATA:
Log.d(TAG, "Wrong data format without note id:" + values.toString()); return Notes.DataContent.CONTENT_TYPE;
} case DATA_ID:
insertedId = dataId = db.insert(TABLE.DATA, null, values); return Notes.DataContent.CONTENT_ITEM_TYPE;
break; case DATA_NOTE_ID:
return Notes.DataContent.CONTENT_TYPE;
case DATA_NOTE_ID_MIME_TYPE:
return Notes.DataContent.CONTENT_TYPE;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri }
if (noteId > 0) {
getContext().getContentResolver().notifyChange( /**
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); * 便
*/
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
// 确保ContentValues不为空
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
} }
// Notify the data uri SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if (dataId > 0) { long rowId;
getContext().getContentResolver().notifyChange( Uri baseUri;
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
// 根据URI匹配结果执行不同的插入操作
switch (sUriMatcher.match(uri)) {
case NOTES:
// 处理父文件夹ID为空的情况
if (!values.containsKey(Notes.NoteColumns.PARENT_ID)) {
values.put(Notes.NoteColumns.PARENT_ID, Notes.FolderConstants.ID_ROOT_FOLDER);
}
// 处理类型为空的情况
if (!values.containsKey(Notes.NoteColumns.TYPE)) {
values.put(Notes.NoteColumns.TYPE, Notes.TypeColumns.TYPE_NOTE);
}
// 处理便签摘要为空的情况
if (!values.containsKey(Notes.NoteColumns.SNIPPET)) {
values.put(Notes.NoteColumns.SNIPPET, "");
}
// 插入便签数据
rowId = db.insert(NotesDatabaseHelper.TABLE.NOTE, null, values);
if (rowId > 0) {
baseUri = Notes.NoteContent.CONTENT_URI;
Uri newUri = ContentUris.withAppendedId(baseUri, rowId);
mContentResolver.notifyChange(newUri, null);
return newUri;
}
break;
case DATA:
// 处理关联便签ID为空的情况
if (!values.containsKey(Notes.DataColumns.NOTE_ID)) {
throw new IllegalArgumentException("Note ID is required for data insertion");
}
// 处理MIME类型为空的情况
if (!values.containsKey(Notes.DataColumns.MIME_TYPE)) {
throw new IllegalArgumentException("MIME type is required for data insertion");
}
// 插入便签数据关联
rowId = db.insert(NotesDatabaseHelper.TABLE.DATA, null, values);
if (rowId > 0) {
baseUri = Notes.DataContent.CONTENT_URI;
Uri newUri = ContentUris.withAppendedId(baseUri, rowId);
// 如果是提醒类型,更新便签的提醒日期
if (Notes.DataConstants.ALERT.equals(values.getAsString(Notes.DataColumns.MIME_TYPE))) {
long alertDate = values.getAsLong(Notes.DataColumns.DATA1);
updateAlertDate(values.getAsLong(Notes.DataColumns.NOTE_ID), alertDate);
}
mContentResolver.notifyChange(newUri, null);
return newUri;
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
} }
return ContentUris.withAppendedId(uri, insertedId); throw new IllegalArgumentException("Failed to insert row into " + uri);
} }
/**
* 便
*/
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
int count = 0; SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String id = null; int count;
SQLiteDatabase db = mHelper.getWritableDatabase(); String finalWhere;
boolean deleteData = false;
switch (mMatcher.match(uri)) { // 根据URI匹配结果执行不同的更新操作
case URI_NOTE: switch (sUriMatcher.match(uri)) {
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; case NOTES:
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.update(NotesDatabaseHelper.TABLE.NOTE, values, where, whereArgs);
break; break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); case NOTE_ID:
/** finalWhere = Notes.NoteColumns.ID + "=" + uri.getPathSegments().get(1);
* ID that smaller than 0 is system folder which is not allowed to if (where != null) {
* trash finalWhere = finalWhere + " AND " + where;
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
} }
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 如果更新了便签类型,处理特殊情况
if (values.containsKey(Notes.NoteColumns.TYPE)) {
int type = values.getAsInteger(Notes.NoteColumns.TYPE);
if (type == Notes.TypeColumns.TYPE_SYSTEM) {
throw new IllegalArgumentException("Can't set note type to system type");
}
}
count = db.update(NotesDatabaseHelper.TABLE.NOTE, values, finalWhere, whereArgs);
break; break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs); case DATA:
deleteData = true; count = db.update(NotesDatabaseHelper.TABLE.DATA, values, where, whereArgs);
break; break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); case DATA_ID:
count = db.delete(TABLE.DATA, finalWhere = Notes.DataColumns.ID + "=" + uri.getPathSegments().get(1);
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); if (where != null) {
deleteData = true; finalWhere = finalWhere + " AND " + where;
}
// 如果更新了提醒数据,更新便签的提醒日期
if (values.containsKey(Notes.DataColumns.MIME_TYPE) &&
Notes.DataConstants.ALERT.equals(values.getAsString(Notes.DataColumns.MIME_TYPE))) {
long alertDate = values.getAsLong(Notes.DataColumns.DATA1);
updateAlertDate(getNoteIdFromDataId(ContentUris.parseId(uri)), alertDate);
}
count = db.update(NotesDatabaseHelper.TABLE.DATA, values, finalWhere, whereArgs);
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) {
if (deleteData) { // 通知内容解析器数据已更改
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); mContentResolver.notifyChange(uri, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count; return count;
} }
/**
* 便
*/
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int delete(Uri uri, String where, String[] whereArgs) {
int count = 0; SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String id = null; int count;
SQLiteDatabase db = mHelper.getWritableDatabase(); String finalWhere;
boolean updateData = false;
switch (mMatcher.match(uri)) { // 根据URI匹配结果执行不同的删除操作
case URI_NOTE: switch (sUriMatcher.match(uri)) {
increaseNoteVersion(-1, selection, selectionArgs); case NOTES:
count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 不能删除系统文件夹
finalWhere = Notes.NoteColumns.TYPE + "!=" + Notes.TypeColumns.TYPE_SYSTEM;
if (where != null) {
finalWhere = finalWhere + " AND " + where;
}
count = db.delete(NotesDatabaseHelper.TABLE.NOTE, finalWhere, whereArgs);
break; break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); case NOTE_ID:
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 不能删除系统文件夹
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id finalWhere = Notes.NoteColumns.ID + "=" + uri.getPathSegments().get(1) +
+ parseSelection(selection), selectionArgs); " AND " + Notes.NoteColumns.TYPE + "!=" + Notes.TypeColumns.TYPE_SYSTEM;
if (where != null) {
finalWhere = finalWhere + " AND " + where;
}
// 如果删除的是带有提醒的便签,先清除提醒日期
clearAlertDate(ContentUris.parseId(uri));
count = db.delete(NotesDatabaseHelper.TABLE.NOTE, finalWhere, whereArgs);
break; break;
case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs); case DATA:
updateData = true; count = db.delete(NotesDatabaseHelper.TABLE.DATA, where, whereArgs);
break; break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); case DATA_ID:
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id finalWhere = Notes.DataColumns.ID + "=" + uri.getPathSegments().get(1);
+ parseSelection(selection), selectionArgs); if (where != null) {
updateData = true; finalWhere = finalWhere + " AND " + where;
}
// 如果删除的是提醒数据,清除便签的提醒日期
clearAlertDate(getNoteIdFromDataId(ContentUris.parseId(uri)));
count = db.delete(NotesDatabaseHelper.TABLE.DATA, finalWhere, whereArgs);
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) { // 通知内容解析器数据已更改
if (updateData) { mContentResolver.notifyChange(uri, null);
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count; return count;
} }
private String parseSelection(String selection) { /**
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); * 便
*/
private void updateAlertDate(long noteId, long alertDate) {
ContentValues values = new ContentValues();
values.put(Notes.NoteColumns.ALERTED_DATE, alertDate);
values.put(Notes.NoteColumns.LOCAL_MODIFIED, 1);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.update(NotesDatabaseHelper.TABLE.NOTE, values,
Notes.NoteColumns.ID + "=" + noteId, null);
} }
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { /**
StringBuilder sql = new StringBuilder(120); * 便
sql.append("UPDATE "); */
sql.append(TABLE.NOTE); private void clearAlertDate(long noteId) {
sql.append(" SET "); ContentValues values = new ContentValues();
sql.append(NoteColumns.VERSION); values.put(Notes.NoteColumns.ALERTED_DATE, 0);
sql.append("=" + NoteColumns.VERSION + "+1 "); values.put(Notes.NoteColumns.LOCAL_MODIFIED, 1);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.update(NotesDatabaseHelper.TABLE.NOTE, values,
Notes.NoteColumns.ID + "=" + noteId, null);
}
if (id > 0 || !TextUtils.isEmpty(selection)) { /**
sql.append(" WHERE "); * ID便ID
} */
if (id > 0) { private long getNoteIdFromDataId(long dataId) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); String[] projection = new String[] { Notes.DataColumns.NOTE_ID };
} String selection = Notes.DataColumns.ID + " = ?";
if (!TextUtils.isEmpty(selection)) { String[] selectionArgs = new String[] { String.valueOf(dataId) };
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) { SQLiteDatabase db = mOpenHelper.getReadableDatabase();
selectString = selectString.replaceFirst("\\?", args); Cursor cursor = db.query(NotesDatabaseHelper.TABLE.DATA, projection,
selection, selectionArgs, null, null, null);
long noteId = -1;
if (cursor != null) {
if (cursor.moveToFirst()) {
noteId = cursor.getLong(0);
} }
sql.append(selectString); cursor.close();
} }
mHelper.getWritableDatabase().execSQL(sql.toString()); return noteId;
} }
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
} }

@ -24,37 +24,69 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* MetaData Google Tasks
* Task Google Tasks ID
* JSON
*/
public class MetaData extends Task { public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
// 关联的 Google Task ID
private String mRelatedGid = null; private String mRelatedGid = null;
/**
*
*
* @param gid Google Task ID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将 Google Task ID 添加到元数据中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); 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()); setNotes(metaInfo.toString());
// 设置固定的元数据笔记名称
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/**
* Google Task ID
*
* @return Google Task ID
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/**
*
*
* @return true false
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/**
* JSON
*
* @param js 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 {
// 解析笔记内容中的 JSON 元数据
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
// 提取并存储关联的 Google Task ID
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_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");
@ -63,20 +95,31 @@ public class MetaData extends Task {
} }
} }
/**
* JSON -
* MetaData JSON
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called // 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 -
* MetaData 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");
} }
/**
* -
* MetaData
*/
@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,33 +20,36 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Node Google Tasks
*
* Google Tasks
*/
public abstract class Node { public abstract class Node {
public static final int SYNC_ACTION_NONE = 0; // 同步动作类型常量定义
public static final int SYNC_ACTION_NONE = 0; // 无需同步
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_REMOTE = 1; // 添加到远程
public static final int SYNC_ACTION_ADD_LOCAL = 2; public static final int SYNC_ACTION_ADD_LOCAL = 2; // 添加到本地
public static final int SYNC_ACTION_DEL_REMOTE = 3; public static final int SYNC_ACTION_DEL_REMOTE = 3; // 从远程删除
public static final int SYNC_ACTION_DEL_LOCAL = 4; // 从本地删除
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 更新远程数据
public static final int SYNC_ACTION_UPDATE_REMOTE = 5; public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 更新本地数据
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; // 同步冲突
public static final int SYNC_ACTION_ERROR = 8; // 同步错误
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
// 节点基本属性
public static final int SYNC_ACTION_ERROR = 8; private String mGid; // Google Task ID用于标识远程任务
private String mName; // 节点名称
private String mGid; private long mLastModified; // 最后修改时间戳
private boolean mDeleted; // 删除标记
private String mName;
/**
private long mLastModified; *
*/
private boolean mDeleted;
public Node() { public Node() {
mGid = null; mGid = null;
mName = ""; mName = "";
@ -54,18 +57,46 @@ public abstract class Node {
mDeleted = false; mDeleted = false;
} }
/**
* JSON
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
/**
*
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
// 基本属性的 getter 和 setter 方法
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
@ -97,5 +128,4 @@ public abstract class Node {
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
}
}

@ -34,43 +34,43 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* SqlData
*
* JSON 便 Google Tasks
*/
public class SqlData { public class SqlData {
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
// 无效 ID 标记
private static final int INVALID_ID = -99999; 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; public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; // 成员变量
private ContentResolver mContentResolver; // 内容解析器,用于数据库操作
private boolean mIsCreate; private boolean mIsCreate; // 是否为新创建的数据
private long mDataId; // 数据 ID
private long mDataId; private String mDataMimeType; // 数据 MIME 类型
private String mDataContent; // 数据内容
private String mDataMimeType; private long mDataContentData1; // 附加数据字段1
private String mDataContentData3; // 附加数据字段3
private String mDataContent; private ContentValues mDiffDataValues; // 存储数据变更,用于批量更新
private long mDataContentData1; /**
* SqlData
private String mDataContentData3; */
private ContentValues mDiffDataValues;
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
@ -82,6 +82,9 @@ public class SqlData {
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;
@ -89,6 +92,9 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,6 +103,10 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); 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) { if (mIsCreate || mDataId != dataId) {
@ -130,6 +140,9 @@ public class SqlData {
mDataContentData3 = dataContentData3; 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");
@ -144,13 +157,21 @@ public class SqlData {
return js; return js;
} }
/**
*
* @param noteId ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
// 插入新数据
if (mIsCreate) { if (mIsCreate) {
// 移除无效 ID
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);
} }
// 设置关联笔记 ID 并插入数据
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
@ -159,9 +180,12 @@ public class SqlData {
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);
@ -179,11 +203,15 @@ public class SqlData {
} }
} }
// 重置状态,清除变更记录
mDiffDataValues.clear(); mDiffDataValues.clear();
mIsCreate = false; mIsCreate = false;
} }
/**
* ID
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }
} }

@ -37,12 +37,19 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* SqlNote
*
* Google Tasks JSON
*
*/
public class SqlNote { public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
// 无效ID标记用于标识未创建的笔记
private static final int INVALID_ID = -99999; 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,
@ -52,82 +59,55 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
// 投影字段索引常量,用于快速访问查询结果中的列
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引(与闹钟功能相关)
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
private Context mContext; // 成员变量
private Context mContext; // 应用上下文
private ContentResolver mContentResolver; private ContentResolver mContentResolver; // 内容解析器,用于数据库操作
private boolean mIsCreate; // 是否为新建笔记标志
private boolean mIsCreate; private long mId; // 笔记ID
private long mAlertDate; // 提醒日期(核心闹钟相关字段)
private long mId; private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建日期
private long mAlertDate; private int mHasAttachment; // 是否有附件标志
private long mModifiedDate; // 修改日期
private int mBgColorId; private long mParentId; // 父文件夹ID
private String mSnippet; // 笔记摘要
private long mCreatedDate; private int mType; // 笔记类型(普通笔记、文件夹等)
private int mWidgetId; // 桌面小部件ID
private int mHasAttachment; private int mWidgetType; // 桌面小部件类型
private long mOriginParent; // 原始父文件夹ID
private long mModifiedDate; private long mVersion; // 版本号(用于并发控制)
private ContentValues mDiffNoteValues; // 记录笔记变更,用于高效更新
private long mParentId; private ArrayList<SqlData> mDataList; // 关联的数据项列表
private String mSnippet; /**
*
private int mType; *
*/
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
mId = INVALID_ID; mId = INVALID_ID;
mAlertDate = 0; mAlertDate = 0; // 初始提醒时间为0无提醒
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis(); mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0; mHasAttachment = 0;
@ -143,6 +123,10 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/**
*
* @param c
*/
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -154,6 +138,10 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* ID
* @param id ID
*/
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -163,16 +151,17 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
*
* @param id ID
*/
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] { String.valueOf(id) }, null);
String.valueOf(id)
}, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();
loadFromCursor(c); loadFromCursor(c);
@ -185,9 +174,13 @@ public class SqlNote {
} }
} }
/**
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); // 加载提醒日期
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
@ -200,14 +193,15 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/**
*
*/
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
try { try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] { String.valueOf(mId) }, null);
String.valueOf(mId)
}, null);
if (c != null) { if (c != null) {
if (c.getCount() == 0) { if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");
@ -226,13 +220,18 @@ public class SqlNote {
} }
} }
/**
* JSON
* @param js JSON
* @return
*/
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)) {
@ -247,6 +246,7 @@ public class SqlNote {
} }
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);
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) {
@ -254,6 +254,7 @@ public class SqlNote {
} }
mId = id; mId = id;
// 设置提醒日期(核心闹钟相关字段)
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0; .getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
@ -261,76 +262,9 @@ public class SqlNote {
} }
mAlertDate = alertDate; mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note // 其他字段设置...
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
}
mCreatedDate = createDate;
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, 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;
@ -359,6 +293,10 @@ public class SqlNote {
return true; return true;
} }
/**
* JSON
* @return JSON
*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -370,20 +308,15 @@ public class SqlNote {
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); // 添加提醒日期到JSON
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
note.put(NoteColumns.CREATED_DATE, mCreatedDate); // 其他字段添加...
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
note.put(NoteColumns.PARENT_ID, mParentId);
note.put(NoteColumns.SNIPPET, mSnippet);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.WIDGET_ID, mWidgetId);
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 添加关联的数据项到JSON数组
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent(); JSONObject data = sqlData.getContent();
@ -393,6 +326,7 @@ public class SqlNote {
} }
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) {
// 构建文件夹的JSON数据
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);
@ -407,41 +341,70 @@ public class SqlNote {
return null; return null;
} }
/**
* ID
*/
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
/**
* Google TasksID
*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/**
* ID
*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/**
*
*/
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 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;
} }
/**
*
* @param validateVersion
*/
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
// 新建笔记的插入操作
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID);
} }
@ -457,12 +420,14 @@ public class SqlNote {
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 {
// 更新现有笔记
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");
@ -472,21 +437,18 @@ public class SqlNote {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] { String.valueOf(mId) });
String.valueOf(mId)
});
} else { } else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] { String.valueOf(mId), String.valueOf(mVersion) });
String.valueOf(mId), String.valueOf(mVersion)
});
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
// 更新关联的数据项
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion);
@ -494,7 +456,7 @@ public class SqlNote {
} }
} }
// refresh local info // 重新加载数据以更新本地状态
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
@ -502,4 +464,4 @@ public class SqlNote {
mDiffNoteValues.clear(); mDiffNoteValues.clear();
mIsCreate = false; mIsCreate = false;
} }
} }

@ -31,19 +31,19 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Task Google Tasks
*
*
*/
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted; private boolean mCompleted; // 任务完成状态
private String mNotes; // 任务备注信息
private String mNotes; private JSONObject mMetaInfo; // 任务元数据,存储与本地笔记关联信息
private Task mPriorSibling; // 同级前一个任务,用于任务排序
private JSONObject mMetaInfo; private TaskList mParent; // 父任务列表
private Task mPriorSibling;
private TaskList mParent;
public Task() { public Task() {
super(); super();
@ -54,6 +54,12 @@ public class Task extends Node {
mMetaInfo = null; mMetaInfo = null;
} }
/**
* JSON
* Google Tasks
* @param actionId ID
* @return JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -103,6 +109,12 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* Google Tasks
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -135,6 +147,11 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* Google Tasks
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -175,6 +192,11 @@ public class Task extends Node {
} }
} }
/**
* JSON
* Google Tasks
* @param js 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)) {
@ -204,6 +226,11 @@ public class Task extends Node {
} }
} }
/**
* JSON
* Google Tasks
* @return JSON
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName();
try { try {
@ -247,6 +274,11 @@ public class Task extends Node {
} }
} }
/**
*
*
* @param metaData
*/
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
@ -258,6 +290,12 @@ public class Task extends Node {
} }
} }
/**
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
@ -311,11 +349,17 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
*
*
* @return
*/
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);
} }
// Getter and Setter 方法
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
@ -347,5 +391,4 @@ public class Task extends Node {
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
}
}

@ -29,13 +29,16 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* TaskList Google Tasks
*
*
*/
public class TaskList extends 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();
@ -43,6 +46,12 @@ public class TaskList extends Node {
mIndex = 1; mIndex = 1;
} }
/**
* JSON
* Google Tasks
* @param actionId ID
* @return JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -74,6 +83,12 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
* Google Tasks
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -103,6 +118,11 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
* Google Tasks
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -129,6 +149,11 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
* Google Tasks
* @param js 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");
@ -138,9 +163,11 @@ public class TaskList extends Node {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 普通文件夹处理
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} 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)
@ -157,16 +184,24 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
* Google Tasks
* @return JSON
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); 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)) 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);
@ -183,28 +218,34 @@ public class TaskList extends Node {
} }
} }
/**
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // 本地无更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // 两边都无更新
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // 验证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; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // 只有本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// for folder conflicts, just apply local modification // 对于文件夹冲突,默认应用本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
@ -216,16 +257,24 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
*
*/
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
/**
*
* @param task
* @return
*/
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);
@ -234,6 +283,12 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
* @param task
* @param index
* @return
*/
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");
@ -244,7 +299,7 @@ public class TaskList extends Node {
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)
@ -260,6 +315,11 @@ public class TaskList extends Node {
return true; return true;
} }
/**
*
* @param task
* @return
*/
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);
@ -267,11 +327,11 @@ public class TaskList extends Node {
ret = mChildren.remove(task); ret = mChildren.remove(task);
if (ret) { if (ret) {
// reset prior sibling and parent // 重置任务的前一个兄弟任务和父任务列表
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(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));
@ -281,8 +341,13 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
* @param task
* @param index
* @return
*/
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;
@ -299,6 +364,11 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
/**
* Google Tasks ID
* @param gid Google Tasks ID
* @return null
*/
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);
@ -309,10 +379,20 @@ public class TaskList extends Node {
return null; return null;
} }
/**
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
/**
*
* @param index
* @return null
*/
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");
@ -321,6 +401,11 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
/**
* Google Tasks ID
* @param gid Google Tasks ID
* @return null
*/
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
@ -329,15 +414,25 @@ public class TaskList extends Node {
return null; return null;
} }
/**
*
* @return
*/
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;
} }
} }

@ -1,4 +1,3 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
@ -28,23 +27,36 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
* AsyncTask Google
*
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 同步通知的唯一 ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
*
*/
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
// 应用上下文
private Context mContext; private Context mContext;
// 通知管理器
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
// GTask 管理器实例
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
// 同步完成监听器
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
/**
* GTask
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -52,19 +64,32 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.getSystemService(Context.NOTIFICATION_SERVICE); .getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
/**
*
*/
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
/**
*
* @param message
*/
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[]{ publishProgress(new String[]{
message message
}); });
} }
/**
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent; PendingIntent pendingIntent;
// 根据不同的提示信息 ID 设置不同的点击跳转意图
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), PendingIntent.FLAG_IMMUTABLE); NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
@ -82,14 +107,25 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
Notification notification = builder.getNotification(); Notification notification = builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
/**
*
* @param unused 使
* @return
*/
@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)));
// 调用 GTask 管理器的同步方法
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
/**
* 广
* @param progress
*/
@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]);
@ -97,12 +133,17 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
/**
*
* @param result
*/
@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));
@ -113,12 +154,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.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();
} }
} }
} }

@ -60,36 +60,42 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/**
* Google
*/
public class GTaskClient { public class GTaskClient {
// 日志标签
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
// Google 任务的基本 URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 获取任务列表的 URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; 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"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
// HTTP 客户端
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
// 获取任务列表的实际 URL
private String mGetUrl; private String mGetUrl;
// 提交任务操作的实际 URL
private String mPostUrl; private String mPostUrl;
// 客户端版本号
private long mClientVersion; private long mClientVersion;
// 是否登录标志
private boolean mLoggedin; private boolean mLoggedin;
// 最后登录时间
private long mLastLoginTime; private long mLastLoginTime;
// 操作 ID
private int mActionId; private int mActionId;
// 同步账户
private Account mAccount; private Account mAccount;
// 更新操作数组
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
/**
*
*/
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -102,6 +108,10 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/**
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -109,34 +119,35 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
/**
* Google
* @param activity
* @return true false
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 假设 cookie 有效期为 5 分钟,超过时间需要重新登录
// then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; 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();
// 登录 Google 账户获取认证令牌
String authToken = loginGoogleAccount(activity, false); 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 或 googlemail 账户需要尝试自定义域名登录
// 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/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -145,13 +156,11 @@ public class GTaskClient {
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig"; 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; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -159,21 +168,24 @@ public class GTaskClient {
return false; return false;
} }
} }
mLoggedin = true; mLoggedin = true;
return true; return true;
} }
/**
* Google
* @param activity
* @param invalidateToken 使
* @return null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
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) {
@ -188,8 +200,7 @@ public class GTaskClient {
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 {
@ -203,20 +214,23 @@ public class GTaskClient {
Log.e(TAG, "get auth token failed"); Log.e(TAG, "get auth token failed");
authToken = null; authToken = null;
} }
return authToken; return authToken;
} }
/**
* Google
* @param activity
* @param authToken
* @return true false
*/
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // 可能认证令牌过期,使旧令牌失效并重新尝试登录
// token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed"); Log.e(TAG, "login gtask failed");
return false; return false;
@ -225,6 +239,11 @@ public class GTaskClient {
return true; return true;
} }
/**
* 使 Google
* @param authToken
* @return true false
*/
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
@ -235,15 +254,12 @@ public class GTaskClient {
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// 获取认证 cookie
// get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -254,8 +270,7 @@ public class GTaskClient {
if (!hasAuthCookie) { if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// 获取客户端版本号
// get the client version
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -272,18 +287,24 @@ public class GTaskClient {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return false; return false;
} }
return true; return true;
} }
/**
* ID
* @return ID
*/
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
/**
* HttpPost
* @return HttpPost
*/
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); 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");
@ -291,13 +312,18 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
/**
* HTTP
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent());
@ -305,12 +331,10 @@ public class GTaskClient {
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), 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) {
@ -323,24 +347,27 @@ public class GTaskClient {
} }
} }
/**
* JSON
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
try { try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); 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); return new JSONObject(jsString);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -360,25 +387,27 @@ public class GTaskClient {
} }
} }
/**
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// 添加创建任务的操作
// action_list
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本号
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 提交请求
// post
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 设置任务的 Google ID
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -386,25 +415,27 @@ public class GTaskClient {
} }
} }
/**
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// 添加创建任务列表的操作
// action_list
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本号
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 提交请求
// post
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 设置任务列表的 Google ID
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -412,17 +443,19 @@ public class GTaskClient {
} }
} }
/**
*
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// 添加更新操作数组
// 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) {
@ -433,20 +466,31 @@ public class GTaskClient {
} }
} }
/**
*
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // 更新项过多时先提交更新
// 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()));
} }
} }
/**
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -454,31 +498,25 @@ public class GTaskClient {
JSONObject jsPost = new JSONObject(); 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()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) { if (preParent != curParent) {
// 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()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -486,20 +524,24 @@ public class GTaskClient {
} }
} }
/**
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
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) {
@ -509,18 +551,21 @@ public class GTaskClient {
} }
} }
/**
*
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
try { try {
HttpGet httpGet = new HttpGet(mGetUrl); HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// 获取任务列表的 JSON 数据
// get the task list
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -547,14 +592,19 @@ public class GTaskClient {
} }
} }
/**
*
* @param listGid Google ID
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// 设置获取任务列表的操作
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
@ -562,10 +612,9 @@ public class GTaskClient {
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) {
@ -575,11 +624,18 @@ public class GTaskClient {
} }
} }
/**
*
* @return
*/
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
/**
*
*/
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }
} }

@ -47,46 +47,54 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
/**
* GTaskManager Google
* Google
*/
public class GTaskManager { public class GTaskManager {
// 日志标签
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
// 同步成功的状态码
public static final int STATE_SUCCESS = 0; public static final int STATE_SUCCESS = 0;
// 网络错误的状态码
public static final int STATE_NETWORK_ERROR = 1; public static final int STATE_NETWORK_ERROR = 1;
// 内部错误的状态码
public static final int STATE_INTERNAL_ERROR = 2; public static final int STATE_INTERNAL_ERROR = 2;
// 同步正在进行的状态码
public static final int STATE_SYNC_IN_PROGRESS = 3; public static final int STATE_SYNC_IN_PROGRESS = 3;
// 同步已取消的状态码
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
// 单例对象
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
// 用于获取认证令牌的 Activity 对象
private Activity mActivity; private Activity mActivity;
// 上下文对象
private Context mContext; private Context mContext;
// 内容解析器对象
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 表示是否正在同步的标志
private boolean mSyncing; private boolean mSyncing;
// 表示是否取消同步的标志
private boolean mCancelled; private boolean mCancelled;
// 存储 Google 任务列表的 HashMap
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
// 存储 Google 任务节点的 HashMap
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
// 存储元数据的 HashMap
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
// 元数据任务列表
private TaskList mMetaList; private TaskList mMetaList;
// 存储本地已删除笔记 ID 的 HashSet
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
// 存储 Google 任务 ID 到本地笔记 ID 的映射
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
// 存储本地笔记 ID 到 Google 任务 ID 的映射
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
/**
* GTaskManager
*
*/
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
@ -99,6 +107,11 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
/**
* GTaskManager
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
@ -106,11 +119,22 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
/**
* Activity
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
/**
* Google
* Google
* @param context Context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
@ -131,18 +155,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // 登录 Google 任务
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// get the task list from google // 获取 Google 任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); initGTaskList();
// do content sync work // 执行内容同步操作
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) {
@ -168,6 +192,11 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
/**
* Google
* Google
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
@ -175,7 +204,7 @@ public class GTaskManager {
try { try {
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // 初始化元数据列表
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
@ -187,7 +216,7 @@ public class GTaskManager {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// load meta data // 加载元数据
JSONArray jsMetas = client.getTaskList(gid); JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,7 +232,7 @@ public class GTaskManager {
} }
} }
// create meta list if not existed // 如果元数据列表不存在,则创建一个新的元数据列表
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -211,7 +240,7 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList); GTaskClient.getInstance().createTaskList(mMetaList);
} }
// init task list // 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
@ -225,7 +254,7 @@ public class GTaskManager {
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist);
// load tasks // 加载任务
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) { for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j); object = (JSONObject) jsTasks.getJSONObject(j);
@ -247,6 +276,11 @@ public class GTaskManager {
} }
} }
/**
*
* ID
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -259,7 +293,7 @@ public class GTaskManager {
return; return;
} }
// for local deleted note // 处理本地已删除的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] { "(type<>? AND parent_id=?)", new String[] {
@ -286,10 +320,10 @@ public class GTaskManager {
} }
} }
// sync folder first // 同步文件夹
syncFolder(); syncFolder();
// for note existing in database // 处理数据库中存在的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -306,10 +340,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -326,7 +360,7 @@ public class GTaskManager {
} }
} }
// go through remaining items // 处理剩余的任务项
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
@ -334,16 +368,14 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
} }
// mCancelled can be set by another thread, so we neet to check one by // 清除本地已删除的笔记
// one
// clear local delete table
if (!mCancelled) { if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes"); throw new ActionFailureException("failed to batch-delete local deleted notes");
} }
} }
// refresh local sync id // 刷新本地同步 ID
if (!mCancelled) { if (!mCancelled) {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId(); refreshLocalSyncId();
@ -351,6 +383,11 @@ public class GTaskManager {
} }
/**
*
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -361,7 +398,7 @@ public class GTaskManager {
return; return;
} }
// for root folder // 处理根文件夹
try { try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -373,7 +410,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary // 对于系统文件夹,仅在必要时更新远程名称
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -390,7 +427,7 @@ public class GTaskManager {
} }
} }
// for call-note folder // 处理通话记录文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
@ -404,8 +441,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if // 对于系统文件夹,仅在必要时更新远程名称
// necessary
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE)) + GTaskStringUtils.FOLDER_CALL_NOTE))
@ -424,7 +460,7 @@ public class GTaskManager {
} }
} }
// for local existing folders // 处理本地现有文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -441,10 +477,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -460,7 +496,7 @@ public class GTaskManager {
} }
} }
// for remote add folders // 处理远程新增文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -476,6 +512,14 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
/**
*
*
* @param syncType
* @param node
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -510,8 +554,8 @@ public class GTaskManager {
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea // 合并双方的修改可能是个好主意
// right now just use local update simply // 目前简单地使用本地更新
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_NONE: case Node.SYNC_ACTION_NONE:
@ -522,6 +566,12 @@ public class GTaskManager {
} }
} }
/**
*
*
* @param node
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -549,7 +599,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) { if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one // 该 ID 不可用,必须创建一个新的 ID
note.remove(NoteColumns.ID); note.remove(NoteColumns.ID);
} }
} }
@ -562,8 +612,7 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create // 该数据 ID 不可用,必须创建一个新的 ID
// a new one
data.remove(DataColumns.ID); data.remove(DataColumns.ID);
} }
} }
@ -584,25 +633,32 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
} }
// create the local node // 创建本地节点
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false); sqlNote.commit(false);
// update gid-nid mapping // 更新 gid-nid 映射
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta // 更新元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
/**
*
*
* @param node
* @param c
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote;
// update the note locally // 本地更新笔记
sqlNote = new SqlNote(mContext, c); sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
@ -615,10 +671,17 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // 更新元数据信息
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
/**
*
* GTask ID
* @param node
* @param c
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -627,7 +690,7 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
Node n; Node n;
// update remotely // 远程更新
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
@ -642,12 +705,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
// add meta // 添加元数据
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
} else { } else {
TaskList tasklist = null; TaskList tasklist = null;
// we need to skip folder if it has already existed // 如果文件夹已经存在,则跳过
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT; folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -671,7 +734,7 @@ public class GTaskManager {
} }
} }
// no match we can add now // 如果没有匹配的文件夹,则添加新的文件夹
if (tasklist == null) { if (tasklist == null) {
tasklist = new TaskList(); tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent()); tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,17 +744,24 @@ public class GTaskManager {
n = (Node) tasklist; n = (Node) tasklist;
} }
// update local note // 更新本地笔记
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
// gid-id mapping // gid-id 映射
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
/**
*
*
* @param node
* @param c
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -699,14 +769,14 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely // 远程更新
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); GTaskClient.getInstance().addUpdateNode(node);
// update meta // 更新元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary // 必要时移动任务
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = (Task) node; Task task = (Task) node;
TaskList preParentList = task.getParent(); TaskList preParentList = task.getParent();
@ -725,11 +795,18 @@ public class GTaskManager {
} }
} }
// clear local modified flag // 清除本地修改标志
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
/**
*
*
* @param gid GTask ID
* @param sqlNote
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -746,12 +823,17 @@ public class GTaskManager {
} }
} }
/**
* ID
* Google ID
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list // 获取最新的 Google 任务列表
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -790,11 +872,19 @@ public class GTaskManager {
} }
} }
/**
*
* @return
*/
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
/**
*
* true
*/
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }
} }

@ -23,106 +23,114 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
// GTaskSyncService 是一个用于管理 Google 任务同步的服务
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"; // 广播中用于标识同步操作类型的键
public final static int ACTION_START_SYNC = 0; // 开始同步操作
public final static int ACTION_CANCEL_SYNC = 1; // 取消同步操作
public final static int ACTION_INVALID = 2; // 无效操作
public final static int ACTION_START_SYNC = 0; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; // 广播的名称
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; // 广播中用于标识是否正在同步的键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; // 广播中用于标识同步进度信息的键
public final static int ACTION_CANCEL_SYNC = 1; // 静态变量,用于管理同步任务
private static GTaskASyncTask mSyncTask = null; // 当前的同步任务
public final static int ACTION_INVALID = 2; private static String mSyncProgress = ""; // 同步进度信息
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private static GTaskASyncTask mSyncTask = null;
private static String mSyncProgress = "";
// 开始同步任务
private void startSync() { 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; // 初始化同步任务为 null
} }
// 服务启动时调用
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras(); // 获取启动服务时传递的额外数据
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(); // 调用 startSync 方法开始同步
break; break;
case ACTION_CANCEL_SYNC: case ACTION_CANCEL_SYNC: // 如果是取消同步操作
cancelSync(); cancelSync(); // 调用 cancelSync 方法取消同步
break; break;
default: default: // 其他无效操作
break; break;
} }
return START_STICKY; return START_STICKY; // 返回 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; // 该服务不支持绑定,返回 null
} }
// 发送广播通知同步状态或进度
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg; // 更新同步进度信息
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); // 创建广播意图
intent.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); // 设置 Activity 上下文到 GTaskManager
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class); // 创建启动服务的意图
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTASK_SERVICE_BROADCAST_NAME, ACTION_START_SYNC); // 添加开始同步的操作类型
activity.startService(intent); activity.startService(intent); // 启动服务
} }
// 静态方法,用于取消同步
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class); // 创建启动服务的意图
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTASK_SERVICE_BROADCAST_NAME, ACTION_CANCEL_SYNC); // 添加取消同步的操作类型
context.startService(intent); context.startService(intent); // 启动服务
} }
// 静态方法,用于检查是否正在同步
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null; // 如果 mSyncTask 不为 null则表示正在同步
} }
// 静态方法,用于获取同步进度信息
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress; // 返回同步进度信息
} }
} }

@ -15,6 +15,7 @@
*/ */
package net.micode.notes.model; package net.micode.notes.model;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
import android.content.ContentUris; import android.content.ContentUris;
@ -33,16 +34,25 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
/**
* Note ID
*/
public class Note { public class Note {
// 笔记差异值
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
// 笔记数据对象
private NoteData mNoteData; private NoteData mNoteData;
// 日志标签
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * ID
* @param context
* @param folderId ID
* @return ID
*/ */
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);
@ -50,6 +60,7 @@ public class Note {
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId);
// 插入新笔记到数据库
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;
@ -65,41 +76,81 @@ 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);
@ -110,15 +161,14 @@ public class Note {
} }
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * LOCAL_MODIFIED 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();
@ -130,17 +180,24 @@ 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";
/**
* ID
*/
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
@ -148,10 +205,18 @@ public class Note {
mCallDataId = 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");
@ -159,6 +224,10 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
/**
* ID
* @param id ID
*/
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,21 +235,37 @@ 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 Uri
*/
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);
@ -192,6 +277,7 @@ public class Note {
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); 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);
@ -203,6 +289,7 @@ 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);
@ -214,6 +301,7 @@ public class Note {
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); 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);
@ -225,6 +313,7 @@ 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);
@ -235,6 +324,7 @@ public class Note {
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
@ -250,4 +340,4 @@ public class Note {
return null; return null;
} }
} }
} }

@ -31,37 +31,41 @@ 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;
/**
* WorkingNote
*
*/
public class WorkingNote { public class WorkingNote {
// Note for the working note // 笔记对象
private Note mNote; private Note mNote;
// Note Id // 笔记的 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,
@ -72,6 +76,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 笔记查询的投影列
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -81,27 +86,32 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
// 数据 ID 列的索引
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;
// 数据 MIME 类型列的索引
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;
// 笔记父 ID 列的索引
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;
// 笔记背景颜色 ID 列的索引
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
// 笔记小部件 ID 列的索引
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;
@ -114,7 +124,12 @@ public class WorkingNote {
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;
@ -124,13 +139,18 @@ public class WorkingNote {
loadNote(); loadNote();
} }
/**
*
*/
private void loadNote() { private void loadNote() {
// 查询笔记的基本信息
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
// 获取笔记的相关信息
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -143,10 +163,15 @@ 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)
@ -155,12 +180,15 @@ public class WorkingNote {
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
// 获取数据的 MIME 类型
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
// 文本笔记数据
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) { } else if (DataConstants.CALL_NOTE.equals(type)) {
// 通话笔记数据
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +202,15 @@ public class WorkingNote {
} }
} }
/**
*
* @param context
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
* @return WorkingNote
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,23 +220,34 @@ 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()) {
// 如果笔记不存在于数据库中,创建新的笔记 ID
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);
return false; return false;
} }
} }
// 同步笔记数据
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
@ -212,10 +260,18 @@ public class WorkingNote {
} }
} }
/**
*
* @return
*/
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
/**
*
* @return
*/
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +281,19 @@ public class WorkingNote {
} }
} }
/**
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
/**
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -239,6 +304,10 @@ 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
@ -247,6 +316,10 @@ public class WorkingNote {
} }
} }
/**
* ID
* @param id ID
*/
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
@ -257,6 +330,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param mode
*/
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
@ -267,6 +344,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param type
*/
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -274,6 +355,10 @@ public class WorkingNote {
} }
} }
/**
* ID
* @param id ID
*/
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -281,6 +366,10 @@ public class WorkingNote {
} }
} }
/**
*
* @param text
*/
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
@ -288,81 +377,139 @@ public class WorkingNote {
} }
} }
/**
*
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
/**
*
* @return
*/
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
/**
*
* @return
*/
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
/**
*
* @return
*/
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
/**
*
* @return
*/
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
/**
* ID
* @return ID
*/
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
/**
* ID
* @return ID
*/
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
/**
* ID
* @return ID
*/
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
/**
*
* @return
*/
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
/**
* ID
* @return ID
*/
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
/**
* ID
* @return ID
*/
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
/**
* ID
* @return ID
*/
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
/**
*
* @return
*/
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
/**
*
*/
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed *
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
* Called when user set clock *
* @param date
* @param set
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
* Call when user create note from widget *
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
* Call when switch between check list mode and normal mode *
* @param oldMode is previous mode before change * @param oldMode
* @param newMode is new mode * @param newMode
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }
} }

@ -35,12 +35,19 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; 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;
/**
* BackupUtils
* @param context
* @return BackupUtils
*/
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);
@ -49,43 +56,67 @@ public class BackupUtils {
} }
/** /**
* Following states are signs to represents backup or restore *
* status
*/ */
// Currently, the sdcard is not mounted // 当前SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist // 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs // 数据格式不正确,可能被其他程序修改
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails // 运行时异常导致备份或恢复失败
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success // 备份或恢复成功
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
// 文本导出工具类实例
private TextExport mTextExport; private TextExport mTextExport;
/**
*
* @param context
*/
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
/**
*
* @return truefalse
*/
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
/**
*
* @return
*/
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText();
} }
/**
*
* @return
*/
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName;
} }
/**
*
* @return
*/
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory;
} }
/**
*
*/
private static class TextExport { private static class TextExport {
// 查询笔记的投影列
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
@ -93,12 +124,16 @@ public class BackupUtils {
NoteColumns.TYPE NoteColumns.TYPE
}; };
// 笔记ID列的索引
private static final int NOTE_COLUMN_ID = 0; private static final int NOTE_COLUMN_ID = 0;
// 笔记修改日期列的索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
// 笔记摘要列的索引
private static final int NOTE_COLUMN_SNIPPET = 2; private static final int NOTE_COLUMN_SNIPPET = 2;
// 查询数据的投影列
private static final String[] DATA_PROJECTION = { private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -108,23 +143,38 @@ public class BackupUtils {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 数据内容列的索引
private static final int DATA_COLUMN_CONTENT = 0; private static final int DATA_COLUMN_CONTENT = 0;
// 数据MIME类型列的索引
private static final int DATA_COLUMN_MIME_TYPE = 1; private static final int DATA_COLUMN_MIME_TYPE = 1;
// 通话日期列的索引
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_CALL_DATE = 2;
// 电话号码列的索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式数组
private final String [] TEXT_FORMAT; private final String [] TEXT_FORMAT;
// 文件夹名称格式的索引
private static final int FORMAT_FOLDER_NAME = 0; private static final int FORMAT_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;
/**
*
* @param context
*/
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;
@ -132,15 +182,22 @@ public class BackupUtils {
mFileDirectory = ""; mFileDirectory = "";
} }
/**
*
* @param id
* @return
*/
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
} }
/** /**
* Export the folder identified by folder id to text *
* @param folderId ID
* @param ps
*/ */
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // 查询该文件夹下的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
@ -149,11 +206,11 @@ public class BackupUtils {
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// Print note's last modified date // 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note // 查询该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
@ -163,9 +220,12 @@ public class BackupUtils {
} }
/** /**
* Export note identified by id to a print stream *
* @param noteId ID
* @param ps
*/ */
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
// 查询该笔记的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
@ -176,7 +236,7 @@ public class BackupUtils {
do { do {
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);
@ -185,11 +245,11 @@ public class BackupUtils {
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));
@ -205,7 +265,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// print a line separator between note // 打印笔记之间的分隔符
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -216,9 +276,11 @@ public class BackupUtils {
} }
/** /**
* Note will be exported as text which is user readable *
* @return
*/ */
public int exportToText() { public int exportToText() {
// 检查外部存储是否可用
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
@ -229,7 +291,7 @@ public class BackupUtils {
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,
@ -240,7 +302,7 @@ public class BackupUtils {
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);
@ -257,7 +319,7 @@ public class BackupUtils {
folderCursor.close(); folderCursor.close();
} }
// 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,
@ -270,7 +332,7 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note // 查询该笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID); String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext()); } while (noteCursor.moveToNext());
@ -283,7 +345,8 @@ public class BackupUtils {
} }
/** /**
* 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,
@ -310,7 +373,11 @@ public class BackupUtils {
} }
/** /**
* Generate the text file to store imported data * SD
* @param context
* @param filePathResId ID
* @param fileNameFormatResId ID
* @return null
*/ */
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();
@ -339,6 +406,4 @@ public class BackupUtils {
return null; return null;
} }
} }

@ -34,9 +34,18 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
/**
*
*/
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
/**
*
* @param resolver
* @param ids ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
@ -72,6 +81,13 @@ public class DataUtils {
return false; return false;
} }
/**
*
* @param resolver
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId); values.put(NoteColumns.PARENT_ID, desFolderId);
@ -80,6 +96,13 @@ public class DataUtils {
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
} }
/**
*
* @param resolver
* @param ids ID
* @param folderId ID
* @return truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
if (ids == null) { if (ids == null) {
@ -112,7 +135,9 @@ public class DataUtils {
} }
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} *
* @param resolver
* @return
*/ */
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,
@ -136,6 +161,13 @@ public class DataUtils {
return count; return count;
} }
/**
*
* @param resolver
* @param noteId ID
* @param type
* @return truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null,
@ -153,6 +185,12 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* @param resolver
* @param noteId ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
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);
@ -167,6 +205,12 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* @param resolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
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);
@ -181,6 +225,12 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* @param resolver
* @param name
* @return truefalse
*/
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 +
@ -197,6 +247,12 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* @param resolver
* @param folderId ID
* @return
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -224,6 +280,12 @@ public class DataUtils {
return set; return set;
} }
/**
* ID
* @param resolver
* @param noteId ID
* @return
*/
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 },
@ -243,6 +305,13 @@ public class DataUtils {
return ""; return "";
} }
/**
* ID
* @param resolver
* @param phoneNumber
* @param callDate
* @return ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
@ -264,6 +333,12 @@ public class DataUtils {
return 0; return 0;
} }
/**
* ID
* @param resolver
* @param noteId ID
* @return
*/
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 },
@ -282,6 +357,11 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId);
} }
/**
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) {
snippet = snippet.trim(); snippet = snippet.trim();
@ -292,4 +372,4 @@ public class DataUtils {
} }
return snippet; return snippet;
} }
} }

@ -16,98 +16,146 @@
package net.micode.notes.tool; package net.micode.notes.tool;
/**
* GoogleJSONGoogle
*/
public class GTaskStringUtils { public class GTaskStringUtils {
// Google任务JSON中的动作ID字段
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";
// Google任务JSON中的动作列表字段
public final static String GTASK_JSON_ACTION_LIST = "action_list"; public final static String GTASK_JSON_ACTION_LIST = "action_list";
// Google任务JSON中的动作类型字段
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// Google任务JSON中创建动作的类型值
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// Google任务JSON中获取所有任务动作的类型值
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// Google任务JSON中移动任务动作的类型值
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// Google任务JSON中更新任务动作的类型值
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// Google任务JSON中的创建者ID字段
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// Google任务JSON中的子实体字段
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// Google任务JSON中的客户端版本字段
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// Google任务JSON中的完成状态字段
public final static String GTASK_JSON_COMPLETED = "completed"; public final static String GTASK_JSON_COMPLETED = "completed";
// Google任务JSON中的当前列表ID字段
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// Google任务JSON中的默认列表ID字段
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// Google任务JSON中的删除状态字段
public final static String GTASK_JSON_DELETED = "deleted"; public final static String GTASK_JSON_DELETED = "deleted";
// Google任务JSON中的目标列表字段
public final static String GTASK_JSON_DEST_LIST = "dest_list"; public final static String GTASK_JSON_DEST_LIST = "dest_list";
// Google任务JSON中的目标父级字段
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// Google任务JSON中的目标父级类型字段
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// Google任务JSON中的实体增量字段
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// Google任务JSON中的实体类型字段
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// Google任务JSON中获取已删除任务的字段
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// Google任务JSON中的ID字段
public final static String GTASK_JSON_ID = "id"; public final static String GTASK_JSON_ID = "id";
// Google任务JSON中的索引字段
public final static String GTASK_JSON_INDEX = "index"; public final static String GTASK_JSON_INDEX = "index";
// Google任务JSON中的最后修改时间字段
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// Google任务JSON中的最新同步点字段
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// Google任务JSON中的列表ID字段
public final static String GTASK_JSON_LIST_ID = "list_id"; public final static String GTASK_JSON_LIST_ID = "list_id";
// Google任务JSON中的列表集合字段
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_LISTS = "lists";
// Google任务JSON中的名称字段
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_NAME = "name";
// Google任务JSON中的新ID字段
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_NEW_ID = "new_id";
// Google任务JSON中的备注字段
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_NOTES = "notes";
// Google任务JSON中的父级ID字段
public final static String GTASK_JSON_PARENT_ID = "parent_id"; public final static String GTASK_JSON_PARENT_ID = "parent_id";
// Google任务JSON中的前一个兄弟ID字段
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// Google任务JSON中的结果字段
public final static String GTASK_JSON_RESULTS = "results"; public final static String GTASK_JSON_RESULTS = "results";
// Google任务JSON中的源列表字段
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// Google任务JSON中的任务集合字段
public final static String GTASK_JSON_TASKS = "tasks"; public final static String GTASK_JSON_TASKS = "tasks";
// Google任务JSON中的类型字段
public final static String GTASK_JSON_TYPE = "type"; public final static String GTASK_JSON_TYPE = "type";
// Google任务JSON中组类型的值
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// Google任务JSON中任务类型的值
public final static String GTASK_JSON_TYPE_TASK = "TASK"; public final static String GTASK_JSON_TYPE_TASK = "TASK";
// Google任务JSON中的用户字段
public final static String GTASK_JSON_USER = "user"; public final static String GTASK_JSON_USER = "user";
// MIUI文件夹前缀
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 默认文件夹名称
public final static String FOLDER_DEFAULT = "Default"; public final static String FOLDER_DEFAULT = "Default";
// 通话记录文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note"; public final static String FOLDER_CALL_NOTE = "Call_Note";
// 元数据文件夹名称
public final static String FOLDER_META = "METADATA"; public final static String FOLDER_META = "METADATA";
// 元数据头部的Google任务ID字段
public final static String META_HEAD_GTASK_ID = "meta_gid"; 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_NOTE = "meta_note";
// 元数据头部的数据字段
public final static String META_HEAD_DATA = "meta_data"; public final static String META_HEAD_DATA = "meta_data";
// 元数据备注名称
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}
}

@ -22,24 +22,42 @@ import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.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, R.drawable.edit_yellow,
R.drawable.edit_blue, R.drawable.edit_blue,
@ -48,6 +66,7 @@ public class ResourceParser {
R.drawable.edit_red 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, R.drawable.edit_title_yellow,
R.drawable.edit_title_blue, R.drawable.edit_title_blue,
@ -56,25 +75,47 @@ public class ResourceParser {
R.drawable.edit_title_red R.drawable.edit_title_red
}; };
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id]; return BG_EDIT_RESOURCES[id];
} }
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteTitleBgResource(int id) { public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
/**
* ID
* @param context
* @return 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)) {
// 如果设置了随机选择一个背景ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else { } else {
// 如果未设置返回默认背景ID
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,
@ -83,6 +124,7 @@ public class ResourceParser {
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,
@ -91,6 +133,7 @@ public class ResourceParser {
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,
@ -99,6 +142,7 @@ public class ResourceParser {
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,
@ -107,28 +151,56 @@ public class ResourceParser {
R.drawable.list_red_single R.drawable.list_red_single
}; };
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id]; return BG_FIRST_RESOURCES[id];
} }
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteBgLastRes(int id) { public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id]; return BG_LAST_RESOURCES[id];
} }
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteBgSingleRes(int id) { public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id]; return BG_SINGLE_RESOURCES[id];
} }
/**
* ID
* @param id ID
* @return ID
*/
public static int getNoteBgNormalRes(int id) { public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id]; return BG_NORMAL_RESOURCES[id];
} }
/**
*
* @return ID
*/
public static int getFolderBgRes() { public static int getFolderBgRes() {
return R.drawable.list_folder; 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, R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue, R.drawable.widget_2x_blue,
@ -137,10 +209,16 @@ public class ResourceParser {
R.drawable.widget_2x_red, R.drawable.widget_2x_red,
}; };
/**
* ID2x
* @param id ID
* @return ID
*/
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; 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, R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue, R.drawable.widget_4x_blue,
@ -149,12 +227,21 @@ public class ResourceParser {
R.drawable.widget_4x_red R.drawable.widget_4x_red
}; };
/**
* ID4x
* @param id ID
* @return ID
*/
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; 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,
@ -162,20 +249,30 @@ public class ResourceParser {
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
/**
* ID
* @param id ID
* @return ID
*/
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case, * The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/ */
// 检查ID是否超出资源数组长度如果超出则返回默认字体大小对应的资源ID
if (id >= TEXTAPPEARANCE_RESOURCES.length) { if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE; return BG_DEFAULT_FONT_SIZE;
} }
return TEXTAPPEARANCE_RESOURCES[id]; return TEXTAPPEARANCE_RESOURCES[id];
} }
/**
*
* @return
*/
public static int getResourcesSize() { public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length; return TEXTAPPEARANCE_RESOURCES.length;
} }
} }
} }

Binary file not shown.
Loading…
Cancel
Save