Compare commits

...

14 Commits
zjh ... main

Author SHA1 Message Date
pqfx375oj cb41373238 Merge pull request 'wbq 合并' (#5) from wbq into main
8 months ago
pqfx375oj e224e056b7 Merge pull request 'cxh合并' (#1) from cxh into main
8 months ago
jacky-qiao 4cdf502c86 Merge branch 'main' of https://bdgit.educoder.net/pqfx375oj/Code-Reading-MiNote
8 months ago
zhangjinhan a495b394fa 加了文档到main里面
8 months ago
zhangjinhan f154c9b770 我将我之前所处理的部分提交到main里面来了
8 months ago
WizHua 9b27be9301 注释了gtask中的部分代码
8 months ago
chengxinghua 982a01e921 注释了gtask/data部分代码
8 months ago
jacky-qiao 5bb28547f7 代码注释(真)
8 months ago
jacky-qiao 1d17b6468f 代码注释(真)
8 months ago
jacky-qiao afe5b77cb2 代码注释(真
8 months ago
jacky-qiao a4caade656 代码注释(真)
8 months ago
m2mcrutap a116891fa6 ADD file via upload
8 months ago
pkagifq93 7411415837 ADD file via upload
8 months ago
pkagifq93 b88ed5b58f ADD file via upload
8 months ago

@ -0,0 +1,26 @@
package com.example.application;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.application", appContext.getPackageName());
}
}

@ -26,9 +26,12 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
public class Contact { public class Contact {
// 保存联系人名与电话号码映射的缓存
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
// 日志标记
private static final String TAG = "Contact"; private static final String TAG = "Contact";
// 查询联系人所用的选择条件
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,36 +39,54 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
*
* @param context
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 初始化联系人缓存
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 如果缓存中已经存在该电话号码的联系人名,直接返回
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 替换选择条件中的占位符
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 执行查询
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME }, // 查询显示名称
selection, selection,
new String[] { phoneNumber }, new String[] { phoneNumber },
null); null);
// 如果查询结果不为空且移动到结果集的第一行
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取联系人姓名
String name = cursor.getString(0); String name = cursor.getString(0);
// 将联系人姓名缓存起来
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 捕获索引越界异常,记录错误日志
Log.e(TAG, " Cursor get string error " + e.toString()); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
} finally { } finally {
// 关闭cursor释放资源
cursor.close(); cursor.close();
} }
} else { } else {
// 如果没有找到匹配的联系人,记录日志
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; return null;
} }

@ -1,279 +1,283 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* you may not use this file except in compliance with the License. * 使
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, * "按原样"
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
public class Notes { public class Notes {
// 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; // 笔记类型
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 * IDs
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER}
*/ */
public static final int ID_ROOT_FOLDER = 0; public static final int ID_ROOT_FOLDER = 0; // 根文件夹
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3; // 垃圾箱文件夹
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // Intent Extra Strings
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0; // 小部件类型
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x小部件类型
public static final int TYPE_WIDGET_4X = 1; // 4x小部件类型
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
*/ */
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
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* The parent's id for note or folder * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Alert date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";
/** /**
* Folder's name or text content of note *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
/** /**
* Note's widget id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
/** /**
* Note's widget type *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
/** /**
* Note's background color's id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";
/** /**
* For text note, it doesn't has attachment, for multi-media *
* note, it has at least one attachment * <P> : 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 *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";
/** /**
* The file type: folder or note *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";
/** /**
* The last sync id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
/** /**
* Sign to indicate local modified or not *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
/** /**
* Original parent id before moving into temporary folder * ID
* <P> Type : INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/** /**
* The gtask id * gtask ID
* <P> Type : TEXT </P> * <P> : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
/** /**
* The version code *
* <P> Type : INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : 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. * MIME
* <P> Type: Text </P> * <P> : Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";
/** /**
* The reference id to note that this data belongs to * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Data's content *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String CONTENT = "content"; public static final String CONTENT = "content";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* integer data type *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static final String DATA1 = "data1";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* integer data type *
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static final String DATA2 = "data2";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * TEXT
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static final String DATA3 = "data3";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * TEXT
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA4 = "data4";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * {@link #MIMETYPE}
* TEXT data type * TEXT
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not *
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <P> : Integer 1: 0: </P>
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1;
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 *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1;
/** /**
* Phone number for this record *
* <P> Type: TEXT </P> * <P> : 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
} }
} }

@ -1,92 +1,99 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* you may not use this file except in compliance with the License. * 使
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * "原样"
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
// 指定包名
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentValues; // 导入必要的类
import android.content.Context; import android.content.ContentValues; // 用于数据库内容的存储
import android.database.sqlite.SQLiteDatabase; import android.content.Context; // 上下文类
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; // SQLite数据库类
import android.util.Log; import android.database.sqlite.SQLiteOpenHelper; // SQLite数据库帮助类
import android.util.Log; // 日志类
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
// 导入自定义数据列和常量
import net.micode.notes.data.Notes.DataColumns; // 数据列模型
import net.micode.notes.data.Notes.DataConstants; // 数据常量
import net.micode.notes.data.Notes.NoteColumns; // 笔记列模型
// 创建NotesDatabaseHelper类继承自SQLiteOpenHelper
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
// 数据库版本号
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
// 定义表名的接口
public interface TABLE { public interface TABLE {
// 笔记表的名称
public static final String NOTE = "note"; public static final String NOTE = "note";
// 数据表的名称
public static final String DATA = "data"; public static final String DATA = "data";
} }
// 日志标签
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
// 单例实例
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
// 创建笔记表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + 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," + // 小部件ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
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 ''," + // GTASK ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号
")"; ")";
// 创建数据表的SQL语句
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," + // 数据ID主键
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // 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字段的索引
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/** // 当更新笔记时增加文件夹的笔记计数的触发器
* Increase folder's note count when move note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " + " BEGIN " +
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
@ -94,9 +101,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END"; " END";
/** // 当从文件夹中移动笔记时减少文件夹的笔记计数的触发器
* Decrease folder's note count when move note from folder
*/
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 +
@ -107,9 +112,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END"; " END";
/** // 当在文件夹中插入新笔记时增加文件夹的笔记计数的触发器
* Increase folder's note count when insert new note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE + " AFTER INSERT ON " + TABLE.NOTE +
@ -119,9 +122,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END"; " END";
/** // 当从文件夹中删除笔记时减少文件夹的笔记计数的触发器
* Decrease folder's note count when delete note from the folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -132,9 +133,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END"; " END";
/** // 在插入类型为NOTE的数据时更新笔记内容的触发器
* Update note's content when insert data with type {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA + " AFTER INSERT ON " + TABLE.DATA +
@ -145,9 +144,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/** // 当类型为NOTE的数据发生变化时更新笔记内容的触发器
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*/
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 +
@ -158,9 +155,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/** // 当类型为NOTE的数据被删除时更新笔记内容的触发器
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/
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 +
@ -171,9 +166,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/** // 删除已删除笔记的所有数据的触发器
* Delete datas belong to note which has been deleted
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -182,9 +175,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/** // 删除已删除文件夹中的笔记的触发器
* Delete notes belong to folder which has been deleted
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
@ -193,9 +184,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/** // 当文件夹被移动到垃圾桶时移动文件夹中的笔记的触发器
* Move notes belong to folder which has been moved to trash folder
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE + " AFTER UPDATE ON " + TABLE.NOTE +
@ -206,26 +195,30 @@ 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); // 执行创建表的SQL语句
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db); // 重新创建触发器
createSystemFolder(db); createSystemFolder(db); // 创建系统文件夹
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created"); // 日志输出
} }
// 重新创建笔记表的所有触发器
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); // 删除触发器
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); // 删除触发器
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); // 删除触发器
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); // 删除触发器
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);
@ -235,128 +228,130 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
// 创建系统文件夹
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues(); // 创建内容值对象
/** // 为通话记录文件夹插入记录
* call record foler for call notes
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入记录
/** // 创建根文件夹
* root folder which is default folder values.clear(); // 清空内容值
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入记录
/** // 创建临时文件夹
* temporary folder which is used for moving note values.clear(); // 清空内容值
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入记录
/** // 创建垃圾桶文件夹
* create trash folder values.clear(); // 清空内容值
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); 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); // 执行创建表的SQL语句
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db); // 重新创建触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建索引
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created"); // 日志输出
} }
// 重新创建数据表的所有触发器
private void reCreateDataTableTriggers(SQLiteDatabase db) { private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); // 删除触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); // 删除触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); // 删除触发器
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
// 获取NotesDatabaseHelper的单例实例
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) { // 如果实例为空,则创建新的实例
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
} }
return mInstance; return mInstance; // 返回实例
} }
// 当创建数据库时被调用
@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的标志
if (oldVersion == 1) { if (oldVersion == 1) { // 如果旧版本是1
upgradeToV2(db); upgradeToV2(db); // 升级到V2
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // 跳过V2的标志设为true
oldVersion++; oldVersion++; // 增加版本号
} }
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) { // 如果旧版本是2且没有跳过
upgradeToV3(db); upgradeToV3(db); // 升级到V3
reCreateTriggers = true; reCreateTriggers = true; // 设置重创建触发器的标志为true
oldVersion++; oldVersion++; // 增加版本号
} }
if (oldVersion == 3) { if (oldVersion == 3) { // 如果旧版本是3
upgradeToV4(db); upgradeToV4(db); // 升级到V4
oldVersion++; oldVersion++; // 增加版本号
} }
if (reCreateTriggers) { if (reCreateTriggers) { // 如果需要重创建触发器
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db); // 重新创建笔记表的触发器
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db); // 重新创建数据表的触发器
} }
if (oldVersion != newVersion) { if (oldVersion != newVersion) { // 如果版本不一致,则抛出异常
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + " fails");
} }
} }
// 升级到V2
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); // 删除笔记表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); // 删除数据表
createNoteTable(db); createNoteTable(db); // 创建笔记表
createDataTable(db); createDataTable(db); // 创建数据表
} }
// 升级到V3
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // 删除未使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id // 为笔记添加一个新的字符ID列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder // 添加一个垃圾桶系统文件夹
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values); // 插入记录
} }
// 升级到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"); // 为笔记表添加版本列
} }
} }

@ -16,7 +16,7 @@
package net.micode.notes.data; package net.micode.notes.data;
// 导入需要的Android和本地类
import android.app.SearchManager; import android.app.SearchManager;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentUris; import android.content.ContentUris;
@ -34,271 +34,317 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* NotesProvider ContentProvider
*
*/
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;
// 日志标签
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1; // 定义URI常量
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE = 1; // 笔记 URI
private static final int URI_DATA = 3; private static final int URI_NOTE_ITEM = 2; // 单个笔记 URI
private static final int URI_DATA_ITEM = 4; private static final int URI_DATA = 3; // 数据 URI
private static final int URI_DATA_ITEM = 4; // 单个数据 URI
private static final int URI_SEARCH = 5; private static final int URI_SEARCH = 5; // 搜索 URI
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议 URI
// 静态代码块,初始化 URI 匹配器并添加各种 URI 匹配规则
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 笔记的 URI
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 单个笔记的 URI
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 数据的 URI
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 单个数据的 URI
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 搜索 URI
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); // 搜索建议 URI
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); // 带参数的搜索建议 URI
} }
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * x'0A'
* we will trim '\n' and white space in order to show more information. *
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," // 笔记 ID
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," // 笔记 ID 作为意图额外数据
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," // 修剪后的内容作为建议文本1
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," // 修剪后的内容作为建议文本2
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," // 搜索结果图标
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," // 意图行为
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; // 笔记内容类型
// 搜索笔记的 SQL 查询语句
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 ?" // 根据内容片段进行模糊匹配
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // 排除回收站的内容
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 仅匹配笔记类型
@Override @Override
public boolean onCreate() { public boolean onCreate() {
// 初始化数据库助手
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true; // 创建成功
} }
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
// 查询方法处理不同的URI请求并返回结果的Cursor
Cursor c = null; Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取可读数据库
String id = null; String id = null; // 用于存储ID
switch (mMatcher.match(uri)) {
switch (mMatcher.match(uri)) { // 根据URI匹配不同的查询类型
case URI_NOTE: case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, // 查询所有笔记
sortOrder); c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, sortOrder);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); // 查询单个笔记
id = uri.getPathSegments().get(1); // 从URI中获取笔记ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA: case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, // 查询所有数据
sortOrder); c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); // 查询单个数据
id = uri.getPathSegments().get(1); // 从URI中获取数据ID
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
// 搜索请求不支持排序或选择
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 获取搜索建议的参数
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
// 从查询参数获取搜索字符串
searchString = uri.getQueryParameter("pattern"); searchString = uri.getQueryParameter("pattern");
} }
if (TextUtils.isEmpty(searchString)) { if (TextUtils.isEmpty(searchString)) {
return null; return null; // 如果搜索字符串为空则返回null
} }
try { try {
// 使用通配符模糊匹配
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString }); // 执行搜索查询
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString()); Log.e(TAG, "got exception: " + ex.toString()); // 记录异常
} }
break; break;
default: default:
// 未知的URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) { if (c != null) {
// 设置通知URI数据变化时通知的URI
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
} }
return c; return c; // 返回查询结果
} }
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase(); // 插入数据方法
long dataId = 0, noteId = 0, insertedId = 0; SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
switch (mMatcher.match(uri)) { long dataId = 0, noteId = 0, insertedId = 0; // 初始化ID
switch (mMatcher.match(uri)) { // 根据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;
case URI_DATA: case URI_DATA:
// 插入新的数据
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
// 获取关联的笔记ID
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values.toString()); Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 记录错误日志
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
default: default:
// 未知的URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri
// 当笔记插入成功时通知笔记URI
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);
} }
// Notify the data uri // 当数据插入成功时通知数据URI
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId); // 返回新插入项的URI
} }
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0; // 删除数据方法
String id = null; int count = 0; // 计数删除的行数
SQLiteDatabase db = mHelper.getWritableDatabase(); String id = null; // 用于存储ID
boolean deleteData = false; SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
switch (mMatcher.match(uri)) { boolean deleteData = false; // 标记是否删除数据
switch (mMatcher.match(uri)) { // 根据URI匹配不同的删除类型
case URI_NOTE: case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 删除所有笔记
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 除去系统文件夹
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); // 删除单个笔记
/** id = uri.getPathSegments().get(1); // 从URI中获取笔记ID
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
break; break; // 系统文件夹不允许删除
} }
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA:
// 删除所有数据
count = db.delete(TABLE.DATA, selection, selectionArgs); count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true; deleteData = true; // 标记为删除数据
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); // 删除单个数据
id = uri.getPathSegments().get(1); // 从URI中获取数据ID
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true; deleteData = true; // 标记为删除数据
break; break;
default: default:
// 未知的URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) { if (count > 0) {
if (deleteData) { if (deleteData) {
// 如果删除了数据通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
// 通知数据URI
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count; return count; // 返回删除的行数
} }
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; // 更新数据方法
String id = null; int count = 0; // 计数更新的行数
SQLiteDatabase db = mHelper.getWritableDatabase(); String id = null; // 用于存储ID
boolean updateData = false; SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写数据库
switch (mMatcher.match(uri)) { boolean updateData = false; // 标记是否更新数据
switch (mMatcher.match(uri)) { // 根据URI匹配不同的更新类型
case URI_NOTE: case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs); // 更新所有笔记
increaseNoteVersion(-1, selection, selectionArgs); // 更新版本
count = db.update(TABLE.NOTE, values, selection, selectionArgs); count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); // 更新单个笔记
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); id = uri.getPathSegments().get(1); // 从URI中获取笔记ID
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 更新版本
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA:
// 更新所有数据
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true; updateData = true; // 标记为更新数据
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); // 更新单个数据
id = uri.getPathSegments().get(1); // 从URI中获取数据ID
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
updateData = true; updateData = true; // 标记为更新数据
break; break;
default: default:
// 未知的URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
// 如果更新了数据通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
// 通知数据URI
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
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 + ')' : ""); // 如果选择条件不为空则添加 AND
} }
// 辅助方法,用于增加笔记版本
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 ");
sql.append(TABLE.NOTE); sql.append(TABLE.NOTE);
sql.append(" SET "); sql.append(" SET ");
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 "); // 增加版本号
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE "); // 如果有ID或选择条件添加WHERE
} }
if (id > 0) { if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); sql.append(NoteColumns.ID + "=" + String.valueOf(id)); // 添加ID条件
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
// 处理选择参数
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) { for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args); selectString = selectString.replaceFirst("\\?", args); // 替换占位符
} }
sql.append(selectString); sql.append(selectString);
} }
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL更新版本号
} }
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub // 返回特定URI的MIME类型这里暂时不实现
return null; return null;
} }

@ -1,82 +1,94 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache License, Version 2.0
* you may not use this file except in compliance with the License. * 使
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data; // 定义该类的位置
import android.database.Cursor; import android.database.Cursor; // 导入Android的Cursor类用于数据库操作
import android.util.Log; import android.util.Log; // 导入Android的Log类用于日志输出
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils; // 导入自定义工具类,用于字符串处理
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONException; // 导入JSON异常处理类
import org.json.JSONObject; // 导入JSON对象类
// MetaData类继承自Task类表示元数据的管理类
public class MetaData extends Task { public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName(); // 获取当前类名作为日志标签
private String mRelatedGid = null; private String mRelatedGid = null; // 声明一个私有属性用于存储相关的GID
// 设置元数据的方法接收GID和JSON对象作为参数
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将GID放入metadata信息中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) { } catch (JSONException e) {
// 捕获JSON异常并记录错误
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
} }
// 设置笔记内容为JSON对象的字符串表示
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
// 设置名称为常量名称
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
// 获取相关GID的方法
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid; // 返回相关GID
} }
// 重写isWorthSaving方法判断是否值得保存
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null; // 如果笔记内容不为空,则值得保存
} }
// 重写通过远程JSON设置内容的方法
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js); // 调用父类的方法
if (getNotes() != null) { if (getNotes() != null) { // 如果笔记内容不为空
try { try {
// 将笔记内容转换为JSON对象
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
// 获取相关GID并保存
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
// 捕获JSON异常并记录警告
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
mRelatedGid = null; mRelatedGid = null; // 将相关GID设置为null
} }
} }
} }
// 重写通过本地JSON设置内容的方法该方法不应被调用
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); // 抛出异常,指明不应调用
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
// 重写从内容获取本地JSON的方法该方法不应被调用
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); // 抛出异常,指明不应调用
} }
// 重写获取同步操作的方法,该方法不应被调用
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called"); // 抛出异常,指明不应调用
} }
} }

@ -14,88 +14,95 @@
* limitations under the License. * limitations under the License.
*/ */
// 定义包名
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
// 导入必要的类
import android.database.Cursor; import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
// 抽象类 Node表示一个数据节点的基本结构
public abstract class Node { public abstract class Node {
public static final int SYNC_ACTION_NONE = 0; // 定义同步操作的常量
public static final int SYNC_ACTION_NONE = 0; // 无操作
public static final int SYNC_ACTION_ADD_REMOTE = 1; public static final int SYNC_ACTION_ADD_REMOTE = 1; // 从远程添加
public static final int SYNC_ACTION_ADD_LOCAL = 2; // 从本地添加
public static final int SYNC_ACTION_ADD_LOCAL = 2; public static final int SYNC_ACTION_DEL_REMOTE = 3; // 从远程删除
public static final int SYNC_ACTION_DEL_LOCAL = 4; // 从本地删除
public static final int SYNC_ACTION_DEL_REMOTE = 3; public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 从远程更新
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 从本地更新
public static final int SYNC_ACTION_DEL_LOCAL = 4; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; // 更新冲突
public static final int SYNC_ACTION_ERROR = 8; // 错误操作
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
// 定义节点的属性
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; private String mGid; // 唯一标识符
private String mName; // 节点名称
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; private long mLastModified; // 最后修改时间
private boolean mDeleted; // 是否删除标记
public static final int SYNC_ACTION_ERROR = 8;
// 构造函数,初始化节点属性
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
public Node() { public Node() {
mGid = null; mGid = null; // 初始化 Gid 为 null
mName = ""; mName = ""; // 初始化名称为空字符串
mLastModified = 0; mLastModified = 0; // 初始化最后修改时间为 0
mDeleted = false; mDeleted = false; // 初始化删除状态为 false
} }
// 抽象方法,获取创建操作的 JSON 对象
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
// 抽象方法,获取更新操作的 JSON 对象
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
// 抽象方法,通过远程 JSON 设置内容
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
// 抽象方法,通过本地 JSON 设置内容
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
// 抽象方法,从内容获取本地 JSON
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
// 抽象方法,从 Cursor 获取同步操作类型
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
// 设置 Gid
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
// 设置名称
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
// 设置最后修改时间
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
// 设置删除状态
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
// 获取 Gid
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
// 获取名称
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
// 获取最后修改时间
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
// 获取删除状态
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
} }

@ -1,189 +1,186 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011 MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* you may not use this file except in compliance with the License. * 使
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data; // 定义包名
import android.content.ContentResolver; import android.content.ContentResolver; // 导入ContentResolver类用于管理内容提供者的操作
import android.content.ContentUris; import android.content.ContentUris; // 导入ContentUris类用于构造内容URI
import android.content.ContentValues; import android.content.ContentValues; // 导入ContentValues类用于存储行的列值
import android.content.Context; import android.content.Context; // 导入Context类表示应用环境
import android.database.Cursor; import android.database.Cursor; // 导入Cursor类用于访问数据库查询结果
import android.net.Uri; import android.net.Uri; // 导入Uri类用于表示内容的URI
import android.util.Log; import android.util.Log; // 导入Log类用于记录调试信息
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes; // 导入Notes类表示笔记相关的数据结构
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; // 导入笔记列常量
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE; // 导入数据库表名常量
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException; // 导入自定义异常类
import org.json.JSONException; import org.json.JSONException; // 导入JSONException类用于处理JSON异常
import org.json.JSONObject; import org.json.JSONObject; // 导入JSONObject类表示一个JSON对象
public class SqlData { public class SqlData { // 定义SqlData类
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName(); // 定义日志标签
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999; // 定义无效ID常量
// 定义数据投影数组,包含要查询的列
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
// 列索引常量
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; private ContentResolver mContentResolver; // 内容解析器实例
private boolean mIsCreate; // 标记是否为创建状态
private boolean mIsCreate; private long mDataId; // 数据ID
private String mDataMimeType; // 数据MIME类型
private long mDataId; private String mDataContent; // 数据内容
private long mDataContentData1; // 数据内容的第一个额外字段
private String mDataMimeType; private String mDataContentData3; // 数据内容的第三个额外字段
private ContentValues mDiffDataValues; // 存储变化的数据值
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
// 构造函数用于创建新的SqlData实例
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = true; mIsCreate = true; // 设置为创建状态
mDataId = INVALID_ID; mDataId = INVALID_ID; // 初始化ID为无效值
mDataMimeType = DataConstants.NOTE; mDataMimeType = DataConstants.NOTE; // 默认MIME类型为笔记
mDataContent = ""; mDataContent = ""; // 初始化内容为空
mDataContentData1 = 0; mDataContentData1 = 0; // 第一个数据字段初始化为0
mDataContentData3 = ""; mDataContentData3 = ""; // 第三个数据字段初始化为空
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues(); // 创建内容值实例
} }
// 构造函数用于从游标中加载SqlData实例
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; mIsCreate = false; // 设置为非创建状态
loadFromCursor(c); loadFromCursor(c); // 从游标加载数据
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues(); // 创建内容值实例
} }
// 从游标中加载数据到SqlData实例
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN); // 获取数据ID
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); // 获取MIME类型
mDataContent = c.getString(DATA_CONTENT_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN); // 获取内容
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); // 获取第一个数据字段
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); // 获取第三个数据字段
} }
// 设置内容从JSONObject填充数据
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; // 获取ID
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) { // 如果是创建状态或ID不相等
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId); // 更新变化的ID值
} }
mDataId = dataId; mDataId = dataId; // 更新数据ID
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; // 获取MIME类型
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { // 如果是创建状态或MIME类型不同
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); // 更新变化的MIME类型
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType; // 更新MIME类型
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; // 获取内容
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) { // 如果是创建状态或内容不同
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent); // 更新变化的内容
} }
mDataContent = dataContent; mDataContent = dataContent; // 更新内容
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; // 获取第一个数据字段
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) { // 如果是创建状态或字段不同
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1); // 更新变化的第一个数据字段
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1; // 更新第一个数据字段
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; // 获取第三个数据字段
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { // 如果是创建状态或字段不同
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3); // 更新变化的第三个数据字段
} }
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3; // 更新第三个数据字段
} }
// 获取内容返回为JSONObject
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) { // 如果是创建状态
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet"); // 记录错误日志
return null; return null; // 返回null
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建新的JSON对象
// 将数据添加到JSON对象中
js.put(DataColumns.ID, mDataId); js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType); js.put(DataColumns.MIME_TYPE, mDataMimeType);
js.put(DataColumns.CONTENT, mDataContent); js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1); js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3);
return js; return js; // 返回填充的JSON对象
} }
// 提交更改到数据库
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)) { // 如果ID无效且变化值中包含ID
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID); // 移除变化值中的ID
} }
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId); // 添加笔记ID到变化值
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); // 插入数据
try { try {
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1)); // 获取新创建的ID
} catch (NumberFormatException e) { } catch (NumberFormatException e) { // 捕获数字格式异常
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString()); // 记录错误日志
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed"); // 抛出创建失败异常
} }
} else { } else { // 如果不是创建状态
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) { // 如果有变化值
int result = 0; int result = 0; // 定义返回结果
if (!validateVersion) { if (!validateVersion) { // 如果不验证版本
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); // 更新数据
} else { } else { // 如果验证版本
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version) String.valueOf(noteId), String.valueOf(version)
}); }); // 根据版本更新数据
} }
if (result == 0) { if (result == 0) { // 如果没有更新行
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing"); // 记录警告日志
} }
} }
} }
mDiffDataValues.clear(); mDiffDataValues.clear(); // 清空变化的数据值
mIsCreate = false; mIsCreate = false; // 设置为非创建状态
} }
// 获取数据ID
public long getId() { public long getId() {
return mDataId; return mDataId; // 返回数据ID
} }
} }

