pfqhleasr 11 months ago committed by liuyitao
commit 2befdcdade

@ -1,4 +1,4 @@
#Thu Dec 21 01:12:17 CST 2023 #Tue Dec 26 23:16:26 CST 2023
base.0=C\:\\Users\\lenovo\\Desktop\\git1\\MiNotes\\src\\Notes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex base.0=C\:\\Users\\lenovo\\Desktop\\git1\\MiNotes\\src\\Notes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex
path.0=classes.dex path.0=classes.dex
renamed.0=classes.dex renamed.0=classes.dex

@ -25,48 +25,67 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
public class Contact { /*
private static HashMap<String, String> sContactCache; *:
private static final String TAG = "Contact"; */
public class Contact {//联系人
private static HashMap<String, String> sContactCache;// sContactCache 是一个静态的 HashMap用于缓存联系人信息用于缓存联系人信息的HashMap
private static final String TAG = "Contact";// TAG 日志标签
// 定义字符串CALLER_ID_SELECTION
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";// 定义查询条件的字符串
/*
*
*
*
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) { if(sContactCache == null) {// 如果联系人缓存为空
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();// 初始化联系人缓存
} }
if(sContactCache.containsKey(phoneNumber)) { /*
return sContactCache.get(phoneNumber); * HashMapphoneNumber
*/
if(sContactCache.containsKey(phoneNumber)) {// 如果在缓存中找到了电话号码对应的联系人信息
return sContactCache.get(phoneNumber);// 直接从缓存中返回联系人信息
} }
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));//PhoneNumberUtils.toCallerIDMinMatch() 方法将电话号码转换为最小匹配模式,构建带有电话号码的查询条件
/*
* phoneNumber
* */
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI,// 联系人数据的URI
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME },// 要查询的字段,这里是联系人名字
selection, selection,// 查询条件
new String[] { phoneNumber }, new String[] { phoneNumber },// 查询条件中的占位符对应的值
null); null);// 不指定排序
/*
* moveToFirst()
* */
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {// 找到相关信息
String name = cursor.getString(0); String name = cursor.getString(0);// 获取联系人名字
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);// 将联系人名字放入缓存
return name; return name;// 返回联系人名字
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); } catch (IndexOutOfBoundsException e) {// 捕获IndexOutOfBoundsException异常
return null; Log.e(TAG, " Cursor get string error " + e.toString());// 记录异常日志
return null;// 返回null
} finally { } finally {
cursor.close(); cursor.close();// 关闭查询结果的Cursor
} }
// 未找到相关信息
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);// 记录未找到联系人信息的日志
return null; return null;
} }
} }

