请求合并 #6

Merged
psq5hzxpo merged 2 commits from luhaozhe_branch into master 3 weeks ago

@ -25,10 +25,24 @@ import android.util.Log;
import java.util.HashMap;
/**
*
*/
public class Contact {
/**
*
*/
private static HashMap<String, String> sContactCache;
/**
*
*/
private static final String TAG = "Contact";
/**
*
* PHONE_NUMBERS_EQUAL(18874902291,?) AND Data.MIMETYPE ='Phone.CONTENT_ITEM_TYPE'
* AND Data.RAW_CONTACT_ID IN (SELECT raw_contact_id FROM phone_lookup WHERE min_match = '+')
*/
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,26 +50,38 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* @param context
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 初始化联系人缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存中是否已存在该电话号码对应的联系人
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 构建查询条件
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人信息
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
Data.CONTENT_URI,//联系人数据表
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人姓名并缓存
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
return name;
@ -63,6 +89,7 @@ public class Contact {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 关闭游标
cursor.close();
}
} else {

@ -17,263 +17,343 @@
package net.micode.notes.data;
import android.net.Uri;
/**
* 便
* 便IDURI
* 广使
*/
public class Notes {
/**
* ContentProvider便
*/
public static final String AUTHORITY = "micode_notes";
/**
*
*/
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* 便
* - TYPE_NOTE便
* - TYPE_FOLDER
* - TYPE_SYSTEM
*/
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;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID
/**
* Intent
* - INTENT_EXTRA_ALERT_DATE
* - INTENT_EXTRA_BACKGROUND_IDID
* - INTENT_EXTRA_WIDGET_IDID
* - INTENT_EXTRA_WIDGET_TYPE
* - INTENT_EXTRA_FOLDER_IDID
* - INTENT_EXTRA_CALL_DATE
*/
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
/**
*
* - TYPE_WIDGET_INVALIDE
* - TYPE_WIDGET_2X2x2
* - TYPE_WIDGET_4X4x4
*/
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x2小部件类型
public static final int TYPE_WIDGET_4X = 1; // 4x4小部件类型
/**
* 便
* - NOTE便
* - CALL_NOTE便
*/
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 普通文本便签数据类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话记录便签数据类型
}
/**
* Uri to query all notes and folders
* 便URI
* NoteProvidernote
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* 便URI
* NoteProviderdata
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* Note
* 便
*/
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
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";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
* 便
* <P> : INTEGER (long) </P>
*/
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";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
* 便
* <P> : TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
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";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : 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>
* 便便便
* <P> : INTEGER </P>
*/
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";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
* 便
* <P> : INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
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";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* 便ID
* <P> : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* GoogleIDGoogle Tasks
* <P> : TEXT </P>
*/
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";
}
/**
* Data
* 便
* 便便便
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* 便便便
* <P> : TEXT </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
* 便ID
* DataNote
* <P> : INTEGER (long) </P>
*/
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";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* 1MIME
* <P> : 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>
* 2MIME
* <P> : 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>
* 3MIME
* <P> : 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>
* 4MIME
* <P> : 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>
* 5MIME
* <P> : TEXT </P>
*/
public static final String DATA5 = "data5";
}
/**
* 便
* DataColumns便
*/
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
* 便 checklist
* <P> : Integer 1:checklist 0: </P>
* DataDATA1
*/
public static final String MODE = DATA1;
/**
* Checklist
*/
public static final int MODE_CHECK_LIST = 1;
/**
* 便MIME
*/
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";
/**
* 便URI
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
* 便
* DataColumns便
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
* DataDATA1
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
* DataDATA3
*/
public static final String PHONE_NUMBER = DATA3;
/**
* 便MIME
*/
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";
/**
* 便URI
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -27,21 +27,51 @@ import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "note.db";
// 数据库版本号
private static final int DB_VERSION = 4;
// 数据库表名定义
public interface TABLE {
// 笔记表:存储笔记和文件夹的基本信息
public static final String NOTE = "note";
// 数据表:存储笔记的详细内容,支持多种类型的笔记数据
public static final String DATA = "data";
}
// 日志标签
private static final String TAG = "NotesDatabaseHelper";
// 单例实例,确保整个应用只有一个数据库帮助类实例
private static NotesDatabaseHelper mInstance;
// 创建笔记表的SQL语句
// 笔记表存储笔记和文件夹的基本信息,包括:
// - ID唯一标识符
// - PARENT_ID父文件夹ID
// - ALERTED_DATE提醒日期
// - BG_COLOR_ID背景颜色ID
// - CREATED_DATE创建日期
// - HAS_ATTACHMENT是否有附件
// - MODIFIED_DATE修改日期
// - NOTES_COUNT子笔记数量仅文件夹使用
// - SNIPPET笔记内容片段或文件夹名称
// - TYPE类型笔记、文件夹、系统文件夹
// - WIDGET_ID关联的小部件ID
// - WIDGET_TYPE小部件类型
// - SYNC_ID同步ID
// - LOCAL_MODIFIED本地是否修改
// - ORIGIN_PARENT_ID原始父文件夹ID
// - GTASK_IDGoogle任务ID
// - VERSION版本号
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +93,15 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建数据表的SQL语句
// 数据表存储笔记的详细内容,支持多种类型的笔记数据,包括:
// - ID唯一标识符
// - MIME_TYPE数据类型如文本笔记、通话笔记等
// - NOTE_ID关联的笔记ID
// - CREATED_DATE创建日期
// - MODIFIED_DATE修改日期
// - CONTENT数据内容
// - DATA1, DATA2, DATA3, DATA4, DATA5扩展字段根据不同数据类型存储不同信息
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -83,7 +122,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
*
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
@ -95,7 +134,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Decrease folder's note count when move note from folder
*
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
@ -108,7 +147,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Increase folder's note count when insert new note to the folder
*
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
@ -120,7 +159,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Decrease folder's note count when delete note from the folder
*
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
@ -133,7 +172,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
*
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@ -146,7 +185,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
@ -159,7 +198,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
@ -172,7 +211,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete datas belong to note which has been deleted
*
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@ -183,7 +222,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete notes belong to folder which has been deleted
*
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@ -194,7 +233,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Move notes belong to folder which has been moved to trash folder
*
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
@ -210,14 +249,27 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
super(context, DB_NAME, null, DB_VERSION);
}
/**
*
* @param db SQLite
*/
public void createNoteTable(SQLiteDatabase db) {
// 创建笔记表
db.execSQL(CREATE_NOTE_TABLE_SQL);
// 重新创建笔记表相关触发器
reCreateNoteTableTriggers(db);
// 创建系统文件夹
createSystemFolder(db);
// 记录日志
Log.d(TAG, "note table has been created");
}
/**
*
* @param db SQLite
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,136 +278,194 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_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_DELETE_TRIGGER); // 删除笔记时减少父文件夹的笔记计数
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); // 删除笔记时删除关联的数据
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); // 插入笔记时增加父文件夹的笔记计数
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); // 删除文件夹时删除其所有子笔记
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); // 将文件夹移到回收站时,将其所有子笔记也移到回收站
}
/**
*
*
* -
* -
* -
* -
* @param db SQLite
*/
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
// 创建通话记录文件夹:用于存储通话记录
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*/
// 创建根文件夹:默认文件夹,用于存储普通笔记
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*/
// 创建临时文件夹:用于移动笔记时的临时存储
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*/
// 创建回收站文件夹:用于存储被删除的笔记和文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* NotesDatabaseHelper
* 使线线
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
/**
*
* @param db SQLite
*/
public void createDataTable(SQLiteDatabase db) {
// 创建数据表
db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据表相关触发器
reCreateDataTableTriggers(db);
// 为data表的note_id字段创建索引提高查询效率
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
// 记录日志
Log.d(TAG, "data table has been created");
}
/**
*
* @param db SQLite
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除已存在的数据表触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
// 创建新的数据表触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); // 插入文本笔记数据时更新笔记内容
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); // 更新文本笔记数据时更新笔记内容
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); // 删除文本笔记数据时清空笔记内容
}
/**
*
* @param db SQLite
*/
@Override
public void onCreate(SQLiteDatabase db) {
// 创建笔记表及其相关触发器和系统文件夹
createNoteTable(db);
// 创建数据表及其相关触发器和索引
createDataTable(db);
}
/**
*
* @param db SQLite
* @param oldVersion
* @param newVersion
* @throws IllegalStateException
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
boolean reCreateTriggers = false; // 是否需要重新创建触发器
boolean skipV2 = false; // 是否跳过v2版本升级
// 从v1升级到v2
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // v2到v3的升级已包含在v1到v2的升级中
oldVersion++;
}
// 从v2升级到v3
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
reCreateTriggers = true; // v3升级需要重新创建触发器
oldVersion++;
}
// 从v3升级到v4
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 如果需要,重新创建触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 检查升级是否成功
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
throw new IllegalStateException("Upgrade notes database to version " + newVersion + " fails");
}
}
/**
* v1v2
*
* @param db SQLite
*/
private void upgradeToV2(SQLiteDatabase db) {
// 删除旧的笔记表和数据表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 创建新的笔记表
createNoteTable(db);
// 创建新的数据表
createDataTable(db);
}
/**
* v2v3
* GoogleID
* @param db SQLite
*/
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
// 删除不再使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 为笔记表添加Google任务ID字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加回收站系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* v3v4
*
* @param db SQLite
*/
private void upgradeToV4(SQLiteDatabase db) {
// 为笔记表添加版本号字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}

@ -35,35 +35,65 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便
* ContentProvider便
* 便
*/
public class NotesProvider extends ContentProvider {
/**
* URIURI
*/
private static final UriMatcher mMatcher;
/**
*
*/
private NotesDatabaseHelper mHelper;
/**
*
*/
private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
/**
* URI
* - URI_NOTE便
* - URI_NOTE_ITEM便
* - URI_DATA便
* - URI_DATA_ITEM便
* - URI_SEARCH便
* - URI_SEARCH_SUGGEST
*/
private static final int URI_NOTE = 1; // 所有便签和文件夹
private static final int URI_NOTE_ITEM = 2; // 单个便签或文件夹
private static final int URI_DATA = 3; // 所有便签数据
private static final int URI_DATA_ITEM = 4; // 单个便签数据
private static final int URI_SEARCH = 5; // 搜索便签
private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议
static {
// 初始化URI匹配器设置各种URI模式对应的处理类型
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配所有便签和文件夹
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单个便签或文件夹
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配所有便签数据
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 匹配单个便签数据
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 匹配搜索请求
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); // 匹配搜索建议
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); // 匹配带参数的搜索建议
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*
* x'0A'SQLite'\n''\n'
*
* - ID便ID
* - SUGGEST_COLUMN_INTENT_EXTRA_DATA便ID
* - SUGGEST_COLUMN_TEXT_1TEXT_2
* - SUGGEST_COLUMN_ICON_1
* - SUGGEST_COLUMN_INTENT_ACTION
* - SUGGEST_COLUMN_INTENT_DATA
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@ -73,65 +103,94 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
* 便
* 便便
*/
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" // 模糊匹配关键词
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // 排除回收站中的便签
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 只搜索普通便签
/**
*
* @return true
*/
@Override
public boolean onCreate() {
// 获取数据库帮助类的单例实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* 便
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return
* @throws IllegalArgumentException URI
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
// 获取只读数据库连接
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
// 根据URI类型执行不同的查询逻辑
switch (mMatcher.match(uri)) {
case URI_NOTE:
case URI_NOTE: // 查询所有便签和文件夹
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
case URI_NOTE_ITEM: // 查询单个便签或文件夹
id = uri.getPathSegments().get(1); // 从URI中获取ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
case URI_DATA: // 查询所有便签数据
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
case URI_DATA_ITEM: // 查询单个便签数据
id = uri.getPathSegments().get(1); // 从URI中获取ID
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
case URI_SEARCH: // 搜索便签
case URI_SEARCH_SUGGEST: // 搜索建议
// 搜索请求不允许指定排序方式和投影列
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
// 获取搜索关键词
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 从URI路径中获取搜索关键词
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
// 从URI查询参数中获取搜索关键词
searchString = uri.getQueryParameter("pattern");
}
// 如果搜索关键词为空返回null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 构建模糊查询字符串
searchString = String.format("%%%s%%", searchString);
// 执行搜索查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
@ -141,21 +200,33 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 设置内容变更通知URI当数据发生变化时通知观察者
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
* 便
* @param uri URI
* @param values
* @return URIID
* @throws IllegalArgumentException URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
// 获取可写数据库连接
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
// 根据URI类型执行不同的插入逻辑
switch (mMatcher.match(uri)) {
case URI_NOTE:
case URI_NOTE: // 插入便签或文件夹
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
case URI_DATA: // 插入便签数据
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
@ -166,37 +237,49 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知便签URI数据变更
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// 通知数据URI数据变更
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
// 返回包含新插入数据ID的URI
return ContentUris.withAppendedId(uri, insertedId);
}
/**
* 便
* @param uri URI
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
// 获取可写数据库连接
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
// 根据URI类型执行不同的删除逻辑
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
case URI_NOTE: // 删除便签或文件夹
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 排除系统文件夹
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
case URI_NOTE_ITEM: // 删除单个便签或文件夹
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
* ID0
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
@ -205,11 +288,11 @@ public class NotesProvider extends ContentProvider {
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
case URI_DATA: // 删除便签数据
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
case URI_DATA_ITEM: // 删除单个便签数据
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -218,6 +301,8 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 通知数据变更
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -227,28 +312,40 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
* 便
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
// 获取可写数据库连接
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
// 根据URI类型执行不同的更新逻辑
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
case URI_NOTE: // 更新便签或文件夹
increaseNoteVersion(-1, selection, selectionArgs); // 增加便签版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
case URI_NOTE_ITEM: // 更新单个便签或文件夹
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加便签版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
case URI_DATA: // 更新便签数据
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
case URI_DATA_ITEM: // 更新单个便签数据
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
@ -258,6 +355,7 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 通知数据变更
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -267,17 +365,28 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
*
* @param selection
* @return
*/
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* 便
* @param id 便ID-1便
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号自增1
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
@ -293,9 +402,15 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString);
}
// 执行SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URIMIME
* @param uri URI
* @return MIMEnull
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub

@ -25,11 +25,27 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* MetaData -
* <p>
* TaskGoogle Task
* 便Google Task
* </p>
*/
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; // 关联的全局唯一标识符
/**
*
* <p>
* TasknotesMETA_NOTE_NAME
* </p>
*
* @param gid
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@ -40,15 +56,36 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
*
*
* @return
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
*
* <p>
* notesnull
* </p>
*
* @return
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* JSON
* <p>
* notesGID
* </p>
*
* @param js JSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
@ -63,17 +100,45 @@ public class MetaData extends Task {
}
}
/**
* JSON
* <p>
* IllegalAccessError
* </p>
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/**
* JSON
* <p>
* IllegalAccessError
* </p>
*
* @return JSON
* @throws IllegalAccessError
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
*
* <p>
* IllegalAccessError
* </p>
*
* @param c
* @return
* @throws IllegalAccessError
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -20,33 +20,38 @@ import android.database.Cursor;
import org.json.JSONObject;
/**
* Node -
* <p>
* Google Task
*
* </p>
*/
public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
/**
*
*/
public static final int SYNC_ACTION_NONE = 0; // 无需同步
public static final int SYNC_ACTION_ADD_REMOTE = 1; // 添加到远程
public static final int SYNC_ACTION_ADD_LOCAL = 2; // 添加到本地
public static final int SYNC_ACTION_DEL_REMOTE = 3; // 从远程删除
public static final int SYNC_ACTION_DEL_LOCAL = 4; // 从本地删除
public static final int SYNC_ACTION_UPDATE_REMOTE = 5; // 更新远程
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; // 更新本地
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; // 更新冲突
public static final int SYNC_ACTION_ERROR = 8; // 同步错误
private String mGid; // 全局唯一标识符
private String mName; // 节点名称
private long mLastModified; // 最后修改时间
private boolean mDeleted; // 是否已删除
/**
*
* <p>
*
* </p>
*/
public Node() {
mGid = null;
mName = "";
@ -54,46 +59,137 @@ public abstract class Node {
mDeleted = false;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* <p>
* JSON
* </p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* <p>
* JSON
* </p>
*
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent();
/**
*
* <p>
*
* </p>
*
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c);
/**
*
*
* @param gid
*/
public void setGid(String gid) {
this.mGid = gid;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.mName = name;
}
/**
*
*
* @param lastModified
*/
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
/**
*
*
* @param deleted
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
*
*
* @return
*/
public String getGid() {
return this.mGid;
}
/**
*
*
* @return
*/
public String getName() {
return this.mName;
}
/**
*
*
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
*
*
* @return
*/
public boolean getDeleted() {
return this.mDeleted;
}

@ -35,42 +35,55 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* SqlData - 便
* <p>
* 便
* 便JSON
* </p>
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
private static final String TAG = SqlData.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999;
private static final int INVALID_ID = -99999; // 无效ID常量
/**
*
* <p>
* 便
* </p>
*/
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mDataId;
private String mDataMimeType;
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
/**
*
*/
public static final int DATA_ID_COLUMN = 0; // 数据ID列索引
public static final int DATA_MIME_TYPE_COLUMN = 1; // 数据MIME类型列索引
public static final int DATA_CONTENT_COLUMN = 2; // 数据内容列索引
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; // 数据内容DATA1列索引
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; // 数据内容DATA3列索引
private ContentResolver mContentResolver; // 内容解析器
private boolean mIsCreate; // 是否为新建数据
private long mDataId; // 数据ID
private String mDataMimeType; // 数据MIME类型
private String mDataContent; // 数据内容
private long mDataContentData1; // 数据内容DATA1
private String mDataContentData3; // 数据内容DATA3
private ContentValues mDiffDataValues; // 差异值集合,用于更新操作
/**
*
* <p>
*
* </p>
*
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -82,6 +95,15 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* <p>
* SqlData
* </p>
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,6 +111,14 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* <p>
*
* </p>
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,6 +127,15 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
@ -130,6 +169,16 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/**
* JSON
* <p>
* JSON
* null
* </p>
*
* @return JSONnull
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,6 +193,18 @@ public class SqlData {
return js;
}
/**
*
* <p>
* mIsCreate
*
* </p>
*
* @param noteId 便ID
* @param validateVersion
* @param version
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -183,6 +244,11 @@ public class SqlData {
mIsCreate = false;
}
/**
* ID
*
* @return ID
*/
public long getId() {
return mDataId;
}

@ -38,11 +38,24 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* SqlNote - 便
* <p>
* 便便
* 便JSON
* </p>
*/
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常量
/**
* 便
* <p>
* 便
* </p>
*/
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,76 +65,54 @@ public class SqlNote {
NoteColumns.VERSION
};
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
/**
*
*/
public static final int ID_COLUMN = 0; // ID列索引
public static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引
public static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引
public static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引
public static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件列索引
public static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引
public static final int NOTES_COUNT_COLUMN = 6; // 便签数量列索引
public static final int PARENT_ID_COLUMN = 7; // 父ID列索引
public static final int SNIPPET_COLUMN = 8; // 摘要列索引
public static final int TYPE_COLUMN = 9; // 类型列索引
public static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引
public static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引
public static final int SYNC_ID_COLUMN = 12; // 同步ID列索引
public static final int LOCAL_MODIFIED_COLUMN = 13; // 本地修改标记列索引
public static final int ORIGIN_PARENT_ID_COLUMN = 14; // 原始父ID列索引
public static final int GTASK_ID_COLUMN = 15; // Google Task ID列索引
public static final int VERSION_COLUMN = 16; // 版本号列索引
private Context mContext; // 上下文对象
private ContentResolver mContentResolver; // 内容解析器
private boolean mIsCreate; // 是否为新建便签
private long mId; // 便签ID
private long mAlertDate; // 提醒日期
private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建日期
private int mHasAttachment; // 是否有附件
private long mModifiedDate; // 修改日期
private long mParentId; // 父ID
private String mSnippet; // 摘要
private int mType; // 类型
private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
private long mOriginParent; // 原始父ID
private long mVersion; // 版本号
private ContentValues mDiffNoteValues; // 差异值集合,用于更新操作
private ArrayList<SqlData> mDataList; // 便签内容数据列表
/**
*
* <p>
* 便
* </p>
*
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -143,6 +134,15 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
/**
*
* <p>
* SqlNote 便
* </p>
*
* @param context
* @param c 便
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -154,6 +154,15 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
/**
*
* <p>
* 便ID SqlNote 便
* </p>
*
* @param context
* @param id 便ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -166,6 +175,14 @@ public class SqlNote {
}
/**
* ID便
* <p>
* ID便loadFromCursor(Cursor c)
* </p>
*
* @param id 便ID
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
@ -185,6 +202,14 @@ public class SqlNote {
}
}
/**
* 便
* <p>
* 便
* </p>
*
* @param c 便
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -200,6 +225,12 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
/**
* 便
* <p>
* 便mDataList
* </p>
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
@ -226,6 +257,16 @@ public class SqlNote {
}
}
/**
* JSON便
* <p>
* JSON便
* 便
* </p>
*
* @param js 便JSON
* @return truefalse
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -359,6 +400,15 @@ public class SqlNote {
return true;
}
/**
* 便JSON
* <p>
* 便JSON便
* 便null
* </p>
*
* @return 便JSONnull
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -407,39 +457,91 @@ public class SqlNote {
return null;
}
/**
* ID
*
* @param id ID
*/
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
/**
* Google Task ID
*
* @param gid Google Task ID
*/
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
/**
* ID
*
* @param syncId ID
*/
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
/**
*
* <p>
* 0
* </p>
*/
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
/**
* 便ID
*
* @return 便ID
*/
public long getId() {
return mId;
}
/**
* ID
*
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
* 便
*
* @return 便
*/
public String getSnippet() {
return mSnippet;
}
/**
* 便
*
* @return 便
*/
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/**
* 便
* <p>
* mIsCreate便便
*
* </p>
*
* @param validateVersion
* @throws ActionFailureException 便
* @throws IllegalStateException ID便
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
@ -471,13 +573,11 @@ public class SqlNote {
mVersion ++;
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
});
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});

@ -32,19 +32,32 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* Task -
* <p>
* Google TaskNode
*
* </p>
*/
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; // 任务元信息
private Task mPriorSibling;
private Task mPriorSibling; // 前序兄弟任务
private TaskList mParent;
private TaskList mParent; // 父任务列表
/**
*
* <p>
*
* </p>
*/
public Task() {
super();
mCompleted = false;
@ -54,6 +67,16 @@ public class Task extends Node {
mMetaInfo = null;
}
/**
* JSON
* <p>
* JSONIDID
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +126,16 @@ public class Task extends Node {
return js;
}
/**
* JSON
* <p>
* JSONIDID
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -135,6 +168,15 @@ public class Task extends Node {
return js;
}
/**
* JSON
* <p>
* JSONID
* </p>
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,6 +217,14 @@ public class Task extends Node {
}
}
/**
* JSON
* <p>
* JSON便
* </p>
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -204,6 +254,14 @@ public class Task extends Node {
}
}
/**
* JSON
* <p>
* JSON便
* </p>
*
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -247,6 +305,14 @@ public class Task extends Node {
}
}
/**
*
* <p>
* MetaDatanotesJSONObject
* </p>
*
* @param metaData MetaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,6 +324,20 @@ public class Task extends Node {
}
}
/**
*
* <p>
*
* </p>
*
* @param c
* @return
* - SYNC_ACTION_NONE
* - SYNC_ACTION_UPDATE_LOCAL
* - SYNC_ACTION_UPDATE_REMOTE
* - SYNC_ACTION_UPDATE_CONFLICT
* - SYNC_ACTION_ERROR
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -311,39 +391,87 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
/**
*
*
* @param completed
*/
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
/**
*
*
* @param notes
*/
public void setNotes(String notes) {
this.mNotes = notes;
}
/**
*
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
/**
*
*
* @param parent
*/
public void setParent(TaskList parent) {
this.mParent = parent;
}
/**
*
*
* @return
*/
public boolean getCompleted() {
return this.mCompleted;
}
/**
*
*
* @return
*/
public String getNotes() {
return this.mNotes;
}
/**
*
*
* @return
*/
public Task getPriorSibling() {
return this.mPriorSibling;
}
/**
*
*
* @return
*/
public TaskList getParent() {
return this.mParent;
}

@ -30,19 +30,42 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* TaskList -
* <p>
* Google TaskNodeTask
*
* </p>
*/
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; // 子任务列表
/**
*
* <p>
*
* </p>
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON
* <p>
* JSONID
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -74,6 +97,16 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* JSONIDID
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +136,15 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* JSONID
* </p>
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -129,6 +171,14 @@ public class TaskList extends Node {
}
}
/**
* JSON
* <p>
* JSON便
* </p>
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -157,6 +207,14 @@ public class TaskList extends Node {
}
}
/**
* JSON
* <p>
* JSON便
* </p>
*
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -183,6 +241,19 @@ public class TaskList extends Node {
}
}
/**
*
* <p>
*
* </p>
*
* @param c
* @return
* - SYNC_ACTION_NONE
* - SYNC_ACTION_UPDATE_LOCAL
* - SYNC_ACTION_UPDATE_REMOTE
* - SYNC_ACTION_ERROR
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
@ -216,10 +287,27 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
*
* <p>
*
* </p>
*
* @param task
* @return
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -234,6 +322,16 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @param index
* @return
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -260,6 +358,15 @@ public class TaskList extends Node {
return true;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @return
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -281,6 +388,16 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @param index
* @return
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -299,6 +416,15 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* GID
* <p>
* GID
* </p>
*
* @param gid GID
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +435,28 @@ public class TaskList extends Node {
return null;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
* <p>
*
* </p>
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +465,15 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
* GID
* <p>
* GID
* </p>
*
* @param gid GID
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -329,14 +482,38 @@ public class TaskList extends Node {
return null;
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
* <p>
*
* </p>
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public int getIndex() {
return this.mIndex;
}

@ -16,17 +16,47 @@
package net.micode.notes.gtask.exception;
/**
* ActionFailureException -
* <p>
* Google Task
* RuntimeException
* </p>
*/
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
private static final long serialVersionUID = 4425249765923293627L; // 序列化版本号
/**
*
* <p>
* ActionFailureException
* </p>
*/
public ActionFailureException() {
super();
}
/**
*
* <p>
* 使ActionFailureException
* </p>
*
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
}
/**
*
* <p>
* 使ActionFailureException
* </p>
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -16,17 +16,47 @@
package net.micode.notes.gtask.exception;
/**
* NetworkFailureException -
* <p>
* Google Task
* Exception
* </p>
*/
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
private static final long serialVersionUID = 2107610287180234136L; // 序列化版本号
/**
*
* <p>
* NetworkFailureException
* </p>
*/
public NetworkFailureException() {
super();
}
/**
*
* <p>
* 使NetworkFailureException
* </p>
*
* @param paramString
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
/**
*
* <p>
* 使NetworkFailureException
* </p>
*
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -29,22 +29,53 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* Google Task
* AsyncTask Google Task
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/**
* Google Task
*/
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
*
*
*/
public interface OnCompleteListener {
/**
*
*/
void onComplete();
}
/**
*
*/
private Context mContext;
/**
*
*/
private NotificationManager mNotifiManager;
/**
* Google Task
*/
private GTaskManager mTaskManager;
/**
*
*/
private OnCompleteListener mOnCompleteListener;
/**
*
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
@ -53,64 +84,108 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance();
}
/**
*
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
}
/**
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
// 创建通知实例,设置图标、标题和时间
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.defaults = Notification.DEFAULT_LIGHTS; // 使用默认灯光效果
notification.flags = Notification.FLAG_AUTO_CANCEL; // 点击后自动取消
// 根据通知类型设置不同的跳转意图
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
// 同步失败时跳转到设置页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {
// 同步成功时跳转到笔记列表页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
}
// 设置通知的详细信息并显示
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
*
* @param unused
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
// 发布登录进度
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 调用任务管理器执行同步
return mTaskManager.sync(mContext, this);
}
/**
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
// 显示同步中通知
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是同步服务,则发送广播通知进度
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
/**
*
* @param result
*/
@Override
protected void onPostExecute(Integer result) {
// 根据同步结果显示不同的通知
if (result == GTaskManager.STATE_SUCCESS) {
// 同步成功
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
// 更新最后同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
// 网络错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
// 内部错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
// 同步取消
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
// 如果设置了完成监听器,则在新线程中调用
if (mOnCompleteListener != null) {
new Thread(new Runnable() {

@ -61,35 +61,85 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* Google Task
* Google Task
*
*/
public class GTaskClient {
/**
*
*/
private static final String TAG = GTaskClient.class.getSimpleName();
/**
* Google Task URL
*/
private static final String GTASK_URL = "https://mail.google.com/tasks/";
/**
* Google Task GET URL
*/
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
/**
* Google Task POST URL
*/
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
/**
* GTaskClient
*/
private static GTaskClient mInstance = null;
/**
* HTTP Google Task
*/
private DefaultHttpClient mHttpClient;
/**
* 使 GET URL
*/
private String mGetUrl;
/**
* 使 POST URL
*/
private String mPostUrl;
/**
* Google Task
*/
private long mClientVersion;
/**
*
*/
private boolean mLoggedin;
/**
*
*/
private long mLastLoginTime;
/**
* ID
*/
private int mActionId;
/**
*
*/
private Account mAccount;
/**
*
*/
private JSONArray mUpdateArray;
/**
*
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +152,10 @@ public class GTaskClient {
mUpdateArray = null;
}
/**
* GTaskClient
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,15 +163,19 @@ public class GTaskClient {
return mInstance;
}
/**
* Google Task
* @param activity Activity
* @return
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
// 假设登录 cookie 5 分钟后过期,需要重新登录
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
// 切换账户后需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
@ -136,7 +194,7 @@ public class GTaskClient {
return false;
}
// login with custom domain if necessary
// 如果是自定义域名,使用自定义 URL 登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -151,7 +209,7 @@ public class GTaskClient {
}
}
// try to login with google official url
// 如果自定义域名登录失败,尝试使用 Google 官方 URL 登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,6 +222,12 @@ public class GTaskClient {
return true;
}
/**
* Google
* @param activity Activity
* @param invalidateToken 使
* @return null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -189,7 +253,7 @@ public class GTaskClient {
return null;
}
// get the token now
// 获取认证令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -207,10 +271,16 @@ public class GTaskClient {
return authToken;
}
/**
* Google Task
* 使
* @param activity Activity
* @param authToken
* @return
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 可能认证令牌已过期,使令牌失效并重新尝试
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -225,6 +295,11 @@ public class GTaskClient {
return true;
}
/**
* Google Task
* @param authToken
* @return
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -236,14 +311,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 登录 Google Task
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
// 获取认证 Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -255,7 +330,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
// 获取客户端版本
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -272,7 +347,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
// 简单捕获所有异常
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -280,10 +355,18 @@ public class GTaskClient {
return true;
}
/**
* ID
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* HTTP POST
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +374,12 @@ public class GTaskClient {
return httpPost;
}
/**
* HTTP
* @param entity HTTP
* @return
* @throws IOException IO
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -323,6 +412,12 @@ public class GTaskClient {
}
}
/**
* HTTP POST Google Task
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -360,6 +455,11 @@ public class GTaskClient {
}
}
/**
* Google Task
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
@ -386,6 +486,11 @@ public class GTaskClient {
}
}
/**
* Google Task
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
@ -412,6 +517,10 @@ public class GTaskClient {
}
}
/**
* Google Task
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {

@ -48,45 +48,109 @@ import java.util.Iterator;
import java.util.Map;
/**
* Google Task
* Google Task
*/
public class GTaskManager {
/**
*
*/
private static final String TAG = GTaskManager.class.getSimpleName();
/**
*
*/
public static final int STATE_SUCCESS = 0;
/**
*
*/
public static final int STATE_NETWORK_ERROR = 1;
/**
*
*/
public static final int STATE_INTERNAL_ERROR = 2;
/**
*
*/
public static final int STATE_SYNC_IN_PROGRESS = 3;
/**
*
*/
public static final int STATE_SYNC_CANCELLED = 4;
/**
* GTaskManager
*/
private static GTaskManager mInstance = null;
/**
* Activity
*/
private Activity mActivity;
/**
*
*/
private Context mContext;
/**
* 访
*/
private ContentResolver mContentResolver;
/**
*
*/
private boolean mSyncing;
/**
*
*/
private boolean mCancelled;
/**
* Google Task GID
*/
private HashMap<String, TaskList> mGTaskListHashMap;
/**
* Google Task GID
*/
private HashMap<String, Node> mGTaskHashMap;
/**
* GID
*/
private HashMap<String, MetaData> mMetaHashMap;
/**
*
*/
private TaskList mMetaList;
/**
* ID
*/
private HashSet<Long> mLocalDeleteIdMap;
/**
* GID ID
*/
private HashMap<String, Long> mGidToNid;
/**
* ID GID
*/
private HashMap<Long, String> mNidToGid;
/**
* GTaskManager
*/
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +163,10 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
/**
* GTaskManager
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,11 +174,21 @@ public class GTaskManager {
return mInstance;
}
/**
* Activity
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
// 用于获取认证令牌
mActivity = activity;
}
/**
* Google Task
* @param context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -131,18 +209,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
// 登录 Google Task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// get the task list from google
// 从 Google 获取任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// do content sync work
// 执行内容同步工作
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -168,6 +246,11 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* Google Task
* Google
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -247,6 +330,11 @@ public class GTaskManager {
}
}
/**
*
* ID
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;

@ -23,25 +23,60 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* Google Task
* Service Google Task 广
*/
public class GTaskSyncService extends Service {
/**
* Intent
*/
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() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,6 +91,10 @@ public class GTaskSyncService extends Service {
}
}
/**
*
*
*/
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();

@ -34,12 +34,34 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* 便
* 便
* 便便
*/
public class Note {
/**
* 便便
* 便
*/
private ContentValues mNoteDiffValues;
/**
* 便便
*/
private NoteData mNoteData;
/**
*
*/
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
* 便便ID
* @param context
* @param folderId ID便
* @return 便ID
* @throws IllegalStateException 便
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
@ -65,93 +87,168 @@ public class Note {
return noteId;
}
/**
* 便
*/
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
mNoteDiffValues = new ContentValues(); // 初始化便签差异值
mNoteData = new NoteData(); // 初始化便签数据
}
/**
* 便
* @param key
* @param value
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(key, value); // 存储属性变化
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间
}
/**
* 便
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* 便ID
* @param id 便ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* 便ID
* @return 便ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* 便ID
* @param id 便ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
* 便
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
* 便
* @return 便truefalse
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
* 便
* @param context
* @param noteId 便ID
* @return
* @throws IllegalArgumentException 便ID
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 如果便签没有被修改,直接返回成功
if (!isLocalModified()) {
return true;
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
* 便 {@link NoteColumns#LOCAL_MODIFIED}
* {@link NoteColumns#MODIFIED_DATE}使便
* 便
*/
// 更新便签属性
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
// 不返回,继续执行后续操作
}
mNoteDiffValues.clear();
mNoteDiffValues.clear(); // 清空便签差异值
// 如果便签数据被修改,将数据同步到数据库
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
return false; // 数据同步失败返回false
}
return true;
return true; // 同步成功
}
/**
* 便便
* 便便
*/
private class NoteData {
/**
* 便ID
*/
private long mTextDataId;
/**
* 便便
*/
private ContentValues mTextDataValues;
/**
* 便ID
*/
private long mCallDataId;
/**
* 便便
*/
private ContentValues mCallDataValues;
/**
*
*/
private static final String TAG = "NoteData";
/**
* 便
*/
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
mTextDataValues = new ContentValues(); // 初始化文本便签差异值
mCallDataValues = new ContentValues(); // 初始化通话记录便签差异值
mTextDataId = 0; // 初始化文本便签数据ID
mCallDataId = 0; // 初始化通话记录便签数据ID
}
/**
* 便
* @return 便truefalse
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* 便ID
* @param id 便ID
* @throws IllegalArgumentException ID0
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +256,11 @@ public class Note {
mTextDataId = id;
}
/**
* 便ID
* @param id 便ID
* @throws IllegalArgumentException ID0
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,88 +268,112 @@ public class Note {
mCallDataId = id;
}
/**
* 便
* @param key
* @param value
*/
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mCallDataValues.put(key, value); // 存储通话记录数据变化
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间
}
/**
* 便
* @param key
* @param value
*/
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mTextDataValues.put(key, value); // 存储文本数据变化
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间
}
/**
* 便ContentResolver
* @param context
* @param noteId 便ID
* @return nullnull
* @throws IllegalArgumentException 便ID
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 创建ContentProvider操作列表用于批量处理数据操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
// 处理文本便签数据
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 设置便签ID
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
// 插入新的文本便签数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); // 设置MIME类型
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); // 获取新插入的数据ID
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
return null; // 插入失败返回null
}
} else {
// 更新现有文本便签数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
mTextDataValues.clear();
mTextDataValues.clear(); // 清空文本便签差异值
}
// 处理通话记录便签数据
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
mCallDataValues.put(DataColumns.NOTE_ID, noteId); // 设置便签ID
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
// 插入新的通话记录便签数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); // 设置MIME类型
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); // 获取新插入的数据ID
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
return null; // 插入失败返回null
}
} else {
// 更新现有通话记录便签数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
mCallDataValues.clear();
mCallDataValues.clear(); // 清空通话记录便签差异值
}
// 如果有操作需要执行,应用批量操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
// 返回操作结果成功返回便签URI失败返回null
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
return null; // 远程异常返回null
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
return null; // 操作应用异常返回null
}
}
return null;
return null; // 没有操作需要执行返回null
}
}
}

@ -32,105 +32,170 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* 便便
* 便
* 便
*/
public class WorkingNote {
// Note for the working note
/**
* 便便
*/
private Note mNote;
// Note Id
/**
* 便ID
*/
private long mNoteId;
// Note content
/**
* 便
*/
private String mContent;
// Note mode
/**
* 便0-1- checklist
*/
private int mMode;
/**
*
*/
private long mAlertDate;
/**
*
*/
private long mModifiedDate;
/**
* ID
*/
private int mBgColorId;
/**
* ID
*/
private int mWidgetId;
/**
*
*/
private int mWidgetType;
/**
* ID
*/
private long mFolderId;
/**
*
*/
private Context mContext;
/**
*
*/
private static final String TAG = "WorkingNote";
/**
*
*/
private boolean mIsDeleted;
/**
* 便便
*/
private NoteSettingChangedListener mNoteSettingStatusListener;
/**
* 便
*/
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
DataColumns.ID, // 数据ID
DataColumns.CONTENT, // 数据内容
DataColumns.MIME_TYPE, // 数据类型
DataColumns.DATA1, // 扩展数据1
DataColumns.DATA2, // 扩展数据2
DataColumns.DATA3, // 扩展数据3
DataColumns.DATA4, // 扩展数据4
};
/**
* 便便
*/
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
NoteColumns.MODIFIED_DATE // 修改日期
};
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
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_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
/**
*
*/
private static final int DATA_ID_COLUMN = 0; // 数据ID列索引
private static final int DATA_CONTENT_COLUMN = 1; // 数据内容列索引
private static final int DATA_MIME_TYPE_COLUMN = 2; // 数据类型列索引
private static final int DATA_MODE_COLUMN = 3; // 数据模式列索引
/**
* 便
*/
private static final int NOTE_PARENT_ID_COLUMN = 0; // 父文件夹ID列索引
private static final int NOTE_ALERTED_DATE_COLUMN = 1; // 提醒日期列索引
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引
private static final int NOTE_WIDGET_ID_COLUMN = 3; // 小部件ID列索引
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; // 小部件类型列索引
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; // 修改日期列索引
/**
* 便
* @param context
* @param folderId ID便
*/
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();
mFolderId = folderId;
mNote = new Note();
mNoteId = 0;
mIsDeleted = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mAlertDate = 0; // 初始化为没有提醒
mModifiedDate = System.currentTimeMillis(); // 初始化修改时间为当前时间
mFolderId = folderId; // 设置文件夹ID
mNote = new Note(); // 创建便签对象
mNoteId = 0; // 新便签ID为0
mIsDeleted = false; // 初始化为未删除
mMode = 0; // 初始化为普通模式
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 初始化为无效小部件类型
}
// Existing note construct
/**
* 便
* @param context
* @param noteId 便ID
* @param folderId ID
*/
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
mNoteId = noteId; // 设置便签ID
mFolderId = folderId; // 设置文件夹ID
mIsDeleted = false; // 初始化为未删除
mNote = new Note(); // 创建便签对象
loadNote(); // 加载便签数据
}
/**
* 便
* @throws IllegalArgumentException ID便
*/
private void loadNote() {
// 查询便签基本信息
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
// 从游标中获取便签信息
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -143,10 +208,15 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
loadNoteData(); // 加载便签详细数据
}
/**
* 便
* @throws IllegalArgumentException ID便
*/
private void loadNoteData() {
// 查询便签详细数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
@ -157,10 +227,12 @@ public class WorkingNote {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
// 文本便签数据
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 通话记录便签数据
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +246,15 @@ public class WorkingNote {
}
}
/**
* 便
* @param context
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
* @return 便
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,12 +264,23 @@ public class WorkingNote {
return note;
}
/**
* ID便
* @param context
* @param id 便ID
* @return 便
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
* 便
* @return
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
// 如果便签不存在于数据库中,创建新便签
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
@ -196,10 +288,11 @@ public class WorkingNote {
}
}
// 同步便签数据到数据库
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
* 便
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
@ -212,11 +305,23 @@ public class WorkingNote {
}
}
/**
* 便
* @return 便ID0truefalse
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
* 便
* @return 便truefalse
*/
private boolean isWorthSaving() {
// 以下情况不保存:
// 1. 便签被标记为删除
// 2. 便签不存在于数据库中且内容为空
// 3. 便签存在于数据库中但没有被修改
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
@ -225,31 +330,51 @@ public class WorkingNote {
}
}
/**
* 便
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
// 通知监听器提醒日期变化
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
/**
* 便
* @param mark
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
// 如果便签关联了小部件,通知监听器小部件变化
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}
/**
* ID
* @param id ID
*/
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
// 通知监听器背景颜色变化
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}
@ -257,8 +382,13 @@ public class WorkingNote {
}
}
/**
* 便checklist
* @param mode 0-1-checklist
*/
public void setCheckListMode(int mode) {
if (mMode != mode) {
// 通知监听器模式变化
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
@ -267,6 +397,10 @@ public class WorkingNote {
}
}
/**
*
* @param type
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +408,10 @@ public class WorkingNote {
}
}
/**
* ID
* @param id ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +419,10 @@ public class WorkingNote {
}
}
/**
* 便
* @param text 便
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,80 +430,139 @@ public class WorkingNote {
}
}
/**
* 便便
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
/**
* 便
* @return truefalse
*/
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
/**
* 便
* @return 便
*/
public String getContent() {
return mContent;
}
/**
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
* @return ID
*/
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
/**
* ID
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
* @return ID
*/
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
/**
* 便
* @return 便0-1-checklist
*/
public int getCheckListMode() {
return mMode;
}
/**
* 便ID
* @return 便ID
*/
public long getNoteId() {
return mNoteId;
}
/**
* ID
* @return ID
*/
public long getFolderId() {
return mFolderId;
}
/**
* ID
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* 便
* 便
*/
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
* 便
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*
* @param date
* @param set
*/
void onClockAlertChanged(long date, boolean set);
/**
* Call when user create note from widget
* 便便
*/
void onWidgetChanged();
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
* checklist
* @param oldMode
* @param newMode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}

@ -36,11 +36,31 @@ import java.io.IOException;
import java.io.PrintStream;
/**
* BackupUtils -
* <p>
* 便使
* 便SD
* </p>
*
* @author MiCode Open Source Community
* @version 1.0
*/
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static final String TAG = "BackupUtils"; // 日志标签
// 单例模式实现
private static BackupUtils sInstance;
/**
*
* <p>
* 线
* </p>
*
* @param context
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
@ -49,43 +69,91 @@ public class BackupUtils {
}
/**
* Following states are signs to represents backup or restore
* status
*
*/
// Currently, the sdcard is not mounted
// SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
// 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
// 数据格式损坏,可能被其他程序修改
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
// 运行时异常导致备份或恢复失败
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
// 备份或恢复成功
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
private TextExport mTextExport; // 文本导出实例
/**
*
* <p>
*
* </p>
*
* @param context
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**
*
* <p>
* SD
* </p>
*
* @return
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
*
* <p>
* 便SD
* </p>
*
* @return
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
/**
* TextExport -
* <p>
* 便
* </p>
*/
private static class TextExport {
/**
* 便
*/
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
@ -93,12 +161,14 @@ public class BackupUtils {
NoteColumns.TYPE
};
// 便签列索引常量
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
/**
*
*/
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
@ -108,23 +178,31 @@ public class BackupUtils {
DataColumns.DATA4,
};
// 数据列索引常量
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式数组
private final String [] TEXT_FORMAT;
// 格式类型常量
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;
private String mFileName;
private String mFileDirectory;
private Context mContext; // 上下文对象
private String mFileName; // 文件名
private String mFileDirectory; // 文件目录
/**
*
* <p>
*
* </p>
*
* @param context
*/
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
@ -132,28 +210,43 @@ public class BackupUtils {
mFileDirectory = "";
}
/**
*
* <p>
* ID
* </p>
*
* @param id ID
* @return
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
* Export the folder identified by folder id to text
* 便
* <p>
* 便
* </p>
*
* @param folderId ID
* @param ps
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
// 查询该文件夹下的便签
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
folderId
}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
// 打印便签的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询该便签的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
@ -163,12 +256,19 @@ public class BackupUtils {
}
/**
* Export note identified by id to a print stream
* 便
* <p>
* 便
* </p>
*
* @param noteId 便ID
* @param ps
*/
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询该便签的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
noteId
}, null);
if (dataCursor != null) {
@ -176,7 +276,7 @@ public class BackupUtils {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
// 打印电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
@ -185,16 +285,17 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
// 打印通话附件位置
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 打印便签内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
@ -205,10 +306,11 @@ public class BackupUtils {
}
dataCursor.close();
}
// print a line separator between note
// 打印便签之间的分隔线
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
Character.LINE_SEPARATOR, Character.LINE_SEPARATOR
});
} catch (IOException e) {
Log.e(TAG, e.toString());
@ -216,20 +318,28 @@ public class BackupUtils {
}
/**
* Note will be exported as text which is user readable
* 便
* <p>
* SD
* </p>
*
* @return
*/
public int exportToText() {
// 检查SD卡是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取打印流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 首先导出文件夹及其便签
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -240,7 +350,7 @@ public class BackupUtils {
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 打印文件夹名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
@ -257,7 +367,7 @@ public class BackupUtils {
folderCursor.close();
}
// Export notes in root's folder
// 导出根文件夹下的便签
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -270,7 +380,7 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询该便签的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
@ -283,7 +393,12 @@ public class BackupUtils {
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*
* <p>
*
* </p>
*
* @return null
*/
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
@ -310,7 +425,15 @@ public class BackupUtils {
}
/**
* Generate the text file to store imported data
* SD
* <p>
*
* </p>
*
* @param context
* @param filePathResId ID
* @param fileNameFormatResId ID
* @return null
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder();

@ -35,8 +35,29 @@ import java.util.ArrayList;
import java.util.HashSet;
/**
* DataUtils -
* <p>
* 便
* 便
* </p>
*
* @author MiCode Open Source Community
* @version 1.0
*/
public class DataUtils {
public static final String TAG = "DataUtils";
public static final String TAG = "DataUtils"; // 日志标签
/**
* 便
* <p>
* ContentProviderID便
* </p>
*
* @param resolver ContentResolver
* @param ids 便ID
* @return
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
@ -72,6 +93,17 @@ public class DataUtils {
return false;
}
/**
* 便
* <p>
* 便ID
* </p>
*
* @param resolver ContentResolver
* @param id 便ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
@ -80,6 +112,17 @@ public class DataUtils {
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
* 便
* <p>
* ContentProvider便ID
* </p>
*
* @param resolver ContentResolver
* @param ids 便ID
* @param folderId ID
* @return
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
if (ids == null) {
@ -112,7 +155,13 @@ public class DataUtils {
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @return
*/
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
@ -136,6 +185,17 @@ public class DataUtils {
return count;
}
/**
* 便
* <p>
* 便
* </p>
*
* @param resolver ContentResolver
* @param noteId 便ID
* @param type 便
* @return
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
@ -153,6 +213,16 @@ public class DataUtils {
return exist;
}
/**
* 便
* <p>
* ID便
* </p>
*
* @param resolver ContentResolver
* @param noteId 便ID
* @return
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -167,6 +237,16 @@ public class DataUtils {
return exist;
}
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param dataId ID
* @return
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -181,6 +261,16 @@ public class DataUtils {
return exist;
}
/**
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @param name
* @return
*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
@ -197,6 +287,16 @@ public class DataUtils {
return exist;
}
/**
* 便
* <p>
* 便
* </p>
*
* @param resolver ContentResolver
* @param folderId ID
* @return
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -224,6 +324,16 @@ public class DataUtils {
return set;
}
/**
* 便ID
* <p>
* 便
* </p>
*
* @param resolver ContentResolver
* @param noteId 便ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
@ -243,6 +353,17 @@ public class DataUtils {
return "";
}
/**
* 便ID
* <p>
* 便ID
* </p>
*
* @param resolver ContentResolver
* @param phoneNumber
* @param callDate
* @return 便ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
@ -264,6 +385,17 @@ public class DataUtils {
return 0;
}
/**
* 便ID
* <p>
* 便
* </p>
*
* @param resolver ContentResolver
* @param noteId 便ID
* @return 便
* @throws IllegalArgumentException 便
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
@ -282,6 +414,15 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
*
* <p>
*
* </p>
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();

@ -16,98 +16,252 @@
package net.micode.notes.tool;
/**
* GTaskStringUtils - GTask
* <p>
* GTaskGoogle TaskJSON
* 便Google Task
* </p>
*
* @author MiCode Open Source Community
* @version 1.0
*/
public class GTaskStringUtils {
// ------------------- GTask JSON字段名常量 -------------------
/**
* JSON - ID
*/
public final static String GTASK_JSON_ACTION_ID = "action_id";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_LIST = "action_list";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/**
* JSON -
*/
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
/**
* JSON - ID
*/
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/**
* JSON -
*/
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/**
* JSON -
*/
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/**
* JSON -
*/
public final static String GTASK_JSON_COMPLETED = "completed";
/**
* JSON - ID
*/
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/**
* JSON - ID
*/
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/**
* JSON -
*/
public final static String GTASK_JSON_DELETED = "deleted";
/**
* JSON -
*/
public final static String GTASK_JSON_DEST_LIST = "dest_list";
/**
* JSON -
*/
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/**
* JSON -
*/
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/**
* JSON -
*/
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/**
* JSON -
*/
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/**
* JSON -
*/
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/**
* JSON - ID
*/
public final static String GTASK_JSON_ID = "id";
/**
* JSON -
*/
public final static String GTASK_JSON_INDEX = "index";
/**
* JSON -
*/
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/**
* JSON -
*/
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
/**
* JSON - ID
*/
public final static String GTASK_JSON_LIST_ID = "list_id";
/**
* JSON -
*/
public final static String GTASK_JSON_LISTS = "lists";
/**
* JSON -
*/
public final static String GTASK_JSON_NAME = "name";
/**
* JSON - ID
*/
public final static String GTASK_JSON_NEW_ID = "new_id";
/**
* JSON -
*/
public final static String GTASK_JSON_NOTES = "notes";
/**
* JSON - ID
*/
public final static String GTASK_JSON_PARENT_ID = "parent_id";
/**
* JSON - ID
*/
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
/**
* JSON -
*/
public final static String GTASK_JSON_RESULTS = "results";
/**
* JSON -
*/
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/**
* JSON -
*/
public final static String GTASK_JSON_TASKS = "tasks";
/**
* JSON -
*/
public final static String GTASK_JSON_TYPE = "type";
/**
* JSON -
*/
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/**
* JSON -
*/
public final static String GTASK_JSON_TYPE_TASK = "TASK";
/**
* JSON -
*/
public final static String GTASK_JSON_USER = "user";
// ------------------- 文件夹相关常量 -------------------
/**
* MIUI
*/
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/**
*
*/
public final static String FOLDER_DEFAULT = "Default";
/**
*
*/
public final static String FOLDER_CALL_NOTE = "Call_Note";
/**
*
*/
public final static String FOLDER_META = "METADATA";
// ------------------- 元数据相关常量 -------------------
/**
* - GTask ID
*/
public final static String META_HEAD_GTASK_ID = "meta_gid";
/**
* - 便
*/
public final static String META_HEAD_NOTE = "meta_note";
/**
* -
*/
public final static String META_HEAD_DATA = "meta_data";
/**
* 便
*/
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -22,24 +22,87 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* ResourceParser -
* <p>
* 便
* 便
* </p>
*
* @author MiCode Open Source Community
* @version 1.0
*/
public class ResourceParser {
// ------------------- 颜色常量 -------------------
/**
* -
*/
public static final int YELLOW = 0;
/**
* -
*/
public static final int BLUE = 1;
/**
* -
*/
public static final int WHITE = 2;
/**
* - 绿
*/
public static final int GREEN = 3;
/**
* -
*/
public static final int RED = 4;
/**
*
*/
public static final int BG_DEFAULT_COLOR = YELLOW;
// ------------------- 字体大小常量 -------------------
/**
* -
*/
public static final int TEXT_SMALL = 0;
/**
* -
*/
public static final int TEXT_MEDIUM = 1;
/**
* -
*/
public static final int TEXT_LARGE = 2;
/**
* -
*/
public static final int TEXT_SUPER = 3;
/**
*
*/
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
/**
* NoteBgResources - 便
* <p>
* 便便
* </p>
*/
public static class NoteBgResources {
/**
* 便
*/
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
@ -48,6 +111,9 @@ public class ResourceParser {
R.drawable.edit_red
};
/**
* 便
*/
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
@ -56,15 +122,42 @@ public class ResourceParser {
R.drawable.edit_title_red
};
/**
* 便
* <p>
* ID便
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* 便
* <p>
* ID便
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
* <p>
* IDID
* </p>
*
* @param context
* @return ID
*/
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -74,7 +167,16 @@ public class ResourceParser {
}
}
/**
* NoteItemBgResources - 便
* <p>
* 便
* </p>
*/
public static class NoteItemBgResources {
/**
*
*/
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
@ -83,6 +185,9 @@ public class ResourceParser {
R.drawable.list_red_up
};
/**
*
*/
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
@ -91,6 +196,9 @@ public class ResourceParser {
R.drawable.list_red_middle
};
/**
*
*/
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
@ -99,6 +207,9 @@ public class ResourceParser {
R.drawable.list_red_down,
};
/**
*
*/
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
@ -107,28 +218,81 @@ public class ResourceParser {
R.drawable.list_red_single
};
/**
*
* <p>
* ID
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
*
* <p>
* ID
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
*
* <p>
* ID
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
*
* <p>
* ID
* </p>
*
* @param id ID
* @return ID
*/
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
/**
*
* <p>
*
* </p>
*
* @return ID
*/
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
* WidgetBgResources -
* <p>
* 便2x4x
* </p>
*/
public static class WidgetBgResources {
/**
* 2x
*/
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
@ -137,10 +301,22 @@ public class ResourceParser {
R.drawable.widget_2x_red,
};
/**
* 2x
* <p>
* ID2x
* </p>
*
* @param id ID
* @return ID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
/**
* 4x
*/
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
@ -149,12 +325,30 @@ public class ResourceParser {
R.drawable.widget_4x_red
};
/**
* 4x
* <p>
* ID4x
* </p>
*
* @param id ID
* @return ID
*/
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
/**
* TextAppearanceResources -
* <p>
*
* </p>
*/
public static class TextAppearanceResources {
/**
*
*/
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
@ -162,6 +356,16 @@ public class ResourceParser {
R.style.TextAppearanceSuper
};
/**
*
* <p>
* ID
* ID
* </p>
*
* @param id ID
* @return ID
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
@ -174,6 +378,14 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
* <p>
*
* </p>
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}

Loading…
Cancel
Save