@ -16,33 +16,35 @@
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager; // 导入相关的类
import android.content.ContentResolver; import android.appwidget.AppWidgetManager; // 用于访问小部件管理器
import android.content.ContentValues; import android.content.ContentResolver; // 用于访问内容提供者
import android.content.Context; import android.content.ContentValues; // 表示一组键值对
import android.database.Cursor; import android.content.Context; // Android的上下文类
import android.net.Uri; import android.database.Cursor; // 用于访问查询结果
import android.util.Log; import android.net.Uri; // 表示统一资源标识符
import android.util.Log; // 日志记录工具
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes; // 引入笔记数据类
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.DataColumns; // 数据列常量
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.data.Notes.NoteColumns; // 笔记列常量
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.gtask.exception.ActionFailureException; // 异常类
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.GTaskStringUtils; // 工具类用于处理GTask字符串
import net.micode.notes.tool.ResourceParser; // 资源解析工具类
import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONArray; // 用于处理JSON数组
import org.json.JSONObject; import org.json.JSONException; // JSON异常处理
import org.json.JSONObject; // 用于处理JSON对象
import java.util.ArrayList;
import java.util.ArrayList; // 动态数组
// SqlNote 类表示笔记的数据库操作
public class SqlNote { public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999; // 无效ID常量
// 定义查询笔记所需的列
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,454 +54,443 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
// 定义各个列的索引常量
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
private Context mContext; // 成员变量定义
private Context mContext; // 上下文对象
private ContentResolver mContentResolver; private ContentResolver mContentResolver; // 内容解析器
private boolean mIsCreate; // 指示是否为新建笔记的标志
private boolean mIsCreate; private long mId; // 笔记ID
private long mAlertDate; // 提醒日期
private long mId; private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建日期
private long mAlertDate; private int mHasAttachment; // 是否有附件
private long mModifiedDate; // 修改日期
private int mBgColorId; private long mParentId; // 父级ID
private String mSnippet; // 笔记摘录
private long mCreatedDate; private int mType; // 笔记类型
private int mWidgetId; // 小部件ID
private int mHasAttachment; private int mWidgetType; // 小部件类型
private long mOriginParent; // 原始父级ID
private long mModifiedDate; private long mVersion; // 版本号
private ContentValues mDiffNoteValues; // 存储变化的笔记值
private long mParentId; private ArrayList<SqlData> mDataList; // 存储笔记数据的列表
private String mSnippet; // 构造函数创建新的SqlNote实例
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context; // 设置上下文
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = true; mIsCreate = true; // 设置为新建状态
mId = INVALID_ID; mId = INVALID_ID; // 设置ID为无效值
mAlertDate = 0; mAlertDate = 0; // 初始化提醒日期
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context); // 获取默认背景ID
mCreatedDate = System.currentTimeMillis(); mCreatedDate = System.currentTimeMillis(); // 获取当前时间作为创建日期
mHasAttachment = 0; mHasAttachment = 0; // 初始化无附件
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis(); // 获取当前时间作为修改日期
mParentId = 0; mParentId = 0; // 初始化父级ID
mSnippet = ""; mSnippet = ""; // 初始化笔记摘录
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE; // 默认类型为笔记
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 设置小部件ID为无效值
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 设置小部件类型为无效值
mOriginParent = 0; mOriginParent = 0; // 初始化原始父级ID
mVersion = 0; mVersion = 0; // 初始化版本号
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化变化的笔记值
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化笔记数据列表
} }
// 构造函数根据Cursor创建SqlNote实例
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context; // 设置上下文
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; mIsCreate = false; // 设置为非新建状态
loadFromCursor(c); loadFromCursor(c); // 从Cursor加载数据
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化笔记数据列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果类型为笔记
loadDataContent(); loadDataContent(); // 加载数据内容
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化变化的笔记值
} }
// 构造函数根据ID创建SqlNote实例
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context; // 设置上下文
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver(); // 获取内容解析器
mIsCreate = false; mIsCreate = false; // 设置为非新建状态
loadFromCursor(id); loadFromCursor(id); // 根据ID加载数据
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>(); // 初始化笔记数据列表
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE) // 如果类型为笔记
loadDataContent(); loadDataContent(); // 加载数据内容
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues(); // 初始化变化的笔记值
} }
// 从Cursor中加载笔记数据
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null; // 初始化Cursor
try { try {
// 查询笔记数据
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(id) String.valueOf(id) // 根据ID查询
}, null); }, null);
if (c != null) { if (c != null) { // 如果Cursor不为空
c.moveToNext(); c.moveToNext(); // 移动到下一行
loadFromCursor(c); loadFromCursor(c); // 从Cursor加载数据
} else { } else {
Log.w(TAG, "loadFromCursor: cursor = null"); Log.w(TAG, "loadFromCursor: cursor = null"); // 如果Cursor为空记录警告日志
} }
} finally { } finally {
if (c != null) if (c != null) // 关闭Cursor
c.close(); c.close();
} }
} }
// 从Cursor中加载笔记数据
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; // 初始化Cursor
mDataList.clear(); mDataList.clear(); // 清空数据列表
try { try {
// 查询笔记数据内容
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] {
String.valueOf(mId) String.valueOf(mId) // 根据笔记ID查询
}, null); }, null);
if (c != null) { if (c != null) { // 如果Cursor不为空
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; // 返回
} }
// 遍历Cursor中的数据
while (c.moveToNext()) { while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c); SqlData data = new SqlData(mContext, c); // 创建SqlData实例
mDataList.add(data); mDataList.add(data); // 添加到数据列表
} }
} else { } else {
Log.w(TAG, "loadDataContent: cursor = null"); Log.w(TAG, "loadDataContent: cursor = null"); // 如果Cursor为空记录警告日志
} }
} finally { } finally {
if (c != null) if (c != null) // 关闭Cursor
c.close(); c.close();
} }
} }
// 设置笔记内容
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记对象
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { // 如果是系统文件夹
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder"); // 记录警告日志
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { // 如果是文件夹
// for folder we can only update the snnipet and type // 只更新摘录和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : ""; // 获取摘录
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); // 更新摘录
} }
mSnippet = snippet; mSnippet = snippet; // 设置摘录
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE; // 获取类型
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type); // 更新类型
} }
mType = type; mType = type; // 设置类型
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { // 如果是笔记
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取数据数组
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; // 获取ID
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id); mDiffNoteValues.put(NoteColumns.ID, id); // 更新ID
} }
mId = id; mId = id; // 设置ID
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0; .getLong(NoteColumns.ALERTED_DATE) : 0; // 获取提醒日期
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
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 int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); // 获取背景颜色ID
if (mIsCreate || mBgColorId != bgColorId) { if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); // 更新背景颜色ID
} }
mBgColorId = bgColorId; mBgColorId = bgColorId; // 设置背景颜色ID
long createDate = note.has(NoteColumns.CREATED_DATE) ? note long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); // 获取创建日期
if (mIsCreate || mCreatedDate != createDate) { if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); // 更新创建日期
} }
mCreatedDate = createDate; mCreatedDate = createDate; // 设置创建日期
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0; .getInt(NoteColumns.HAS_ATTACHMENT) : 0; // 获取附件标志
if (mIsCreate || mHasAttachment != hasAttachment) { if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); // 更新附件标志
} }
mHasAttachment = hasAttachment; mHasAttachment = hasAttachment; // 设置附件标志
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); // 获取修改日期
if (mIsCreate || mModifiedDate != modifiedDate) { if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); // 更新修改日期
} }
mModifiedDate = modifiedDate; mModifiedDate = modifiedDate; // 设置修改日期
long parentId = note.has(NoteColumns.PARENT_ID) ? note long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0; .getLong(NoteColumns.PARENT_ID) : 0; // 获取父级ID
if (mIsCreate || mParentId != parentId) { if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); // 更新父级ID
} }
mParentId = parentId; mParentId = parentId; // 设置父级ID
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : ""; // 获取摘录
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); // 更新摘录
} }
mSnippet = snippet; mSnippet = snippet; // 设置摘录
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE; // 获取类型
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type); // 更新类型
} }
mType = type; mType = type; // 设置类型
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID; : AppWidgetManager.INVALID_APPWIDGET_ID; // 获取小部件ID
if (mIsCreate || mWidgetId != widgetId) { if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); // 更新小部件ID
} }
mWidgetId = widgetId; mWidgetId = widgetId; // 设置小部件ID
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; // 获取小部件类型
if (mIsCreate || mWidgetType != widgetType) { if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); // 更新小部件类型
} }
mWidgetType = widgetType; mWidgetType = widgetType; // 设置小部件类型
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; // 获取原始父级ID
if (mIsCreate || mOriginParent != originParent) { if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); // 更新原始父级ID
} }
mOriginParent = originParent; mOriginParent = originParent; // 设置原始父级ID
// 加载数据数组中的每一项
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); // 获取JSON数据对象
SqlData sqlData = null; SqlData sqlData = null; // 初始化SqlData对象
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) { // 如果数据中有ID
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID); // 获取数据ID
for (SqlData temp : mDataList) { for (SqlData temp : mDataList) { // 查找对应的SqlData实例
if (dataId == temp.getId()) { if (dataId == temp.getId()) {
sqlData = temp; sqlData = temp; // 找到对应的SqlData
} }
} }
} }
if (sqlData == null) { if (sqlData == null) { // 如果没有找到对应的SqlData
sqlData = new SqlData(mContext); sqlData = new SqlData(mContext); // 创建新的SqlData实例
mDataList.add(sqlData); mDataList.add(sqlData); // 添加到数据列表
} }
sqlData.setContent(data); sqlData.setContent(data); // 设置SqlData内容
} }
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕获JSON异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈信息
return false; return false; // 返回false表示失败
} }
return true; return true; // 返回true表示成功
} }
// 获取笔记内容
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建新的JSON对象
if (mIsCreate) { if (mIsCreate) { // 如果是新建状态
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet"); // 记录错误日志
return null; return null; // 返回null
} }
JSONObject note = new JSONObject(); JSONObject note = new JSONObject(); // 创建笔记对象
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果类型为笔记
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId); // 添加ID
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ALERTED_DATE, mAlertDate); // 添加提醒日期
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.BG_COLOR_ID, mBgColorId); // 添加背景颜色ID
note.put(NoteColumns.CREATED_DATE, mCreatedDate); note.put(NoteColumns.CREATED_DATE, mCreatedDate); // 添加创建日期
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); // 添加附件标志
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); // 添加修改日期
note.put(NoteColumns.PARENT_ID, mParentId); note.put(NoteColumns.PARENT_ID, mParentId); // 添加父级ID
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet); // 添加摘录
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType); // 添加笔记类型
note.put(NoteColumns.WIDGET_ID, mWidgetId); note.put(NoteColumns.WIDGET_ID, mWidgetId); // 添加小部件ID
note.put(NoteColumns.WIDGET_TYPE, mWidgetType); note.put(NoteColumns.WIDGET_TYPE, mWidgetType); // 添加小部件类型
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); // 添加原始父级ID
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将笔记对象放入结果JSON
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray(); // 创建数据数组
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) { // 遍历数据列表
JSONObject data = sqlData.getContent(); JSONObject data = sqlData.getContent(); // 获取数据的JSON对象
if (data != null) { if (data != null) { // 如果数据不为空
dataArray.put(data); dataArray.put(data); // 添加到数组
} }
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 将数据数组放入结果JSON
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { // 如果是文件夹或系统类型
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId); // 添加ID
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType); // 添加类型
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet); // 添加摘录
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将笔记对象放入结果JSON
} }
return js; return js; // 返回结果JSON对象
} catch (JSONException e) { } catch (JSONException e) { // 捕获JSON异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈信息
} }
return null; return null; // 返回null
} }
// 设置父级ID
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id; // 设置父级ID
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id); // 更新变化的值
} }
// 设置GTask Id
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); // 更新变化的值
} }
// 设置同步ID
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); // 更新变化的值
} }
// 重置本地修改标志
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); // 更新变化的值
} }
// 获取笔记ID
public long getId() { public long getId() {
return mId; return mId; // 返回ID
} }
// 获取父级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)) {
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID); // 移除ID
} }
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); // 插入笔记
try { try {
mId = Long.valueOf(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1)); // 获取笔记ID
} catch (NumberFormatException e) { } catch (NumberFormatException e) { // 捕获数字格式异常
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString()); // 记录错误日志
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed"); // 抛出创建失败异常
} }
if (mId == 0) { if (mId == 0) { // 如果ID为0表示创建失败
throw new IllegalStateException("Create thread id failed"); throw new IllegalStateException("Create thread id failed"); // 抛出异常
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果类型为笔记
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1); sqlData.commit(mId, false, -1); // 提交每个SqlData
} }
} }
} 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"); // 抛出异常
} }
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) { // 如果有变化的值
mVersion ++; mVersion++; // 增加版本号
int result = 0; int result = 0; // 结果初始化
if (!validateVersion) { if (!validateVersion) { // 如果不需要验证版本
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId) String.valueOf(mId) // 根据ID更新
}); });
} else { } else { // 需要验证版本
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] {
String.valueOf(mId), String.valueOf(mVersion) String.valueOf(mId), String.valueOf(mVersion) // 根据ID和版本更新
}); });
} }
if (result == 0) { if (result == 0) { // 如果没有更新,可能是同步中
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing"); // 记录警告日志
} }
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) { // 如果类型为笔记
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) { // 提交每个SqlData
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion);
} }
} }
} }
// refresh local info // 刷新本地信息
loadFromCursor(mId); loadFromCursor(mId); // 重新加载笔记数据
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent(); // 重新加载数据内容
mDiffNoteValues.clear(); mDiffNoteValues.clear(); // 清空变化的值
mIsCreate = false; mIsCreate = false; // 设置为非新建状态
} }
} }