@ -17,12 +17,18 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
/*
*Notes 便
*/
public class Notes { public class Notes {
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes"; // 定义内容提供器的权限
public static final String TAG = "Notes"; public static final String TAG = "Notes";// 定义日志标签
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1; //以下三个常量对NoteColumns.TYPE的值进行设置对应不同的便签类型
public static final int TYPE_SYSTEM = 2; public static final int TYPE_NOTE = 0;// 便签类型为普通便签
public static final int TYPE_FOLDER = 1;// 便签类型为文件夹
public static final int TYPE_SYSTEM = 2;// 便签类型为系统文件夹
/** /**
* Following IDs are system folders' identifiers * Following IDs are system folders' identifiers
@ -30,179 +36,198 @@ public class Notes {
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_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";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
/*
*
* */
public static final int ID_ROOT_FOLDER = 0;// 默认文件夹
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";// 背景颜色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;// 2x2大小的Widget
public static final int TYPE_WIDGET_4X = 1;// 4x4大小的Widget
/*
* 便
* */
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;// 文本便签数据类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;// 电话便签数据类型
} }
/** /**
* Uri to query all notes and folders * Uri to query all notes and folders
*/ */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");// 查询所有便签和文件夹的标识符
/** /**
* Uri to query data * Uri to query data
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");// 查询数据的标识符
/*
* NoteColumns
*/
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";// 行的唯一标识符
/** /**
* The parent's id for note or folder * The parent's id for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";// 父级的ID
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";// 创建日期
/** /**
* Latest modified date * Latest modified date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";// 最后修改日期
/** /**
* Alert date * Alert date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";// 提醒日期
/** /**
* Folder's name or text content of note * Folder's name or text content of note
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";// 文件夹名称或便签的文本内容
/** /**
* Note's widget id * Note's widget id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";// 便签的Widget ID
/** /**
* Note's widget type * Note's widget type
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";// 便签的Widget类型
/** /**
* Note's background color's id * Note's background color's id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";// 便签的背景颜色ID
/** /**
* For text note, it doesn't has attachment, for multi-media * For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment * note, it has at least one attachment
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment";// 是否有附件
/** /**
* Folder's count of notes * Folder's count of notes
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";// 文件夹中的便签数量
/** /**
* The file type: folder or note * The file type: folder or note
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";// 文件类型:文件夹或便签
/** /**
* The last sync id * The last sync id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";// 最后同步的ID
/** /**
* Sign to indicate local modified or not * Sign to indicate local modified or not
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";// 标识是否本地修改
/** /**
* Original parent id before moving into temporary folder * Original parent id before moving into temporary folder
* <P> Type : INTEGER </P> * <P> Type : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";// 移动到临时文件夹之前的原始父级ID
/** /**
* The gtask id * The gtask id
* <P> Type : TEXT </P> * <P> Type : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";// Google任务ID
/** /**
* The version code * The version code
* <P> Type : INTEGER (long) </P> * <P> Type : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";// 版本号
} }
/*
* DataColumns
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";// 标识符
/** /**
* The MIME type of the item represented by this row. * The MIME type of the item represented by this row.
* <P> Type: Text </P> * <P> Type: Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";// 数据的MIME类型
/** /**
* The reference id to note that this data belongs to * The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";// 数据ID
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";// 创建日期
/** /**
* Latest modified date * Latest modified date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";// 最后修改日期
/** /**
* Data's content * Data's content
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String CONTENT = "content"; public static final String CONTENT = "content";// 内容
/** /**
@ -210,70 +235,76 @@ public class Notes {
* integer data type * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static final String DATA1 = "data1";// 通用数据1
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static final String DATA2 = "data2";// 通用数据2
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static final String DATA3 = "data3";// 通用数据3
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA4 = "data4";// 通用数据4
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";// 通用数据5
} }
/*
* 便
*/
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <P> Type: Integer 1:check list mode 0: normal mode </P>
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1;// 模式
public static final int MODE_CHECK_LIST = 1; public static final int MODE_CHECK_LIST = 1;// 待办清单模式
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";// 内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";// 单个条目的内容类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");// 查询文本便签的URI
} }
/*
* 便
*/
public static final class CallNote implements DataColumns { public static final class CallNote implements DataColumns {
/** /**
* Call date for this record * Call date for this record
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1;// 通话日期
/** /**
* Phone number for this record * Phone number for this record
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3;// 电话号码
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";// 内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";// 单个条目的内容类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");// 查询电话便签的URI
} }
} }

@ -16,68 +16,88 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentValues;
import android.content.Context; import android.content.ContentValues;//就是用于保存一些数据string boolean byte double float int long short ...)信息,这些信息可以被数据库操作时使用。
import android.database.sqlite.SQLiteDatabase; import android.content.Context;//加载和访问资源。android中主要是这两个功能但是这里具体不清楚
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase;//主要提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query()。配合content.values
import android.database.sqlite.SQLiteOpenHelper;//用来管理数据的创建和版本更新
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/*
* SQLOpenhelper,note
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";// 数据库名
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;// 版本号
public interface TABLE { public interface TABLE {
/*
* notedata,
* */
public static final String NOTE = "note"; public static final String NOTE = "note";
public static final String DATA = "data"; public static final String DATA = "data";
} }
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";// 日志标签,用于在日志中标识数据库操作的相关信息
/*
* NotesDatabaseHelper getInstance() NotesDatabaseHelper
* 使
*/
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
/*
* TABLE.NOTE便
*/
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," +// 便签ID
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 便签父级的ID
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +// 便签的提醒日期
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 便签的背景颜色ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 便签的创建日期
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +// 便签是否有附件
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 便签的最后修改日期
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +// 文件夹中的便签数量
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +// 文件夹名称或便签的文本内容
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +// 便签的类型
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +// 便签的Widget ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +// 便签的Widget类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +// 便签的同步ID
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +// 便签的本地修改标记
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 原始父级便签的ID
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +// 便签在Google任务中的ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +// 便签的版本号
")"; ")";
/*
* TABLE.DATA便
*/
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," +// 数据ID
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," +// 数据ID数据的MIME类型
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +// 数据所属的便签的ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 数据的创建日期
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 数据的最后修改日期
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +// 数据的内容
DataColumns.DATA1 + " INTEGER," + DataColumns.DATA1 + " INTEGER," +// 数据的附加信息1
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," +// 数据的附加信息2
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +// 数据的附加信息3
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +// 数据的附加信息4
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +// 数据的附加信息5
")"; ")";
/*
* note_id_index TABLE.DATA DataColumns.NOTE_ID
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
@ -85,6 +105,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Increase folder's note count when move note to the folder * Increase folder's note count when move note to the folder
*/ */
/*
* TABLE.NOTE NoteColumns.PARENT_ID 便
* TABLE.NOTE NoteColumns.NOTES_COUNT 1
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
@ -97,6 +122,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Decrease folder's note count when move note from folder * Decrease folder's note count when move note from folder
*/ */
/*
* TABLE.NOTE NoteColumns.PARENT_ID 便
* TABLE.NOTE NoteColumns.NOTES_COUNT 1
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " + "CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
@ -110,6 +140,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Increase folder's note count when insert new note to the folder * Increase folder's note count when insert new note to the folder
*/ */
/*
* TABLE.NOTE 便便
* TABLE.NOTE NoteColumns.NOTES_COUNT 1
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE + " AFTER INSERT ON " + TABLE.NOTE +
@ -122,6 +157,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Decrease folder's note count when delete note from the folder * Decrease folder's note count when delete note from the folder
*/ */
/*
* TABLE.NOTE 便便
* TABLE.NOTE NoteColumns.NOTES_COUNT 1
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -135,6 +175,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} * Update note's content when insert data with type {@link DataConstants#NOTE}
*/ */
/*
* TABLE.DATA DataConstants.NOTE 便
* TABLE.NOTE NoteColumns.SNIPPET
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA + " AFTER INSERT ON " + TABLE.DATA +
@ -148,6 +193,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed * Update note's content when data with {@link DataConstants#NOTE} type has changed
*/ */
/*
* DataConstants.NOTE 便
* TABLE.DATA 便
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA + " AFTER UPDATE ON " + TABLE.DATA +
@ -161,6 +211,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted * Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/ */
/*
* DataConstants.NOTE 便
* TABLE.DATA 便
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " + "CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA + " AFTER delete ON " + TABLE.DATA +
@ -174,6 +229,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Delete datas belong to note which has been deleted * Delete datas belong to note which has been deleted
*/ */
/*
* 便便
* TABLE.NOTE 便便
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -185,6 +245,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Delete notes belong to folder which has been deleted * Delete notes belong to folder which has been deleted
*/ */
/*
* 便
* TABLE.NOTE 便
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -196,6 +261,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* Move notes belong to folder which has been moved to trash folder * Move notes belong to folder which has been moved to trash folder
*/ */
/*
* 便
* TABLE.NOTE 便IDID
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE + " AFTER UPDATE ON " + TABLE.NOTE +
@ -206,10 +276,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/*
*
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
/*
*
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
@ -217,7 +293,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/*
*
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 通过执行SQL语句DROP TRIGGER IF EXISTS来删除已存在的触发器以确保不会重复创建
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -225,22 +305,28 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);// 增加文件夹计数的触发器
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);// 减少文件夹计数的触发器
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);// 删除文件夹计数的触发器
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);// 在删除时同时删除数据的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);// 增加文件夹计数的触发器
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);// 在删除时同时删除文件夹中的笔记的触发器
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);// 将笔记移动到垃圾箱的触发器
} }
/*
* NoteColumns
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
/** /**
* call record foler for call notes * call record foler for call notes
*/ */
/*
*
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
@ -248,6 +334,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* root folder which is default folder * root folder which is default folder
*/ */
/*
*
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -256,6 +345,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* temporary folder which is used for moving note * temporary folder which is used for moving note
*/ */
/*
*
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -264,19 +356,28 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* create trash folder * create trash folder
*/ */
/*
*
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/*
*
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);// 执行 CREATE_DATA_TABLE_SQL 的 SQL 语句来创建数据表
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);// 调用 reCreateDataTableTriggers() 方法重新创建数据表中的触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);// 执行 CREATE_DATA_NOTE_ID_INDEX_SQL 的 SQL 语句来创建一个索引
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/*
*
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) { private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -287,6 +388,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/*
*
* 线.
* 使
* 使
*/
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
@ -295,59 +402,93 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
} }
@Override @Override
/*
*
*/
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
@Override @Override
/*
*
*/
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;// 是否进行V2升级
/*
* 1upgradeToV2
*/
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; oldVersion++;
} }
/*
* 2V2upgradeToV3
*/
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
/*
* 3upgradeToV4
*/
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} }
/*
* reCreateNoteTableTriggersreCreateDataTableTriggers
*/
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
} }
/*
*
*/
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + "fails");
} }
} }
/*
* V2
* */
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
/*
* SQLDROP TABLE IF EXISTSNOTEDATA
* */
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db); createNoteTable(db);// 调用createNoteTable和createDataTable方法来创建新的NOTE表格
createDataTable(db); createDataTable(db);// 调用createNoteTable和createDataTable方法来创建新的DATA表格
} }
/*
* V3
* */
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
/*
* SQLDROP TRIGGER IF EXISTS使
* */
// drop unused triggers // drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
/*
* ALTER TABLENOTEGTASK_IDTEXT''
* */
// add a column for gtask id // add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
/*
* ContentValuesNOTE
* */
// add a trash system folder // add a trash system folder
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@ -355,8 +496,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/*
* V4
* */
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");// 通过执行ALTER TABLE语句向NOTE表格中添加一个新的列VERSION该列的类型是INTEGER并设置默认值为0
} }
} }

