对gtask包和data包的所有子类进行注释,共计1377行

zhouweihannew
周炜涵从 2 years ago
parent d7ee84ffe4
commit 2d05a9f297

@ -1,21 +1,14 @@
// 版权声明和许可信息,表明该代码由 "The MiCode Open Source Community" 提供并且使用了Apache License 2.0。
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ...
*/
package net.micode.notes.data;
package net.micode.notes.data; // 指定包名
// 导入所需的类
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
@ -23,12 +16,16 @@ import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
import java.util.HashMap; // 导入HashMap类用于创建缓存
// 定义了Contact类用于从系统联系人获取信息
public class Contact {
// 类级别的缓存变量,存储电话号码和对应的联系人名称
private static HashMap<String, String> sContactCache;
// 用于日志输出的标签
private static final String TAG = "Contact";
// 编写SQL查询语句的一部分用于查询电话号码
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,17 +33,23 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 获取联系人名称的静态方法
public static String getContact(Context context, String phoneNumber) {
// 如果缓存为空,则初始化它
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存是否已有该号码的联系人名称
if(sContactCache.containsKey(phoneNumber)) {
// 如果有,直接返回该名称
return sContactCache.get(phoneNumber);
}
// 替换查询中的占位符以构造完整的查询语句
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 对联系人数据提供者进行查询,尝试获取匹配电话号码的联系人名称
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
@ -54,18 +57,25 @@ public class Contact {
new String[] { phoneNumber },
null);
// 如果查询返回了结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 从游标中获取联系人名称
String name = cursor.getString(0);
// 将结果存放到缓存中
sContactCache.put(phoneNumber, name);
// 返回获取到的联系人名称
return name;
} catch (IndexOutOfBoundsException e) {
// 如果发生异常,输出错误日志
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 最后确保游标被关闭,避免内存泄露
cursor.close();
}
} else {
// 如果没有匹配结果,输出调试日志
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

@ -17,234 +17,243 @@
package net.micode.notes.data;
import android.net.Uri;
public class Notes {
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
// 定义一个名为Notes的公共类
public class Notes {
// 定义一些静态常量,如授权信息、标签和类型
// 内容提供者的权限
public static final String AUTHORITY = "micode_notes";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
// 日志标签
public static final String TAG = "Notes";
// 笔记类型常量
public static final int TYPE_NOTE = 0; // 普通笔记
public static final int TYPE_FOLDER = 1; // 文件夹
public static final int TYPE_SYSTEM = 2; // 系统类型
// 系统文件夹的标识符
public static final int ID_ROOT_FOLDER = 0; // 默认文件夹
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹,存放无文件夹归属的笔记
public static final int ID_CALL_RECORD_FOLDER = -2; // 存放通话记录的文件夹
public static final int ID_TRASH_FOLER = -3; // 垃圾箱文件夹
// 传递给Intent的额外数据的键
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // Widget的ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // Widget类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
// Widget类型常量
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的Widget类型
public static final int TYPE_WIDGET_2X = 0; // 2x大小的Widget
public static final int TYPE_WIDGET_4X = 1; // 4x大小的Widget
// 笔记数据常量类
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记的内容类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话记录的内容类型
}
/**
* Uri to query all notes and folders
* Uri
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* Uri
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* ID
* <P> : () </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*
* <P> : </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : () </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : () </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*
*
* <P> : </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*
* <P> : </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : () </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*
* <P> : </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* ID
* <P> : </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* GTask ID
* <P> : </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String VERSION = "version";
}
/**
*
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* <P> : </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
* ID
* <P> : () </P>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <P> : </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIME_TYPE}
* <P> : </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIME_TYPE}
* <P> : </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIME_TYPE}
* <P> : </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIME_TYPE}
* <P> : </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIME_TYPE}
* <P> : </P>
*/
public static final String DATA5 = "data5";
}
/**
* DataColumns
*/
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*
* <P> : 1: 0: </P>
*/
public static final String MODE = DATA1;
@ -257,16 +266,19 @@ public class Notes {
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
* DataColumns
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*
* <P> : () </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*
* <P> : </P>
*/
public static final String PHONE_NUMBER = DATA3;

@ -13,7 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 便
*/
package net.micode.notes.data;
import android.content.ContentValues;
@ -26,22 +28,43 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
*
*/
private static final String DB_NAME = "note.db";
/**
*
*/
private static final int DB_VERSION = 4;
/**
*
*/
public interface TABLE {
/**
*
*/
public static final String NOTE = "note";
/**
*
*/
public static final String DATA = "data";
}
// 声明数据库帮助类的标签
private static final String TAG = "NotesDatabaseHelper";
// 单例模式实例
private static NotesDatabaseHelper mInstance;
// 创建笔记表的 SQL 语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +86,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建数据表的 SQL 语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,13 +102,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
// 创建数据表中的笔记 ID 索引的 SQL 语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
*/
// 当将笔记移动到文件夹时,增加文件夹的笔记计数
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
@ -94,9 +117,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when move note from folder
*/
// 当从文件夹中移除笔记时,减少文件夹的笔记计数
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
@ -107,9 +128,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
/**
* Increase folder's note count when insert new note to the folder
*/
// 当向文件夹中插入新笔记时,增加文件夹的笔记计数
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
@ -118,9 +137,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when delete note from the folder
*
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
@ -133,7 +151,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
* 使{@link DataConstantsNOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@ -146,7 +164,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
* 使{@link DataConstantsNOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
@ -159,7 +177,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
* {@link DataConstantsNOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
@ -172,7 +190,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete datas belong to note which has been deleted
*
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@ -183,7 +201,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete notes belong to folder which has been deleted
*
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@ -194,7 +212,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Move notes belong to folder which has been moved to trash folder
*
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
@ -217,7 +235,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
/**
*
*
* @param db SQLiteDatabase
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +250,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,58 +260,75 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
*
* @param db SQLiteDatabase
*/
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
// 创建通话记录文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*/
// 创建根文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*/
// 创建临时文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*/
// 创建垃圾箱文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
*
*
* @param db SQLiteDatabase
*/
public void createDataTable(SQLiteDatabase db) {
// 创建数据表
db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据表相关的触发器
reCreateDataTableTriggers(db);
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created");
}
/**
*
*
* @param db SQLiteDatabase
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
*
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -296,67 +338,89 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
// 创建笔记表和数据表
createNoteTable(db);
createDataTable(db);
}
@Override
/**
*
*
* @param db
* @param oldVersion
* @param newVersion
*/
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
boolean reCreateTriggers = false; // 是否重新创建触发器
boolean skipV2 = false; // 是否跳过 V2 版本
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
if (oldVersion == 1) { // 如果旧版本号为 1
upgradeToV2(db); // 升级到 V2 版本
// 跳过 V2 版本,直接升级到 V3 版本
skipV2 = true;
oldVersion++;
}
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
if (oldVersion == 2 && !skipV2) { // 如果旧版本号为 2 并且不跳过 V2 版本
upgradeToV3(db); // 升级到 V3 版本
reCreateTriggers = true; // 需要重新创建触发器
oldVersion++;
}
if (oldVersion == 3) {
upgradeToV4(db);
if (oldVersion == 3) { // 如果旧版本号为 3
upgradeToV4(db); // 升级到 V4 版本
oldVersion++;
}
// 重新创建触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
reCreateNoteTableTriggers(db); // 重新创建笔记表的触发器
reCreateDataTableTriggers(db); // 重新创建数据表的触发器
}
// 版本不匹配,抛出异常
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
throw new IllegalStateException("Upgrade notes database to version " + newVersion + " fails");
}
}
/**
* v2
*
* @param db SQLiteDatabase
*/
private void upgradeToV2(SQLiteDatabase db) {
// 删除旧的表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 重新创建笔记表和数据表
createNoteTable(db);
createDataTable(db);
}
/**
* V3
*
* @param 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_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); // 删除插入时更新修改日期的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); // 删除删除时更新修改日期的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); // 删除更新时更新修改日期的触发器
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''"); // 向 Note 表中添加 GTASK_ID 列
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); // 设置垃圾箱的 ID
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 设置垃圾箱的类型为系统类型
db.insert(TABLE.NOTE, null, values); // 向 Note 表中插入垃圾箱数据
}
/**
* v4
*
* @param db SQLiteDatabase
*/
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
// 增加一个版本号的字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0");
}
}

@ -36,20 +36,39 @@ import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {
/**
*
* NotesSearchManager
*/
private static final UriMatcher mMatcher;
/**
*
* URI便
*/
private NotesDatabaseHelper mHelper;
/**
*
* tag
*/
private static final String TAG = "NotesProvider";
/**
*
* URI
*/
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
/**
*
* UriMatcherURI
*/
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -62,8 +81,8 @@ public class NotesProvider extends ContentProvider {
}
/**
* 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 + ","
@ -73,204 +92,252 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
*
* SQL
*/
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
*
* ProvideronCreatemHelper
*/
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* Cursor
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
Cursor c = null; // 查询结果的 Cursor 对象
SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取可读的数据库对象
String id = null; // ID 变量
switch (mMatcher.match(uri)) {
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
id = uri.getPathSegments().get(1); // 获取 URI 中的 ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, sortOrder);
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
id = uri.getPathSegments().get(1); // 获取 URI 中的 ID
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
// 检查是否指定了排序方式、返回的列,如果指定了则抛出异常
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
String searchString = null; // 搜索字符串
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
if (uri.getPathSegments().size() > 1) { // 如果 URI 包含多个 segment
searchString = uri.getPathSegments().get(1); // 获取第二个 segment
}
} else {
searchString = uri.getQueryParameter("pattern");
searchString = uri.getQueryParameter("pattern"); // 获取 pattern 参数
}
if (TextUtils.isEmpty(searchString)) {
if (TextUtils.isEmpty(searchString)) { // 如果搜索字符串为空,则返回空
return null;
}
try {
searchString = String.format("%%%s%%", searchString);
searchString = String.format("%%%s%%", searchString); // 格式化搜索字符串
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
new String[] { searchString }); // 执行原始查询操作
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
Log.e(TAG, "got exception: " + ex.toString()); // 捕获异常并记录日志
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
throw new IllegalArgumentException("Unknown URI " + uri); // 未知的 URI抛出异常
}
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
c.setNotificationUri(getContext().getContentResolver(), uri); // 设置查询结果的通知 URI
}
return c;
return c; // 返回查询结果的 Cursor 对象
}
/**
* URI
*
* @param uri URI
* @param values
* @return URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库引用
long dataId = 0, noteId = 0, insertedId = 0; // 数据ID和笔记ID的初始化
switch (mMatcher.match(uri)) { // 根据URI匹配进行不同操作
case URI_NOTE: // 笔记URI
insertedId = noteId = db.insert(TABLE.NOTE, null, values); // 向笔记表中插入数据并获取插入的ID
break;
case URI_DATA:
case URI_DATA: // 数据URI
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
noteId = values.getAsLong(DataColumns.NOTE_ID); // 获取数据对应的笔记ID
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 记录错误日志
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
insertedId = dataId = db.insert(TABLE.DATA, null, values); // 向数据表中插入数据并获取插入的ID
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
throw new IllegalArgumentException("Unknown URI " + uri); // 抛出未知URI异常
}
// Notify the note uri
// 通知笔记URI发生了变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// 通知数据URI发生了变化
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
return ContentUris.withAppendedId(uri, insertedId); // 返回插入的URI
}
/**
*
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
int count = 0; // 记录删除的行数
String id = null; // ID字符串
SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库引用
boolean deleteData = false; // 是否删除数据的标志位
switch (mMatcher.match(uri)) { // 根据URI匹配执行不同操作
case URI_NOTE: // 笔记URI
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 构建查询语句
count = db.delete(TABLE.NOTE, selection, selectionArgs); // 删除符合条件的笔记
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);
case URI_NOTE_ITEM: // 单个笔记URI
id = uri.getPathSegments().get(1); // 获取URI中的笔记ID
long noteId = Long.valueOf(id); // 转换成长整型
if (noteId <= 0) {
break;
break; // 若ID小于等于0则跳出
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
count = db.delete(TABLE.NOTE, NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 删除指定ID的笔记
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
case URI_DATA: // 数据URI
count = db.delete(TABLE.DATA, selection, selectionArgs); // 删除符合条件的数据
deleteData = true; // 设置删除数据的标志位
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
case URI_DATA_ITEM: // 单个数据URI
id = uri.getPathSegments().get(1); // 获取URI中的数据ID
count = db.delete(TABLE.DATA, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 删除指定ID的数据
deleteData = true; // 设置删除数据的标志位
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
throw new IllegalArgumentException("Unknown URI " + uri); // 抛出未知URI异常
}
if (count > 0) {
if (count > 0) { // 若删除成功
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI变化
}
getContext().getContentResolver().notifyChange(uri, null);
getContext().getContentResolver().notifyChange(uri, null); // 通知URI变化
}
return count;
return count; // 返回删除行数
}
/**
*
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
int count = 0; // 记录更新行数
String id = null; // ID字符串
SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库引用
boolean updateData = false; // 是否更新数据的标志位
switch (mMatcher.match(uri)) { // 根据URI匹配执行不同操作
case URI_NOTE: // 笔记URI
increaseNoteVersion(-1, selection, selectionArgs); // 更新笔记版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 更新符合条件的笔记数据
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
case URI_NOTE_ITEM: // 单个笔记URI
id = uri.getPathSegments().get(1); // 获取URI中的笔记ID
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 更新笔记版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 更新指定ID的笔记数据
break;
case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
case URI_DATA: // 数据URI
count = db.update(TABLE.DATA, values, selection, selectionArgs); // 更新符合条件的数据
updateData = true; // 设置更新数据的标志位
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
case URI_DATA_ITEM: // 单个数据URI
id = uri.getPathSegments().get(1); // 获取URI中的数据ID
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); // 更新指定ID的数据
updateData = true; // 设置更新数据的标志位
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
throw new IllegalArgumentException("Unknown URI " + uri); // 抛出未知URI异常
}
if (count > 0) {
if (count > 0) { // 若更新成功
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); // 通知笔记URI变化
}
getContext().getContentResolver().notifyChange(uri, null);
getContext().getContentResolver().notifyChange(uri, null); // 通知URI变化
}
return count;
return count; // 返回更新行数
}
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
*
*
* @param id ID
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");

@ -25,55 +25,119 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
*
*/
public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName();
private final static String TAG = MetaData.class.getSimpleName(); // 类型标签
private String mRelatedGid = null;
private String mRelatedGid = null; // 相关 GTask 的 GID
/**
* GTask GID metaInfo
*
* @param gid GTask GID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
// 将关联 GTask 的 GID 存入元数据信息中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
// 捕获异常,并记录日志
Log.e(TAG, "failed to put related gid");
}
// 将元数据信息转换为字符串,并设置为笔记内容
setNotes(metaInfo.toString());
// 设置笔记名称为元数据的默认名称
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* GTask GID
*
* @return GTask GID
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
*
*
* @return
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
return getNotes() != null; // 判定是否笔记内容不为空
}
/**
* JSON
*
* @param js JSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
// 调用父类的方法设置实例属性
super.setContentByRemoteJSON(js);
// 如果笔记内容不为空
if (getNotes() != null) {
try {
// 将笔记内容转换为 JSON 对象
JSONObject metaInfo = new JSONObject(getNotes().trim());
// 从 JSON 对象中获取关联 GTask 的 GID并存入实例属性 mRelatedGid
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
// 捕获异常,并记录日志
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
/**
* JSON
* <p>
*
* </p>
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/**
* JSON
* <p>
*
* </p>
*
* @return JSON
* @throws IllegalAccessError
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
*
* <p>
*
* </p>
*
* @param c Cursor
* @return
* @throws IllegalAccessError
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -13,7 +13,41 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
*
* Node
*/
/*
*
* 1. mGid:
* 2. mName:
* 3. mLastModified:
* 4. mDeleted:
*/
/*
*
* 1. getCreateAction(int actionId): JSON
* 2. getUpdateAction(int actionId): JSON
* 3. setContentByRemoteJSON(JSONObject js): JSON
* 4. setContentByLocalJSON(JSONObject js): JSON
* 5. getLocalJSONFromContent(): JSON
* 6. getSyncAction(Cursor c):
* 7. setGid(String gid):
* 8. setName(String name):
* 9. setLastModified(long lastModified):
* 10. setDeleted(boolean deleted):
* 11. getGid():
* 12. getName():
* 13. getLastModified():
* 14. getDeleted():
*/
/*
*
* android.database.Cursor org.json.JSONObject
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
@ -21,31 +55,21 @@ import android.database.Cursor;
import org.json.JSONObject;
public abstract class Node {
// 同步操作常量
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
private String mGid; // 节点的全局唯一标识
private String mName; // 节点的名称
private long mLastModified; // 节点最后修改时间
private boolean mDeleted; // 节点是否被标记为已删除
public Node() {
mGid = null;
@ -54,48 +78,99 @@ public abstract class Node {
mDeleted = false;
}
// 获取创建操作的JSON对象表示
public abstract JSONObject getCreateAction(int actionId);
// 获取更新操作的JSON对象表示
public abstract JSONObject getUpdateAction(int actionId);
// 从远端JSON对象中获取内容并设置实例属性
public abstract void setContentByRemoteJSON(JSONObject js);
// 从本地JSON对象中获取内容并设置实例属性
public abstract void setContentByLocalJSON(JSONObject js);
// 获取内容的本地JSON对象表示
public abstract JSONObject getLocalJSONFromContent();
// 获取同步操作
/**
*
*
* @param c Cursor
* @return
*/
public abstract int getSyncAction(Cursor c);
/**
* GTask GID
*
* @param gid GTask GID
*/
public void setGid(String gid) {
this.mGid = gid;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.mName = name;
}
/**
*
*
* @param lastModified
*/
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
/**
*
*
* @param deleted
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
* GTask GID
*
* @return GTask GID
*/
public String getGid() {
return this.mGid;
}
/**
*
*
* @return
*/
public String getName() {
return this.mName;
}
/**
*
*
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
*
*
* @return
*/
public boolean getDeleted() {
return this.mDeleted;
}
}