@ -14,338 +14,355 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data; // 声明该类属于 net.micode.notes.gtask.data 包
import android.database.Cursor; import android.database.Cursor; // 导入 Cursor 类,用于操作数据库结果集
import android.text.TextUtils; import android.text.TextUtils; // 导入 TextUtils 类,用于处理文本操作
import android.util.Log; import android.util.Log; // 导入 Log 类,用于日志记录
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes; // 导入 Notes 类,用于引用笔记相关的常量和方法
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; // 导入笔记列常量
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException; // 导入自定义异常类
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils; // 导入工具类,用于处理任务字符串
import org.json.JSONArray; import org.json.JSONArray; // 导入 JSONArray 类,用于处理 JSON 数组
import org.json.JSONException; import org.json.JSONException; // 导入 JSONException 类,用于处理 JSON 异常
import org.json.JSONObject; import org.json.JSONObject; // 导入 JSONObject 类,用于处理 JSON 对象
// 定义 Task 类,继承自 Node 类
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName(); // 定义日志标签
private boolean mCompleted; private boolean mCompleted; // 任务完成状态
private String mNotes; private String mNotes; // 任务备注
private JSONObject mMetaInfo; private JSONObject mMetaInfo; // 任务的元信息JSON 格式)
private Task mPriorSibling; private Task mPriorSibling; // 任务的前一个兄弟任务
private TaskList mParent; private TaskList mParent; // 任务的父任务列表
// 构造函数,初始化任务的状态
public Task() { public Task() {
super(); super(); // 调用父类构造函数
mCompleted = false; mCompleted = false; // 默认未完成
mNotes = null; mNotes = null; // 默认无备注
mPriorSibling = null; mPriorSibling = null; // 默认无前一个兄弟任务
mParent = null; mParent = null; // 默认无父任务列表
mMetaInfo = null; mMetaInfo = null; // 默认无元信息
} }
// 获取创建任务的操作 JSON 对象
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建 JSON 对象
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);
// action_id // action_id - 设置操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.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));
// entity_delta // entity_delta - 创建任务的实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者 ID初始化为 null
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK); GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型为任务
if (getNotes() != null) { if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将实体数据加入 JSON 对象
// parent_id // parent_id - 设置父任务 ID
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// 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);
// list_id // list_id - 设置任务列表 ID
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// prior_sibling_id // prior_sibling_id - 设置前一个兄弟任务 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());
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("fail to generate task-create jsonobject"); throw new ActionFailureException("fail to generate task-create jsonobject"); // 抛出自定义异常
} }
return js; return js; // 返回创建操作的 JSON 对象
} }
// 获取更新任务的操作 JSON 对象
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建 JSON 对象
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);
// action_id // action_id - 设置操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // id - 设置任务 ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // entity_delta - 更新的实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
if (getNotes() != null) { if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注
} }
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 任务删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将实体数据加入 JSON 对象
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject"); // 抛出自定义异常
} }
return js; return js; // 返回更新操作的 JSON 对象
} }
// 根据远程 JSON 设置任务内容
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) { // 如果 JSON 对象不为空
try { try {
// id // id - 获取任务 ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // last_modified - 获取最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // name - 获取任务名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
// notes // notes - 获取任务备注
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
} }
// deleted // deleted - 获取任务删除状态
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// completed // completed - 获取任务完成状态
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("fail to get task content from jsonobject"); throw new ActionFailureException("fail to get task content from jsonobject"); // 抛出自定义异常
} }
} }
} }
// 根据本地 JSON 设置任务内容
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) { // 检查 JSON 对象是否包含必要字段
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); // 记录警告日志
} }
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记信息
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取数据数组
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { // 检查笔记类型
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type"); // 记录错误日志
return; return; // 退出
} }
// 遍历数据数组,寻找内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT)); // 设置任务名称
break; break; // 找到后退出循环
} }
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈跟踪
} }
} }
// 从任务内容生成本地 JSON
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 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;
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建 JSON 对象
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); // 将数据数组加入 JSON 对象
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); // 将笔记对象加入 JSON 对象
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);
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; // 返回元信息 JSON 对象
} }
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); e.printStackTrace(); // 打印堆栈跟踪
return null; return null; // 返回空
} }
} }
// 设置任务的元信息
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) { // 检查元数据和笔记是否为空
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes()); // 将笔记设置为元信息的 JSON 对象
} catch (JSONException e) { } catch (JSONException e) { // 捕获 JSON 异常
Log.w(TAG, e.toString()); Log.w(TAG, e.toString()); // 记录警告日志
mMetaInfo = null; mMetaInfo = null; // 将元信息设置为 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) { // 检查笔记信息是否为 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)) { // 检查笔记 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; // 返回父任务列表
} }
} }

@ -16,156 +16,169 @@
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
// 导入所需的类
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
// TaskList类继承自Node类表示一个任务列表
public class TaskList extends Node { public class TaskList extends Node {
// 定义日志标签
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName();
// 任务列表的索引
private int mIndex; private int mIndex;
// 存储子任务的列表
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
// TaskList的构造函数初始化子任务列表和索引
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1; // 默认索引为1
} }
// 获取创建任务列表的JSON对象
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个新的JSON对象
try { try {
// action_type // 设置动作类型为创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // 设置动作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // 设置索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta // 创建实体的变化对象
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 设置名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将实体变化对象放入主对象中
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject"); throw new ActionFailureException("fail to generate tasklist-create jsonobject"); // 抛出异常
} }
return js; return js; // 返回生成的JSON对象
} }
// 获取更新任务列表的JSON对象
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个新的JSON对象
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 // 创建实体的变化对象
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 设置名称
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 设置删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); // 将实体变化对象放入主对象中
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); throw new ActionFailureException("fail to generate tasklist-update jsonobject"); // 抛出异常
} }
return js; return js; // 返回生成的JSON对象
} }
// 根据远程JSON设置任务列表的内容
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // 设置任务列表ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // 设置最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // 设置名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject"); throw new ActionFailureException("fail to get tasklist content from jsonobject"); // 抛出异常
} }
} }
} }
// 根据本地JSON设置任务列表的内容
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// 检查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 avaiable"); // 发出警告日志
} }
try { try {
// 获取任务列表的文件夹对象
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 根据文件夹类型设置名称
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); 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)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE); + GTaskStringUtils.FOLDER_CALL_NOTE);
else else
Log.e(TAG, "invalid system folder"); Log.e(TAG, "invalid system folder"); // 打印错误日志
} else { } else {
Log.e(TAG, "error type"); Log.e(TAG, "error type"); // 打印错误日志
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString()); // 打印错误日志
e.printStackTrace(); e.printStackTrace();
} }
} }
// 从内容生成本地JSON对象
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject(); // 创建一个新的JSON对象
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject(); // 创建文件夹的JSON对象
String folderName = getName(); String folderName = getName(); // 获取任务列表名称
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length()); // 去掉前缀
// 设置文件夹名称和类型
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
@ -173,171 +186,183 @@ public class TaskList extends Node {
else else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); js.put(GTaskStringUtils.META_HEAD_NOTE, folder); // 将文件夹对象放入主对象中
return js; return js; // 返回生成的JSON对象
} 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 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 // 校验任务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; // 出现异常时返回错误状态
} }
// 获取子任务数量
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size(); // 返回子任务列表大小
} }
// 添加子任务
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task); // 尝试添加任务
if (ret) { if (ret) {
// need to set prior sibling and parent // 需要设置前一个兄弟任务和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this); // 设置父任务
} }
} }
return ret; return ret; // 返回添加结果
} }
// 根据索引添加子任务
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index"); // 打印错误日志
return false; return false; // 返回失败
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task); // 查找任务在列表中的位置
if (task != null && pos == -1) { if (task != null && pos == -1) {
mChildren.add(index, task); mChildren.add(index, task); // 根据索引添加任务
// update the task list // 更新任务列表
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0)
preTask = mChildren.get(index - 1); preTask = mChildren.get(index - 1); // 获取前一个任务
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1); // 获取后一个任务
task.setPriorSibling(preTask); task.setPriorSibling(preTask); // 设置前一个兄弟任务
if (afterTask != null) if (afterTask != null)
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task); // 设置后一个兄弟任务
} }
return true; return true; // 返回成功
} }
// 移除子任务
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task); // 查找任务在列表中的位置
if (index != -1) { if (index != -1) {
ret = mChildren.remove(task); ret = mChildren.remove(task); // 尝试移除任务
if (ret) { if (ret) {
// reset prior sibling and parent // 重置前一个兄弟任务和父任务
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(null); task.setParent(null);
// update the task list // 更新任务列表
if (index != mChildren.size()) { if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1)); // 更新前一个兄弟任务
} }
} }
} }
return ret; return ret; // 返回移除结果
} }
// 移动子任务
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index"); // 打印错误日志
return false; return false; // 返回失败
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task); // 查找任务在列表中的位置
if (pos == -1) { if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list"); // 打印错误日志
return false; return false; // 返回失败
} }
if (pos == index) if (pos == index)
return true; return true; // 位置不变返回成功
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index)); // 移除并重新添加任务
} }
// 根据GID查找子任务
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)) {
return t; return t; // 找到任务返回
} }
} }
return null; return null; // 未找到返回null
} }
// 获取子任务索引
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task); // 返回任务在列表中的位置
} }
// 根据索引获取子任务
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index"); // 打印错误日志
return null; return null; // 返回null
} }
return mChildren.get(index); return mChildren.get(index); // 返回任务
} }
// 根据GID获取子任务
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))
return task; return task; // 找到任务返回
} }
return null; return null; // 未找到返回null
} }
// 获取子任务列表
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren; // 返回子任务列表
} }
// 设置索引
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index; // 设置任务列表索引
} }
// 获取索引
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex; // 返回任务列表索引
} }
} }

@ -20,26 +20,53 @@
* // 指出根据许可证分发的软件是“按现状”提供的,没有明示或暗示的任何保证或条件 * // 指出根据许可证分发的软件是“按现状”提供的,没有明示或暗示的任何保证或条件
*/ */
<<<<<<< HEAD
package net.micode.notes.gtask.exception; // 定义该类所在的包
=======
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
// 指定该Java文件的包路径 // 指定该Java文件的包路径
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
/**
* ActionFailureException
*
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
<<<<<<< HEAD
private static final long serialVersionUID = 4425249765923293627L; // 序列化版本UID用于序列化机制
=======
// 声明一个名为ActionFailureException的公共类该类继承自RuntimeException // 声明一个名为ActionFailureException的公共类该类继承自RuntimeException
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
// 声明一个常量serialVersionUID用于序列化时保持版本的兼容性 // 声明一个常量serialVersionUID用于序列化时保持版本的兼容性
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
// 默认构造函数
public ActionFailureException() { public ActionFailureException() {
<<<<<<< HEAD
super(); // 调用父类的构造函数
=======
super(); super();
// 默认构造函数调用父类RuntimeException的无参构造函数 // 默认构造函数调用父类RuntimeException的无参构造函数
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} }
// 带有错误信息的构造函数
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
<<<<<<< HEAD
super(paramString); // 调用父类构造函数,传递错误信息
=======
super(paramString); super(paramString);
// 带有一个字符串参数的构造函数调用父类RuntimeException的带字符串参数的构造函数 // 带有一个字符串参数的构造函数调用父类RuntimeException的带字符串参数的构造函数
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} }
// 带有错误信息和根本原因的构造函数
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
<<<<<<< HEAD
super(paramString, paramThrowable); // 调用父类构造函数,传递错误信息和原因
=======
super(paramString, paramThrowable); super(paramString, paramThrowable);
// 带有一个字符串和一个Throwable参数的构造函数调用父类RuntimeException的相应构造函数 // 带有一个字符串和一个Throwable参数的构造函数调用父类RuntimeException的相应构造函数
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} }
} }

@ -14,6 +14,19 @@
* limitations under the License. * limitations under the License.
*/ */
<<<<<<< HEAD
package net.micode.notes.gtask.exception; // 定义包路径
/**
* NetworkFailureException
*
*/
public class NetworkFailureException extends Exception {
// 序列版本UID用于序列化
private static final long serialVersionUID = 2107610287180234136L;
// 默认构造函数
=======
// 该类所属的包名表明这个类是位于net.micode.notes.gtask.exception包下用于存放相关的异常类 // 该类所属的包名表明这个类是位于net.micode.notes.gtask.exception包下用于存放相关的异常类
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
@ -23,20 +36,33 @@ public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
// 无参构造函数调用父类Exception的无参构造函数用于创建一个默认的NetworkFailureException实例不附带任何详细信息 // 无参构造函数调用父类Exception的无参构造函数用于创建一个默认的NetworkFailureException实例不附带任何详细信息
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public NetworkFailureException() { public NetworkFailureException() {
super(); super(); // 调用父类的构造函数
} }
<<<<<<< HEAD
// 带有消息的构造函数
=======
// 带有一个字符串参数的构造函数,该字符串参数通常用于传递异常相关的详细描述信息, // 带有一个字符串参数的构造函数,该字符串参数通常用于传递异常相关的详细描述信息,
// 调用父类Exception的对应构造函数将传入的字符串作为异常的详细消息 // 调用父类Exception的对应构造函数将传入的字符串作为异常的详细消息
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString); // 调用父类的构造函数,传入异常消息
} }
<<<<<<< HEAD
// 带有消息和原因的构造函数
=======
// 带有一个字符串参数和一个Throwable参数的构造函数字符串参数用于传递异常相关的详细描述信息 // 带有一个字符串参数和一个Throwable参数的构造函数字符串参数用于传递异常相关的详细描述信息
// Throwable参数通常用于关联引起当前异常的其他异常例如底层网络库抛出的原始异常等 // Throwable参数通常用于关联引起当前异常的其他异常例如底层网络库抛出的原始异常等
// 调用父类Exception的对应构造函数进行初始化将两个参数传递给父类构造函数 // 调用父类Exception的对应构造函数进行初始化将两个参数传递给父类构造函数
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable); // 调用父类的构造函数,传入异常消息和原因
} }
} <<<<<<< HEAD
}
=======
}
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae

@ -12,19 +12,27 @@
* *
*/ */
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote; // 定义包名
import android.app.Notification; import android.app.Notification; // 导入通知相关类
import android.app.NotificationManager; import android.app.NotificationManager; // 导入通知管理类
import android.app.PendingIntent; import android.app.PendingIntent; // 导入待处理意图类
import android.content.Context; import android.content.Context; // 导入上下文类
import android.content.Intent; import android.content.Intent; // 导入意图类
import android.os.AsyncTask; import android.os.AsyncTask; // 导入异步任务类
import net.micode.notes.R; <<<<<<< HEAD
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.R; // 导入资源文件
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesListActivity; // 导入笔记列表活动
import net.micode.notes.ui.NotesPreferenceActivity; // 导入笔记偏好设置活动
// 定义GTaskASyncTask类继承自AsyncTask
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 定义用于同步通知的ID
// 定义完成监听器接口
=======
// 异步任务类用于执行GTask同步操作 // 异步任务类用于执行GTask同步操作
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
@ -32,10 +40,19 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义完成监听接口 // 定义完成监听接口
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete(); // 监听完成事件
} }
<<<<<<< HEAD
private Context mContext; // 上下文
private NotificationManager mNotifiManager; // 通知管理器
private GTaskManager mTaskManager; // 任务管理器
private OnCompleteListener mOnCompleteListener; // 完成监听器
// 构造函数,初始化上下文和监听器
=======
// 上下文对象 // 上下文对象
private Context mContext; private Context mContext;
// 通知管理器 // 通知管理器
@ -46,23 +63,35 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
// 构造函数,初始化上下文、通知管理器、任务管理器和完成监听器 // 构造函数,初始化上下文、通知管理器、任务管理器和完成监听器
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context; // 设置上下文
mOnCompleteListener = listener; mOnCompleteListener = listener; // 设置完成监听器
mNotifiManager = (NotificationManager) mContext mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE); .getSystemService(Context.NOTIFICATION_SERVICE); // 获取通知服务
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance(); // 获取任务管理器实例
} }
<<<<<<< HEAD
// 取消同步
=======
// 取消同步的方法 // 取消同步的方法
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync(); // 调用任务管理器的取消同步方法
} }
<<<<<<< HEAD
// 发布进度
public void publishProgess(String message) {
publishProgress(new String[] {
message // 发布进度消息
=======
// 发布进度消息的方法 // 发布进度消息的方法
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
}); });
} }
@ -71,6 +100,16 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 创建通知对象 // 创建通知对象
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
<<<<<<< HEAD
notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光效果
notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置自动取消标志
PendingIntent pendingIntent; // 定义待处理意图
// 根据tickerId判断要跳转的活动
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); // 启动偏好设置活动
=======
notification.defaults = Notification.DEFAULT_LIGHTS; notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL; notification.flags = Notification.FLAG_AUTO_CANCEL;
// 根据tickerId创建不同的PendingIntent // 根据tickerId创建不同的PendingIntent
@ -78,29 +117,36 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} else { } else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0); // 启动笔记列表活动
} }
// 设置通知的最新事件信息 // 设置通知的最新事件信息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); pendingIntent);
<<<<<<< HEAD
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // 发送通知
=======
// 发送通知 // 发送通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} }
// 后台执行同步操作的方法 // 后台执行同步操作的方法
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
// 发布登录进度
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this); // 调用同步方法并返回状态
} }
// 更新进度的方法 // 更新进度的方法
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]); // 显示同步进度通知
// 如果上下文是GTaskSyncService则广播进度消息
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
@ -109,25 +155,32 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 执行完毕后的方法 // 执行完毕后的方法
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
<<<<<<< HEAD
// 根据同步结果显示相应的通知
=======
// 根据结果展示不同的通知 // 根据结果展示不同的通知
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); // 记录最后同步时间
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); // 显示网络错误通知
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); // 显示内部错误通知
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled)); // 显示取消同步通知
} }
<<<<<<< HEAD
// 如果存在完成监听器则在新线程中调用其onComplete方法
=======
// 如果存在完成监听器,则通知监听器任务完成 // 如果存在完成监听器,则通知监听器任务完成
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete(); // 调用完成监听器的onComplete方法
} }
}).start(); }).start();
} }