@ -35,7 +35,15 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
//ContentProvider提供的方法
//query查询
//insert插入
//update更新
//delete删除
//getType得到数据类型
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// UriMatcher用于匹配Uri
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
@ -51,7 +59,9 @@ public class NotesProvider extends ContentProvider {
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6;
static { static {
// 创建UriMatcher时调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 把需要匹配Uri路径全部给注册上
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -65,6 +75,8 @@ public class NotesProvider extends ContentProvider {
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * 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. * we will trim '\n' and white space in order to show more information.
*/ */
// 声明 NOTES_SEARCH_PROJECTION
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
@ -73,6 +85,7 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 声明NOTES_SNIPPET_SEARCH_QUERY
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
@ -80,18 +93,24 @@ public class NotesProvider extends ContentProvider {
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
// Context只有在onCreate()中才被初始化
// 对mHelper进行实例化
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
@Override @Override
// 查询uri在数据库中对应的位置
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 匹配查找uri
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 对于不同的匹配值,在数据库中查找相应的条目
case URI_NOTE: case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
@ -113,6 +132,7 @@ public class NotesProvider extends ContentProvider {
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
// 不合法的参数异常
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
@ -120,6 +140,8 @@ public class NotesProvider extends ContentProvider {
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
// getPathSegments()方法得到一个String的List
// 在uri.getPathSegments().get(1)为第2个元素
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
@ -139,6 +161,7 @@ public class NotesProvider extends ContentProvider {
} }
break; break;
default: default:
// 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) { if (c != null) {
@ -148,13 +171,17 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 插入一个uri
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 新增一个条目
case URI_NOTE: case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
// 如果存在查找NOTE_ID
case URI_DATA: case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
@ -167,6 +194,7 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri // Notify the note uri
// notifyChange获得一个ContextResolver对象并且更新里面的内容
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
@ -178,13 +206,17 @@ public class NotesProvider extends ContentProvider {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
// 返回插入的uri的路径
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
@Override @Override
// 删除一个uri
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
//Uri代表要操作的数据Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示
int count = 0; int count = 0;
String id = null; String id = null;
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
@ -228,6 +260,7 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 更新一个uri
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
@ -267,10 +300,12 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
// 将字符串解析成规定格式
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
//增加一个noteVersion
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -293,6 +328,7 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString); sql.append(selectString);
} }
// execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }

@ -96,7 +96,6 @@ public class MetaData extends Task {
// this function should not be called // this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
@ -114,7 +113,4 @@ public class MetaData extends Task {
*/ */
} }
} }
}

@ -53,54 +53,53 @@ public abstract class Node {
private boolean mDeleted;//表征是否被删除 private boolean mDeleted;//表征是否被删除
public Node() { public Node() {
mGid = null; mGid = null; // 初始化 mGid 为 null
mName = ""; mName = ""; // 初始化 mName 为空字符串
mLastModified = 0; mLastModified = 0; // 初始化 mLastModified 为 0
mDeleted = false; mDeleted = false; // 初始化 mDeleted 为 false
} }
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId); // 获取创建节点的操作信息的抽象方法
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId); // 获取更新节点的操作信息的抽象方法
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js); // 根据远程JSON数据设置节点内容的抽象方法
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js); // 根据本地JSON数据设置节点内容的抽象方法
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent(); // 从节点内容中获取本地JSON数据的抽象方法
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c); // 获取同步节点的操作信息的抽象方法
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid; // 设置 mGid 的取值为传入的 gid
} }
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name; // 设置 mName 的取值为传入的 name
} }
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified; // 设置 mLastModified 的取值为传入的 lastModified
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted; // 设置 mDeleted 的取值为传入的 deleted
} }
public String getGid() { public String getGid() {
return this.mGid; return this.mGid; // 返回 mGid 的取值
} }
public String getName() { public String getName() {
return this.mName; return this.mName; // 返回 mName 的取值
} }
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified; // 返回 mLastModified 的取值
} }
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted; // 返回 mDeleted 的取值
} }
} }

@ -50,12 +50,11 @@ public class SqlData {
* TAG * TAG
* getSimpleName () * getSimpleName ()
*/ */
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();// 定义一个私有的静态常量 TAG用于在日志输出中作为标签
private static final int INVALID_ID = -99999;//为mDataId置初始值-99999 private static final int INVALID_ID = -99999;//为mDataId置初始值-99999
/*
/**
* NotesDataColumn * NotesDataColumn
*/ */
@ -64,35 +63,34 @@ public class SqlData {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
/*
/**
* sql5 * sql5
*/ */
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;// 数据记录ID所在列的索引通常为第 0 列
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;// 数据的MIME类型所在列的索引通常为第 1 列
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;// 数据内容所在列的索引,通常为第 2 列
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;// 数据中的DATA1字段所在列的索引通常为第 3 列
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;// 数据中的DATA3字段所在列的索引通常为第 4 列
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
//判断是否直接用Content生成是为true否则为false //判断是否直接用Content生成是为true否则为false
private boolean mIsCreate; private boolean mIsCreate;// 表示数据记录是否是新创建的标识
private long mDataId; private long mDataId;// 数据记录的ID
private String mDataMimeType; private String mDataMimeType;// 数据记录的MIME类型
private String mDataContent; private String mDataContent;// 数据记录的内容
private long mDataContentData1; private long mDataContentData1;// 数据记录中的DATA1字段
private String mDataContentData3; private String mDataContentData3;// 数据记录中的DATA3字段
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;// 保存数据记录的差异值
/* /*
* *
@ -119,10 +117,10 @@ public class SqlData {
* *
*/ */
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();// 获取 ContentResolver 对象
mIsCreate = false; mIsCreate = false;// 将数据记录的新建标识设置为 false
loadFromCursor(c); loadFromCursor(c);// 从 Cursor 对象中加载数据记录
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();// 创建 ContentValues 对象,用于保存数据记录的差异值
} }
/* /*
@ -130,11 +128,12 @@ public class SqlData {
* *
*/ */
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); // 获取游标中对应字段位置的字段值,并保存到成员变量中
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);//获取数据记录的ID值并保存到成员变量 mDataId 中
mDataContent = c.getString(DATA_CONTENT_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);//获取数据记录的MIME类型并保存到成员变量 mDataMimeType 中。
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN);//获取数据记录的内容,并保存到成员变量 mDataContent 中。
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);//获取数据记录中的DATA1字段值并保存到成员变量 mDataContentData1 中。
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);//获取数据记录中的DATA3字段值并保存到成员变量 mDataContentData3 中。
} }
@ -143,57 +142,56 @@ public class SqlData {
* *
*/ */
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
//如果传入的JSONObject对象中有DataColumns.ID这一项则设置否则设为INVALID_ID long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; // 从JSONObject中获取DataColumns.ID字段的值如果不存在则设置为INVALID_ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; if (mIsCreate || mDataId != dataId) { // 如果是新创建的数据或者mDataId与dataId不相等
if (mIsCreate || mDataId != dataId) { mDiffDataValues.put(DataColumns.ID, dataId); // 将dataId添加到差异数据中
mDiffDataValues.put(DataColumns.ID, dataId);
} }
mDataId = dataId; mDataId = dataId; // 更新mDataId的值
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; : DataConstants.NOTE; // 从JSONObject中获取DataColumns.MIME_TYPE字段的值如果不存在则设置为DataConstants.NOTE
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { // 如果是新创建的数据或者mDataMimeType与dataMimeType不相等
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); // 将dataMimeType添加到差异数据中
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType; // 更新mDataMimeType的值
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; // 从JSONObject中获取DataColumns.CONTENT字段的值如果不存在则设置为空字符串
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) { // 如果是新创建的数据或者mDataContent与dataContent不相等
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent); // 将dataContent添加到差异数据中
} }
mDataContent = dataContent; mDataContent = dataContent; // 更新mDataContent的值
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; // 从JSONObject中获取DataColumns.DATA1字段的值如果不存在则设置为0
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) { // 如果是新创建的数据或者mDataContentData1与dataContentData1不相等
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1); // 将dataContentData1添加到差异数据中
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1; // 更新mDataContentData1的值
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; // 从JSONObject中获取DataColumns.DATA3字段的值如果不存在则设置为空字符串
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { // 如果是新创建的数据或者mDataContentData3与dataContentData3不相等
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3); // 将dataContentData3添加到差异数据中
} }
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3; // 更新mDataContentData3的值
} }
/* /*
* *
* *
*/ */
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
// 如果数据还未在数据库中创建则打印错误日志并返回null
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
return null; return null;
} }
//创建JSONObject对象。并将相关数据放入其中并返回。 //创建JSONObject对象。并将相关数据放入其中并返回。
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId); js.put(DataColumns.ID, mDataId); // 将mDataId字段的值放入JSONObject中
js.put(DataColumns.MIME_TYPE, mDataMimeType); js.put(DataColumns.MIME_TYPE, mDataMimeType); // 将mDataMimeType字段的值放入JSONObject中
js.put(DataColumns.CONTENT, mDataContent); js.put(DataColumns.CONTENT, mDataContent); // 将mDataContent字段的值放入JSONObject中
js.put(DataColumns.DATA1, mDataContentData1); js.put(DataColumns.DATA1, mDataContentData1); // 将mDataContentData1字段的值放入JSONObject中
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3); // 将mDataContentData3字段的值放入JSONObject中
return js; return js; // 返回JSONObject对象
} }
/* /*
@ -203,15 +201,21 @@ public class SqlData {
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
// 如果数据还未在数据库中创建,则执行插入操作
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
// 如果mDataId为无效值并且mDiffDataValues中包含DataColumns.ID字段则移除该字段
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);
} }
// 设置DataColumns.NOTE_ID字段的值为noteId
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
// 在Notes.CONTENT_DATA_URI中插入mDiffDataValues并返回Uri对象
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
// 将Uri路径中的第二个片段转换为long类型并赋值给mDataId
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// 如果获取ID出错则输出错误日志并抛出ActionFailureException异常
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
@ -219,9 +223,11 @@ public class SqlData {
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
// 如果不需要验证版本则直接通过mDataId更新mDiffDataValues到数据库中
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else {
// 如果需要验证版本则通过noteId和version进行更新
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
@ -230,20 +236,23 @@ public class SqlData {
}); });
} }
if (result == 0) { if (result == 0) {
// 如果没有更新任何数据,则输出警告日志
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
} }
// 清空差异数据
mDiffDataValues.clear(); mDiffDataValues.clear();
// 将新建标记设为false
mIsCreate = false; mIsCreate = false;
} }
/* /**
* id * ID
* * @return ID
*
*/ */
public long getId() { public long getId() {
return mDataId; return mDataId;
} }
} }