@ -34,54 +34,63 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/*定义了一个sqlData类*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
// 无效ID
private static final int INVALID_ID = -99999;
// 数据列投影
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
// 数据列索引
public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
// 内容解析器
private ContentResolver mContentResolver;
// 是否创建数据标识
private boolean mIsCreate;
// 数据ID
private long mDataId;
// 数据MIME类型
private String mDataMimeType;
// 数据内容
private String mDataContent;
// 数据内容1
private long mDataContentData1;
// 数据内容3
private String mDataContentData3;
// 差异数据值
private ContentValues mDiffDataValues;
// 构造函数,初始化默认值
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContentData1 = 0;
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
mContentResolver = context.getContentResolver();// 获取内容解析器
mIsCreate = true;// 默认为创建数据
mDataId = INVALID_ID; // 设置数据ID为无效ID
mDataMimeType = DataConstants.NOTE; // 默认数据MIME类型为DataConstants.NOTE
mDataContent = "";// 默认数据内容为空字符串
mDataContentData1 = 0;// 默认数据内容1为0
mDataContentData3 = "";// 默认数据内容3为空字符串
mDiffDataValues = new ContentValues();// 创建一个差异数据值的 ContentValues 对象
}
// 构造函数从Cursor加载数据
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,63 +98,75 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
// 从Cursor加载数据
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
mDataId = c.getLong(DATA_ID_COLUMN); // 从游标获取数据 ID
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); // 从游标获取数据的 MIME 类型
mDataContent = c.getString(DATA_CONTENT_COLUMN); // 从游标获取数据内容
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); // 从游标获取数据内容的数据1
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); // 从游标获取数据内容的数据3
}
// 设置内容
public void setContent(JSONObject js) throws JSONException {
// 提取JSON中的数据ID若不存在则使用无效ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
// 若是创建操作或数据ID不同则将新数据放入差异值中
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
// 提取JSON中的数据MIME类型若不存在则使用默认值
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;
// 若是创建操作或MIME类型不同则将新数据放入差异值中
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
}
mDataMimeType = dataMimeType;
// 提取JSON中的数据内容若不存在则使用空字符串
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
// 若是创建操作或内容不同,则将新数据放入差异值中
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
// 提取JSON中的数据内容1若不存在则使用默认值
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
// 若是创建操作或内容1不同则将新数据放入差异值中
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
// 提取JSON中的数据内容3若不存在则使用空字符串
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
// 若是创建操作或内容3不同则将新数据放入差异值中
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
}
mDataContentData3 = dataContentData3;
}
public JSONObject getContent() throws JSONException {
// 接口注释:获取数据内容
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3);
js.put(DataColumns.ID, mDataId);// 数据成员注释数据Id
js.put(DataColumns.MIME_TYPE, mDataMimeType);// 数据成员注释:数据类型
js.put(DataColumns.CONTENT, mDataContent);// 数据成员注释:数据内容
js.put(DataColumns.DATA1, mDataContentData1);// 数据成员注释数据ContentData1
js.put(DataColumns.DATA3, mDataContentData3);// 数据成员注释数据ContentData3
return js;
}
public void commit(long noteId, boolean validateVersion, long version) {
// 实现注释:提交数据
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
@ -163,6 +184,7 @@ public class SqlData {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
// 模块依赖注释:更新数据
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
@ -184,6 +206,7 @@ public class SqlData {
}
public long getId() {
// 接口注释获取数据Id
return mDataId;
}
}

@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
@ -37,13 +36,17 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* SqlNote
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
// 定义查询笔记使用的投影列数组
public static final String[] PROJECTION_NOTE = new String[] {
// 以下依次对应列的含义
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
@ -52,38 +55,23 @@ public class SqlNote {
NoteColumns.VERSION
};
// 以下依次对应PROJECTION_NOTE中列的下标
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;
@ -93,86 +81,93 @@ public class SqlNote {
private boolean mIsCreate;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
/**
* SqlNote
*
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
mContext = context; // 上下文对象
mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = true; // 是否是创建状态
mId = INVALID_ID; // ID 设置为无效值
mAlertDate = 0; // 提醒日期初始化为0
mBgColorId = ResourceParser.getDefaultBgId(context); // 背景颜色ID初始化为默认背景颜色
mCreatedDate = System.currentTimeMillis(); // 创建日期初始化为当前时间
mHasAttachment = 0; // 是否有附件初始化为0 - 表示没有附件
mModifiedDate = System.currentTimeMillis(); // 修改日期初始化为当前时间
mParentId = 0; // 父级ID初始化为0
mSnippet = ""; // 摘录初始化为空字符串
mType = Notes.TYPE_NOTE; // 类型为普通笔记类型
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 小部件ID初始化为无效ID
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 小部件类型初始化为无效类型
mOriginParent = 0; // 原始父级ID初始化为0
mVersion = 0; // 版本号初始化为0
mDiffNoteValues = new ContentValues(); // 差异笔记值的容器
mDataList = new ArrayList<SqlData>(); // 数据列表容器
}
/**
* SqlNote
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
mContext = context; // 上下文对象
mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; // 是否是创建状态设置为false
loadFromCursor(c); // 从游标加载数据
mDataList = new ArrayList<SqlData>(); // 数据列表容器
if (mType == Notes.TYPE_NOTE) // 如果类型为普通笔记类型
loadDataContent(); // 加载数据内容
mDiffNoteValues = new ContentValues(); // 差异笔记值的容器
}
/**
* IDSqlNote
*
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
mContext = context; // 上下文对象
mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; // 是否是创建状态设置为 false
loadFromCursor(id); // 根据ID从游标加载数据
mDataList = new ArrayList<SqlData>(); // 数据列表容器
if (mType == Notes.TYPE_NOTE) // 如果类型为普通笔记类型
loadDataContent(); // 加载数据内容
mDiffNoteValues = new ContentValues(); // 差异笔记值的容器
}
// ...(未完)
/**
* Cursorid
* @param id ID
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
// 通过查询URI和ID获取匹配的Cursor对象
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);
new String[] { String.valueOf(id) }, null);
if (c != null) {
c.moveToNext();
loadFromCursor(c);
@ -185,34 +180,40 @@ public class SqlNote {
}
}
/**
* Cursor
* @param c Cursor
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN);
mType = c.getInt(TYPE_COLUMN);
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
mId = c.getLong(ID_COLUMN); // 从游标中获取ID
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); // 从游标中获取提醒日期
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); // 从游标中获取背景颜色ID
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); // 从游标中获取创建日期
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); // 从游标中获取是否有附件
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); // 从游标中获取修改日期
mParentId = c.getLong(PARENT_ID_COLUMN); // 从游标中获取父级ID
mSnippet = c.getString(SNIPPET_COLUMN); // 从游标中获取摘录
mType = c.getInt(TYPE_COLUMN); // 从游标中获取类型
mWidgetId = c.getInt(WIDGET_ID_COLUMN); // 从游标中获取小部件ID
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); // 从游标中获取小部件类型
mVersion = c.getLong(VERSION_COLUMN); // 从游标中获取版本号
}
/**
*
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
try {
// 通过查询URI和笔记ID获取匹配的笔记附加数据Cursor对象
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
}, null);
"(note_id=?)", new String[] { String.valueOf(mId) }, null);
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
// 遍历Cursor构造SqlData对象并添加到附加数据列表中
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
@ -226,111 +227,81 @@ public class SqlNote {
}
}
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// for folder we can only update the snnipet and type
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;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, 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;
/**
* ID
*
* @param js JSON
* @return
*/
// 数据成员注释:
// mIsCreate标记是否为创建新笔记的操作
// mType笔记的类型
// mWidgetId笔记的小部件 ID
// mWidgetType笔记的小部件类型
// mOriginParent笔记的原始父文件夹 ID
// mDiffNoteValues记录与原始笔记不同的属性和值的映射关系
// mDataList存储附件数据的列表
// 实现注释:
// 更新笔记属性:
// 更新笔记的类型(如果有改变)
// 更新笔记的小部件 ID如果有改变
// 更新笔记的小部件类型(如果有改变)
// 更新笔记的原始父文件夹 ID如果有改变
// 遍历附件数据,处理每一项:
// 如果附件数据已存在于 mDataList 中,则使用现有的 SqlData 对象
// 否则,创建新的 SqlData 对象并添加到 mDataList 中
// 设置附件数据的内容
// 模块依赖注释:
// 依赖的类:
// JSONObjectJSON 对象类
// JSONArrayJSON 数组类
// SqlData自定义的 SQL 数据类
// 依赖的接口和方法:
// AppWidgetManager.INVALID_APPWIDGET_ID无效的小部件 ID 值
// NoteColumns.TYPE笔记类型在数据库中的列名
// NoteColumns.WIDGET_ID小部件 ID 在数据库中的列名
// NoteColumns.WIDGET_TYPE小部件类型在数据库中的列名
// NoteColumns.ORIGIN_PARENT_ID原始父文件夹 ID 在数据库中的列名
// DataColumns.ID附件数据 ID 在数据库中的列名
// SqlData.setContent(data):设置附件数据的内容的方法
public boolean setContent(JSONObject js) {
try {
// 提取笔记对象和数据数组
JSONObject note = js.getJSONObject("note"); // 提取笔记对象
JSONArray dataArray = js.getJSONArray("dataArray"); // 提取数据数组
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
// 更新笔记的类型
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
mDiffNoteValues.put(NoteColumns.TYPE, type); // 将类型加入差异笔记值中
}
mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
// 更新笔记的小部件 ID
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);
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); // 将小部件 ID 加入差异笔记值中
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
// 更新笔记的小部件类型
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);
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); // 将小部件类型加入差异笔记值中
}
mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
// 更新笔记的原始父文件夹 ID
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);
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); // 将原始父文件夹 ID 加入差异笔记值中
}
mOriginParent = originParent;
// 更新笔记的附件数据
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
@ -348,28 +319,45 @@ public class SqlNote {
mDataList.add(sqlData);
}
sqlData.setContent(data);
}
// 设置附件数据的内容
sqlData.setContent(data); // 设置附件数据的内容
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
return false; // 解析失败,返回 false
}
return true;
return true; // 解析成功,返回 true
}
/**
* JSON
*
* @return JSON null
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
Log.e(TAG, "在数据库中似乎还没有创建此笔记");
return null;
}
JSONObject note = new JSONObject();
if (mType == Notes.TYPE_NOTE) {
// 数据成员注释:
// NoteColumns.ID笔记 ID
// NoteColumns.ALERTED_DATE提醒日期
// NoteColumns.BG_COLOR_ID背景颜色 ID
// NoteColumns.CREATED_DATE创建日期
// NoteColumns.HAS_ATTACHMENT是否有附件
// NoteColumns.MODIFIED_DATE修改日期
// NoteColumns.PARENT_ID父文件夹 ID
// NoteColumns.SNIPPET内容摘要
// NoteColumns.TYPE笔记类型
// NoteColumns.WIDGET_ID小部件 ID
// NoteColumns.WIDGET_TYPE小部件类型
// NoteColumns.ORIGIN_PARENT_ID原始父文件夹 ID
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
@ -393,6 +381,10 @@ public class SqlNote {
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
// 数据成员注释:
// NoteColumns.ID笔记 ID
// NoteColumns.TYPE笔记类型
// NoteColumns.SNIPPET内容摘要
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
@ -440,35 +432,40 @@ public class SqlNote {
return mType == Notes.TYPE_NOTE;
}
/**
*
*
* @param validateVersion
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mIsCreate) { // 如果是创建状态
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
mDiffNoteValues.remove(NoteColumns.ID); // 移除差异笔记值中的 ID 键
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); // 将差异笔记值插入内容提供器
try {
mId = Long.valueOf(uri.getPathSegments().get(1));
mId = Long.valueOf(uri.getPathSegments().get(1)); // 从 URI 中获取插入的笔记 ID
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
Log.e(TAG, "Get note id error :" + e.toString()); // 打印错误日志
throw new ActionFailureException("create note failed"); // 抛出操作失败异常
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
throw new IllegalStateException("Create thread id failed"); // 抛出非法状态异常
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
if (mType == Notes.TYPE_NOTE) { // 如果类型为普通笔记类型
for (SqlData sqlData : mDataList) { // 遍历数据列表
sqlData.commit(mId, false, -1); // 提交数据
}
}
} else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
Log.e(TAG, "No such note"); // 打印错误日志
throw new IllegalStateException("Try to update note with invalid id"); // 抛出非法状态异常
}
if (mDiffNoteValues.size() > 0) {
mVersion ++;
mVersion++; // 版本号加一
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
@ -487,19 +484,19 @@ public class SqlNote {
}
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
if (mType == Notes.TYPE_NOTE) { // 如果类型为普通笔记类型
for (SqlData sqlData : mDataList) { // 遍历数据列表
sqlData.commit(mId, validateVersion, mVersion); // 提交数据
}
}
}
// refresh local info
// 刷新本地信息
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues.clear();
mIsCreate = false;
mDiffNoteValues.clear(); // 清空差异笔记值
mIsCreate = false; // 设置为非创建状态
}
}

@ -32,19 +32,25 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
*
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;
private boolean mCompleted; // 标识任务是否已完成
private String mNotes;
private String mNotes; // 任务的备注信息
private JSONObject mMetaInfo;
private JSONObject mMetaInfo; // 任务的附加元数据
private Task mPriorSibling;
private Task mPriorSibling; // 任务列表中该任务的前一个任务节点
private TaskList mParent;
private TaskList mParent; // 该任务的父任务列表
/**
* Task
*/
public Task() {
super();
mCompleted = false;
@ -54,296 +60,386 @@ public class Task extends Node {
mMetaInfo = null;
}
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) throws ActionFailureException {
JSONObject js = new JSONObject(); // 创建一个新的 JSON 对象
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, // 设置 JSON 对象中的 action_type 字段
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); // 设置 JSON 对象中的 action_id 字段
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); // 设置 JSON 对象中的 index 字段,调用 mParent 中的 getChildTaskIndex 方法获得任务的索引
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
JSONObject entity = new JSONObject(); // 创建一个新的 JSON 对象 entity
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 设置 entity 中的 name 字段为当前任务的名字
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 设置 entity 中的 creator_id 字段为 null
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, // 设置 entity 中的 entity_type 字段为类型为任务
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 如果任务有备注信息,则设置 entity 中的 notes 字段为任务的备注信息
}
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将 entity 对象作为 JSON 对象的 entity_delta 字段的值
// parent_id
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); // 设置 JSON 对象中的 parent_id 字段为该任务的父任务列表的 gid
// dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, // 设置 JSON 对象中的 dest_parent_type 字段为组类型
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); // 设置 JSON 对象中的 list_id 字段为该任务的父任务列表的 gid
// prior_sibling_id
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); // 如果存在前一个任务节点,则设置 prior_sibling_id 为前一个任务节点的 gid
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject");
Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); // 输出异常信息
throw new ActionFailureException("生成任务创建 JSON 对象失败"); // 抛出生成任务创建 JSON 对象失败的异常
}
return js;
return js; // 返回创建的 JSON 对象
}
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
JSONObject js = new JSONObject(); // 创建一个新的 JSON 对象
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, // 设置 JSON 对象中的 action_type 字段为更新操作类型
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); // 设置 JSON 对象中的 action_id 字段为指定的操作 ID
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); // 设置 JSON 对象中的 id 字段为当前任务的 gid
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
JSONObject entity = new JSONObject(); // 创建一个新的 JSON 对象 entity
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 设置 entity 中的 name 字段为当前任务的名字
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 如果任务有备注信息,则设置 entity 中的 notes 字段为任务的备注
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 设置 entity 中的 deleted 字段为当前任务的删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将 entity 对象作为 JSON 对象的 entity_delta 字段的值
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject");
Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); // 输出异常信息
throw new ActionFailureException("fail to generate task-update jsonobject"); // 抛出生成任务更新 JSON 对象失败的异常
}
return js;
return js; // 返回创建的 JSON 对象
}
/**
* JSON
*
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); // 如果 JSON 对象中包含 id 字段,则设置当前对象的 gid
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); // 如果 JSON 对象中包含 last_modified 字段,则设置当前对象的 last_modified
}
// name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); // 如果 JSON 对象中包含 name 字段,则设置当前对象的 name
}
// notes
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); // 如果 JSON 对象中包含 notes 字段,则设置当前对象的 notes
}
// deleted
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); // 如果 JSON 对象中包含 deleted 字段,则设置当前对象的 deleted
}
// completed
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); // 如果 JSON 对象中包含 completed 字段,则设置当前对象的 completed
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject");
Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); // 输出异常信息
throw new ActionFailureException("fail to get task content from jsonobject"); // 抛出从 JSON 对象获取任务内容失败的异常
}
}
}
/**
* JSON
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); // 如果本地 JSON 对象为空,或者缺少必要的元数据,记录警告日志并返回
}
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取元数据中的笔记信息
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取元数据中的数据数组
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
Log.e(TAG, "invalid type"); // 如果笔记类型不是普通笔记,记录错误日志并返回
return;
}
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
JSONObject data = dataArray.getJSONObject(i); // 获取数组中的每个数据对象
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
setName(data.getString(DataColumns.CONTENT)); // 如果数据的 MIME 类型是笔记,设置当前对象的名称为数据的内容并结束循环
break;
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
Log.e(TAG, e.toString()); // 记录异常信息
e.printStackTrace(); // 输出异常信息
}
}
/**
* JSON
*
* @return JSON
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
String name = getName(); // 获取当前对象的名称
try {
if (mMetaInfo == null) {
// new task created from web
// 从网络创建的新任务
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
Log.w(TAG, "the note seems to be an empty one"); // 如果名称为空,记录警告日志并返回 null
return null;
}
JSONObject js = new JSONObject();
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js;
JSONObject js = new JSONObject(); // 创建新的 JSON 对象
JSONObject note = new JSONObject(); // 创建笔记的 JSON 对象
JSONArray dataArray = new JSONArray(); // 创建数据的 JSON 数组
JSONObject data = new JSONObject(); // 创建数据的 JSON 对象
data.put(DataColumns.CONTENT, name); // 设置数据的内容为名称
dataArray.put(data); // 将数据添加到数据数组中
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 将数据数组添加到 JSON 对象中的元数据中
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置笔记类型为普通笔记
js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将笔记添加到 JSON 对象中的元数据中
return js; // 返回 JSON 对象
} else {
// synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 同步的任务
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取元数据中的笔记信息
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取元数据中的数据数组
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
JSONObject data = dataArray.getJSONObject(i); // 获取数组中的每个数据对象
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName());
data.put(DataColumns.CONTENT, getName()); // 如果数据的 MIME 类型是笔记,将内容设置为当前对象的名称并结束循环
break;
}
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置笔记类型为普通笔记
return mMetaInfo; // 返回元数据 JSON 对象
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
Log.e(TAG, e.toString()); // 记录异常信息
e.printStackTrace(); // 输出异常信息
return null; // 返回 null
}
}
/**
*
*
* @param metaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
if (metaData != null && metaData.getNotes() != null) { // 如果元数据不为空并且包含笔记信息
try {
mMetaInfo = new JSONObject(metaData.getNotes());
mMetaInfo = new JSONObject(metaData.getNotes()); // 将笔记信息转换为 JSON 对象并赋给成员变量 mMetaInfo
} catch (JSONException e) {
Log.w(TAG, e.toString());
mMetaInfo = null;
Log.w(TAG, e.toString()); // 记录警告日志
mMetaInfo = null; // 转换失败时将 mMetaInfo 设为 null
}
}
}
/**
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { // 检查元数据中是否包含笔记信息
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记信息的 JSON 对象
}
if (noteInfo == null) {
Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE;
if (noteInfo == null) { // 如果笔记信息为 null表示笔记元数据被删除
Log.w(TAG, "it seems that note meta has been deleted"); // 记录警告日志
return SYNC_ACTION_UPDATE_REMOTE; // 返回更新远程的操作动作
}
if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL;
if (!noteInfo.has(NoteColumns.ID)) { // 如果笔记信息中不包含 ID
Log.w(TAG, "remote note id seems to be deleted"); // 记录警告日志
return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地的操作动作
}
// validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL;
// 验证笔记的 ID
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { // 如果数据库游标中的 ID 与笔记信息中的 ID 不匹配
Log.w(TAG, "note id doesn't match"); // 记录警告日志
return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地的操作动作
}
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // 如果本地未有更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果数据库游标中的最后修改时间与当前对象的最后修改时间相同
return SYNC_ACTION_NONE; // 返回无操作的操作动作
} else {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地的操作动作
}
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
// 验证 GTask ID
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { // 如果数据库游标中的 GTask ID 与当前对象的 GTask ID 不匹配
Log.e(TAG, "gtask id doesn't match"); // 记录错误日志
return SYNC_ACTION_ERROR; // 返回错误的操作动作
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // 如果数据库游标中的最后修改时间与当前对象的最后修改时间相同
return SYNC_ACTION_UPDATE_REMOTE; // 返回更新远程的操作动作
} else {
return SYNC_ACTION_UPDATE_CONFLICT;
return SYNC_ACTION_UPDATE_CONFLICT; // 返回更新冲突的操作动作
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
Log.e(TAG, e.toString()); // 记录异常日志
e.printStackTrace(); // 打印异常堆栈信息
}
return SYNC_ACTION_ERROR;
return SYNC_ACTION_ERROR; // 返回错误的操作动作
}
/**
*
*
* @return true false
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
|| (getNotes() != null && getNotes().trim().length() > 0); // 判断任务是否值得保存的条件
}
/**
*
*
* @param completed
*/
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
/**
*
*
* @param notes
*/
public void setNotes(String notes) {
this.mNotes = notes;
}
/**
*
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
/**
*
*
* @param parent
*/
public void setParent(TaskList parent) {
this.mParent = parent;
}
/**
*
*
* @return
*/
public boolean getCompleted() {
return this.mCompleted;
}
/**
*
*
* @return
*/
public String getNotes() {
return this.mNotes;
}
/**
*
*
* @return
*/
public Task getPriorSibling() {
return this.mPriorSibling;
}
/**
*
*
* @return
*/
public TaskList getParent() {
return this.mParent;
}