@ -1,62 +1,119 @@
<<<<<<< HEAD
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 定义包名
=======
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.accounts.Account; // 导入相关类和接口
import android.accounts.AccountManager; import android.accounts.Account; // 引入账户类
import android.accounts.AccountManagerFuture; import android.accounts.AccountManager; // 引入账户管理类
import android.app.Activity; import android.accounts.AccountManagerFuture; // 引入账户管理未来对象类
import android.os.Bundle; import android.app.Activity; // 引入活动类
import android.text.TextUtils; import android.os.Bundle; // 引入包类
import android.util.Log; import android.text.TextUtils; // 引入文本工具类
import android.util.Log; // 引入日志工具类
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.Task; // 导入自定义数据模型和异常处理类
import net.micode.notes.gtask.data.TaskList; import net.micode.notes.gtask.data.Node; // 引入节点数据模型
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.data.Task; // 引入任务数据模型
import net.micode.notes.gtask.exception.NetworkFailureException; import net.micode.notes.gtask.data.TaskList; // 引入任务列表数据模型
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.gtask.exception.ActionFailureException; // 引入动作失败异常
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.gtask.exception.NetworkFailureException; // 引入网络失败异常
import net.micode.notes.tool.GTaskStringUtils; // 引入GTask字符串工具类
import org.apache.http.HttpEntity; import net.micode.notes.ui.NotesPreferenceActivity; // 引入笔记偏好活动类
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException; // 导入Apache HttpClient相关的类
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.HttpEntity; // 引入HTTP实体类
import org.apache.http.client.methods.HttpGet; import org.apache.http.HttpResponse; // 引入HTTP响应类
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.ClientProtocolException; // 引入客户端协议异常
import org.apache.http.cookie.Cookie; import org.apache.http.client.entity.UrlEncodedFormEntity; // 引入URL编码表单实体类
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.client.methods.HttpGet; // 引入HTTP GET请求类
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.client.methods.HttpPost; // 引入HTTP POST请求类
import org.apache.http.message.BasicNameValuePair; import org.apache.http.cookie.Cookie; // 引入Cookie类
import org.apache.http.params.BasicHttpParams; import org.apache.http.impl.client.BasicCookieStore; // 引入基本Cookie存储类
import org.apache.http.params.HttpConnectionParams; import org.apache.http.impl.client.DefaultHttpClient; // 引入默认HTTP客户端类
import org.apache.http.params.HttpParams; import org.apache.http.message.BasicNameValuePair; // 引入基本名称值对类
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.BasicHttpParams; // 引入基本HTTP参数类
import org.json.JSONArray; import org.apache.http.params.HttpConnectionParams; // 引入HTTP连接参数类
import org.json.JSONException; import org.apache.http.params.HttpParams; // 引入HTTP参数类
import org.json.JSONObject;
// 导入JSON相关的类
import java.io.BufferedReader; import org.json.JSONArray; // 引入JSON数组类
import java.io.IOException; import org.json.JSONException; // 引入JSON异常类
import java.io.InputStream; import org.json.JSONObject; // 引入JSON对象类
import java.io.InputStreamReader;
import java.util.LinkedList; <<<<<<< HEAD
import java.util.List; // 引入JDK类
import java.util.zip.GZIPInputStream; import java.io.BufferedReader; // 引入缓冲读取器类
import java.util.zip.Inflater; import java.io.IOException; // 引入IO异常类
import java.util.zip.InflaterInputStream; import java.io.InputStream; // 引入输入流类
import java.io.InputStreamReader; // 引入输入流读取器类
import java.util.LinkedList; // 引入链表类
import java.util.List; // 引入列表类
import java.util.zip.GZIPInputStream; // 引入GZIP输入流类
import java.util.zip.Inflater; // 引入解压缩类
import java.util.zip.InflaterInputStream; // 引入解压缩输入流类
// GTaskClient类负责处理与Google任务(GTask)的通信
=======
// GTaskClient类用于与Google Tasks进行交互实现诸如登录、任务和任务列表的创建、更新、移动、删除以及获取相关数据等功能 // GTaskClient类用于与Google Tasks进行交互实现诸如登录、任务和任务列表的创建、更新、移动、删除以及获取相关数据等功能
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public class GTaskClient { public class GTaskClient {
// 日志标签
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
<<<<<<< HEAD
// Google任务相关的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
=======
// Google Tasks的基础URL // Google Tasks的基础URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 用于获取Google Tasks数据的URL // 用于获取Google Tasks数据的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// 用于向Google Tasks发送POST请求的URL // 用于向Google Tasks发送POST请求的URL
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
<<<<<<< HEAD
// HTTP客户端
private DefaultHttpClient mHttpClient;
// GET和POST请求的URL
private String mGetUrl;
private String mPostUrl;
// 客户端版本和登录状态相关的字段
private long mClientVersion;
private boolean mLoggedin;
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
// 更新数组
private JSONArray mUpdateArray;
// 私有构造函数,初始化类的成员变量
=======
// 用于发送HTTP请求的HttpClient对象 // 用于发送HTTP请求的HttpClient对象
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
// 获取数据的具体URL // 获取数据的具体URL
@ -77,6 +134,7 @@ public class GTaskClient {
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
// 私有构造函数,初始化相关成员变量 // 私有构造函数,初始化相关成员变量
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -89,7 +147,11 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
<<<<<<< HEAD
// 获取单例实例
=======
// 获取GTaskClient的单例实例 // 获取GTaskClient的单例实例
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -97,62 +159,96 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
<<<<<<< HEAD
// 登录方法
public boolean login(Activity activity) {
// 假设cookie在5分钟后过期
=======
// 执行登录操作 // 执行登录操作
public boolean login(Activity activity) { public boolean login(Activity activity) {
// 假设Cookie在5分钟后过期若距离上次登录时间超过5分钟则需要重新登录 // 假设Cookie在5分钟后过期若距离上次登录时间超过5分钟则需要重新登录
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false; // 如果超时,设置未登录
} }
<<<<<<< HEAD
// 如果账户切换,需要重新登录
if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
mLoggedin = false; // 账户切换,重新登录
=======
// 如果已登录,但当前账户与设置中的同步账户不一致,也需要重新登录 // 如果已登录,但当前账户与设置中的同步账户不一致,也需要重新登录
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} }
// 若已经登录,无需再次登录
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in");
return true; return true;
} }
<<<<<<< HEAD
mLastLoginTime = System.currentTimeMillis(); // 更新最后登录时间
String authToken = loginGoogleAccount(activity, false); // 获取Google账户的认证令牌
=======
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();
// 登录Google账户获取授权令牌 // 登录Google账户获取授权令牌
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false; // 登录失败
} }
<<<<<<< HEAD
// 如果为自定义域,则尝试进行登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
=======
// 如果账户不是以gmail.com或googlemail.com结尾可能是自定义域名则使用自定义域名相关的URL进行登录 // 如果账户不是以gmail.com或googlemail.com结尾可能是自定义域名则使用自定义域名相关的URL进行登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; mGetUrl = url.toString() + "ig"; // 更新GET请求的URL
mPostUrl = url.toString() + "r/ig"; mPostUrl = url.toString() + "r/ig"; // 更新POST请求的URL
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true; mLoggedin = true; // 登录成功
} }
} }
<<<<<<< HEAD
// 尝试以 Google 官方 URL 登录
=======
// 如果使用自定义域名登录失败则尝试使用Google官方URL登录 // 如果使用自定义域名登录失败则尝试使用Google官方URL登录
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL; // 恢复默认的GET请求URL
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL; // 恢复默认的POST请求URL
if (!tryToLoginGtask(activity, authToken)) { if (!tryToLoginGtask(activity, authToken)) {
return false; return false; // 登录失败
} }
} }
mLoggedin = true; mLoggedin = true; // 设置为已登录
return true; return true;
} }
<<<<<<< HEAD
// 获取Google账户认证令牌的方法
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity); // 获取账户管理器
Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取Google账户
=======
// 登录Google账户获取授权令牌 // 登录Google账户获取授权令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
@ -160,15 +256,23 @@ public class GTaskClient {
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
// 获取所有Google类型的账户 // 获取所有Google类型的账户
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
// 如果没有可用的Google账户日志记录并返回null
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
return null; return null;
} }
<<<<<<< HEAD
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); // 获取同步的账户名
=======
// 获取设置中的同步账户名称 // 获取设置中的同步账户名称
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
Account account = null; Account account = null;
// 找到设置中与账户名匹配的账户
for (Account a : accounts) { for (Account a : accounts) {
if (a.name.equals(accountName)) { if (a.name.equals(accountName)) {
account = a; account = a;
@ -176,49 +280,78 @@ public class GTaskClient {
} }
} }
if (account != null) { if (account != null) {
mAccount = account; mAccount = account; // 设置账户
} else { } else {
Log.e(TAG, "unable to get an account with the same name in the settings"); Log.e(TAG, "unable to get an account with the same name in the settings");
return null; return null; // 找不到匹配账户返回null
} }
<<<<<<< HEAD
// 获取认证令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null);
=======
// 获取授权令牌 // 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取结果
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); // 读取令牌
// 如果需要无效化令牌,则重新获取
if (invalidateToken) { if (invalidateToken) {
// 如果需要使令牌失效,则先失效再重新获取 // 如果需要使令牌失效,则先失效再重新获取
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false); // 递归调用获取新令牌
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "get auth token failed"); Log.e(TAG, "get auth token failed");
authToken = null; authToken = null; // 获取token失败
} }
return authToken; return authToken; // 返回令牌
} }
<<<<<<< HEAD
// 尝试登录到GTask
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// 如果认证令牌过期,则无效化并尝试重新登录
=======
// 尝试登录Google Tasks // 尝试登录Google Tasks
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// 如果登录失败可能是授权令牌过期先使令牌失效再重新尝试登录Google账户获取新令牌然后再次登录Google Tasks // 如果登录失败可能是授权令牌过期先使令牌失效再重新尝试登录Google账户获取新令牌然后再次登录Google Tasks
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false; // 登录失败
} }
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed"); Log.e(TAG, "login gtask failed");
return false; return false; // 登录失败
} }
} }
return true; return true; // 登录成功
} }
<<<<<<< HEAD
// 使用认证令牌登录到GTask
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; // 连接超时设置
int timeoutSocket = 15000; // Socket超时设置
HttpParams httpParameters = new BasicHttpParams(); // 创建基本HTTP参数
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 设置Socket超时
mHttpClient = new DefaultHttpClient(httpParameters); // 创建HTTP客户端
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); // 创建Cookie存储
mHttpClient.setCookieStore(localBasicCookieStore); // 设置Cookie存储
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 设置HTTP协议参数
// 登录GTask
=======
// 实际执行登录Google Tasks的操作获取相关信息如客户端版本号等 // 实际执行登录Google Tasks的操作获取相关信息如客户端版本号等
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
@ -233,25 +366,33 @@ public class GTaskClient {
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// 登录Google Tasks发送带有授权令牌的GET请求 // 登录Google Tasks发送带有授权令牌的GET请求
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken; // 创建登录URL
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl); // 创建GET请求
HttpResponse response = null; HttpResponse response = mHttpClient.execute(httpGet); // 执行请求
response = mHttpClient.execute(httpGet);
<<<<<<< HEAD
// 获取Cookie
=======
// 获取登录后的Cookie信息检查是否包含认证相关的Cookie名称包含"GTL" // 获取登录后的Cookie信息检查是否包含认证相关的Cookie名称包含"GTL"
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false; // 验证是否存在认证Cookie
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) { if (cookie.getName().contains("GTL")) {
hasAuthCookie = true; hasAuthCookie = true; // 存在认证Cookie
} }
} }
if (!hasAuthCookie) { if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie"); // 没有认证Cookie的警告
} }
<<<<<<< HEAD
// 从响应中获取客户端版本
=======
// 从响应中获取客户端版本号等信息通过解析返回的JavaScript代码中的相关数据 // 从响应中获取客户端版本号等信息通过解析返回的JavaScript代码中的相关数据
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -259,194 +400,275 @@ public class GTaskClient {
int end = resString.lastIndexOf(jsEnd); int end = resString.lastIndexOf(jsEnd);
String jsString = null; String jsString = null;
if (begin != -1 && end != -1 && begin < end) { if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end); // 提取JSON字符串
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString); // 创建JSON对象
mClientVersion = js.getLong("v"); mClientVersion = js.getLong("v"); // 获取客户端版本
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false; // 处理JSON异常返回登录失败
} catch (Exception e) { } catch (Exception e) {
<<<<<<< HEAD
=======
// 捕获其他所有异常,若发生异常则登录失败 // 捕获其他所有异常,若发生异常则登录失败
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return false; return false; // 处理其他异常,返回登录失败
} }
return true; return true; // 登录成功
} }
<<<<<<< HEAD
// 获取下一个动作ID
=======
// 获取下一个操作的ID // 获取下一个操作的ID
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++; // 返回当前ID并递增
} }
<<<<<<< HEAD
// 创建HTTP POST请求
=======
// 创建用于发送POST请求的HttpPost对象并设置相关请求头 // 创建用于发送POST请求的HttpPost对象并设置相关请求头
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl); // 创建POST请求
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // 设置请求头
httpPost.setHeader("AT", "1"); httpPost.setHeader("AT", "1"); // 设置自定义请求头
return httpPost; return httpPost; // 返回POST请求
} }
<<<<<<< HEAD
// 获取HTTP响应内容
=======
// 从HTTP实体中获取响应内容根据内容编码如gzip、deflate等进行相应的解压处理 // 从HTTP实体中获取响应内容根据内容编码如gzip、deflate等进行相应的解压处理
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null; // 声明内容编码
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue(); // 获取内容编码
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent(); // 获取输入流
// 根据内容编码类型进行处理
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent()); // 处理GZIP编码
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater); input = new InflaterInputStream(entity.getContent(), inflater); // 处理Deflate编码
} }
try { try {
InputStreamReader isr = new InputStreamReader(input); InputStreamReader isr = new InputStreamReader(input); // 创建输入流读取器
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr); // 创建缓冲读取器
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); // 创建字符串构建器
// 持续读取内容
while (true) { while (true) {
String buff = br.readLine(); String buff = br.readLine(); // 读取一行
if (buff == null) { if (buff == null) {
return sb.toString(); return sb.toString(); // 如果没有内容,返回结果
} }
sb = sb.append(buff); sb = sb.append(buff); // 添加读取内容
} }
} finally { } finally {
input.close(); input.close(); // 关闭输入流
} }
} }
<<<<<<< HEAD
// 发送POST请求
=======
// 发送POST请求将JSON数据发送到Google Tasks服务器并处理响应返回的JSON数据 // 发送POST请求将JSON数据发送到Google Tasks服务器并处理响应返回的JSON数据
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first"); // 如果未登录,记录错误
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in"); // 抛出异常
} }
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost(); // 创建POST请求
try { try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); // 创建参数列表
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString())); // 添加请求参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); // 创建实体
httpPost.setEntity(entity); httpPost.setEntity(entity); // 设置POST实体
<<<<<<< HEAD
// 执行POST请求并获取响应
=======
// 执行POST请求并获取响应然后解析响应内容为JSONObject返回 // 执行POST请求并获取响应然后解析响应内容为JSONObject返回
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity()); // 获取响应内容
return new JSONObject(jsString); return new JSONObject(jsString); // 返回响应的JSON对象
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("postRequest failed"); // 抛出网络失败异常
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("postRequest failed"); // 抛出IO异常
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject"); throw new ActionFailureException("unable to convert response content to jsonobject"); // 抛出JSON转换异常
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("error occurs when posting request"); // 其它异常处理
} }
} }
<<<<<<< HEAD
// 创建任务
=======
// 创建一个任务并发送到Google Tasks服务器 // 创建一个任务并发送到Google Tasks服务器
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建动作列表
<<<<<<< HEAD
// 添加创建动作到动作列表
=======
// 将任务的创建操作添加到操作列表中 // 将任务的创建操作添加到操作列表中
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加动作列表到JSON对象
<<<<<<< HEAD
// 添加客户端版本到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行POST请求
=======
// 设置客户端版本号 // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求并处理响应获取新创建任务的ID并设置到任务对象中 // 发送POST请求并处理响应获取新创建任务的ID并设置到任务对象中
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取返回结果
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务的ID
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("create task: handing jsonobject failed"); // 抛出JSON处理异常
} }
} }
<<<<<<< HEAD
// 创建任务列表
=======
// 创建一个任务列表并发送到Google Tasks服务器 // 创建一个任务列表并发送到Google Tasks服务器
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建动作列表
<<<<<<< HEAD
// 添加创建动作到动作列表
=======
// 将任务列表的创建操作添加到操作列表中 // 将任务列表的创建操作添加到操作列表中
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加动作列表到JSON对象
<<<<<<< HEAD
// 添加客户端版本到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行POST请求
=======
// 设置客户端版本号 // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求并处理响应获取新创建任务列表的ID并设置到任务列表对象中 // 发送POST请求并处理响应获取新创建任务列表的ID并设置到任务列表对象中
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取返回结果
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务列表的ID
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("create tasklist: handing jsonobject failed"); // 抛出JSON处理异常
} }
} }
<<<<<<< HEAD
// 提交更新
=======
// 提交更新操作,将暂存的更新操作数组发送到服务器 // 提交更新操作,将暂存的更新操作数组发送到服务器
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
// 如果存在更新数组
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
<<<<<<< HEAD
// 添加动作列表到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 添加客户端版本到JSON对象
=======
// 设置操作列表 // 设置操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 设置客户端版本号 // 设置客户端版本号
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost); // 执行POST请求
mUpdateArray = null; mUpdateArray = null; // 清空更新数组
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed"); throw new ActionFailureException("commit update: handing jsonobject failed"); // 抛出JSON处理异常
} }
} }
} }
<<<<<<< HEAD
// 添加更新节点
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 更新项目过多可能会导致错误最多设为10个项目
=======
// 添加一个节点的更新操作到暂存的更新操作数组中限制最多10个更新项 // 添加一个节点的更新操作到暂存的更新操作数组中限制最多10个更新项
// 将节点的更新操作添加到更新数组中如果更新数组中的元素超过10个则先提交更新 // 将节点的更新操作添加到更新数组中如果更新数组中的元素超过10个则先提交更新
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// 过多的更新项可能会导致错误所以设置最大更新项数量为10个 // 过多的更新项可能会导致错误所以设置最大更新项数量为10个
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate(); // 提交更新
} }
// 如果更新数组为空则创建一个新的JSONArray对象用于存放更新操作 // 如果更新数组为空则创建一个新的JSONArray对象用于存放更新操作
if (mUpdateArray == null) if (mUpdateArray == null)
<<<<<<< HEAD
mUpdateArray = new JSONArray(); // 初始化更新数组
mUpdateArray.put(node.getUpdateAction(getActionId())); // 将更新的节点添加到数组
}
}
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException {
commitUpdate(); // 提交更新
=======
mUpdateArray = new JSONArray(); mUpdateArray = new JSONArray();
// 将节点的更新操作通过节点获取操作ID使用当前的操作ID添加到更新数组中 // 将节点的更新操作通过节点获取操作ID使用当前的操作ID添加到更新数组中
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId()));
@ -457,11 +679,37 @@ public class GTaskClient {
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建动作列表
JSONObject action = new JSONObject(); JSONObject action = new JSONObject(); // 创建动作对象
<<<<<<< HEAD
// 构建移动动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 设置任务ID
// 如果前后父任务相同且任务有前兄弟则附加前兄弟ID
if (preParent == curParent && task.getPriorSibling() != null) {
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 源任务列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 目标父任务列表ID
// 如果任务从一个任务列表移动到另一个任务列表则附加目标列表ID
if (preParent != curParent) {
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action); // 添加动作到动作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加动作列表到JSON对象
// 添加客户端版本到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); // 执行POST请求
=======
// 操作列表相关设置 // 操作列表相关设置
// 设置操作类型为移动任务(对应预定义的移动操作类型常量) // 设置操作类型为移动任务(对应预定义的移动操作类型常量)
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
@ -493,22 +741,51 @@ public class GTaskClient {
// 发送POST请求将包含移动任务操作信息的JSON数据发送到服务器进行处理 // 发送POST请求将包含移动任务操作信息的JSON数据发送到服务器进行处理
postRequest(jsPost); postRequest(jsPost);
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
<<<<<<< HEAD
throw new ActionFailureException("move task: handing jsonobject failed"); // 抛出JSON处理异常
}
}
// 删除节点
=======
// 如果JSON处理出现异常抛出操作失败异常并说明是移动任务时处理JSON对象失败 // 如果JSON处理出现异常抛出操作失败异常并说明是移动任务时处理JSON对象失败
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed");
} }
} }
// 删除节点比如任务、任务列表等通过设置节点的删除标记为true并将其更新操作发送到服务器来实现删除 // 删除节点比如任务、任务列表等通过设置节点的删除标记为true并将其更新操作发送到服务器来实现删除
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建动作列表
<<<<<<< HEAD
// 标记节点为已删除并添加到动作列表
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId())); // 获取节点更新动作并添加到列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加动作列表到JSON对象
// 添加客户端版本到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); // 执行POST请求
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed"); // 抛出JSON处理异常
}
}
// 获取任务列表
=======
// 操作列表相关设置 // 操作列表相关设置
// 将节点标记为已删除 // 将节点标记为已删除
node.setDeleted(true); node.setDeleted(true);
@ -533,13 +810,21 @@ public class GTaskClient {
} }
// 获取所有的任务列表信息,前提是已经登录成功,否则会抛出异常提示需要先登录 // 获取所有的任务列表信息,前提是已经登录成功,否则会抛出异常提示需要先登录
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first"); // 如果未登录,记录错误
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in"); // 抛出异常
} }
try { try {
<<<<<<< HEAD
HttpGet httpGet = new HttpGet(mGetUrl); // 创建GET请求
HttpResponse response = mHttpClient.execute(httpGet); // 执行请求
// 获取任务列表
String resString = getResponseContent(response.getEntity()); // 获取响应内容
=======
// 创建一个HTTP GET请求对象用于获取任务列表数据请求的URL是之前设置好的获取数据的URL // 创建一个HTTP GET请求对象用于获取任务列表数据请求的URL是之前设置好的获取数据的URL
HttpGet httpGet = new HttpGet(mGetUrl); HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null; HttpResponse response = null;
@ -548,14 +833,36 @@ public class GTaskClient {
// 从响应的实体中获取内容并进行处理提取出包含任务列表信息的JSON数据部分 // 从响应的实体中获取内容并进行处理提取出包含任务列表信息的JSON数据部分
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin); int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd); int end = resString.lastIndexOf(jsEnd);
String jsString = null; String jsString = null;
// 提取JSON字符串
if (begin != -1 && end != -1 && begin < end) { if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end);
} }
<<<<<<< HEAD
JSONObject js = new JSONObject(jsString); // 创建JSON对象
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); // 返回任务列表
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); // 抛出网络请求失败异常
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); // 抛出IO异常
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed"); // 抛出JSON处理异常
}
}
// 获取指定任务列表
=======
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString);
// 从解析后的JSON对象中获取任务列表数组并返回对应预定义的任务列表的JSON键 // 从解析后的JSON对象中获取任务列表数组并返回对应预定义的任务列表的JSON键
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
@ -578,13 +885,37 @@ public class GTaskClient {
} }
// 根据给定的任务列表全局唯一ID获取该任务列表中的任务信息需要先提交之前暂存的更新操作 // 根据给定的任务列表全局唯一ID获取该任务列表中的任务信息需要先提交之前暂存的更新操作
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建动作列表
JSONObject action = new JSONObject(); JSONObject action = new JSONObject(); // 创建动作对象
<<<<<<< HEAD
// 构建获取所有任务的动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 设置列表ID
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 不获取已删除的任务
actionList.put(action); // 添加动作到动作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加动作列表到JSON对象
// 添加客户端版本到JSON对象
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost); // 执行POST请求
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 返回任务数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed"); // 抛出JSON处理异常
}
}
// 获取同步账户
=======
// 操作列表相关设置 // 操作列表相关设置
// 设置操作类型为获取所有任务(对应预定义的获取所有任务操作类型常量) // 设置操作类型为获取所有任务(对应预定义的获取所有任务操作类型常量)
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
@ -616,11 +947,20 @@ public class GTaskClient {
} }
// 获取当前用于同步的账户信息 // 获取当前用于同步的账户信息
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount; // 返回账户信息
} }
<<<<<<< HEAD
// 重置更新数组
public void resetUpdateArray() {
mUpdateArray = null; // 清空更新数组
}
}
=======
// 重置更新数组,即将其置为空,一般用于清除之前暂存的更新操作相关数据 // 重置更新数组,即将其置为空,一般用于清除之前暂存的更新操作相关数据
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae

@ -1,31 +1,54 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011, MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* you may not use this file except in compliance with the License. * 使
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License.
*/ */
// 定义包
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; // 导入需要的类
import android.content.ContentResolver; import android.app.Activity; // 用于活动管理的类
import android.content.ContentUris; import android.content.ContentResolver; // 用于内容提供者的类
import android.content.ContentValues; import android.content.ContentUris; // 处理内容 URI 的工具类
import android.content.Context; import android.content.ContentValues; // 包含 ContentProvider 插入或更新所需值的类
import android.database.Cursor; import android.content.Context; // 应用上下文类
import android.util.Log; import android.database.Cursor; // 数据库查询结果的类
import android.util.Log; // 记录日志的工具类
// 导入项目中的相关类
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
<<<<<<< HEAD
import net.micode.notes.data.Notes.DataColumns; // 数据列常量
import net.micode.notes.data.Notes.NoteColumns; // 笔记列常量
import net.micode.notes.gtask.data.MetaData; // 任务元数据类
import net.micode.notes.gtask.data.Node; // 节点类
import net.micode.notes.gtask.data.SqlNote; // SQL 笔记类
import net.micode.notes.gtask.data.Task; // 任务类
import net.micode.notes.gtask.data.TaskList; // 任务列表类
import net.micode.notes.gtask.exception.ActionFailureException; // 操作失败异常
import net.micode.notes.gtask.exception.NetworkFailureException; // 网络失败异常
import net.micode.notes.tool.DataUtils; // 数据工具类
import net.micode.notes.tool.GTaskStringUtils; // GTask 字符串工具类
import org.json.JSONArray; // JSON 数组类
import org.json.JSONException; // JSON 异常类
import org.json.JSONObject; // JSON 对象类
import java.util.HashMap; // 哈希表实现
import java.util.HashSet; // 哈希集合实现
import java.util.Iterator; // 迭代器类
=======
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData; import net.micode.notes.gtask.data.MetaData;
@ -919,3 +942,4 @@ public class GTaskManager {
mCancelled = true; mCancelled = true;
} }
} }
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae

@ -23,6 +23,45 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
<<<<<<< HEAD
/**
* GTaskSyncService Google
* Android Service
*/
public class GTaskSyncService extends Service {
// 主要用于标识同步动作的字符串名称
public final static String ACTION_STRING_NAME = "sync_action_type";
// 开始同步的操作类型常量
public final static int ACTION_START_SYNC = 0;
// 取消同步的操作类型常量
public final static int ACTION_CANCEL_SYNC = 1;
// 无效的操作类型常量
public final static int ACTION_INVALID = 2;
// 广播名称,用于通知同步服务的状态
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 广播参数,用于标识当前是否正在同步
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
// 广播参数,用于传递同步进度消息
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 静态变量,表示当前的异步任务
private static GTaskASyncTask mSyncTask = null;
// 存储当前同步的进度信息
private static String mSyncProgress = "";
/**
*
*/
private void startSync() {
// 如果没有正在进行的同步任务,则创建并启动新的任务
=======
// GTaskSyncService类继承自Service用于管理与Google Tasks的同步相关操作包括启动同步、取消同步以及广播同步状态等功能 // GTaskSyncService类继承自Service用于管理与Google Tasks的同步相关操作包括启动同步、取消同步以及广播同步状态等功能
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
@ -56,12 +95,17 @@ public class GTaskSyncService extends Service {
// 启动同步的私有方法,用于创建并执行同步任务 // 启动同步的私有方法,用于创建并执行同步任务
private void startSync() { private void startSync() {
// 如果当前没有正在执行的同步任务mSyncTask为null // 如果当前没有正在执行的同步任务mSyncTask为null
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
if (mSyncTask == null) { if (mSyncTask == null) {
// 创建一个新的GTaskASyncTask对象传入当前服务上下文this以及一个完成监听器OnCompleteListener // 创建一个新的GTaskASyncTask对象传入当前服务上下文this以及一个完成监听器OnCompleteListener
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
// 当同步任务完成时会调用的回调方法 // 当同步任务完成时会调用的回调方法
public void onComplete() { public void onComplete() {
<<<<<<< HEAD
// 同步任务完成后,重置任务状态并发送广播
=======
// 将正在执行的同步任务对象置为null表示同步已结束 // 将正在执行的同步任务对象置为null表示同步已结束
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
mSyncTask = null; mSyncTask = null;
// 发送一个空消息的广播(可能用于通知其他组件同步已完成等状态变化) // 发送一个空消息的广播(可能用于通知其他组件同步已完成等状态变化)
sendBroadcast(""); sendBroadcast("");
@ -69,15 +113,28 @@ public class GTaskSyncService extends Service {
stopSelf(); stopSelf();
} }
}); });
<<<<<<< HEAD
// 发送初始广播,表示同步开始
sendBroadcast("");
// 执行异步任务
=======
// 发送一个空消息的广播(可能在创建任务后就先通知其他组件同步即将开始等情况) // 发送一个空消息的广播(可能在创建任务后就先通知其他组件同步即将开始等情况)
sendBroadcast(""); sendBroadcast("");
// 执行同步任务,开始真正的同步操作流程 // 执行同步任务,开始真正的同步操作流程
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
mSyncTask.execute(); mSyncTask.execute();
} }
} }
<<<<<<< HEAD
/**
*
*/
=======
// 取消同步的私有方法,用于取消正在执行的同步任务(如果存在的话) // 取消同步的私有方法,用于取消正在执行的同步任务(如果存在的话)
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
private void cancelSync() { private void cancelSync() {
// 如果有正在进行的同步任务,则取消该任务
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
@ -86,13 +143,18 @@ public class GTaskSyncService extends Service {
// 服务创建时调用的方法在这里将正在执行的同步任务对象初始化为null确保服务启动时处于初始状态 // 服务创建时调用的方法在这里将正在执行的同步任务对象初始化为null确保服务启动时处于初始状态
@Override @Override
public void onCreate() { public void onCreate() {
// 服务创建时,初始化同步任务为空
mSyncTask = null; mSyncTask = null;
} }
// 当服务通过startService()方法启动时会调用此方法用于处理传入的Intent并根据不同的操作意图执行相应操作 // 当服务通过startService()方法启动时会调用此方法用于处理传入的Intent并根据不同的操作意图执行相应操作
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
<<<<<<< HEAD
// 从 Intent 中获取数据
=======
// 从传入的Intent中获取附加的Bundle数据通常用于传递额外的参数信息 // 从传入的Intent中获取附加的Bundle数据通常用于传递额外的参数信息
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
// 如果获取到的Bundle不为null且包含表示操作类型的键ACTION_STRING_NAME // 如果获取到的Bundle不为null且包含表示操作类型的键ACTION_STRING_NAME
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
@ -100,17 +162,23 @@ public class GTaskSyncService extends Service {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
// 如果操作类型是启动同步ACTION_START_SYNC // 如果操作类型是启动同步ACTION_START_SYNC
case ACTION_START_SYNC: case ACTION_START_SYNC:
// 开始同步操作
startSync(); startSync();
break; break;
// 如果操作类型是取消同步ACTION_CANCEL_SYNC // 如果操作类型是取消同步ACTION_CANCEL_SYNC
case ACTION_CANCEL_SYNC: case ACTION_CANCEL_SYNC:
// 取消同步操作
cancelSync(); cancelSync();
break; break;
// 其他未知或不处理的操作类型,直接跳过不做操作 // 其他未知或不处理的操作类型,直接跳过不做操作
default: default:
break; break;
} }
<<<<<<< HEAD
// 返回服务的启动模式
=======
// 返回START_STICKY表示服务在被系统意外终止后会尝试重新创建并保持启动状态常用于需要持续运行的服务场景 // 返回START_STICKY表示服务在被系统意外终止后会尝试重新创建并保持启动状态常用于需要持续运行的服务场景
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
return START_STICKY; return START_STICKY;
} }
// 如果不符合上述条件或者操作类型无效等情况调用父类的onStartCommand方法进行默认处理 // 如果不符合上述条件或者操作类型无效等情况调用父类的onStartCommand方法进行默认处理
@ -120,48 +188,93 @@ public class GTaskSyncService extends Service {
// 当系统内存不足时会调用此方法,在这里用于取消正在执行的同步任务(如果存在的话),释放内存资源 // 当系统内存不足时会调用此方法,在这里用于取消正在执行的同步任务(如果存在的话),释放内存资源
@Override @Override
public void onLowMemory() { public void onLowMemory() {
// 当系统内存不足时,取消同步任务
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
<<<<<<< HEAD
=======
// 用于服务绑定操作的方法这里返回null表示不支持绑定操作如果需要支持绑定需要返回一个有效的IBinder对象 // 用于服务绑定操作的方法这里返回null表示不支持绑定操作如果需要支持绑定需要返回一个有效的IBinder对象
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
// 返回 null 表示不提供绑定服务的功能
return null; return null;
} }
<<<<<<< HEAD
/**
* 广
*/
=======
// 发送广播的公共方法,用于向其他组件广播同步服务的相关状态信息,包括同步进度消息、是否正在同步等 // 发送广播的公共方法,用于向其他组件广播同步服务的相关状态信息,包括同步进度消息、是否正在同步等
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
// 创建 Intent 用于发送广播
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
// 设置当前是否正在同步的标志
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
// 设置进度消息
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
// 发送广播
sendBroadcast(intent); sendBroadcast(intent);
} }
<<<<<<< HEAD
/**
*
*/
public static void startSync(Activity activity) {
// 设置活动上下文
=======
// 静态公共方法用于在外部比如Activity中启动同步服务进行同步操作需要传入对应的Activity作为上下文来启动服务 // 静态公共方法用于在外部比如Activity中启动同步服务进行同步操作需要传入对应的Activity作为上下文来启动服务
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
// 设置GTaskManager的Activity上下文可能用于获取相关授权等操作与同步操作相关联 // 设置GTaskManager的Activity上下文可能用于获取相关授权等操作与同步操作相关联
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
// 添加启动同步的指令
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
// 启动服务
activity.startService(intent); activity.startService(intent);
} }
<<<<<<< HEAD
/**
*
*/
=======
// 静态公共方法用于在外部比如其他组件中取消正在进行的同步操作需要传入上下文Context来启动服务发送取消同步的意图 // 静态公共方法用于在外部比如其他组件中取消正在进行的同步操作需要传入上下文Context来启动服务发送取消同步的意图
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
// 添加取消同步的指令
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
// 启动服务
context.startService(intent); context.startService(intent);
} }
<<<<<<< HEAD
/**
*
*/
=======
// 静态公共方法用于判断当前是否正在进行同步操作通过检查正在执行的同步任务对象是否为null来返回相应的布尔值结果 // 静态公共方法用于判断当前是否正在进行同步操作通过检查正在执行的同步任务对象是否为null来返回相应的布尔值结果
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
<<<<<<< HEAD
/**
*
*/
=======
// 静态公共方法,用于获取当前的同步进度相关的字符串消息,返回存储同步进度消息的静态变量的值 // 静态公共方法,用于获取当前的同步进度相关的字符串消息,返回存储同步进度消息的静态变量的值
>>>>>>> a495b394fa4686564cc2bfe7d054eb66276713ae
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

@ -33,7 +33,7 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
// 代表一个笔记,包含笔记的基本信息和笔记数据
public class Note { public class Note {
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
private NoteData mNoteData; private NoteData mNoteData;
@ -70,36 +70,44 @@ public class Note {
mNoteData = new NoteData(); mNoteData = new NoteData();
} }
// 设置笔记的基本信息
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
// 设置文本笔记的数据
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
// 设置文本笔记的数据ID
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
// 获取文本笔记的数据ID
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }
// 设置通话笔记的数据ID
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }
// 设置通话笔记的数据
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
// 判断笔记是否被本地修改过
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
// 同步笔记到数据库
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -130,6 +138,7 @@ public class Note {
return true; return true;
} }
// 笔记数据类,包含文本数据和通话数据
private class NoteData { private class NoteData {
private long mTextDataId; private long mTextDataId;
@ -148,10 +157,12 @@ public class Note {
mCallDataId = 0; mCallDataId = 0;
} }
// 判断笔记数据是否被本地修改过
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
// 设置文本数据ID
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +170,7 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
// 设置通话数据ID
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,18 +178,21 @@ public class Note {
mCallDataId = id; mCallDataId = id;
} }
// 设置通话数据
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
// 设置文本数据
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
// 将笔记数据推送到内容解析器
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
@ -250,4 +265,4 @@ public class Note {
return null; return null;
} }
} }
} }

@ -13,16 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.model; package net.micode.notes.model;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
@ -30,8 +30,8 @@ import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
// 表示正在编辑的笔记类
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -41,27 +41,28 @@ public class WorkingNote {
private String mContent; private String mContent;
// Note mode // Note mode
private int mMode; private int mMode;
private long mAlertDate; private long mAlertDate;
private long mModifiedDate; private long mModifiedDate;
private int mBgColorId; private int mBgColorId;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private long mFolderId; private long mFolderId;
private Context mContext; private Context mContext;
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
private boolean mIsDeleted; private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据库查询笔记数据的列
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -71,7 +72,8 @@ public class WorkingNote {
DataColumns.DATA3, DataColumns.DATA3,
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 数据库查询笔记信息的列
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -80,28 +82,28 @@ public class WorkingNote {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // 新笔记构造方法
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
@ -113,8 +115,8 @@ public class WorkingNote {
mMode = 0; mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// Existing note construct // 已有笔记构造方法
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
@ -123,12 +125,13 @@ public class WorkingNote {
mNote = new Note(); mNote = new Note();
loadNote(); loadNote();
} }
// 从数据库加载笔记信息
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -145,13 +148,14 @@ public class WorkingNote {
} }
loadNoteData(); loadNoteData();
} }
// 从数据库加载笔记数据
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
@ -173,7 +177,8 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
} }
} }
// 创建一个空笔记
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -182,11 +187,13 @@ public class WorkingNote {
note.setWidgetType(widgetType); note.setWidgetType(widgetType);
return note; return note;
} }
// 从数据库加载笔记
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
// 保存笔记到数据库
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { if (isWorthSaving()) {
if (!existInDatabase()) { if (!existInDatabase()) {
@ -195,9 +202,9 @@ public class WorkingNote {
return false; return false;
} }
} }
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
@ -211,11 +218,13 @@ public class WorkingNote {
return false; return false;
} }
} }
// 判断笔记是否存在于数据库中
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
// 判断笔记是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
@ -224,11 +233,13 @@ public class WorkingNote {
return true; return true;
} }
} }
// 设置笔记信息改变监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
// 设置闹钟提醒日期
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -238,7 +249,8 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
// 标记笔记是否已删除
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -246,7 +258,8 @@ public class WorkingNote {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
} }
// 设置笔记背景颜色ID
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
@ -256,7 +269,8 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
// 设置笔记的检查列表模式
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
@ -266,98 +280,115 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
} }
// 设置笔记的窗口小部件类型
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
} }
} }
// 设置笔记的窗口小部件ID
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
} }
} }
// 设置工作文本内容
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
} }
} }
// 将笔记转换为通话笔记
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
// 检查笔记是否有闹钟提醒
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
// 获取笔记内容
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
// 获取闹钟提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取笔记修改日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取笔记背景颜色资源ID
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
// 获取笔记背景颜色ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取笔记标题背景颜色资源ID
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
// 获取检查列表模式
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
// 获取笔记ID
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
// 获取笔记所在的文件夹ID
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
// 获取窗口小部件ID
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取窗口小部件类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 笔记信息改变监听器接口
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
* Called when user set clock * Called when user set clock
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
* Call when user create note from widget * Call when user create note from widget
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
* Call when switch between check list mode and normal mode * Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change * @param oldMode is previous mode before change
@ -365,4 +396,4 @@ public class WorkingNote {
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }
} }