@ -43,198 +43,184 @@ public class SqlNote {
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
// 定义查询笔记的投影,包含需要查询的列
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, // 笔记ID
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.ALERTED_DATE, // 提醒时间
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, NoteColumns.BG_COLOR_ID, // 背景颜色
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, NoteColumns.CREATED_DATE, // 创建时间
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.VERSION NoteColumns.MODIFIED_DATE, // 修改时间
NoteColumns.NOTES_COUNT, // 子笔记数量
NoteColumns.PARENT_ID, // 父笔记ID
NoteColumns.SNIPPET, // 摘要
NoteColumns.TYPE, // 类型
NoteColumns.WIDGET_ID, // Widget ID
NoteColumns.WIDGET_TYPE, // Widget 类型
NoteColumns.SYNC_ID, // 同步ID
NoteColumns.LOCAL_MODIFIED, // 本地修改标记
NoteColumns.ORIGIN_PARENT_ID, // 原始父笔记ID
NoteColumns.GTASK_ID, // Google Task ID
NoteColumns.VERSION // 版本号
}; };
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0; // ID 列索引
public static final int ALERTED_DATE_COLUMN = 1; // ALERTED_DATE 列索引
public static final int ALERTED_DATE_COLUMN = 1; public static final int BG_COLOR_ID_COLUMN = 2; // BG_COLOR_ID 列索引
public static final int CREATED_DATE_COLUMN = 3; // CREATED_DATE 列索引
public static final int BG_COLOR_ID_COLUMN = 2; public static final int HAS_ATTACHMENT_COLUMN = 4; // HAS_ATTACHMENT 列索引
public static final int MODIFIED_DATE_COLUMN = 5; // MODIFIED_DATE 列索引
public static final int CREATED_DATE_COLUMN = 3; public static final int NOTES_COUNT_COLUMN = 6; // NOTES_COUNT 列索引
public static final int PARENT_ID_COLUMN = 7; // PARENT_ID 列索引
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int SNIPPET_COLUMN = 8; // SNIPPET 列索引
public static final int TYPE_COLUMN = 9; // TYPE 列索引
public static final int MODIFIED_DATE_COLUMN = 5; public static final int WIDGET_ID_COLUMN = 10; // WIDGET_ID 列索引
public static final int WIDGET_TYPE_COLUMN = 11; // WIDGET_TYPE 列索引
public static final int NOTES_COUNT_COLUMN = 6; public static final int SYNC_ID_COLUMN = 12; // SYNC_ID 列索引
public static final int LOCAL_MODIFIED_COLUMN = 13; // LOCAL_MODIFIED 列索引
public static final int PARENT_ID_COLUMN = 7; public static final int ORIGIN_PARENT_ID_COLUMN = 14; // ORIGIN_PARENT_ID 列索引
public static final int GTASK_ID_COLUMN = 15; // GTASK_ID 列索引
public static final int SNIPPET_COLUMN = 8; public static final int VERSION_COLUMN = 16; // VERSION 列索引
public static final int TYPE_COLUMN = 9; private Context mContext; // 上下文对象
private ContentResolver mContentResolver; // ContentResolver 对象
public static final int WIDGET_ID_COLUMN = 10; private boolean mIsCreate; // 是否是新建数据的标记
private long mId; // 数据ID
public static final int WIDGET_TYPE_COLUMN = 11; private long mAlertDate; // 提醒时间
private int mBgColorId; // 背景颜色
public static final int SYNC_ID_COLUMN = 12; private long mCreatedDate; // 创建时间
private int mHasAttachment; // 是否有附件
public static final int LOCAL_MODIFIED_COLUMN = 13; private long mModifiedDate; // 修改时间
private long mParentId; // 父笔记ID
public static final int ORIGIN_PARENT_ID_COLUMN = 14; private String mSnippet; // 摘要
private int mType; // 类型
public static final int GTASK_ID_COLUMN = 15; private int mWidgetId; // Widget ID
private int mWidgetType; // Widget 类型
public static final int VERSION_COLUMN = 16; private long mOriginParent; // 原始父笔记ID
private long mVersion; // 版本号
private Context mContext; private ContentValues mDiffNoteValues; // 笔记数据差异值
private ArrayList<SqlData> mDataList; // SqlData 列表
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context; // 初始化上下文对象
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 初始化 ContentResolver 对象
mIsCreate = true; mIsCreate = true; // 标记为新建数据
mId = INVALID_ID; mId = INVALID_ID; // 初始化 ID 为无效值
mAlertDate = 0; mAlertDate = 0; // 初始化提醒时间为 0
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context);// 初始化背景颜色为默认值
mCreatedDate = System.currentTimeMillis(); mCreatedDate = System.currentTimeMillis(); // 初始化创建时间为当前时间
mHasAttachment = 0; mHasAttachment = 0; // 初始化是否有附件为 0
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis(); // 初始化修改时间为当前时间
mParentId = 0; mParentId = 0; // 初始化父笔记 ID 为 0
mSnippet = ""; mSnippet = ""; // 初始化摘要为空字符串
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE; // 初始化类型为普通笔记
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 初始化 Widget ID 为无效值
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 初始化 Widget 类型为无效类型
mOriginParent = 0; mOriginParent = 0; // 初始化原始父笔记 ID 为 0
mVersion = 0; mVersion = 0; // 初始化版本号为 0
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化笔记数据差异值为空 ContentValues 对象
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化 SqlData 列表为空列表
} }
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context; // 初始化上下文对象
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 初始化 ContentResolver 对象
mIsCreate = false; mIsCreate = false; // 标记为非新建数据
loadFromCursor(c); loadFromCursor(c); // 从 Cursor 中加载数据
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化 SqlData 列表为空列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果类型为普通笔记
loadDataContent(); loadDataContent(); // 加载笔记内容数据
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化笔记数据差异值为新的 ContentValues 对象
} }
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context; // 初始化上下文对象
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 初始化 ContentResolver 对象
mIsCreate = false; mIsCreate = false; // 标记为非新建数据
loadFromCursor(id); loadFromCursor(id); // 从数据库中加载指定 ID 的数据
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化 SqlData 列表为空列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果类型为普通笔记
loadDataContent(); loadDataContent(); // 加载笔记内容数据
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化笔记数据差异值为新的 ContentValues 对象
} }
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;// 初始化游标对象
try { try {
// 通过 ID 查询笔记数据
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(id) String.valueOf(id)
}, null); }, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext(); // 移动到第一条数据
loadFromCursor(c); loadFromCursor(c); // 载入数据
} else { } else {
Log.w(TAG, "loadFromCursor: cursor = null"); Log.w(TAG, "loadFromCursor: cursor = null");// 输出警告日志
} }
} finally { } finally {
if (c != null) if (c != null)
c.close(); c.close(); // 关闭游标
} }
} }
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN); // 从游标中获取并设置 ID
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); // 从游标中获取并设置提醒日期
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); // 从游标中获取并设置背景色ID
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); mCreatedDate = c.getLong(CREATED_DATE_COLUMN); // 从游标中获取并设置创建日期
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); // 从游标中获取并设置是否有附件
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); // 从游标中获取并设置修改日期
mParentId = c.getLong(PARENT_ID_COLUMN); mParentId = c.getLong(PARENT_ID_COLUMN); // 从游标中获取并设置父节点ID
mSnippet = c.getString(SNIPPET_COLUMN); mSnippet = c.getString(SNIPPET_COLUMN); // 从游标中获取并设置摘要
mType = c.getInt(TYPE_COLUMN); mType = c.getInt(TYPE_COLUMN); // 从游标中获取并设置类型
mWidgetId = c.getInt(WIDGET_ID_COLUMN); mWidgetId = c.getInt(WIDGET_ID_COLUMN); // 从游标中获取并设置小部件ID
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); // 从游标中获取并设置小部件类型
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN); // 从游标中获取并设置版本号
} }
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null; // 初始化游标对象
mDataList.clear(); mDataList.clear(); // 清空数据列表
try { try {
// 通过笔记ID查询数据内容
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}, null); }, null);
if (c != null) { if (c != null) {
if (c.getCount() == 0) { if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");// 输出警告日志
return; return;
} }
while (c.moveToNext()) { while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c); SqlData data = new SqlData(mContext, c); // 创建数据对象
mDataList.add(data); mDataList.add(data); // 将数据对象添加到数据列表中
} }
} else { } else {
Log.w(TAG, "loadDataContent: cursor = null"); Log.w(TAG, "loadDataContent: cursor = null");// 输出警告日志
} }
} finally { } finally {
if (c != null) if (c != null)
c.close(); c.close();// 关闭游标
} }
} }
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
// 解析JSON对象中的note字段
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 检查note的类型
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 如果类型为系统类型,则无法设置系统文件夹
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 如果类型为文件夹类型则更新snippet和type
// for folder we can only update the snnipet and type // for folder we can only update the snnipet and type
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
// 如果正在创建一个新的note或者之前的snippet和当前传入的snippet不相等则更新snippet字段
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
@ -242,98 +228,50 @@ public class SqlNote {
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE;
// 如果正在创建一个新的note或者之前的type和当前传入的type不相等则更新type字段
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
mType = type; mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { }else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
// 如果类型为笔记类型则解析data数组
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 获取note的ID字段如果没有则设置为INVALID_ID常量值
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
// 如果正在创建一个新的note或者之前的id和当前传入的id不相等则更新ID字段
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id); mDiffNoteValues.put(NoteColumns.ID, id);
} }
mId = id; mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note // 解析并更新其他成员变量
.getLong(NoteColumns.ALERTED_DATE) : 0; long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
} }
mAlertDate = alertDate; mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note // 解析snippet和type字段
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || mBgColorId != bgColorId) { // 如果正在创建一个新的note或者之前的snippet和当前传入的snippet不相等则更新snippet字段
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)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
mSnippet = snippet; mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
: Notes.TYPE_NOTE; // 如果正在创建一个新的note或者之前的type和当前传入的type不相等则更新type字段
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
mType = type; mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) // 遍历data数组
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
mOriginParent = originParent;
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null; SqlData sqlData = null;
// 检查data数组中的id字段并查找对应的SqlData对象
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) { for (SqlData temp : mDataList) {
@ -343,111 +281,130 @@ public class SqlNote {
} }
} }
// 如果未找到对应的SqlData对象则创建一个新的对象并添加到数据列表中
if (sqlData == null) { if (sqlData == null) {
sqlData = new SqlData(mContext); sqlData = new SqlData(mContext);
mDataList.add(sqlData); mDataList.add(sqlData);
} }
// 调用SqlData对象的setContent方法传递JSON数据进行处理
sqlData.setContent(data); sqlData.setContent(data);
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
// 处理异常情况打印错误信息并返回false
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
// 返回true表示设置内容成功
return true; return true;
} }
public JSONObject getContent() { public JSONObject getContent() {// 定义一个返回JSONObject类型的方法getContent()
try { try {// 尝试执行以下代码块
JSONObject js = new JSONObject(); // 创建一个空的 JSONObject 对象
JSONObject js = new JSONObject();// 实例化一个空的JSONObject对象
if (mIsCreate) { // 如果笔记还没有创建到数据库中,则返回 null
Log.e(TAG, "it seems that we haven't created this in database yet"); if (mIsCreate) {// 判断mIsCreate属性值
return null; Log.e(TAG, "it seems that we haven't created this in database yet");// 打印错误日志
return null;// 返回null
} }
JSONObject note = new JSONObject(); // 根据笔记类型创建不同的 JSONObject
if (mType == Notes.TYPE_NOTE) { JSONObject note = new JSONObject(); // 实例化一个JSONObject对象
note.put(NoteColumns.ID, mId); if (mType == Notes.TYPE_NOTE) { // 判断mType属性值是否为Notes.TYPE_NOTE
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ID, mId); // 向note对象中添加ID键值对
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.ALERTED_DATE, mAlertDate); // 添加ALERTED_DATE键值对
note.put(NoteColumns.CREATED_DATE, mCreatedDate); note.put(NoteColumns.BG_COLOR_ID, mBgColorId); // 添加BG_COLOR_ID键值对
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); note.put(NoteColumns.CREATED_DATE, mCreatedDate); // 添加CREATED_DATE键值对
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); // 添加HAS_ATTACHMENT键值对
note.put(NoteColumns.PARENT_ID, mParentId); note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); // 添加MODIFIED_DATE键值对
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.PARENT_ID, mParentId); // 添加PARENT_ID键值对
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.SNIPPET, mSnippet); // 添加SNIPPET键值对
note.put(NoteColumns.WIDGET_ID, mWidgetId); note.put(NoteColumns.TYPE, mType); // 添加TYPE键值对
note.put(NoteColumns.WIDGET_TYPE, mWidgetType); note.put(NoteColumns.WIDGET_ID, mWidgetId); // 添加WIDGET_ID键值对
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); note.put(NoteColumns.WIDGET_TYPE, mWidgetType); // 添加WIDGET_TYPE键值对
js.put(GTaskStringUtils.META_HEAD_NOTE, note); note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); // 添加ORIGIN_PARENT_ID键值对
// 将笔记信息添加为 META_HEAD_NOTE 的值
JSONArray dataArray = new JSONArray(); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将note对象添加为js对象的META_HEAD_NOTE键值对
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent(); // 如果是笔记类型,将其附加数据添加到 META_HEAD_DATA 中
if (data != null) { JSONArray dataArray = new JSONArray(); // 实例化一个JSONArray对象
dataArray.put(data); for (SqlData sqlData : mDataList) { // 遍历mDataList列表
JSONObject data = sqlData.getContent(); // 调用sqlData对象的getContent方法并将返回值赋给data
if (data != null) { // 判断data是否为null
dataArray.put(data); // 将data对象添加到dataArray中
} }
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);// 将dataArray对象添加为js对象的META_HEAD_DATA键值对
note.put(NoteColumns.ID, mId); } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { // 判断mType属性值是否为Notes.TYPE_FOLDER或Notes.TYPE_SYSTEM
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.ID, mId); // 添加ID键值对
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.TYPE, mType); // 添加TYPE键值对
js.put(GTaskStringUtils.META_HEAD_NOTE, note); note.put(NoteColumns.SNIPPET, mSnippet); // 添加SNIPPET键值对
// 将笔记信息添加为 META_HEAD_NOTE 的值
js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将note对象添加为js对象的META_HEAD_NOTE键值对
} }
return js; return js;
} catch (JSONException e) { } catch (JSONException e) { // 捕获JSONException异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); e.printStackTrace(); // 打印异常轨迹
} }
return null; // 如果出现异常,则返回 null
return null; // 返回null
} }
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }//设置父节点ID
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
//设置Google任务ID
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
//设置同步ID
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
//重置本地修改标记
public long getId() { public long getId() {
return mId; return mId;
} }
//获取笔记ID
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
//获取父节点ID
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
//获取摘要信息
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
//是否为笔记类型
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
// 如果是新建笔记
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
// 如果mId为无效值并且mDiffNoteValues中包含NoteColumns.ID字段则移除该字段
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID);
} }
// 在Notes.CONTENT_NOTE_URI中插入mDiffNoteValues并返回Uri对象
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try { try {
// 将Uri路径中的第二个片段转换为long类型并赋值给mId
mId = Long.valueOf(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
@ -457,12 +414,14 @@ public class SqlNote {
throw new IllegalStateException("Create thread id failed"); throw new IllegalStateException("Create thread id failed");
} }
// 如果是笔记类型,则循环提交数据内容更改
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1); sqlData.commit(mId, false, -1);
} }
} }
} else { } else {
// 如果不是新建笔记
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note"); Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id"); throw new IllegalStateException("Try to update note with invalid id");
@ -471,13 +430,15 @@ public class SqlNote {
mVersion ++; mVersion ++;
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
// 如果不需要验证版本则直接通过mId更新mDiffNoteValues到数据库中
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}); });
} else { } else {
// 如果需要验证版本则通过mId和mVersion进行更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] {
String.valueOf(mId), String.valueOf(mVersion) String.valueOf(mId), String.valueOf(mVersion)
}); });
@ -487,6 +448,7 @@ public class SqlNote {
} }
} }
// 如果是笔记类型,则循环提交数据内容更改
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion);
@ -494,11 +456,12 @@ public class SqlNote {
} }
} }
// refresh local info // 刷新本地信息
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
// 清空mDiffNoteValues和将mIsCreate设置为false
mDiffNoteValues.clear(); mDiffNoteValues.clear();
mIsCreate = false; mIsCreate = false;
} }