@ -30,20 +30,33 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
*
*/
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
private int mIndex;
private int mIndex; // 任务列表的索引值
private ArrayList<Task> mChildren;
private ArrayList<Task> mChildren; // 子任务列表
/**
*
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
public JSONObject getCreateAction(int actionId) {
/**
*
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) throws ActionFailureException {
JSONObject js = new JSONObject();
try {
@ -73,8 +86,14 @@ public class TaskList extends Node {
return js;
}
public JSONObject getUpdateAction(int actionId) {
/**
*
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) throws ActionFailureException {
JSONObject js = new JSONObject();
try {
@ -103,20 +122,25 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
*
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
// 从JSON对象中获取任务列表的ID并设置
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
// 从JSON对象中获取任务列表的最后修改时间并设置
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
// 从JSON对象中获取任务列表的名称并设置
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
@ -129,23 +153,29 @@ public class TaskList extends Node {
}
}
/**
* JSON
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
Log.w(TAG, "setContentByLocalJSON: nothing is available");
}
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 如果是文件夹类型的笔记,获取名称并设置为任务列表的名称
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 如果是系统类型的笔记
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");
} else {
@ -157,6 +187,11 @@ public class TaskList extends Node {
}
}
/**
* JSON
*
* @return JSON
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -164,8 +199,9 @@ public class TaskList extends Node {
String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length());
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName.length());
// 设置文件夹名称和类型到JSON对象中
folder.put(NoteColumns.SNIPPET, folderName);
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
@ -183,28 +219,34 @@ public class TaskList extends Node {
}
}
/**
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
// 没有本地更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
// 两边都没有更新
return SYNC_ACTION_NONE;
} else {
// apply remote to local
// 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// validate gtask id
// 验证 GTask ID 是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
// 只有本地修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
// 对于文件夹冲突,只应用本地修改
return SYNC_ACTION_UPDATE_REMOTE;
}
}
@ -220,20 +262,31 @@ public class TaskList extends Node {
return mChildren.size();
}
/**
*
*
* @param task
* @return true false
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// need to set prior sibling and parent
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
// 需要设置前一个兄弟和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren.get(mChildren.size() - 1));
task.setParent(this);
}
}
return ret;
}
/**
*
*
* @param task
* @param index
* @return true false
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -244,7 +297,7 @@ public class TaskList extends Node {
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
// 更新任务列表
Task preTask = null;
Task afterTask = null;
if (index != 0)
@ -260,6 +313,12 @@ public class TaskList extends Node {
return true;
}
/**
*
*
* @param task
* @return true false
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -267,20 +326,26 @@ public class TaskList extends Node {
ret = mChildren.remove(task);
if (ret) {
// reset prior sibling and parent
// 重置前一个兄弟和父任务
task.setPriorSibling(null);
task.setParent(null);
// update the task list
// 更新任务列表
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
mChildren.get(index).setPriorSibling(index == 0 ? null : mChildren.get(index - 1));
}
}
}
return ret;
}
/**
*
*
* @param task
* @param index
* @return true false
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -290,7 +355,7 @@ public class TaskList extends Node {
int pos = mChildren.indexOf(task);
if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list");
Log.e(TAG, "move child task: the task should be in the list");
return false;
}
@ -299,6 +364,12 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* gid
*
* @param gid gid
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +380,22 @@ public class TaskList extends Node {
return null;
}
/**
*
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,7 +404,13 @@ public class TaskList extends Node {
return mChildren.get(index);
}
public Task getChilTaskByGid(String gid) {
/**
* gid
*
* @param gid gid
* @return null
*/
public Task getChildTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
return task;
@ -329,14 +418,29 @@ public class TaskList extends Node {
return null;
}
/**
*
*
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
*
* @return
*/
public int getIndex() {
return this.mIndex;
}