@ -1,112 +1,110 @@
```java
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Apache License, Version 2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* 使 * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.os.Environment; import android.os.Environment;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.util.Log; import android.util.Log;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
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;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
// 备份工具类,用于将笔记数据备份到文本文件中。 // 备份工具类,用于将笔记数据导出为文本文件
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// 单例模式 // 单例实例
private static BackupUtils sInstance; private static BackupUtils sInstance;
// 获取BackupUtils的单例,如果不存在则创建。 // 获取BackupUtils的单例实例
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) {
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
} }
return sInstance; return sInstance;
} }
/** /**
* *
*/ */
// SD卡未挂载 // SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// 备份文件不存在 // 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// 数据格式不正确,可能被其他程序更改 // 数据损坏或格式不正确
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// 运行时异常导致备份或恢复失败 // 系统错误导致备份或恢复失败
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// 备份或恢复成功 // 备份或恢复成功
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
private TextExport mTextExport; private TextExport mTextExport;
// 私有构造函数用于创建BackupUtils实例。 // 构造函数初始化TextExport实例
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
// 检查外部存储是否可用 // 检查外部存储是否可用
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
// 导出笔记数据到文本文件。 // 导出笔记数据为文本文件
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText();
} }
// 获取导出的文本文件名 // 获取导出的文本文件名
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName;
} }
// 获取导出的文本文件目录 // 获取导出的文本文件目录
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory;
} }
// 内部类,用于将笔记数据导出到文本。 // 文本导出类,用于将笔记数据导出为文本格式
private static class TextExport { private static class TextExport {
// 笔记数据投影数组。
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE NoteColumns.TYPE
}; };
// 数据列索引。
private static final int NOTE_COLUMN_ID = 0; private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2; private static final int NOTE_COLUMN_SNIPPET = 2;
// 数据数据投影数组。
private static final String[] DATA_PROJECTION = { private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -115,56 +113,53 @@ public class BackupUtils {
DataColumns.DATA3, DataColumns.DATA3,
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 数据列索引。
private static final int DATA_COLUMN_CONTENT = 0; private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1; private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 导出文本的格式数组。 private final String [] TEXT_FORMAT;
private final String[] TEXT_FORMAT; private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_FOLDER_NAME = 0; private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_DATE = 1; private static final int FORMAT_NOTE_CONTENT = 2;
private static final int FORMAT_NOTE_CONTENT = 2;
// 上下文对象,用于访问资源和内容解析器。
private Context mContext; private Context mContext;
// 导出文件的名称和目录。
private String mFileName; private String mFileName;
private String mFileDirectory; private String mFileDirectory;
// 构造函数,初始化上下文和格式数组。 // 构造函数,初始化导出格式和上下文
public TextExport(Context context) { public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context;
mFileName = ""; mFileName = "";
mFileDirectory = ""; mFileDirectory = "";
} }
// 根据ID获取对应的格式字符串。 // 根据ID获取导出格式字符串
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
} }
/** // 导出指定文件夹下的笔记到文本文件
* ID
*/
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于该文件夹的笔记 // 查询属于该文件夹的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
}, null); }, null);
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// 打印笔记最后修改日期 // 打印笔记最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于该笔记的数据 // 查询属于该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
@ -172,16 +167,14 @@ public class BackupUtils {
notesCursor.close(); notesCursor.close();
} }
} }
/** // 导出指定笔记到文本输出流
* ID
*/
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
}, null); }, null);
if (dataCursor != null) { if (dataCursor != null) {
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
@ -191,7 +184,7 @@ public class BackupUtils {
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) { if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
@ -216,7 +209,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// 打印笔记之间的分隔线。 // 打印笔记之间的分隔
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -225,36 +218,33 @@ public class BackupUtils {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
} }
} }
/** // 将笔记数据导出为用户可读的文本文件
*
*/
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "媒体未挂载"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
} }
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream();
if (ps == null) { if (ps == null) {
Log.e(TAG, "获取打印流出错"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// 首先导出文件夹及其笔记 // 首先导出文件夹及其笔记
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
null, null);
if (folderCursor != null) { if (folderCursor != null) {
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) {
do { do {
// 打印文件夹名称 // 打印文件夹名称
String folderName = ""; String folderName = "";
if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name); folderName = mContext.getString(R.string.call_record_folder_name);
} else { } else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
@ -268,22 +258,21 @@ public class BackupUtils {
} }
folderCursor.close(); folderCursor.close();
} }
// 导出根文件夹中的笔记。 // 导出根文件夹下的笔记
// 导出根文件夹中的笔记
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0", null, null); NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) { if (noteCursor != null) {
if (noteCursor.moveToFirst()) { if (noteCursor.moveToFirst()) {
do { do {
// 打印笔记最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于这条笔记的数据 // 查询属于笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID); String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext()); } while (noteCursor.moveToNext());
@ -291,20 +280,16 @@ public class BackupUtils {
noteCursor.close(); noteCursor.close();
} }
ps.close(); ps.close();
// 返回成功状态码
return STATE_SUCCESS; return STATE_SUCCESS;
} }
/** // 获取指向导出文本文件的PrintStream
*
*/
private PrintStream getExportToTextPrintStream() { private PrintStream getExportToTextPrintStream() {
// 生成存储导出数据的文本文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format); R.string.file_name_txt_format);
if (file == null) { if (file == null) {
Log.e(TAG, "创建导出文件失败"); Log.e(TAG, "create file to exported failed");
return null; return null;
} }
mFileName = file.getName(); mFileName = file.getName();
@ -323,34 +308,33 @@ public class BackupUtils {
return ps; return ps;
} }
} }
/** // 生成用于存储导入数据的文本文件
* SD private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
*/ StringBuilder sb = new StringBuilder();
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { sb.append(Environment.getExternalStorageDirectory());
StringBuilder sb = new StringBuilder(); sb.append(context.getString(filePathResId));
sb.append(Environment.getExternalStorageDirectory()); File filedir = new File(sb.toString());
sb.append(context.getString(filePathResId)); sb.append(context.getString(
File filedir = new File(sb.toString()); fileNameFormatResId,
sb.append(context.getString( DateFormat.format(context.getString(R.string.format_date_ymd),
fileNameFormatResId, System.currentTimeMillis())));
DateFormat.format(context.getString(R.string.format_date_ymd), File file = new File(sb.toString());
System.currentTimeMillis())));
File file = new File(sb.toString()); try {
if (!filedir.exists()) {
try { filedir.mkdir();
if (!filedir.exists()) { }
filedir.mkdir(); if (!file.exists()) {
} file.createNewFile();
if (!file.exists()) { }
file.createNewFile(); return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
return file;
} catch (SecurityException e) { return null;
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
return null;
}

@ -1,16 +1,17 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Apache License, Version 2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* 使 * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
@ -33,25 +34,25 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
// 数据工具类,提供对笔记数据的操作函数 // 数据工具类,提供批量删除笔记、移动笔记到文件夹等操作
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
// 批量删除笔记 // 批量删除笔记
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "id集合为空"); Log.d(TAG, "the ids is null");
return true; return true;
} }
if (ids.size() == 0) { if (ids.size() == 0) {
Log.d(TAG, "id集合中没有元素"); Log.d(TAG, "no id is in the hashset");
return true; return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
if (id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "不要删除系统根文件夹"); Log.e(TAG, "Don't delete system folder root");
continue; continue;
} }
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
@ -61,7 +62,7 @@ public class DataUtils {
try { try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "删除笔记失败, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
@ -86,7 +87,7 @@ public class DataUtils {
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "id集合为空"); Log.d(TAG, "the ids is null");
return true; return true;
} }
@ -102,7 +103,7 @@ public class DataUtils {
try { try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "移动笔记失败, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
@ -115,22 +116,22 @@ public class DataUtils {
} }
/** /**
* *
*/ */
public static int getUserFolderCount(ContentResolver resolver) { public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" }, new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) }, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null); null);
int count = 0; int count = 0;
if (cursor != null) { if(cursor != null) {
if (cursor.moveToFirst()) { if(cursor.moveToFirst()) {
try { try {
count = cursor.getInt(0); count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取文件夹数量失败:" + e.toString()); Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
cursor.close(); cursor.close();
} }
@ -139,12 +140,12 @@ public class DataUtils {
return count; return count;
} }
// 检查笔记在数据库中是否可见 // 检查指定类型的笔记是否可见
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String[] { String.valueOf(type) }, new String [] {String.valueOf(type)},
null); null);
boolean exist = false; boolean exist = false;
@ -157,7 +158,7 @@ public class DataUtils {
return exist; return exist;
} }
// 检查笔记在数据库中是否存在 // 检查笔记是否存数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, null, null, null);
@ -172,7 +173,7 @@ public class DataUtils {
return exist; return exist;
} }
// 检查数据在数据库中是否存在 // 检查数据是否存数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
@ -187,16 +188,16 @@ public class DataUtils {
return exist; return exist;
} }
// 检查文件夹名称是否可见 // 检查指定名称的用户文件夹是否存在
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if(cursor != null) {
if (cursor.getCount() > 0) { if(cursor.getCount() > 0) {
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -204,7 +205,7 @@ public class DataUtils {
return exist; return exist;
} }
// 获取文件夹笔记的小部件属性 // 获取指定文件夹下的笔记小部件信息
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -234,80 +235,74 @@ public class DataUtils {
// 根据笔记ID获取通话号码 // 根据笔记ID获取通话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null); null);
// 如果游标不为空并且移动到第一行,则尝试获取通话号码
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
return cursor.getString(0); // 返回获取到的字符串 return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取通话号码失败:" + e.toString()); // 记录异常信息 Log.e(TAG, "Get call number fails " + e.toString());
} finally { } finally {
cursor.close(); // 确保游标被关闭 cursor.close();
} }
} }
return ""; // 如果失败,返回空字符串 return "";
}
// 根据电话号码和通话日期获取笔记ID // 根据通话号码和通话日期获取笔记ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String[] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)", + CallNote.PHONE_NUMBER + ",?)",
new String[] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null); null);
// 如果游标不为空并且移动到第一行则尝试获取笔记ID
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {
return cursor.getLong(0); // 返回获取到的长整型数 return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取通话笔记ID失败" + e.toString()); // 记录异常信息 Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
cursor.close(); // 确保游标被关闭 cursor.close();
} }
return 0; // 如果失败返回0 return 0;
} }
// 根据笔记ID获取摘要 // 根据笔记ID获取笔记摘要
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?", NoteColumns.ID + "=?",
new String[] { String.valueOf(noteId) }, new String [] { String.valueOf(noteId)},
null); null);
// 如果游标不为空并且移动到第一行,则尝试获取摘要
if (cursor != null) { if (cursor != null) {
String snippet = ""; String snippet = "";
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
snippet = cursor.getString(0); // 获取摘要 snippet = cursor.getString(0);
} }
cursor.close(); // 确保游标被关闭 cursor.close();
return snippet; // 返回摘要 return snippet;
} }
throw new IllegalArgumentException("未找到ID为" + noteId + "的笔记"); // 如果失败,抛出异常 throw new IllegalArgumentException("Note is not found with id: " + noteId);
} }
// 获取格式化后的摘要 // 格式化笔记摘要
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) {
snippet = snippet.trim(); // 去除首尾空白 snippet = snippet.trim();
int index = snippet.indexOf('\n'); // 查找换行符 int index = snippet.indexOf('\n');
if (index != -1) { if (index != -1) {
snippet = snippet.substring(0, index); // 截取换行符之前的字符串 snippet = snippet.substring(0, index);
} }
} }
return snippet; // 返回格式化后的摘要 return snippet;
} }
} }

@ -13,148 +13,102 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
// GTaskStringUtils类主要用于定义一些与Google Tasks相关操作中使用的字符串常量方便在代码中统一引用和管理 // 此类用于定义和存储GTask相关的JSON字段名常量
public class GTaskStringUtils { public class GTaskStringUtils {
// 表示操作的唯一ID的JSON键名用于在与Google Tasks交互的JSON数据中标识某个具体操作的ID
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";
// 表示操作列表的JSON键名用于在与Google Tasks交互的JSON数据中存放一组操作的集合通常是一个JSON数组
public final static String GTASK_JSON_ACTION_LIST = "action_list"; public final static String GTASK_JSON_ACTION_LIST = "action_list";
// 表示操作类型的JSON键名用于在与Google Tasks交互的JSON数据中指定某个操作具体是什么类型的操作比如创建、获取、移动等
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// 表示创建操作类型的具体值,对应创建相关的操作,例如创建任务、创建任务列表等操作时使用该值来标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// 表示获取所有(任务等)操作类型的具体值,用于获取某个任务列表下的所有任务等情况时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// 表示移动操作类型的具体值,用于在移动任务、任务列表等位置时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// 表示更新操作类型的具体值,用于对任务、任务列表等进行更新操作时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// 表示创建者ID的JSON键名用于在与Google Tasks交互的JSON数据中存放创建某个任务、任务列表等的用户ID信息
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// 表示子实体的JSON键名可能用于在涉及包含子元素的结构如任务列表包含多个任务等情况标识子实体相关信息
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// 表示客户端版本号的JSON键名用于在与Google Tasks交互的JSON数据中告知服务器当前客户端的版本信息便于进行兼容性等相关处理
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// 表示是否完成的JSON键名可能用于任务等实体中标识该任务是否已经完成的状态信息
public final static String GTASK_JSON_COMPLETED = "completed"; public final static String GTASK_JSON_COMPLETED = "completed";
// 表示当前列表ID的JSON键名可能用于在涉及多列表切换、关联等场景时标识当前所在的任务列表的ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// 表示默认列表ID的JSON键名用于标识某个用户、某个应用场景下的默认任务列表的ID信息
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// 表示是否已删除的JSON键名用于在任务、任务列表等实体中标识其是否已经被删除的状态信息
public final static String GTASK_JSON_DELETED = "deleted"; public final static String GTASK_JSON_DELETED = "deleted";
// 表示目标列表的JSON键名在进行移动操作等涉及改变所属列表的操作时用于指定要移动到的目标任务列表的ID
public final static String GTASK_JSON_DEST_LIST = "dest_list"; public final static String GTASK_JSON_DEST_LIST = "dest_list";
// 表示目标父级的JSON键名在进行移动操作、关联操作等涉及改变父级元素的情况时用于指定要移动到或关联的目标父级元素的相关信息比如任务列表等
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// 表示目标父级类型的JSON键名可能用于进一步明确目标父级元素的具体类型例如是任务列表类型还是其他类型等
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// 表示实体差异的JSON键名可能用于在对比、更新实体时标识实体之间发生变化的部分相关信息
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// 表示实体类型的JSON键名用于在与Google Tasks交互的JSON数据中明确某个实体如任务、任务列表等具体是什么类型
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// 表示是否获取已删除的JSON键名在进行查询操作时用于指定是否要获取已经被标记为删除的任务、任务列表等信息
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// 表示唯一ID的JSON键名通常用于标识任务、任务列表等实体在Google Tasks系统中的全局唯一标识符
public final static String GTASK_JSON_ID = "id"; public final static String GTASK_JSON_ID = "id";
// 表示索引的JSON键名可能用于在任务列表中标识某个任务的排列顺序等索引相关信息
public final static String GTASK_JSON_INDEX = "index"; public final static String GTASK_JSON_INDEX = "index";
// 表示最后修改时间的JSON键名用于记录任务、任务列表等实体最后一次被修改的时间信息便于进行同步、更新等操作时的判断
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// 表示最新同步点的JSON键名可能用于记录与Google Tasks进行数据同步时的最新同步时间点等相关信息便于后续判断同步范围、增量等情况
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// 表示列表ID的JSON键名常用于标识某个具体的任务列表的ID信息与其他相关操作配合使用比如获取某个列表下的任务等操作
public final static String GTASK_JSON_LIST_ID = "list_id"; public final static String GTASK_JSON_LIST_ID = "list_id";
// 表示任务列表复数形式的JSON键名用于在与Google Tasks交互的JSON数据中存放多个任务列表信息的集合通常是一个JSON数组
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_LISTS = "lists";
// 表示名称的JSON键名用于任务、任务列表等实体中存放它们的名称信息方便展示、识别等操作
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_NAME = "name";
// 表示新ID的JSON键名可能在某些创建、更新操作后用于存放新生成的实体ID信息比如创建任务后返回的新任务ID等情况
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_NEW_ID = "new_id";
// 表示备注笔记的JSON键名可能用于存放与任务相关的一些备注、说明等文本信息
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_NOTES = "notes";
// 表示父级ID的JSON键名用于在任务、任务列表等实体中标识其所属的父级元素的ID信息建立层级关系
public final static String GTASK_JSON_PARENT_ID = "parent_id"; public final static String GTASK_JSON_PARENT_ID = "parent_id";
// 表示前一个兄弟节点任务等ID的JSON键名在任务列表中用于标识某个任务之前相邻的兄弟任务的ID常用于排序、移动等操作场景
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// 表示操作结果的JSON键名在执行某些操作如批量操作等用于存放操作的结果信息通常是一个JSON数组
public final static String GTASK_JSON_RESULTS = "results"; public final static String GTASK_JSON_RESULTS = "results";
// 表示源列表的JSON键名在进行移动操作等涉及改变所属列表的操作时用于指定操作前所在的原始任务列表的ID
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// 表示任务复数形式的JSON键名用于在与Google Tasks交互的JSON数据中存放多个任务信息的集合通常是一个JSON数组
public final static String GTASK_JSON_TASKS = "tasks"; public final static String GTASK_JSON_TASKS = "tasks";
// 表示类型的JSON键名用于在与Google
// Tasks交互的JSON数据中明确某个实体如任务、任务列表等具体是什么类型和GTASK_JSON_ENTITY_TYPE作用类似但使用场景可能稍有不同
public final static String GTASK_JSON_TYPE = "type"; public final static String GTASK_JSON_TYPE = "type";
// 表示分组类型的具体值,用于标识某个实体是分组类型(例如任务分组等情况)
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// 表示任务类型的具体值,用于明确某个实体是任务类型,方便在代码中进行类型判断等操作
public final static String GTASK_JSON_TYPE_TASK = "TASK"; public final static String GTASK_JSON_TYPE_TASK = "TASK";
// 表示用户的JSON键名可能用于存放与操作相关的用户信息比如执行操作的用户账号等情况
public final static String GTASK_JSON_USER = "user"; public final static String GTASK_JSON_USER = "user";
// MIUI系统中笔记相关的文件夹前缀字符串用于在名称等地方标识该文件夹是属于MIUI笔记应用相关的文件夹
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 表示默认文件夹名称的字符串常量,用于标识默认的任务列表、文件夹等的名称
public final static String FOLDER_DEFAULT = "Default"; public final static String FOLDER_DEFAULT = "Default";
// 表示通话记录笔记文件夹名称的字符串常量,用于明确该文件夹是存放通话记录相关笔记的
public final static String FOLDER_CALL_NOTE = "Call_Note"; public final static String FOLDER_CALL_NOTE = "Call_Note";
// 表示元数据文件夹名称的字符串常量,用于标识存放元数据相关内容的文件夹名称
public final static String FOLDER_META = "METADATA"; public final static String FOLDER_META = "METADATA";
// 表示元数据中Google Tasks ID的键名可能用于在元数据结构中关联对应的Google Tasks实体的ID信息
public final static String META_HEAD_GTASK_ID = "meta_gid"; public final static String META_HEAD_GTASK_ID = "meta_gid";
// 表示元数据中笔记相关内容的键名,用于在元数据结构中存放与笔记相关的具体信息
public final static String META_HEAD_NOTE = "meta_note"; public final static String META_HEAD_NOTE = "meta_note";
// 表示元数据中数据相关内容的键名,用于在元数据结构中存放一些额外的数据信息(可能是和任务、笔记等相关的数据集合等情况)
public final static String META_HEAD_DATA = "meta_data"; public final static String META_HEAD_DATA = "meta_data";
// 表示元数据笔记名称的字符串常量,同时提示不要更新和删除该元数据笔记(可能是具有特殊用途的固定元数据相关说明)
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
} }

@ -13,71 +13,66 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
// 该类所属的包名表明这个类位于net.micode.notes.tool包下用于提供一些资源相关的解析和获取功能
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
// ResourceParser类主要用于对应用中的各种资源如背景图片、文本样式等进行管理和提供获取方法方便在不同的界面等场景中使用
public class ResourceParser { public class ResourceParser {
// 定义颜色相关的常量,用整数表示不同的颜色选项,方便在代码中进行统一的颜色选择和判断,这里分别对应黄色、蓝色、白色、绿色、红色 // 定义笔记背景颜色的常量
public static final int YELLOW = 0; public static final int YELLOW = 0;
public static final int BLUE = 1; public static final int BLUE = 1;
public static final int WHITE = 2; public static final int WHITE = 2;
public static final int GREEN = 3; public static final int GREEN = 3;
public static final int RED = 4; public static final int RED = 4;
// 定义默认的背景颜色常量其值为黄色对应上面定义的颜色常量中的YELLOW表示在没有特殊设置时默认使用的背景颜色 // 默认笔记背景颜色
public static final int BG_DEFAULT_COLOR = YELLOW; public static final int BG_DEFAULT_COLOR = YELLOW;
// 定义文本大小相关的常量,用整数表示不同的文本大小选项,方便在代码中统一处理文本大小相关的设置和获取,这里分别对应小、中、大、超大文本尺寸 // 定义笔记文本大小的常量
public static final int TEXT_SMALL = 0; public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1; public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2; public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3; public static final int TEXT_SUPER = 3;
// 定义默认的字体大小常量其值为中等大小对应上面定义的文本大小常量中的TEXT_MEDIUM表示在没有特殊设置时默认使用的字体大小 // 默认笔记背景文本大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 内部静态类NoteBgResources用于管理笔记编辑界面相关的背景资源图片资源 // 用于获取编辑笔记时的背景资源
public static class NoteBgResources { public static class NoteBgResources {
// 定义一个私有的静态整型数组存储笔记编辑界面背景图片资源的ID对应不同颜色的编辑界面背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_EDIT_RESOURCES = new int [] {
private final static int[] BG_EDIT_RESOURCES = new int[] { R.drawable.edit_yellow,
R.drawable.edit_yellow, R.drawable.edit_blue,
R.drawable.edit_blue, R.drawable.edit_white,
R.drawable.edit_white, R.drawable.edit_green,
R.drawable.edit_green, R.drawable.edit_red
R.drawable.edit_red
}; };
// 定义一个私有的静态整型数组存储笔记编辑界面标题背景图片资源的ID对应不同颜色的编辑界面标题背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
private final static int[] BG_EDIT_TITLE_RESOURCES = new int[] { R.drawable.edit_title_yellow,
R.drawable.edit_title_yellow, R.drawable.edit_title_blue,
R.drawable.edit_title_blue, R.drawable.edit_title_white,
R.drawable.edit_title_white, R.drawable.edit_title_green,
R.drawable.edit_title_green, R.drawable.edit_title_red
R.drawable.edit_title_red
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记编辑界面的背景图片资源ID方便在设置编辑界面背景时使用 // 根据ID获取编辑笔记的背景资源
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id]; return BG_EDIT_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记编辑界面标题的背景图片资源ID方便在设置编辑界面标题背景时使用 // 根据ID获取编辑笔记标题的背景资源
public static int getNoteTitleBgResource(int id) { public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
// 根据传入的上下文Context获取默认的背景图片ID逻辑是先检查是否在偏好设置中设置了自定义背景颜色通过特定的偏好设置键来判断 // 获取默认笔记背景颜色ID
// 如果设置了则随机选择一个背景资源ID从NoteBgResources中定义的资源数组长度范围内随机否则返回默认的背景颜色IDBG_DEFAULT_COLOR
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -86,114 +81,106 @@ public class ResourceParser {
return BG_DEFAULT_COLOR; return BG_DEFAULT_COLOR;
} }
} }
// 内部静态类NoteItemBgResources用于管理笔记列表项相关的背景资源图片资源 // 用于获取笔记列表项的背景资源
public static class NoteItemBgResources { public static class NoteItemBgResources {
// 定义一个私有的静态整型数组存储笔记列表项第一个元素可能是列表头部等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_FIRST_RESOURCES = new int [] {
private final static int[] BG_FIRST_RESOURCES = new int[] { R.drawable.list_yellow_up,
R.drawable.list_yellow_up, R.drawable.list_blue_up,
R.drawable.list_blue_up, R.drawable.list_white_up,
R.drawable.list_white_up, R.drawable.list_green_up,
R.drawable.list_green_up, R.drawable.list_red_up
R.drawable.list_red_up
}; };
// 定义一个私有的静态整型数组存储笔记列表项中间元素正常的列表项情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_NORMAL_RESOURCES = new int [] {
private final static int[] BG_NORMAL_RESOURCES = new int[] { R.drawable.list_yellow_middle,
R.drawable.list_yellow_middle, R.drawable.list_blue_middle,
R.drawable.list_blue_middle, R.drawable.list_white_middle,
R.drawable.list_white_middle, R.drawable.list_green_middle,
R.drawable.list_green_middle, R.drawable.list_red_middle,
R.drawable.list_red_middle
}; };
// 定义一个私有的静态整型数组存储笔记列表项最后一个元素可能是列表尾部等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_LAST_RESOURCES = new int [] {
private final static int[] BG_LAST_RESOURCES = new int[] { R.drawable.list_yellow_down,
R.drawable.list_yellow_down, R.drawable.list_blue_down,
R.drawable.list_blue_down, R.drawable.list_white_down,
R.drawable.list_white_down, R.drawable.list_green_down,
R.drawable.list_green_down, R.drawable.list_red_down,
R.drawable.list_red_down,
}; };
// 定义一个私有的静态整型数组存储单个笔记可能是独立展示等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_SINGLE_RESOURCES = new int [] {
private final static int[] BG_SINGLE_RESOURCES = new int[] { R.drawable.list_yellow_single,
R.drawable.list_yellow_single, R.drawable.list_blue_single,
R.drawable.list_blue_single, R.drawable.list_white_single,
R.drawable.list_white_single, R.drawable.list_green_single,
R.drawable.list_green_single, R.drawable.list_red_single
R.drawable.list_red_single
}; };
// 根据传入的颜色ID对应前面定义的颜色常量获取笔记列表项第一个元素的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表第一项的背景资源
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id]; return BG_FIRST_RESOURCES[id];
} }
// 根据传入的颜色ID对应前面定义的颜色常量获取笔记列表项最后一个元素的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表最后一项的背景资源
public static int getNoteBgLastRes(int id) { public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id]; return BG_LAST_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取单个笔记的背景图片资源ID方便在设置单个笔记背景时使用 // 根据ID获取单个笔记的背景资源
public static int getNoteBgSingleRes(int id) { public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id]; return BG_SINGLE_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记列表中间元素(正常列表的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表中间项的背景资源
public static int getNoteBgNormalRes(int id) { public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id]; return BG_NORMAL_RESOURCES[id];
} }
// 获取文件夹背景图片资源ID用于设置文件夹在列表等展示场景中的背景图片 // 获取文件夹背景资源
public static int getFolderBgRes() { public static int getFolderBgRes() {
return R.drawable.list_folder; return R.drawable.list_folder;
} }
} }
// 内部静态类WidgetBgResources用于管理桌面小部件相关的背景资源图片资源 // 用于获取小部件的背景资源
public static class WidgetBgResources { public static class WidgetBgResources {
// 定义一个私有的静态整型数组存储2x尺寸桌面小部件的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_2X_RESOURCES = new int [] {
private final static int[] BG_2X_RESOURCES = new int[] { R.drawable.widget_2x_yellow,
R.drawable.widget_2x_yellow, R.drawable.widget_2x_blue,
R.drawable.widget_2x_blue, R.drawable.widget_2x_white,
R.drawable.widget_2x_white, R.drawable.widget_2x_green,
R.drawable.widget_2x_green, R.drawable.widget_2x_red,
R.drawable.widget_2x_red,
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取2x尺寸桌面小部件的背景图片资源ID方便在设置小部件背景时使用 // 根据ID获取2x小部件的背景资源
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; return BG_2X_RESOURCES[id];
} }
// 定义一个私有的静态整型数组存储4x尺寸桌面小部件的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 private final static int [] BG_4X_RESOURCES = new int [] {
private final static int[] BG_4X_RESOURCES = new int[] { R.drawable.widget_4x_yellow,
R.drawable.widget_4x_yellow, R.drawable.widget_4x_blue,
R.drawable.widget_4x_blue, R.drawable.widget_4x_white,
R.drawable.widget_4x_white, R.drawable.widget_4x_green,
R.drawable.widget_4x_green, R.drawable.widget_4x_red
R.drawable.widget_4x_red
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取4x尺寸桌面小部件的背景图片资源ID方便在设置小部件背景时使用 // 根据ID获取4x小部件的背景资源
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; return BG_4X_RESOURCES[id];
} }
} }
// 内部静态类TextAppearanceResources用于管理文本外观相关的资源主要是文本样式资源 // 用于获取文本外观资源
public static class TextAppearanceResources { public static class TextAppearanceResources {
// 定义一个私有的静态整型数组存储不同文本外观样式的资源ID对应不同大小的文本外观样式顺序与前面定义的文本大小常量顺序有一定关联 private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
private final static int[] TEXTAPPEARANCE_RESOURCES = new int[] { R.style.TextAppearanceNormal,
R.style.TextAppearanceNormal, R.style.TextAppearanceMedium,
R.style.TextAppearanceMedium, R.style.TextAppearanceLarge,
R.style.TextAppearanceLarge, R.style.TextAppearanceSuper
R.style.TextAppearanceSuper
}; };
// 根据传入的文本外观资源ID获取对应的文本外观资源ID如果传入的ID大于资源数组的长度可能是由于存储或获取出现异常情况 // 根据ID获取文本外观资源
// 则返回默认的字体大小对应的资源IDBG_DEFAULT_FONT_SIZE以避免出现资源获取错误
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.
@ -205,8 +192,8 @@ public class ResourceParser {
} }
return TEXTAPPEARANCE_RESOURCES[id]; return TEXTAPPEARANCE_RESOURCES[id];
} }
// 获取文本外观资源数组长度,可用于判断资源数量或者进行一些边界相关的操作判断等 // 获取文本外观资源的数量
public static int getResourcesSize() { public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length; return TEXTAPPEARANCE_RESOURCES.length;
} }

@ -39,21 +39,29 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
/**
* ActivityOnClickListenerOnDismissListener
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; private long mNoteId; // 保存笔记的ID
private String mSnippet; private String mSnippet; // 保存笔记的摘要
private static final int SNIPPET_PREW_MAX_LEN = 60; private static final int SNIPPET_PREW_MAX_LEN = 60; // 笔记摘要的最大长度
MediaPlayer mPlayer; MediaPlayer mPlayer; // 用于播放闹钟声音的MediaPlayer实例
/**
*
* @param savedInstanceState
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题窗口
final Window win = getWindow(); final Window win = getWindow(); // 获取当前窗口
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 设置窗口在锁屏时显示
// 如果屏幕未点亮,则添加更多标志以保持屏幕点亮并允许在锁屏时操作
if (!isScreenOn()) { if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
@ -61,98 +69,123 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
Intent intent = getIntent(); Intent intent = getIntent(); // 获取启动该活动的Intent
try { try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从Intent中提取笔记ID
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 根据笔记ID获取摘要
// 如果摘要长度超过最大限制则截取前SNIPPET_PREW_MAX_LEN个字符并添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet; : mSnippet;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace(); // 打印异常信息
return; return; // 如果发生异常,则结束该方法
} }
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer(); // 创建MediaPlayer实例
// 检查数据库中是否存在指定ID的笔记
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog(); showActionDialog(); // 显示操作对话框
playAlarmSound(); playAlarmSound(); // 播放闹钟声音
} else { } else {
finish(); finish(); // 如果笔记不存在,则结束该活动
} }
} }
/**
*
* @return truefalse
*/
private boolean isScreenOn() { private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); // 获取电源管理服务
return pm.isScreenOn(); return pm.isScreenOn(); // 返回屏幕是否点亮的状态
} }
/**
*
*/
private void playAlarmSound() { private void playAlarmSound() {
// 获取实际的默认闹钟铃声URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取当前设置的静音模式影响的音频流类型
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 如果静音模式影响了闹钟音频流则设置MediaPlayer的音频流类型为silentModeStreams
// 否则设置为AudioManager.STREAM_ALARM
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
mPlayer.setDataSource(this, url); mPlayer.setDataSource(this, url); // 设置MediaPlayer的数据源为闹钟铃声URI
mPlayer.prepare(); mPlayer.prepare(); // 准备MediaPlayer
mPlayer.setLooping(true); mPlayer.setLooping(true); // 设置MediaPlayer循环播放
mPlayer.start(); mPlayer.start(); // 开始播放闹钟声音
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (SecurityException e) { } catch (SecurityException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} }
} }
/**
*
*/
private void showActionDialog() { private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 创建AlertDialog.Builder实例
dialog.setTitle(R.string.app_name); dialog.setTitle(R.string.app_name); // 设置对话框标题为应用名称
dialog.setMessage(mSnippet); dialog.setMessage(mSnippet); // 设置对话框消息为笔记摘要
dialog.setPositiveButton(R.string.notealert_ok, this); dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮及其监听器
// 如果屏幕已点亮,则添加进入按钮及其监听器
if (isScreenOn()) { if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); dialog.setNegativeButton(R.string.notealert_enter, this);
} }
dialog.show().setOnDismissListener(this); dialog.show().setOnDismissListener(this); // 显示对话框并设置对话框消失监听器
} }
/**
* OnClickListener
* @param dialog
* @param which ID
*/
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class); // 创建Intent准备跳转到笔记编辑活动
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW); // 设置Intent动作类型为ACTION_VIEW
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.putExtra(Intent.EXTRA_UID, mNoteId); // 添加笔记ID作为附加信息
startActivity(intent); startActivity(intent); // 启动笔记编辑活动
break; break;
default: default:
break; break;
} }
} }
/**
* OnDismissListener
* @param dialog
*/
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); stopAlarmSound(); // 停止播放闹钟声音
finish(); finish(); // 结束该活动
} }
/**
* MediaPlayer
*/
private void stopAlarmSound() { private void stopAlarmSound() {
if (mPlayer != null) { if (mPlayer != null) {
mPlayer.stop(); mPlayer.stop(); // 停止MediaPlayer播放
mPlayer.release(); mPlayer.release(); // 释放MediaPlayer资源
mPlayer = null; mPlayer = null; // 将mPlayer置为null
} }
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
@ -23,21 +23,24 @@ import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
// 该广播接收器用于初始化闹钟,查询即将提醒的笔记并设置闹钟
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
// 查询笔记数据库时使用的列投影
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE
}; };
// 列索引常量,用于从查询结果中提取数据
private static final int COLUMN_ID = 0; private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ALERTED_DATE = 1;
// 接收广播时执行的方法,查询数据库并设置闹钟
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();
@ -46,7 +49,7 @@ public class AlarmInitReceiver extends BroadcastReceiver {
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) }, new String[] { String.valueOf(currentDate) },
null); null);
if (c != null) { if (c != null) {
if (c.moveToFirst()) { if (c.moveToFirst()) {
do { do {
@ -62,4 +65,4 @@ public class AlarmInitReceiver extends BroadcastReceiver {
c.close(); c.close();
} }
} }
} }

@ -13,18 +13,23 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
// 一个继承自BroadcastReceiver的类用于接收闹钟触发的广播
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
// 当接收到广播时,该方法会被调用
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 设置Intent的目标Activity为AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加标志以允许启动新的Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity
context.startActivity(intent); context.startActivity(intent);
} }
} }

File diff suppressed because it is too large Load Diff

@ -13,33 +13,40 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import java.util.Calendar; import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker; import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
// 自定义的日期时间选择对话框继承自AlertDialog并实现了OnClickListener接口
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 存储当前选择的日期时间
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
// 是否使用24小时制
private boolean mIs24HourView; private boolean mIs24HourView;
// 回调接口,当日期时间设置完成后调用
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
// 日期时间选择器控件
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
// 定义日期时间设置完成后的回调接口
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
// 构造函数,初始化对话框并设置初始日期时间
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
@ -63,15 +70,18 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
// 设置是否使用24小时制显示时间
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
// 设置日期时间选择完成后的回调监听器
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
// 更新对话框的标题以显示当前选择的日期时间
private void updateTitle(long date) { private void updateTitle(long date) {
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
@ -80,11 +90,12 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
// 处理用户点击对话框按钮的事件,如果是确认按钮则调用回调监听器
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
@ -24,14 +24,16 @@ import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import android.widget.PopupMenu; import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
// 下拉菜单类,用于在按钮点击时显示一个弹出菜单
public class DropdownMenu { public class DropdownMenu {
private Button mButton; private Button mButton; // 用于触发下拉菜单的按钮
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu; // 弹出菜单对象
private Menu mMenu; private Menu mMenu; // 菜单对象
// 构造函数,初始化下拉菜单,设置按钮背景,并将菜单资源加载到弹出菜单中
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;
mButton.setBackgroundResource(R.drawable.dropdown_icon); mButton.setBackgroundResource(R.drawable.dropdown_icon);
@ -44,18 +46,21 @@ public class DropdownMenu {
} }
}); });
} }
// 设置下拉菜单项点击监听器
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
// 根据菜单项的ID查找菜单项
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); return mMenu.findItem(id);
} }
// 设置按钮的标题
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); mButton.setText(title);
} }
} }

@ -28,26 +28,31 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
// 自定义的 CursorAdapter 用于显示文件夹列表
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
// 定义查询文件夹时需要的列
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 列索引常量
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
// 构造函数,初始化 FoldersListAdapter
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
// 创建一个新的视图项
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); return new FolderListItem(context);
} }
// 绑定数据到视图项
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
@ -57,24 +62,28 @@ public class FoldersListAdapter extends CursorAdapter {
} }
} }
// 根据位置获取文件夹名称
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
// 内部类,定义文件夹列表项的视图结构
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
private TextView mName; private TextView mName;
// 构造函数,初始化 FolderListItem 视图
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name);
} }
// 绑定文件夹名称到视图
public void bind(String name) { public void bind(String name) {
mName.setText(name); mName.setText(name);
} }
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.AlertDialog; import android.app.AlertDialog;
@ -51,7 +51,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
@ -64,26 +64,28 @@ import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;
import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;
import net.micode.notes.widget.NoteWidgetProvider_2x; import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x; import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
// 笔记编辑界面的Activity类
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
// 用于存储笔记头部视图的ViewHolder类
private class HeadViewHolder { private class HeadViewHolder {
public TextView tvModified; public TextView tvModified;
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
public TextView tvAlertDate; public TextView tvAlertDate;
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
} }
// 背景色选择按钮和颜色ID的映射
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
@ -92,7 +94,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
} }
// 背景色选择后的显示标记和颜色ID的映射
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
@ -101,7 +104,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
} }
// 字体大小选择按钮和字体大小ID的映射
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static {
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
@ -109,7 +113,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
} }
// 字体大小选择后的显示标记和字体大小ID的映射
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
@ -117,54 +122,52 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
} }
private static final String TAG = "NoteEditActivity"; private static final String TAG = "NoteEditActivity";
private HeadViewHolder mNoteHeaderHolder; private HeadViewHolder mNoteHeaderHolder;
private View mHeadViewPanel; private View mHeadViewPanel;
private View mNoteBgColorSelector; private View mNoteBgColorSelector;
private View mFontSizeSelector; private View mFontSizeSelector;
private EditText mNoteEditor; private EditText mNoteEditor;
private View mNoteEditorPanel; private View mNoteEditorPanel;
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;
private int mFontSizeId; private int mFontSizeId;
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
public static final String TAG_CHECKED = String.valueOf('\u221A'); public static final String TAG_CHECKED = String.valueOf('\u221A');
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
private LinearLayout mEditTextList; private LinearLayout mEditTextList;
private String mUserQuery; private String mUserQuery;
private Pattern mPattern; private Pattern mPattern;
// 初始化Activity视图
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);
if (savedInstanceState == null && !initActivityState(getIntent())) { if (savedInstanceState == null && !initActivityState(getIntent())) {
finish(); finish();
return; return;
} }
initResources(); initResources();
} }
/** // 当Activity被系统杀死后恢复其状态
* Current activity may be killed when the memory is low. Once it is killed, for another time
* user load this activity, we should restore the former state
*/
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
@ -178,25 +181,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.d(TAG, "Restoring from killed activity"); Log.d(TAG, "Restoring from killed activity");
} }
} }
// 初始化Activity状态根据Intent决定加载笔记或创建新笔记
private boolean initActivityState(Intent intent) { private boolean initActivityState(Intent intent) {
/**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity
*/
mWorkingNote = null; mWorkingNote = null;
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = ""; mUserQuery = "";
/**
* Starting from the searched result
*/
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
} }
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
Intent jump = new Intent(this, NotesListActivity.class); Intent jump = new Intent(this, NotesListActivity.class);
startActivity(jump); startActivity(jump);
@ -215,7 +212,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// New note
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID); AppWidgetManager.INVALID_APPWIDGET_ID);
@ -223,8 +219,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Notes.TYPE_WIDGET_INVALIDE); Notes.TYPE_WIDGET_INVALIDE);
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this)); ResourceParser.getDefaultBgId(this));
// Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
if (callDate != 0 && phoneNumber != null) { if (callDate != 0 && phoneNumber != null) {
@ -249,7 +244,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId); bgResId);
} }
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
@ -261,13 +256,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.setOnSettingStatusChangedListener(this); mWorkingNote.setOnSettingStatusChangedListener(this);
return true; return true;
} }
// Activity恢复时初始化笔记显示
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
initNoteScreen(); initNoteScreen();
} }
// 初始化笔记显示界面,包括背景颜色、字体大小、修改日期等
private void initNoteScreen() { private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
@ -282,19 +279,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR)); | DateUtils.FORMAT_SHOW_YEAR));
/**
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready
*/
showAlertHeader(); showAlertHeader();
} }
// 显示或隐藏提醒头部信息
private void showAlertHeader() { private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
@ -311,28 +305,26 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
}; };
} }
// 处理新的Intent可能需要重新加载笔记或创建新笔记
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); super.onNewIntent(intent);
initActivityState(intent); initActivityState(intent);
} }
// 保存Activity状态在系统需要恢复Activity时使用
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
/**
* For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
} }
// 处理触摸事件,用于隐藏颜色和字体大小选择面板
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
@ -340,7 +332,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
} }
if (mFontSizeSelector.getVisibility() == View.VISIBLE if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) { && !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
@ -348,7 +340,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
// 判断触摸事件是否发生在指定视图内
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
@ -362,7 +355,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return true; return true;
} }
// 初始化视图资源
private void initResources() { private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
@ -378,7 +372,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
ImageView iv = (ImageView) findViewById(id); ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this); iv.setOnClickListener(this);
} }
mFontSizeSelector = findViewById(R.id.font_size_selector); mFontSizeSelector = findViewById(R.id.font_size_selector);
for (int id : sFontSizeBtnsMap.keySet()) { for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id); View view = findViewById(id);
@ -386,17 +380,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}; };
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
} }
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
// 暂停Activity时保存笔记并清理设置状态
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
@ -405,7 +395,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
clearSettingState(); clearSettingState();
} }
// 更新桌面小部件显示
private void updateWidget() { private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
@ -416,21 +407,22 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.e(TAG, "Unspported widget type"); Log.e(TAG, "Unspported widget type");
return; return;
} }
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
mWorkingNote.getWidgetId() mWorkingNote.getWidgetId()
}); });
sendBroadcast(intent); sendBroadcast(intent);
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
// 处理视图点击事件,包括颜色和字体大小选择
public void onClick(View v) { public void onClick(View v) {
int id = v.getId(); int id = v.getId();
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE); View.VISIBLE);
} else if (sBgSelectorBtnsMap.containsKey(id)) { } else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE); View.GONE);
@ -451,17 +443,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
} }
} }
// 处理返回键事件,如果设置面板可见则隐藏,否则保存笔记后返回
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if(clearSettingState()) { if(clearSettingState()) {
return; return;
} }
saveNote(); saveNote();
super.onBackPressed(); super.onBackPressed();
} }
// 清理设置面板状态
private boolean clearSettingState() { private boolean clearSettingState() {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
@ -472,14 +466,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return false; return false;
} }
// 处理笔记背景颜色变化事件
public void onBackgroundColorChanged() { public void onBackgroundColorChanged() {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); View.VISIBLE);
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
} }
// 准备选项菜单,根据笔记状态动态更新菜单项
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) { if (isFinishing()) {
@ -504,7 +500,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return true; return true;
} }
// 处理选项菜单项点击事件
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
@ -552,7 +549,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return true; return true;
} }
// 设置提醒时间
private void setReminder() { private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
@ -562,30 +560,27 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}); });
d.show(); d.show();
} }
/** // 分享笔记内容到支持ACTION_SEND的其他应用
* Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type
*/
private void sendTo(Context context, String info) { private void sendTo(Context context, String info) {
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, info); intent.putExtra(Intent.EXTRA_TEXT, info);
intent.setType("text/plain"); intent.setType("text/plain");
context.startActivity(intent); context.startActivity(intent);
} }
// 创建新笔记,跳转到新笔记编辑界面
private void createNewNote() { private void createNewNote() {
// Firstly, save current editing notes
saveNote(); saveNote();
// For safety, start a new NoteEditActivity
finish(); finish();
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());
startActivity(intent); startActivity(intent);
} }
// 删除当前笔记
private void deleteCurrentNote() { private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
@ -607,16 +602,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
// 判断是否处于同步模式
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
// 处理时钟提醒变化事件,设置或取消提醒
public void onClockAlertChanged(long date, boolean set) { public void onClockAlertChanged(long date, boolean set) {
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
@ -632,31 +625,28 @@ public class NoteEditActivity extends Activity implements OnClickListener,
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
} }
} else { } else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Clock alert setting error"); Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock); showToast(R.string.error_note_empty_for_clock);
} }
} }
// 处理小部件变化事件,更新小部件显示
public void onWidgetChanged() { public void onWidgetChanged() {
updateWidget(); updateWidget();
} }
// 处理EditText删除事件调整列表项索引
public void onEditTextDelete(int index, String text) { public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount(); int childCount = mEditTextList.getChildCount();
if (childCount == 1) { if (childCount == 1) {
return; return;
} }
for (int i = index + 1; i < childCount; i++) { for (int i = index + 1; i < childCount; i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1); .setIndex(i - 1);
} }
mEditTextList.removeViewAt(index); mEditTextList.removeViewAt(index);
NoteEditText edit = null; NoteEditText edit = null;
if(index == 0) { if(index == 0) {
@ -671,15 +661,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.requestFocus(); edit.requestFocus();
edit.setSelection(length); edit.setSelection(length);
} }
// 处理EditText输入事件添加新列表项
public void onEditTextEnter(int index, String text) { public void onEditTextEnter(int index, String text) {
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) { if(index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
} }
View view = getListItem(text, index); View view = getListItem(text, index);
mEditTextList.addView(view, index); mEditTextList.addView(view, index);
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
@ -690,7 +678,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
.setIndex(i); .setIndex(i);
} }
} }
// 切换到列表模式,根据笔记内容生成列表项
private void switchToListMode(String text) { private void switchToListMode(String text) {
mEditTextList.removeAllViews(); mEditTextList.removeAllViews();
String[] items = text.split("\n"); String[] items = text.split("\n");
@ -703,11 +692,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
mEditTextList.addView(getListItem("", index)); mEditTextList.addView(getListItem("", index));
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
mNoteEditor.setVisibility(View.GONE); mNoteEditor.setVisibility(View.GONE);
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
// 获取高亮查询结果,用于显示搜索关键词
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {
@ -724,7 +714,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return spannable; return spannable;
} }
// 生成一个新的列表项视图
private View getListItem(String item, int index) { private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
@ -739,7 +730,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
}); });
if (item.startsWith(TAG_CHECKED)) { if (item.startsWith(TAG_CHECKED)) {
cb.setChecked(true); cb.setChecked(true);
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
@ -749,13 +740,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
} }
edit.setOnTextViewChangeListener(this); edit.setOnTextViewChangeListener(this);
edit.setIndex(index); edit.setIndex(index);
edit.setText(getHighlightQueryResult(item, mUserQuery)); edit.setText(getHighlightQueryResult(item, mUserQuery));
return view; return view;
} }
// 处理EditText文本变化事件显示或隐藏复选框
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
@ -767,7 +759,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
} }
} }
// 处理笔记模式变化事件,从普通模式切换到列表模式或反之
public void onCheckListModeChanged(int oldMode, int newMode) { public void onCheckListModeChanged(int oldMode, int newMode) {
if (newMode == TextNote.MODE_CHECK_LIST) { if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString()); switchToListMode(mNoteEditor.getText().toString());
@ -781,7 +774,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteEditor.setVisibility(View.VISIBLE); mNoteEditor.setVisibility(View.VISIBLE);
} }
} }
// 获取正在编辑的文本内容,根据列表模式添加标签
private boolean getWorkingText() { private boolean getWorkingText() {
boolean hasChecked = false; boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
@ -804,33 +798,23 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return hasChecked; return hasChecked;
} }
// 保存笔记内容到数据库
private boolean saveNote() { private boolean saveNote() {
getWorkingText(); getWorkingText();
boolean saved = mWorkingNote.saveNote(); boolean saved = mWorkingNote.saveNote();
if (saved) { if (saved) {
/**
* There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original
* position in the list when back from edit view, while creating a
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
setResult(RESULT_OK); setResult(RESULT_OK);
} }
return saved; return saved;
} }
// 将笔记快捷方式添加到桌面
private void sendToDesktop() { private void sendToDesktop() {
/**
* Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly
* save it
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {
Intent sender = new Intent(); Intent sender = new Intent();
Intent shortcutIntent = new Intent(this, NoteEditActivity.class); Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
@ -846,28 +830,26 @@ public class NoteEditActivity extends Activity implements OnClickListener,
showToast(R.string.info_note_enter_desktop); showToast(R.string.info_note_enter_desktop);
sendBroadcast(sender); sendBroadcast(sender);
} else { } else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Send to desktop error"); Log.e(TAG, "Send to desktop error");
showToast(R.string.error_note_empty_for_send_to_desktop); showToast(R.string.error_note_empty_for_send_to_desktop);
} }
} }
// 生成桌面快捷方式的标题,截取笔记内容的一部分作为标题
private String makeShortcutIconTitle(String content) { private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, ""); content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, ""); content = content.replace(TAG_UNCHECKED, "");
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; SHORTCUT_ICON_TITLE_MAX_LEN) : content;
} }
// 显示短Toast消息
private void showToast(int resId) { private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT); showToast(resId, Toast.LENGTH_SHORT);
} }
// 显示指定持续时间的Toast消息
private void showToast(int resId, int duration) { private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show(); Toast.makeText(this, resId, duration).show();
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.graphics.Rect; import android.graphics.Rect;
import android.text.Layout; import android.text.Layout;
@ -31,28 +31,29 @@ import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener; import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.widget.EditText; import android.widget.EditText;
import net.micode.notes.R; import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
// 自定义的EditText用于笔记应用中支持删除、添加文本事件监听
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
private int mIndex; private int mIndex;
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
} }
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text * Call by the {@link NoteEditActivity} to delete or add edit text
*/ */
@ -62,65 +63,69 @@ public class NoteEditText extends EditText {
* and the text is null * and the text is null
*/ */
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);
/** /**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen * happen
*/ */
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);
/** /**
* Hide or show item option when text change * Hide or show item option when text change
*/ */
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;
public NoteEditText(Context context) { public NoteEditText(Context context) {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
// 设置当前文本框的索引
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
// 设置文本变化监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
// 处理触摸事件,更新光标位置
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
int x = (int) event.getX(); int x = (int) event.getX();
int y = (int) event.getY(); int y = (int) event.getY();
x -= getTotalPaddingLeft(); x -= getTotalPaddingLeft();
y -= getTotalPaddingTop(); y -= getTotalPaddingTop();
x += getScrollX(); x += getScrollX();
y += getScrollY(); y += getScrollY();
Layout layout = getLayout(); Layout layout = getLayout();
int line = layout.getLineForVertical(y); int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x); int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off); Selection.setSelection(getText(), off);
break; break;
} }
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
// 处理按键按下事件,记录删除操作前的光标位置
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
@ -137,7 +142,8 @@ public class NoteEditText extends EditText {
} }
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
// 处理按键弹起事件,根据按键类型执行相应操作
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { switch(keyCode) {
@ -166,7 +172,8 @@ public class NoteEditText extends EditText {
} }
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
} }
// 当EditText焦点发生变化时调用通知监听器文本是否有内容
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
@ -178,16 +185,17 @@ public class NoteEditText extends EditText {
} }
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect);
} }
// 创建上下文菜单处理URL点击事件
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd); int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) { if (urls.length == 1) {
int defaultResId = 0; int defaultResId = 0;
@ -197,11 +205,11 @@ public class NoteEditText extends EditText {
break; break;
} }
} }
if (defaultResId == 0) { if (defaultResId == 0) {
defaultResId = R.string.note_link_other; defaultResId = R.string.note_link_other;
} }
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() { new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
@ -214,4 +222,4 @@ public class NoteEditText extends EditText {
} }
super.onCreateContextMenu(menu); super.onCreateContextMenu(menu);
} }
} }

@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import net.micode.notes.data.Contact; import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
// 该类用于从数据库游标中提取笔记项数据,并处理与笔记位置相关的逻辑
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
@ -41,7 +41,8 @@ public class NoteItemData {
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
// 定义了游标中各个列的索引位置
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
@ -54,7 +55,8 @@ public class NoteItemData {
private static final int TYPE_COLUMN = 9; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记项的各种属性
private long mId; private long mId;
private long mAlertDate; private long mAlertDate;
private int mBgColorId; private int mBgColorId;
@ -69,13 +71,15 @@ public class NoteItemData {
private int mWidgetType; private int mWidgetType;
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
// 笔记项在列表中的位置信息
private boolean mIsLastItem; private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
// 构造函数,从游标中提取笔记项数据
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
@ -91,7 +95,7 @@ public class NoteItemData {
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = ""; mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
@ -102,20 +106,21 @@ public class NoteItemData {
} }
} }
} }
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
checkPostion(cursor); checkPostion(cursor);
} }
// 检查笔记项在列表中的位置信息
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition(); int position = cursor.getPosition();
if (cursor.moveToPrevious()) { if (cursor.moveToPrevious()) {
@ -133,92 +138,114 @@ public class NoteItemData {
} }
} }
} }
// 判断该笔记项是否是单个笔记跟在一个文件夹后
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
// 判断该笔记项是否是多个笔记跟在一个文件夹后
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
// 判断该笔记项是否是列表中的最后一个项
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
// 获取与该笔记项关联的呼叫记录的联系人名称
public String getCallName() { public String getCallName() {
return mName; return mName;
} }
// 判断该笔记项是否是列表中的第一个项
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
// 判断该笔记项是否是列表中唯一的项
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
// 获取笔记项的ID
public long getId() { public long getId() {
return mId; return mId;
} }
// 获取笔记项的提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取笔记项的创建日期
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }
// 判断该笔记项是否有附件
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }
// 获取笔记项的修改日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取笔记项的背景颜色ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取笔记项的父ID
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
// 获取笔记项包含的笔记数量
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
// 获取笔记项所在的文件夹ID
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }
// 获取笔记项的类型
public int getType() { public int getType() {
return mType; return mType;
} }
// 获取笔记项的小部件类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 获取笔记项的小部件ID
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取笔记项的摘要
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
// 判断该笔记项是否有提醒
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); return (mAlertDate > 0);
} }
// 判断该笔记项是否是呼叫记录类型
public boolean isCallRecord() { public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
// 静态方法,从游标中获取笔记项的类型
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }
} }

@ -126,12 +126,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private NoteItemData mFocusNoteDataItem; private NoteItemData mFocusNoteDataItem;
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)"; + NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_OPEN_NODE = 102;
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@ -951,4 +951,4 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
return false; return false;
} }
} }

@ -13,48 +13,52 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
// 自定义的CursorAdapter用于显示笔记列表
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; private int mNotesCount;
private boolean mChoiceMode; private boolean mChoiceMode;
// 用于存储小部件属性的内部类
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
// 构造函数,初始化上下文和选择索引
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context; mContext = context;
mNotesCount = 0; mNotesCount = 0;
} }
// 创建新的视图项
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
// 绑定数据到视图项
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
@ -63,21 +67,25 @@ public class NotesListAdapter extends CursorAdapter {
isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
} }
} }
// 设置指定位置的项是否被选中,并通知数据集发生变化
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
notifyDataSetChanged(); notifyDataSetChanged();
} }
// 检查当前是否处于多选模式
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
// 设置多选模式,清空选择索引
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
// 全选或全不选所有笔记
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
@ -88,7 +96,8 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
// 获取所有选中的笔记ID集合
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -101,10 +110,11 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
return itemSet; return itemSet;
} }
// 获取所有选中的小部件属性集合
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -127,7 +137,8 @@ public class NotesListAdapter extends CursorAdapter {
} }
return itemSet; return itemSet;
} }
// 获取选中的笔记数量
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
@ -142,31 +153,36 @@ public class NotesListAdapter extends CursorAdapter {
} }
return count; return count;
} }
// 检查是否所有笔记都被选中
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
} }
// 检查指定位置的项是否被选中
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
} }
return mSelectedIndex.get(position); return mSelectedIndex.get(position);
} }
// 当数据内容发生变化时,更新笔记数量
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount();
} }
// 更改Cursor时更新笔记数量
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount();
} }
// 计算笔记数量
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
@ -181,4 +197,4 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.text.format.DateUtils; import android.text.format.DateUtils;
import android.view.View; import android.view.View;
@ -23,13 +23,13 @@ import android.widget.CheckBox;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
// NotesListItem 类继承自 LinearLayout用于表示笔记列表中的一个项
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert;
private TextView mTitle; private TextView mTitle;
@ -37,7 +37,8 @@ public class NotesListItem extends LinearLayout {
private TextView mCallName; private TextView mCallName;
private NoteItemData mItemData; private NoteItemData mItemData;
private CheckBox mCheckBox; private CheckBox mCheckBox;
// 构造函数,初始化 NotesListItem 的视图组件
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);
@ -47,7 +48,8 @@ public class NotesListItem extends LinearLayout {
mCallName = (TextView) findViewById(R.id.tv_name); mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
// 绑定数据到 NotesListItem 的视图组件,并设置选择模式和选中状态
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
@ -55,7 +57,7 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE);
} }
mItemData = data; mItemData = data;
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
@ -78,7 +80,7 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
@ -95,10 +97,11 @@ public class NotesListItem extends LinearLayout {
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data); setBackground(data);
} }
// 根据数据设置 NotesListItem 的背景资源
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
@ -115,8 +118,9 @@ public class NotesListItem extends LinearLayout {
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
// 获取绑定到此 NotesListItem 的数据
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.ActionBar; import android.app.ActionBar;
@ -41,59 +41,60 @@ import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
// 设置界面活动类继承自PreferenceActivity
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
private Account[] mOriAccounts; private Account[] mOriAccounts;
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
// 创建活动时初始化界面
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* 使用应用图标进行导航 */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
mOriAccounts = null; mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
// 恢复活动时刷新界面
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // 如果用户添加了新账户,自动设置同步账户
// account
if (mHasAddedAccount) { if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -112,10 +113,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
} }
refreshUI(); refreshUI();
} }
// 销毁活动时注销广播接收器
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
@ -123,10 +125,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
super.onDestroy(); super.onDestroy();
} }
// 加载账户偏好设置
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
@ -135,11 +138,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // 第一次设置账户
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // 如果账户已经设置,提示用户切换账户的风险
// user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
@ -150,15 +152,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return true; return true;
} }
}); });
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
// 加载同步按钮
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // 设置按钮状态
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
@ -175,8 +178,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // 设置上次同步时间
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
@ -192,30 +195,32 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
} }
// 刷新用户界面
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
// 显示选择账户的对话框
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); dialogBuilder.setPositiveButton(null, null);
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
@ -236,10 +241,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} }
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -253,10 +258,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} }
// 显示更改账户确认对话框
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -264,7 +270,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
@ -282,12 +288,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
dialogBuilder.show(); dialogBuilder.show();
} }
// 获取Google账户列表
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
// 设置同步账户
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
@ -298,11 +306,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
editor.commit(); editor.commit();
// clean up last sync time // 清除上次同步时间
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // 清除本地Gtask相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -311,13 +319,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
} }
// 移除同步账户
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
@ -328,8 +337,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
} }
editor.commit(); editor.commit();
// clean up local gtask related info // 清除本地Gtask相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -339,13 +348,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}).start(); }).start();
} }
// 获取同步账户名称
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
// 设置上次同步时间
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
@ -353,15 +364,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); editor.commit();
} }
// 获取上次同步时间
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
// 广播接收器,用于接收同步状态更新
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
@ -370,10 +383,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }
} }
} }
// 选项菜单项点击事件处理
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
@ -385,4 +399,4 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return false; return false;
} }
} }
} }

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -24,27 +24,32 @@ import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import android.widget.RemoteViews; import android.widget.RemoteViews;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
// 提供笔记小部件功能的抽象类继承自AppWidgetProvider
public abstract class NoteWidgetProvider extends AppWidgetProvider { public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 查询笔记时使用的投影列
public static final String [] PROJECTION = new String [] { public static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 投影列对应的索引
public static final int COLUMN_ID = 0; public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2; public static final int COLUMN_SNIPPET = 2;
// 日志标签
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider";
// 当小部件被删除时调用更新数据库中的小部件ID为无效值
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -56,7 +61,8 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
new String[] { String.valueOf(appWidgetIds[i])}); new String[] { String.valueOf(appWidgetIds[i])});
} }
} }
// 根据小部件ID获取笔记信息
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
@ -64,11 +70,13 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null); null);
} }
// 更新小部件视图
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
// 更新小部件视图,支持隐私模式
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
@ -79,7 +87,7 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) { if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) { if (c.getCount() > 1) {
@ -95,11 +103,11 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
snippet = context.getResources().getString(R.string.widget_havenot_content); snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
} }
if (c != null) { if (c != null) {
c.close(); c.close();
} }
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
@ -117,16 +125,19 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent.FLAG_UPDATE_CURRENT);
} }
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
} }
} }
} }
// 获取背景资源ID的方法由子类实现
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
// 获取布局ID的方法由子类实现
protected abstract int getLayoutId(); protected abstract int getLayoutId();
// 获取小部件类型的ID由子类实现
protected abstract int getWidgetType(); protected abstract int getWidgetType();
} }

@ -13,35 +13,39 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.content.Context; import android.content.Context;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
// 2x2 小部件提供者类,继承自 NoteWidgetProvider
public class NoteWidgetProvider_2x extends NoteWidgetProvider { public class NoteWidgetProvider_2x extends NoteWidgetProvider {
// 更新小部件时调用的方法
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
// 返回 2x2 小部件的布局 ID
@Override @Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_2x; return R.layout.widget_2x;
} }
// 根据背景 ID 返回对应的 2x2 小部件背景资源 ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
} }
// 返回 2x2 小部件的类型 ID
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X;
} }
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -23,24 +7,28 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
// 定义一个4x4小部件的提供者类继承自NoteWidgetProvider
public class NoteWidgetProvider_4x extends NoteWidgetProvider { public class NoteWidgetProvider_4x extends NoteWidgetProvider {
// 覆盖父类的onUpdate方法用于更新小部件的视图
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
// 返回4x4小部件的布局资源ID
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x;
} }
// 根据背景ID返回4x4小部件的背景资源ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
} }
// 返回小部件的类型这里是4x4类型
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X;
} }
} }

@ -0,0 +1,302 @@
package net.micode.notes.data;
import android.net.Uri;
public class Notes {
// 用于表示笔记应用中的各种类型、标识符以及Intent的额外数据
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
//对NoteColumns.TYPE的值进行设置时使用
//即不同种类:笔记、文件夹和系统文件夹
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
//以下id是系统文件夹的标识符即系统文件夹的分类
//ID_ROOT_FOLDER默认文件夹
//ID_TEMPARAY_FOLDER不属于文件夹的笔记
//ID_CALL_RECORD_FOLDER用于存储通话记录以便返回
//ID_TRASH_FOLER垃圾回收站
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;
// 额外的数据键个人理解为就是定义一些布局的ID
// 这部分就是用于设置UI界面的一些布局或小组件的id给它定义成常量了。
// 这样的封装性可能比较好因为如果有部分要修改则直接来这边修改即可不用在activity部分一个一个修改。
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 class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
//下面这些有类似指针的效果? 其实就是定义一堆访问笔记和文件的uri
//GPTAndroid开发中常见的用于定义内容提供者Content ProviderURI
//内容提供者是一种Android组件它允许应用程序共享和存储数据。这里定义了一个URI来查询数据
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
// 雨:这个接口定义了一系列静态的、最终的字符串常量,这些常量代表数据库表中的列名。
// 作用:用于后面创建数据库的表头
// 总的属性有ID、父级ID、创建日期、修改日期、提醒日期、文件标签摘要、小部件ID、小部件类型、背景颜色ID、附件、文件中的标签数量、
// 文件标签类型、最后一个同步ID、本地修改标签、移动前的ID、谷歌任务ID、代码版本信息。
// GPT提示在Android开发中当使用SQLite数据库时通常会为表中的每一列定义一个常量以便在代码中引用。
// 这样做的好处是,如果以后需要更改列名,只需要在一个地方修改,而不需要在整个代码中搜索和替换。
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
// 摘要?
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
//雨在数据同步过程中这个ID可能用来跟踪和识别每次同步操作的唯一性确保数据的一致性。
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
public interface DataColumns {
// DataColumns的接口这个接口包含了一系列静态常量这些常量代表了数据库表中用于存储数据的列名。
// 每个常量都有相应的注释,说明该列的作用和数据类型。
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
//MIME类型是一种标准用于标识文档、文件或字节流的性质和格式。在数据库中这个字段可以用来识别不同类型的数据例如文本、图片、音频或视频等。
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
//归属的Note的ID
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
//创建日期
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
//最近修改日期
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*/
//数据内容
public static final String CONTENT = "content";
// 以下5个是通用数据列它们的具体意义取决于MIME类型由MIME_TYPE字段指定
// 不同的MIME类型可能需要存储不同类型的数据这五个字段提供了灵活性允许根据MIME类型来存储相应的数据。
// 读后面的代码感觉这部分是在表示内容的不同状态?
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
}
//以下是文本便签的定义
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1; //模式这个被存在DATA1列中
public static final int MODE_CHECK_LIST = 1; //所处检查列表模式?
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 定义了MIME类型用于标识文本标签的目录
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";// 定义了MIME类型用于标识文本标签的单个项
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//文本标签内容提供者Content Provider的URI用于访问文本标签数据
}
// 通话记录的定义?
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1; //一个字符串常量,表示通话记录的日期
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3; //意味着在数据库表中这个电话号码信息将被存储在DATA3列中
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";// 同样定义了MIME类型是用于标识通话记录的目录。
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";// 同样定义了MIME类型是用于标识通话记录的单个项。
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");//定义了通话记录内容提供者的URI用于访问通话记录数据。
}
}
Loading…
Cancel
Save