@ -33,141 +33,147 @@ import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName(); // 定义一个私有静态常量TAG值为Task.class.getSimpleName()
private boolean mCompleted; private boolean mCompleted; // 定义一个私有的boolean类型变量mCompleted
private String mNotes; private String mNotes; // 定义一个私有的String类型变量mNotes
private JSONObject mMetaInfo; private JSONObject mMetaInfo; // 定义一个私有的JSONObject类型变量mMetaInfo
private Task mPriorSibling; private Task mPriorSibling; // 定义一个私有的Task类型变量mPriorSibling
private TaskList mParent; private TaskList mParent; // 定义一个私有的TaskList类型变量mParent
public Task() { public Task() { // 定义一个公有的无参构造方法Task()
super(); super(); // 调用父类的无参构造方法
mCompleted = false; mCompleted = false; // 将mCompleted变量初始化为false
mNotes = null; mNotes = null; // 将mNotes变量初始化为null
mPriorSibling = null; mPriorSibling = null; // 将mPriorSibling变量初始化为null
mParent = null; mParent = null; // 将mParent变量初始化为null
mMetaInfo = null; mMetaInfo = null; // 将mMetaInfo变量初始化为null
} }
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个JSONObject对象js
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); // 将键为GTASK_JSON_ACTION_TYPE的值设置为"create"
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 将键为GTASK_JSON_ACTION_ID的值设置为actionId
// index // index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// 将键为GTASK_JSON_INDEX的值设置为当前任务在父列表中的位置
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject(); // 创建一个JSONObject对象entity
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 将键为GTASK_JSON_NAME的值设为任务名
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 将键为GTASK_JSON_CREATOR_ID的值设为"null"
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 将键为GTASK_JSON_ENTITY_TYPE的值设为"task"
GTaskStringUtils.GTASK_JSON_TYPE_TASK); if (getNotes() != null) { // 如果备注信息不为空
if (getNotes() != null) { entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 将键为GTASK_JSON_NOTES的值设为备注信息
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将键为GTASK_JSON_ENTITY_DELTA的值设为entity
// parent_id // parent_id
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); // 将键为GTASK_JSON_PARENT_ID的值设为父列表的唯一标识符
// dest_parent_type // dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 将键为GTASK_JSON_DEST_PARENT_TYPE的值设为"group"
// list_id // list_id
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); // 将键为GTASK_JSON_LIST_ID的值设为父列表的唯一标识符
// prior_sibling_id // prior_sibling_id
if (mPriorSibling != null) { if (mPriorSibling != null) { // 如果前一个兄弟节点不为空
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); // 将键为GTASK_JSON_PRIOR_SIBLING_ID的值设为前一个兄弟节点的唯一标识符
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕捉JSONException异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 在日志中输出异常信息
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject"); throw new ActionFailureException("fail to generate task-create jsonobject"); // 抛出ActionFailureException异常
} }
return js; return js; // 返回JSONObject对象js
} }
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个JSONObject对象js
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); // 将键为GTASK_JSON_ACTION_TYPE的值设置为"update"
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 将键为GTASK_JSON_ACTION_ID的值设置为actionId
// id // id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// 将键为GTASK_JSON_ID的值设置为当前任务的唯一标识符
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject(); // 创建一个JSONObject对象entity
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 将键为GTASK_JSON_NAME的值设为任务名
if (getNotes() != null) { if (getNotes() != null) { // 如果备注信息不为空
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 将键为GTASK_JSON_NOTES的值设为备注信息
} }
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 将键为GTASK_JSON_DELETED的值设置为任务是否被删除的状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将键为GTASK_JSON_ENTITY_DELTA的值设为entity
} catch (JSONException e) { } catch (JSONException e) { // 捕捉JSONException异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 在日志中输出异常信息
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject"); // 抛出ActionFailureException异常
} }
return js; return js; // 返回JSONObject对象js
} }
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) { // 如果参数不为空
try { try {
// id // 获取Google Task的ID并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // 获取Google Task的最后修改时间戳并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // 获取Google Task的名称并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
// notes // 获取Google Task的备注信息并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
} }
// deleted // 获取Google Task的删除状态并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// completed // 获取Google Task的完成状态并设置到本地笔记或任务中
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
} catch (JSONException e) { } catch (JSONException e) { // 如果解析过程出现异常
// 记录异常日志并抛出异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject"); throw new ActionFailureException("fail to get task content from jsonobject");
@ -177,175 +183,182 @@ public class Task extends Node {
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) { // 如果参数为空或缺少必要的数据字段
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is available"); // 记录警告日志
} }
try { try {
// 从JSON对象中获取笔记和数据数组
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 检查笔记类型是否为笔记类型
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type"); // 记录错误日志
return; return; // 返回
} }
// 遍历数据数组
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i); // 获取数据对象
// 如果数据的MIME类型是笔记类型
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT)); // 设置笔记名称
break; break; // 跳出循环
} }
} }
} catch (JSONException e) { } catch (JSONException e) { // 如果解析过程出现异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录异常日志
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈信息
} }
} }
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName(); // 获取名称
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) { // 如果元信息为空
// new task created from web // 从Web创建新任务
if (name == null) { if (name == null) { // 如果名称为空
Log.w(TAG, "the note seems to be an empty one"); Log.w(TAG, "the note seems to be an empty one"); // 记录警告日志
return null; return null; // 返回null
} }
// 创建JSON对象并填充数据
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name); data.put(DataColumns.CONTENT, name); // 设置数据内容为名称
dataArray.put(data); dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; return js; // 返回JSON对象
} else { } else {
// synced task // 同步的任务
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 遍历数据数组
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
// 如果数据的MIME类型是笔记类型
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName()); data.put(DataColumns.CONTENT, getName()); // 设置数据内容为名称
break; break; // 跳出循环
} }
} }
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo; return mMetaInfo; // 返回元信息对象
} }
} catch (JSONException e) { } catch (JSONException e) { // 如果解析过程出现异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录异常日志
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈信息
return null; return null; // 返回null
} }
} }
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) { // 如果元数据不为空且笔记不为空
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes()); // 将笔记转换为JSON对象
} catch (JSONException e) { } catch (JSONException e) { // 如果转换过程出现异常
Log.w(TAG, e.toString()); Log.w(TAG, e.toString()); // 记录警告日志
mMetaInfo = null; mMetaInfo = null; // 设置元信息为空
} }
} }
} }
//获取同步操作类型
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记信息对象
} }
if (noteInfo == null) { if (noteInfo == null) {
Log.w(TAG, "it seems that note meta has been deleted"); Log.w(TAG, "it seems that note meta has been deleted"); // 记录警告日志
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE; // 返回更新远程操作
} }
if (!noteInfo.has(NoteColumns.ID)) { if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted"); Log.w(TAG, "remote note id seems to be deleted"); // 记录警告日志
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地操作
} }
// validate the note id now // 验证笔记ID是否匹配
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match"); // 记录警告日志
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地操作
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // 没有本地更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // 两边都没有更新
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE; // 返回无操作
} else { } else {
// apply remote to local // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL; // 返回更新本地操作
} }
} else { } else {
// validate gtask id // 验证gtask id是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match"); // 记录错误日志
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // 返回错误操作
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // 只有本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE; // 返回更新远程操作
} else { } else {
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT; // 返回更新冲突操作
} }
} }
} catch (Exception e) { } catch (Exception e) { // 如果过程中出现异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印异常堆栈信息
} }
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR; // 返回错误操作
} }
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }//判断任务是否值得保存
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }//设置任务是否已完成
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }//设置任务的笔记
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }//设置任务的前一个兄弟任务
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }//设置任务的父任务列表
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }//获取任务是否已完成
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }//获取任务的笔记
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }//获取任务的前一个兄弟任务
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }//获取任务的父任务列表
} }