@ -16,17 +16,37 @@
package net.micode.notes.gtask.exception;
/**
*
*/
public class ActionFailureException extends RuntimeException {
/**
* ID
*/
private static final long serialVersionUID = 4425249765923293627L;
/**
* ActionFailureException
*/
public ActionFailureException() {
super();
}
/**
* ActionFailureException
*
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
}
/**
* ActionFailureException
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -16,17 +16,37 @@
package net.micode.notes.gtask.exception;
/**
*
*/
public class NetworkFailureException extends Exception {
/**
* ID
*/
private static final long serialVersionUID = 2107610287180234136L;
/**
* NetworkFailureException
*/
public NetworkFailureException() {
super();
}
/**
* NetworkFailureException
*
* @param paramString
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
/**
* NetworkFailureException
*
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -28,28 +28,38 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GTaskAsyncTask
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // GTask同步通知ID
/**
*
*/
public interface OnCompleteListener {
void onComplete();
}
private Context mContext;
private Context mContext;// 上下文对象
private NotificationManager mNotifiManager;
private NotificationManager mNotifiManager;// 通知管理器
private GTaskManager mTaskManager;
private GTaskManager mTaskManager;// GTask管理器
private OnCompleteListener mOnCompleteListener;
private OnCompleteListener mOnCompleteListener;// 完成监听器对象
/**
* GTaskASyncTask
*
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
@ -63,57 +73,93 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
});
}
/**
*
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
// 创建一个通知对象
Notification notification = new Notification(R.drawable.notification, mContext.getString(tickerId),
System.currentTimeMillis());
// 设置通知的默认行为为闪光灯提醒
notification.defaults = Notification.DEFAULT_LIGHTS;
// 设置通知的标志为自动取消
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
// 如果通知ID不是成功通知的ID
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
// 创建一个启动设置偏好活动的PendingIntent
pendingIntent = PendingIntent.getActivity(mContext, 0,
new Intent(mContext, NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
// 创建一个启动笔记列表活动的PendingIntent
pendingIntent = PendingIntent.getActivity(mContext, 0,
new Intent(mContext, NotesListActivity.class), 0);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
// 设置通知的最新事件信息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent);
// 发送通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
*
*
* @param unused 使
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 发布登录同步进度消息
publishProgess(mContext.getString(R.string.sync_progress_login,
NotesPreferenceActivity.getSyncAccountName(mContext)));
// 执行同步任务并返回结果
return mTaskManager.sync(mContext, this);
}
/**
*
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
// 显示同步中通知
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是GTaskSyncService的实例发送广播
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
/**
*
*
* @param result
*/
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {
// 显示成功通知
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
// 设置最后同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
// 显示网络错误通知
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
// 显示内部错误通知
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
// 显示同步取消通知
showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
}
// 如果存在完成监听器,则在新线程中执行完成操作
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}

@ -61,47 +61,71 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* GTaskClientGoogle
*/
public class GTaskClient {
// 日志标签
private static final String TAG = GTaskClient.class.getSimpleName();
// Google任务的基础URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 获取Google任务的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// 提交Google任务的URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// GTaskClient的单例实例
private static GTaskClient mInstance = null;
// 默认的HTTP客户端
private DefaultHttpClient mHttpClient;
// 获取任务的URL
private String mGetUrl;
// 提交任务的URL
private String mPostUrl;
// 客户端版本号
private long mClientVersion;
// 登录状态
private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime;
// 操作ID
private int mActionId;
// 账户信息
private Account mAccount;
// 待更新的任务数组
private JSONArray mUpdateArray;
/**
* GTaskClient
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
mClientVersion = -1;
mLoggedin = false;
mLastLoginTime = 0;
mActionId = 1;
mAccount = null;
mUpdateArray = null;
}
mHttpClient = null; // HTTP客户端
mGetUrl = GTASK_GET_URL; // 获取任务的URL
mPostUrl = GTASK_POST_URL; // 提交任务的URL
mClientVersion = -1; // 客户端版本号
mLoggedin = false; // 登录状态
mLastLoginTime = 0; // 上次登录时间
mActionId = 1; // 操作ID
mAccount = null; // 账户信息
mUpdateArray = null; // 待更新的任务数组
}
/**
* GTaskClient
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,18 +133,21 @@ public class GTaskClient {
return mInstance;
}
/**
* Google
*
* @param activity Activity
* @return truefalse
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
// 假设cookie在5分钟后过期需要重新登录
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
// 如果账户切换,则需要重新登录
if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
mLoggedin = false;
}
@ -136,9 +163,8 @@ public class GTaskClient {
return false;
}
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
// 如果是自定义域名,则使用自定义域名登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index);
@ -151,7 +177,7 @@ public class GTaskClient {
}
}
// try to login with google official url
// 尝试使用Google官方的URL进行登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,6 +190,13 @@ public class GTaskClient {
return true;
}
/**
* Google
*
* @param activity Activity
* @param invalidateToken 使token
* @return authTokennull
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -189,14 +222,14 @@ public class GTaskClient {
return null;
}
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
// 获取token
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
// 使token无效后再次尝试登录
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
@ -207,10 +240,16 @@ public class GTaskClient {
return authToken;
}
/**
* Gtask
*
* @param activity Activity
* @param authToken 使authToken
* @return truefalse
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 可能authToken已过期现在让我们使token失效并重新尝试登录
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -225,25 +264,35 @@ public class GTaskClient {
return true;
}
/**
* GTask
*
* @param authToken 使authToken
* @return truefalse
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
// 设置HTTP连接和等待超时参数
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 创建HttpClient并设置Cookie存储
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 登录GTask
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
// 获取Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -255,7 +304,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
// 获取客户端版本
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -272,7 +321,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
// 捕获所有异常
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -291,14 +340,24 @@ public class GTaskClient {
return httpPost;
}
/**
* HTTP
*
* @param entity
* @return
* @throws IOException IO
*/
private String getResponseContent(HttpEntity entity) throws IOException {
// 获取内容的编码方式
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
}
// 获取响应内容的输入流
InputStream input = entity.getContent();
// 根据编码方式解压缩输入流
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
@ -311,6 +370,7 @@ public class GTaskClient {
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
// 逐行读取响应内容并拼接为字符串
while (true) {
String buff = br.readLine();
if (buff == null) {
@ -319,208 +379,282 @@ public class GTaskClient {
sb = sb.append(buff);
}
} finally {
// 关闭输入流
input.close();
}
}
/**
* POSTJSON
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
// 检查是否已登录
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
// 创建HTTP POST请求
HttpPost httpPost = createHttpPost();
try {
// 将JSON对象添加到POST请求中的参数中
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
// 获取响应内容并转换为JSON对象
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
// 客户端协议异常通常是因为无效的HTTP协议
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
// IO异常包括网络连接问题等
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
// JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
// 其他异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
}
}
/**
*
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建POST请求的JSON对象
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 添加任务的创建动作到action_list
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
// 发起POST请求
JSONObject jsResponse = postRequest(jsPost);
// 处理响应数据
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
// JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
throw new ActionFailureException("create task: handling jsonobject failed");
}
}
/**
*
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建POST请求的JSON对象
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 添加任务列表的创建动作到action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
// 发起POST请求
JSONObject jsResponse = postRequest(jsPost);
// 处理响应数据
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
// JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
throw new ActionFailureException("create tasklist: handling jsonobject failed");
}
}
/**
*
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// action_list
// 添加更新操作数组到action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发起POST请求
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
// JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
throw new ActionFailureException("commit update: handling jsonobject failed");
}
}
}
/**
*
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
// 处理更新操作数组长度超过限制的情况
// 最大限制为10个
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
// 添加更新操作到更新操作数组中
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
/**
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
// 提交已有的更新操作
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 设置移动操作的参数
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
// 判断是否在同一个任务列表内移动,并且不是第一个任务
// 只在这种情况下添加prior_sibing_id参数
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
// 判断是否在不同的任务列表之间移动
// 只在这种情况下添加dest_list参数
if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发起POST请求
postRequest(jsPost);
} catch (JSONException e) {
// JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
throw new ActionFailureException("move task: handling jsonobject failed");
}
}
/**
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 提交已有的更新操作
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 设置节点删除状态并添加删除操作到操作列表中
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 设置操作列表
// client_version
// 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发起POST请求
postRequest(jsPost);
mUpdateArray = null;
mUpdateArray = null; // 清空更新操作数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed");
throw new ActionFailureException("delete node: handing jsonobject failed"); // 处理JSON对象失败时抛出异常
}
}
/**
*
* @return JSONArray
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
// 发起HttpGet请求获取任务列表
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
HttpResponse response = mHttpClient.execute(httpGet);
// get the task list
// 解析响应内容并获取任务列表
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -543,35 +677,40 @@ public class GTaskClient {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
throw new ActionFailureException("get task lists: handing jasonobject failed"); // 处理JSON对象失败时抛出异常
}
}
/**
*
*
* @param listGid
* @return JSONArray
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 提交已有的更新操作
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
JSONObject jsPost = new JSONObject(); // 创建请求JSON对象
JSONArray actionList = new JSONArray(); // 创建操作列表JSON数组
JSONObject action = new JSONObject(); // 创建操作JSON对象
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
// 设置操作类型和其他参数,并将操作对象添加到操作列表中
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 设置操作列表到请求JSON对象中
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 设置客户端版本号
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
JSONObject jsResponse = postRequest(jsPost); // 发起POST请求并获取响应
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 从响应中获取任务列表JSONArray
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
throw new ActionFailureException("get task list: handing jsonobject failed"); // 处理JSON对象失败时抛出异常
}
}

@ -14,6 +14,9 @@
* limitations under the License.
*/
/**
* GTaskSyncService Google Tasks
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
@ -23,25 +26,32 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* GTaskSyncService Google Tasks
*/
public class GTaskSyncService extends Service {
// 用于同步操作类型的动作字符串名称
public final static String ACTION_STRING_NAME = "sync_action_type";
// 用于同步操作的常量
public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2;
// GTask 服务的广播名称
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";
// 用于同步的 AsyncTask
private static GTaskASyncTask mSyncTask = null;
// 同步过程中的进度消息
private static String mSyncProgress = "";
// 开始同步过程
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,6 +66,7 @@ public class GTaskSyncService extends Service {
}
}
// 取消同步过程
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
@ -93,10 +104,14 @@ public class GTaskSyncService extends Service {
}
}
/**
* onBind 使
*/
public IBinder onBind(Intent intent) {
return null;
}
// 发送带有同步状态和进度消息的广播
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +120,7 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
// 从 Activity 开始同步过程
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,16 +128,19 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
// 从 Context 取消同步过程
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
// 检查当前是否正在同步
public static boolean isSyncing() {
return mSyncTask != null;
}
// 获取同步过程中的进度消息
public static String getProgressString() {
return mSyncProgress;
}

Loading…
Cancel
Save