@ -31,72 +31,94 @@ import java.util.ArrayList;
public class TaskList extends Node { public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName(); // TAG用于在日志中标识类名
private int mIndex; private int mIndex; // 任务列表的索引
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren; // 任务列表的子任务集合
/**
* TaskListmChildrenmIndex
*/
public TaskList() { public TaskList() {
super(); super(); // 调用父类Node的构造方法
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>(); // 初始化子任务集合
mIndex = 1; mIndex = 1; // 初始化索引为1
} }
/**
* JSONObject
*
* @param actionId ID
* @return JSONObject
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个JSONObject对象js
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); // 将键为GTASK_JSON_ACTION_TYPE的值设置为"create"
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 将键为GTASK_JSON_ACTION_ID的值设置为actionId
// index // index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// 将键为GTASK_JSON_INDEX的值设置为mIndex
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject(); // 创建一个JSONObject对象entity
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 将键为GTASK_JSON_NAME的值设为任务列表名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 将键为GTASK_JSON_CREATOR_ID的值设为"null"
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 将键为GTASK_JSON_ENTITY_TYPE的值设置为GTASK_JSON_TYPE_GROUP
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// 将键为GTASK_JSON_ENTITY_DELTA的值设为entity
} catch (JSONException e) { } catch (JSONException e) { // 捕捉JSONException异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 在日志中输出异常信息
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject"); throw new ActionFailureException("fail to generate tasklist-create jsonobject");
// 抛出ActionFailureException异常
} }
return js; return js; // 返回JSONObject对象js
} }
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // 设置操作类型为更新
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // 设置操作的ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // 设置任务列表的全局ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // 创建一个表示任务列表实体变化的JSON对象
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
// 设置任务列表的名称
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
// 设置任务列表是否被删除
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
// 将实体变化JSON对象添加到主JSON对象中
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {
// 打印异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 抛出自定义异常
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); throw new ActionFailureException("fail to generate tasklist-update jsonobject");
} }
@ -108,143 +130,206 @@ public class TaskList extends Node {
try { try {
// id // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
// 如果JSON对象包含ID字段则将ID设置为相应的值
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
// 如果JSON对象包含last_modified字段则将last_modified设置为相应的值
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
// 如果JSON对象包含name字段则将name设置为相应的值
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
} catch (JSONException e) { } catch (JSONException e) {
// 打印异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 抛出自定义异常
throw new ActionFailureException("fail to get tasklist content from jsonobject"); throw new ActionFailureException("fail to get tasklist content from jsonobject");
} }
} }
} }
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// 检查传入的JSON对象是否为空或者不包含指定的字段
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); // 如果不满足条件,则打印警告信息
Log.w(TAG, "setContentByLocalJSON: nothing is available");
} }
try { try {
// 获取头部注释的JSON对象
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 检查头部注释的类型是否为文件夹类型
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 如果是文件夹类型,则获取文件夹的名称
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
// 将名称设置为预定义前缀加上文件夹名称的形式
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 如果是系统类型则根据特定的系统文件夹ID设置名称
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
// 如果系统文件夹ID是根文件夹的ID则设置名称为预定义前缀加上默认文件夹名
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
// 如果系统文件夹ID是通话记录文件夹的ID则设置名称为预定义前缀加上通话笔记文件夹名
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE); + GTaskStringUtils.FOLDER_CALL_NOTE);
else else
// 如果系统文件夹ID无效则打印错误信息
Log.e(TAG, "invalid system folder"); Log.e(TAG, "invalid system folder");
} else { } else {
// 如果类型既不是文件夹类型也不是系统类型,则打印错误信息
Log.e(TAG, "error type"); Log.e(TAG, "error type");
} }
} catch (JSONException e) { } catch (JSONException e) {
// 打印异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
/*
* JSON
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
// 创建一个空的JSON对象
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
// 创建一个文件夹JSON对象
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
// 获取文件夹的名称
String folderName = getName(); String folderName = getName();
// 检查文件夹名称是否以预定义前缀开头,如果是,则去掉前缀
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length());
// 将文件夹名称放入文件夹JSON对象中
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
// 检查文件夹名称是否为默认文件夹或通话笔记文件夹,如果是,则设置文件夹类型为系统类型,否则设置为文件夹类型
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
else else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
// 将文件夹JSON对象放入根JSON对象中的头部注释字段中
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
// 返回根JSON对象
return js; return js;
} catch (JSONException e) { } catch (JSONException e) {
// 打印异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 返回空值
return null; return null;
} }
} }
/*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // 没有本地更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // 双方都没有更新
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // 验证gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // 仅有本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// for folder conflicts, just apply local modification // 对于文件夹冲突,只应用本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
} catch (Exception e) { } catch (Exception e) {
// 打印异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
// 返回错误的同步操作类型
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/*
*
* @return
*/
public int getChildTaskCount() { public int getChildTaskCount() {
// 直接返回当前任务的子任务列表长度,即子任务数量
return mChildren.size(); return mChildren.size();
} }
/*
*
* @param task
* @return
*/
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
// 判断要添加的子任务是否为空以及当前任务的子任务列表中是否已经包含该子任务
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
// 如果满足条件,则将该子任务添加到子任务列表中
ret = mChildren.add(task); ret = mChildren.add(task);
if (ret) { if (ret) {
// need to set prior sibling and parent // 设置子任务的前一个兄弟和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
} }
} }
// 返回是否成功添加子任务的信息
return ret; return ret;
} }
/*
*
* @param task
* @param index
* @return
*/
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
// 判断子任务应该插入的位置是否合法
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
// 如果不合法,则记录日志,返回失败
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
return false; return false;
} }
// 查找子任务是否已经在列表中
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);
// 如果子任务不为空且不在列表中,则执行以下操作
if (task != null && pos == -1) { if (task != null && pos == -1) {
// 在指定位置添加子任务
mChildren.add(index, task); mChildren.add(index, task);
// update the task list // 更新任务列表
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0)
@ -252,92 +337,143 @@ public class TaskList extends Node {
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1);
// 设置前一个兄弟和后一个兄弟
task.setPriorSibling(preTask); task.setPriorSibling(preTask);
if (afterTask != null) if (afterTask != null)
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task);
} }
// 返回是否成功添加子任务的信息
return true; return true;
} }
/**
*
*
* @param task
* @return
*/
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task); // 查找子任务在列表中的位置
if (index != -1) { if (index != -1) {
ret = mChildren.remove(task); ret = mChildren.remove(task); // 从列表中移除子任务
if (ret) { if (ret) {
// reset prior sibling and parent // 重置前一个兄弟和父任务
task.setPriorSibling(null); task.setPriorSibling(null); // 将子任务的前一个兄弟设置为null
task.setParent(null); task.setParent(null); // 将子任务的父任务设置为null
// update the task list // 更新任务列表
if (index != mChildren.size()) { if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1)); // 将后一个兄弟的前一个兄弟设置为当前子任务的前一个兄弟
} }
} }
} }
return ret; return ret; // 返回是否成功移除子任务的信息
} }
/*
*
* @param task
* @param index
* @return
*/
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
// 判断子任务应该移动到的位置是否合法
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index"); // 记录日志,返回失败
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task); // 查找子任务在列表中的位置
// 如果子任务不在列表中,则记录日志,返回失败
if (pos == -1) { if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list");
return false; return false;
} }
// 如果子任务本来就在目标位置上,则直接返回成功
if (pos == index) if (pos == index)
return true; return true;
// 先移除子任务,再添加到指定位置,返回移除和添加的结果
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
/*
* ID
* @param gid ID
* @return null
*/
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
if (t.getGid().equals(gid)) { if (t.getGid().equals(gid)) { // 比较子任务的全局ID与给定的gid是否相等
return t; return t; // 如果相等,则返回该子任务
} }
} }
return null; return null; // 如果未找到匹配的子任务则返回null
} }
/*
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task); // 返回子任务在列表中的索引位置
} }
/*
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index"); // 记录日志,索引位置无效
return null; return null;
} }
return mChildren.get(index); return mChildren.get(index); // 返回索引位置对应的子任务
} }
/*
* ID
* @param gid ID
* @return null
*/
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid)) // 比较子任务的全局ID与给定的gid是否相等
return task; return task; // 如果相等,则返回该子任务
} }
return null; return null; // 如果未找到匹配的子任务则返回null
} }
/*
*
* @return
*/
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren; // 返回子任务列表
} }
/*
*
* @param index
*/
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index; // 设置索引位置
} }
/*
*
* @return
*/
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex; // 返回索引位置
} }
} }

Loading…
Cancel
Save