新增了便签置顶/取消置顶、撤回/取消撤回、设为私密/取消私密功能的实现代码 #20

Merged
pvexk5qol merged 1 commits from caoweiqiong_branch into master 4 weeks ago

@ -27,34 +27,21 @@ import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* SQLite
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "note.db";
// 数据库版本号
private static final int DB_VERSION = 4;
private static final int DB_VERSION = 6;
/**
*
*/
public interface TABLE {
// 笔记表名
public static final String NOTE = "note";
// 数据内容表名
public static final String DATA = "data";
}
// 日志标签
private static final String TAG = "NotesDatabaseHelper";
// 单例实例
private static NotesDatabaseHelper mInstance;
// 创建笔记表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -73,10 +60,15 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.TITLE + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.IS_PINNED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.IS_PRIVATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.VIEW_MODE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CUSTOM_BG_URI + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.EXPAND_1 + " TEXT NOT NULL DEFAULT ''" +
")";
// 创建数据内容表的SQL语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -92,7 +84,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
// 为数据内容表的note_id字段创建索引的SQL语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
@ -221,18 +212,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
* @param context
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
*
* @param db SQLite
*/
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@ -240,10 +223,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
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");
@ -262,10 +241,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
* @param db SQLite
*/
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
@ -301,10 +276,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
/**
*
* @param db SQLite
*/
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@ -312,10 +283,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
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");
@ -326,11 +293,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -338,22 +300,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
/**
*
* @param db SQLite
*/
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
/**
*
* @param db SQLite
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
@ -361,7 +313,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // Skip v2 upgrade since it's already done
oldVersion++;
}
@ -373,6 +325,19 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
if (oldVersion == 3) {
upgradeToV4(db);
reCreateTriggers = true;
oldVersion++;
}
if (oldVersion == 4) {
upgradeToV5(db);
reCreateTriggers = true;
oldVersion++;
}
if (oldVersion == 5) {
upgradeToV6(db);
reCreateTriggers = true;
oldVersion++;
}
@ -387,10 +352,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
/**
* 2
* @param db SQLite
*/
// 确保存在 V6 升级方法,防止字段缺失
private void upgradeToV6(SQLiteDatabase db) {
// 使用 try-catch 忽略"列已存在"的错误,防止重复添加崩溃
try { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_PINNED + " INTEGER NOT NULL DEFAULT 0"); } catch(Exception e){}
try { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_PRIVATE + " INTEGER NOT NULL DEFAULT 0"); } catch(Exception e){}
try { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VIEW_MODE + " INTEGER NOT NULL DEFAULT 0"); } catch(Exception e){}
try { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.CUSTOM_BG_URI + " TEXT NOT NULL DEFAULT ''"); } catch(Exception e){}
try { db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.EXPAND_1 + " TEXT NOT NULL DEFAULT ''"); } catch(Exception e){}
}
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -398,10 +369,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
/**
* 3
* @param db SQLite
*/
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
@ -417,12 +384,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
/**
* 4
* @param db SQLite
*/
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
private void upgradeToV5(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_PINNED + " INTEGER NOT NULL DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_PRIVATE + " INTEGER NOT NULL DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VIEW_MODE + " INTEGER NOT NULL DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.CUSTOM_BG_URI + " TEXT NOT NULL DEFAULT ''");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.EXPAND_1 + " TEXT NOT NULL DEFAULT ''");
}
}

@ -35,27 +35,20 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* ContentProvider
*
*/
public class NotesProvider extends ContentProvider {
// Uri匹配器用于解析不同的请求URI
private static final UriMatcher mMatcher;
// 数据库助手实例
private NotesDatabaseHelper mHelper;
// 日志标签
private static final String TAG = "NotesProvider";
// Uri匹配规则常量
private static final int URI_NOTE = 1; // 所有笔记
private static final int URI_NOTE_ITEM = 2; // 单个笔记
private static final int URI_DATA = 3; // 所有数据内容
private static final int URI_DATA_ITEM = 4; // 单个数据内容
private static final int URI_SEARCH = 5; // 搜索
private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议
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 {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
@ -72,7 +65,6 @@ public class NotesProvider extends ContentProvider {
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
// 搜索结果的投影列定义
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
@ -81,33 +73,18 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 搜索笔记内容的SQL查询语句
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
* ContentProvider
* @return true
*/
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
* @throws IllegalArgumentException URI
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
@ -170,13 +147,6 @@ public class NotesProvider extends ContentProvider {
return c;
}
/**
*
* @param uri URI
* @param values
* @return URI
* @throws IllegalArgumentException URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
@ -211,14 +181,6 @@ public class NotesProvider extends ContentProvider {
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;
@ -265,15 +227,6 @@ 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;
@ -314,21 +267,10 @@ 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 ");
@ -354,11 +296,6 @@ public class NotesProvider extends ContentProvider {
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URIMIME
* @param uri URI
* @return MIME
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub

@ -25,22 +25,11 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* Task
* Google Task
*/
public class MetaData extends Task {
// 日志标签
private final static String TAG = MetaData.class.getSimpleName();
// 关联的Google Task ID
private String mRelatedGid = null;
/**
*
* @param gid Google Task ID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@ -51,27 +40,15 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* Google Task ID
* @return Google Task ID
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
*
* @return nulltrue
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* JSON
* @param js JSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
@ -86,33 +63,17 @@ public class MetaData extends Task {
}
}
/**
* JSON
* @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
* @return JSON
* @throws IllegalAccessError
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
*
* @param c
* @return
* @throws IllegalAccessError
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -20,53 +20,33 @@ import android.database.Cursor;
import org.json.JSONObject;
/**
*
* TaskTaskListGoogle Tasks
*/
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;
// Google Task唯一标识符
private String mGid;
// 节点名称
private String mName;
// 最后修改时间
private long mLastModified;
// 是否已删除
private boolean mDeleted;
/**
*
*/
public Node() {
mGid = null;
mName = "";
@ -74,105 +54,46 @@ public abstract class Node {
mDeleted = false;
}
/**
* JSON
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent();
/**
*
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c);
/**
* Google Task
* @param gid Google Task ID
*/
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;
}
/**
* Google Task
* @return Google Task ID
*/
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,66 +35,42 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
*
* ContentResolver
*/
public class SqlData {
// 日志标签
private static final String TAG = SqlData.class.getSimpleName();
// 无效ID常量
private static final int INVALID_ID = -99999;
// 数据查询投影数组
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
// 投影数组中ID列的索引
public static final int DATA_ID_COLUMN = 0;
// 投影数组中MIME类型列的索引
public static final int DATA_MIME_TYPE_COLUMN = 1;
// 投影数组中内容列的索引
public static final int DATA_CONTENT_COLUMN = 2;
// 投影数组中DATA1列的索引
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
// 投影数组中DATA3列的索引
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
// 内容解析器
private ContentResolver mContentResolver;
// 是否为创建操作
private boolean mIsCreate;
// 数据ID
private long mDataId;
// 数据MIME类型
private String mDataMimeType;
// 数据内容
private String mDataContent;
// 数据内容DATA1字段
private long mDataContentData1;
// 数据内容DATA3字段
private String mDataContentData3;
// 差异数据值,用于记录需要更新的字段
private ContentValues mDiffDataValues;
/**
*
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -106,11 +82,6 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -118,10 +89,6 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -130,11 +97,6 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* JSON
* @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) {
@ -168,11 +130,6 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/**
* JSON
* @return JSON
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -187,13 +144,6 @@ public class SqlData {
return js;
}
/**
*
* @param noteId ID
* @param validateVersion
* @param version
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -233,10 +183,6 @@ public class SqlData {
mIsCreate = false;
}
/**
* ID
* @return ID
*/
public long getId() {
return mDataId;
}

@ -38,18 +38,11 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
*
* ContentResolver
*/
public class SqlNote {
// 日志标签
private static final String TAG = SqlNote.class.getSimpleName();
// 无效ID常量
private static final int INVALID_ID = -99999;
// 笔记查询投影数组
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -59,115 +52,76 @@ public class SqlNote {
NoteColumns.VERSION
};
// 投影数组中ID列的索引
public static final int ID_COLUMN = 0;
// 投影数组中提醒日期列的索引
public static final int ALERTED_DATE_COLUMN = 1;
// 投影数组中背景颜色ID列的索引
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;
// 投影数组中父ID列的索引
public static final int PARENT_ID_COLUMN = 7;
// 投影数组中摘要列的索引
public static final int SNIPPET_COLUMN = 8;
// 投影数组中类型列的索引
public static final int TYPE_COLUMN = 9;
// 投影数组中小组件ID列的索引
public static final int WIDGET_ID_COLUMN = 10;
// 投影数组中小组件类型列的索引
public static final int WIDGET_TYPE_COLUMN = 11;
// 投影数组中同步ID列的索引
public static final int SYNC_ID_COLUMN = 12;
// 投影数组中本地修改标记列的索引
public static final int LOCAL_MODIFIED_COLUMN = 13;
// 投影数组中原始父ID列的索引
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
// 投影数组中Google Task ID列的索引
public static final int GTASK_ID_COLUMN = 15;
// 投影数组中版本列的索引
public static final int VERSION_COLUMN = 16;
// 上下文对象
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 是否为创建操作
private boolean mIsCreate;
// 笔记ID
private long mId;
// 提醒日期
private long mAlertDate;
// 背景颜色ID
private int mBgColorId;
// 创建日期
private long mCreatedDate;
// 是否有附件01
private int mHasAttachment;
// 修改日期
private long mModifiedDate;
// 父文件夹ID
private long mParentId;
// 笔记摘要
private String mSnippet;
// 笔记类型(文件夹或笔记)
private int mType;
// 小组件ID
private int mWidgetId;
// 小组件类型
private int mWidgetType;
// 原始父文件夹ID
private long mOriginParent;
// 版本号
private long mVersion;
// 差异笔记值,用于记录需要更新的字段
private ContentValues mDiffNoteValues;
// 数据内容列表
private ArrayList<SqlData> mDataList;
/**
*
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -189,11 +143,6 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
/**
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -205,11 +154,6 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
/**
* ID
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -219,12 +163,9 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/**
* ID
* @param id ID
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
@ -244,10 +185,6 @@ public class SqlNote {
}
}
/**
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -263,9 +200,6 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
/**
*
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
@ -292,11 +226,6 @@ public class SqlNote {
}
}
/**
* JSON
* @param js JSON
* @return
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -430,10 +359,6 @@ public class SqlNote {
return true;
}
/**
* JSON
* @return JSONnull
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -482,76 +407,39 @@ 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);
}
/**
*
*/
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;
}
/**
*
* @param validateVersion
* @throws ActionFailureException
* @throws IllegalStateException ID
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {

@ -32,32 +32,19 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* Google TasksNode
*
*/
public class Task extends Node {
// 日志标签
private static final String TAG = Task.class.getSimpleName();
// 任务是否已完成
private boolean mCompleted;
// 任务的详细说明
private String mNotes;
// 任务的元信息JSON对象
private JSONObject mMetaInfo;
// 前一个兄弟任务(用于排序)
private Task mPriorSibling;
// 父任务列表
private TaskList mParent;
/**
*
*/
public Task() {
super();
mCompleted = false;
@ -67,12 +54,6 @@ public class Task extends Node {
mMetaInfo = null;
}
/**
* JSON
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -122,12 +103,6 @@ public class Task extends Node {
return js;
}
/**
* JSON
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -160,11 +135,6 @@ public class Task extends Node {
return js;
}
/**
* JSON
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -205,10 +175,6 @@ public class Task extends Node {
}
}
/**
* JSON
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -238,10 +204,6 @@ public class Task extends Node {
}
}
/**
* JSON
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -285,10 +247,6 @@ public class Task extends Node {
}
}
/**
*
* @param metaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -300,11 +258,6 @@ public class Task extends Node {
}
}
/**
*
* @param c
* @return SYNC_ACTION_NONESYNC_ACTION_UPDATE_REMOTE
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -358,75 +311,39 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* @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,36 +30,19 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* Google TasksNode
*
*
*/
public class TaskList extends Node {
// 日志标签
private static final String TAG = TaskList.class.getSimpleName();
// 任务列表的索引位置
private int mIndex;
// 任务列表中的子任务集合
private ArrayList<Task> mChildren;
/**
*
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -91,12 +74,6 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -126,11 +103,6 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -157,10 +129,6 @@ public class TaskList extends Node {
}
}
/**
* JSON
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -189,10 +157,6 @@ public class TaskList extends Node {
}
}
/**
* JSON
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -219,11 +183,6 @@ public class TaskList extends Node {
}
}
/**
*
* @param c
* @return SYNC_ACTION_NONESYNC_ACTION_UPDATE_REMOTE
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
@ -257,19 +216,10 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
*
* @param task
* @return
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -284,12 +234,6 @@ public class TaskList extends Node {
return ret;
}
/**
*
* @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");
@ -316,11 +260,6 @@ public class TaskList extends Node {
return true;
}
/**
*
* @param task
* @return
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -342,12 +281,6 @@ public class TaskList extends Node {
return ret;
}
/**
*
* @param task
* @param index
* @return
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -366,11 +299,6 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* Google Task ID
* @param gid Google Task ID
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -381,20 +309,10 @@ public class TaskList extends Node {
return null;
}
/**
*
* @param task
* @return
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -403,11 +321,6 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
* Google Task IDfindChildTaskByGid
* @param gid Google Task ID
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -416,26 +329,14 @@ public class TaskList extends Node {
return null;
}
/**
*
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
* @return
*/
public int getIndex() {
return this.mIndex;
}

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

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

@ -29,44 +29,22 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* Google Tasks
* AsyncTaskGoogle Tasks
*
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 同步通知的ID
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;
@ -75,52 +53,36 @@ 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;
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
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
@ -128,10 +90,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
return mTaskManager.sync(mContext, this);
}
/**
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -140,10 +98,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
/**
*
* @param result
*/
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {

@ -61,58 +61,35 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* Google Tasks
* Google Tasks
*
*/
public class GTaskClient {
// 日志标签
private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks基础URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// Google Tasks GET请求URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// Google Tasks POST请求URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null;
// HTTP客户端实例
private DefaultHttpClient mHttpClient;
// 当前使用的GET请求URL
private String mGetUrl;
// 当前使用的POST请求URL
private String mPostUrl;
// 客户端版本号
private long mClientVersion;
// 是否已登录
private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime;
// 操作ID计数器
private int mActionId;
// 登录的Google账户
private Account mAccount;
// 更新操作的JSON数组
private JSONArray mUpdateArray;
/**
*
*
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -125,10 +102,6 @@ public class GTaskClient {
mUpdateArray = null;
}
/**
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -136,20 +109,15 @@ public class GTaskClient {
return mInstance;
}
/**
* Google Tasks
* GoogleTasks
* @param activity Activity
* @return
*/
public boolean login(Activity activity) {
// 假设Cookie 5分钟后过期需要重新登录
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
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))) {
@ -168,7 +136,7 @@ public class GTaskClient {
return false;
}
// 必要时使用自定义域名登录
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -183,7 +151,7 @@ public class GTaskClient {
}
}
// 尝试使用Google官方URL登录
// try to login with google official url
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -196,12 +164,6 @@ 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);
@ -227,7 +189,7 @@ public class GTaskClient {
return null;
}
// 获取认证令牌
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -245,16 +207,10 @@ public class GTaskClient {
return authToken;
}
/**
* Google Tasks
* 使
* @param activity Activity
* @param authToken Google
* @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");
@ -269,12 +225,6 @@ public class GTaskClient {
return true;
}
/**
* 使Google Tasks
* HTTPCookie
* @param authToken Google
* @return
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -286,14 +236,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// 登录Google Tasks
// login gtask
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// 获取认证Cookie
// get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -305,7 +255,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>";
@ -322,7 +272,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// 捕获所有异常
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -330,20 +280,10 @@ public class GTaskClient {
return true;
}
/**
* ID
* ID
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* HTTP POST
* URL
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -351,13 +291,6 @@ public class GTaskClient {
return httpPost;
}
/**
* HTTP
* gzipdeflate
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -390,13 +323,6 @@ public class GTaskClient {
}
}
/**
* POST
* Google Tasks
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -410,7 +336,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// 执行POST请求
// execute the post
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@ -434,12 +360,6 @@ public class GTaskClient {
}
}
/**
*
* Google Tasks
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
@ -453,7 +373,7 @@ public class GTaskClient {
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -466,12 +386,6 @@ public class GTaskClient {
}
}
/**
*
* Google Tasks
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
@ -482,10 +396,10 @@ public class GTaskClient {
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -498,11 +412,6 @@ public class GTaskClient {
}
}
/**
*
* Google Tasks
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
@ -524,17 +433,10 @@ public class GTaskClient {
}
}
/**
*
*
* 10
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 过多的更新项可能导致错误
// 最大设置为10项
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
@ -545,14 +447,6 @@ public class GTaskClient {
}
}
/**
*
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -567,13 +461,14 @@ public class GTaskClient {
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// 只有在同一任务列表内移动且不是第一个任务时才设置prior_sibling_id
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) {
// 只有在不同任务列表之间移动时才设置dest_list
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
@ -591,12 +486,6 @@ public class GTaskClient {
}
}
/**
*
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
@ -620,12 +509,6 @@ public class GTaskClient {
}
}
/**
*
* Google Tasks
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -664,13 +547,6 @@ public class GTaskClient {
}
}
/**
*
* Google Tasks
* @param listGid GID
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -699,18 +575,10 @@ public class GTaskClient {
}
}
/**
*
* @return 使Google
*/
public Account getSyncAccount() {
return mAccount;
}
/**
*
*
*/
public void resetUpdateArray() {
mUpdateArray = null;
}

@ -48,73 +48,45 @@ import java.util.Iterator;
import java.util.Map;
/**
* Google Tasks
* Google Tasks
*
*/
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;
// 单例实例
private static GTaskManager mInstance = null;
// 用于获取认证令牌的Activity实例
private Activity mActivity;
// 应用上下文
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 是否正在同步
private boolean mSyncing;
// 是否取消同步
private boolean mCancelled;
// Google Tasks列表映射表
private HashMap<String, TaskList> mGTaskListHashMap;
// Google Tasks节点映射表
private HashMap<String, Node> mGTaskHashMap;
// 元数据映射表
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;
/**
*
*
*/
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -127,10 +99,6 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
/**
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -138,23 +106,11 @@ public class GTaskManager {
return mInstance;
}
/**
* Activity
* Google
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
/**
*
* Google Tasks
* @param context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -212,11 +168,6 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* Google Tasks
*
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -296,11 +247,6 @@ public class GTaskManager {
}
}
/**
*
*
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -405,11 +351,6 @@ public class GTaskManager {
}
/**
*
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -535,14 +476,6 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
/**
*
*
* @param syncType
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -589,12 +522,6 @@ public class GTaskManager {
}
}
/**
*
* Google Tasks
* @param node Google Tasks
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -669,13 +596,6 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
*
* 使Google Tasks
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -699,13 +619,6 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
*
* Google Tasks
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -779,13 +692,6 @@ public class GTaskManager {
mNidToGid.put(sqlNote.getId(), n.getGid());
}
/**
*
* 使Google Tasks
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -824,13 +730,6 @@ public class GTaskManager {
sqlNote.commit(true);
}
/**
*
* Google Tasks
* @param gid Google TasksID
* @param sqlNote
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -847,11 +746,6 @@ public class GTaskManager {
}
}
/**
* ID
* ID
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
@ -896,18 +790,10 @@ public class GTaskManager {
}
}
/**
*
* @return
*/
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
/**
*
*
*/
public void cancelSync() {
mCancelled = true;
}

@ -23,43 +23,25 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* Google Tasks
* Google Tasks
* 广
*/
public class GTaskSyncService extends Service {
// 同步操作类型的额外参数名称
public final static String ACTION_STRING_NAME = "sync_action_type";
// 启动同步操作的类型值
public final static int ACTION_START_SYNC = 0;
// 取消同步操作的类型值
public final static int ACTION_CANCEL_SYNC = 1;
// 无效操作的类型值
public final static int ACTION_INVALID = 2;
// 同步服务广播的名称
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() {
@ -74,33 +56,17 @@ public class GTaskSyncService extends Service {
}
}
/**
*
*
*/
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
/**
*
* null
*/
@Override
public void onCreate() {
mSyncTask = null;
}
/**
*
*
* @param intent
* @param flags
* @param startId ID
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@ -120,10 +86,6 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId);
}
/**
*
*
*/
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -131,20 +93,10 @@ public class GTaskSyncService extends Service {
}
}
/**
*
* null
* @param intent
* @return IBinder
*/
public IBinder onBind(Intent intent) {
return null;
}
/**
* 广
* @param msg
*/
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -153,10 +105,6 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
/**
*
* @param activity Activity
*/
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -164,28 +112,16 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
/**
*
* @param context
*/
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
/**
*
* @return
*/
public static boolean isSyncing() {
return mSyncTask != null;
}
/**
*
* @return
*/
public static String getProgressString() {
return mSyncProgress;
}

@ -34,25 +34,12 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
*
* ContentResolver
*/
public class Note {
// 日志标签
private static final String TAG = "Note";
// 存储笔记基本信息的变更值
private ContentValues mNoteDiffValues;
// 存储笔记数据内容的内部对象
private NoteData mNoteData;
private static final String TAG = "Note";
/**
* ID
* @param context
* @param folderId ID
* @return ID
* @throws IllegalStateException
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
@ -78,82 +65,41 @@ public class Note {
return noteId;
}
/**
*
*/
public Note() {
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());
}
/**
*
* @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();
}
/**
* ContentResolver
* @param context
* @param noteId ID
* @return truefalse
* @throws IllegalArgumentException ID
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -164,14 +110,15 @@ public class Note {
}
/**
* {@link NoteColumns#LOCAL_MODIFIED}{@link NoteColumns#MODIFIED_DATE}
* 使
* 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
*/
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();
@ -183,29 +130,17 @@ public class Note {
return true;
}
/**
*
*
*/
private class NoteData {
// 日志标签
private static final String TAG = "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();
@ -213,19 +148,10 @@ public class Note {
mCallDataId = 0;
}
/**
*
* @return truefalse
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* ID
* @param id ID
* @throws IllegalArgumentException ID
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -233,11 +159,6 @@ public class Note {
mTextDataId = id;
}
/**
* ID
* @param id ID
* @throws IllegalArgumentException ID
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -245,38 +166,21 @@ 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());
}
/**
*
* @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());
}
/**
* ContentResolver
* @param context
* @param noteId ID
* @return Urinull
* @throws IllegalArgumentException ID
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
*
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -288,7 +192,6 @@ public class Note {
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
// 新建文本数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
@ -300,7 +203,6 @@ public class Note {
return null;
}
} else {
// 更新已有文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
@ -312,7 +214,6 @@ public class Note {
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
// 新建通话记录数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
@ -324,7 +225,6 @@ public class Note {
return null;
}
} else {
// 更新已有通话记录数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
@ -333,7 +233,6 @@ public class Note {
mCallDataValues.clear();
}
// 执行批量操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(

@ -32,57 +32,40 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
*
* Note
*
*/
public class WorkingNote {
// 日志标签
private static final String TAG = "WorkingNote";
// 上下文对象
private Context mContext;
// 内部Note对象用于实际数据操作
// Note for the working note
private Note mNote;
// 笔记ID
// Note Id
private long mNoteId;
// 笔记内容
// Note content
private String mContent;
// 笔记模式(如普通模式、检查列表模式)
// Note mode
private int mMode;
// 提醒日期
private long mAlertDate;
// 最后修改日期
private long mModifiedDate;
// 背景颜色ID
private int mBgColorId;
private String mTitle;
// 小组件ID
private int mWidgetId;
// 小组件类型
private int mWidgetType;
// 文件夹ID
private long mFolderId;
// 是否已删除
private Context mContext;
private String mCustomBgUri; // [新增]
private static final String TAG = "WorkingNote";
private boolean mIsDeleted;
// 笔记设置变化监听器
private NoteSettingChangedListener mNoteSettingStatusListener;
/**
*
*/
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -93,53 +76,42 @@ public class WorkingNote {
DataColumns.DATA4,
};
/**
*
*/
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.MODIFIED_DATE,
NoteColumns.TITLE,
NoteColumns.CUSTOM_BG_URI
};
// DATA_PROJECTION中ID列的索引
private static final int DATA_ID_COLUMN = 0;
// DATA_PROJECTION中内容列的索引
private static final int DATA_CONTENT_COLUMN = 1;
// DATA_PROJECTION中MIME类型列的索引
private static final int DATA_MIME_TYPE_COLUMN = 2;
// DATA_PROJECTION中模式列的索引
private static final int DATA_MODE_COLUMN = 3;
// NOTE_PROJECTION中父ID列的索引
private static final int NOTE_PARENT_ID_COLUMN = 0;
// NOTE_PROJECTION中提醒日期列的索引
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
// NOTE_PROJECTION中背景颜色ID列的索引
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
// NOTE_PROJECTION中小组件ID列的索引
private static final int NOTE_WIDGET_ID_COLUMN = 3;
// NOTE_PROJECTION中小组件类型列的索引
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
// NOTE_PROJECTION中修改日期列的索引
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
private static final int NOTE_TITLE_COLUMN = 6;
/**
*
* @param context
* @param folderId ID
*/
private static final int NOTE_CUSTOM_BG_COLUMN = 7;
// New note construct
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -152,12 +124,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
/**
*
* @param context
* @param noteId ID
* @param folderId ID
*/
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -167,10 +134,6 @@ public class WorkingNote {
loadNote();
}
/**
*
* @throws IllegalArgumentException ID
*/
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -184,6 +147,8 @@ public class WorkingNote {
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
mTitle = cursor.getString(NOTE_TITLE_COLUMN);
mCustomBgUri = cursor.getString(NOTE_CUSTOM_BG_COLUMN);
}
cursor.close();
} else {
@ -193,10 +158,6 @@ public class WorkingNote {
loadNoteData();
}
/**
*
* @throws IllegalArgumentException ID
*/
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
@ -225,15 +186,6 @@ 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);
@ -243,21 +195,10 @@ 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 truefalse
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
@ -267,11 +208,37 @@ public class WorkingNote {
}
}
// 1. 只有当标题真的为空时(比如第一次编辑新便签),才执行自动提取逻辑
if (TextUtils.isEmpty(mTitle)) {
String plainText = getPlainText(mContent); // 使用之前提供的清洗工具
if (!TextUtils.isEmpty(plainText)) {
String[] lines = plainText.split("\n");
for (String line : lines) {
if (!TextUtils.isEmpty(line.trim())) {
mTitle = line.trim();
break;
}
}
// 限制长度
if (mTitle != null && mTitle.length() > 20) {
mTitle = mTitle.substring(0, 20);
}
}
}
// 2. 无论标题是刚才生成的,还是以前加载的,都写入数据库更新
// 如果用户在外部进行了“重命名”数据库里的值会变loadNote 会拿到新值,此处也会保留新值
mNote.setNoteValue(NoteColumns.TITLE, mTitle);
// 3. 摘要预览清洗Snippet 依然随正文更新,保证预览的时效性)
String plainContent = getPlainText(mContent);
String snippet = plainContent.replace("\n", " ").trim();
if (snippet.length() > 60) snippet = snippet.substring(0, 60);
mNote.setNoteValue(NoteColumns.SNIPPET, snippet);
// 提交修改到数据库
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
&& mNoteSettingStatusListener != null) {
@ -284,17 +251,32 @@ public class WorkingNote {
}
/**
*
* @return truefalse
* [] HTML
*/
private String getPlainText(String html) {
if (TextUtils.isEmpty(html)) return "";
// 1. 处理块级标签,防止文字挤在一起
String result = html.replaceAll("(?i)<br\\s*/?>", "\n") // 换行符
.replaceAll("(?i)</div>", "\n") // 层叠样式结束换行
.replaceAll("(?i)</p>", "\n"); // 段落结束换行
// 2. 利用 Android 原生工具解析 HTML 实体 (如 &nbsp; -> 空格)
// 注意:这里使用 toString() 剥离大部分标准标签
result = android.text.Html.fromHtml(result).toString();
// 3. 正则强力保底清洗
result = result.replaceAll("<[^>]+>", "") // 删掉所有尖括号内的代码
.replaceAll("\\uFFFC", "") // 删掉 Android 的 ImageSpan 占位符(OBJECT_REPLACEMENT_CHARACTER)
.replaceAll("&[^;]+;", ""); // 删掉残留的 HTML 实体(如 &amp;
return result.trim();
}
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
*
* @return truefalse
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -304,19 +286,10 @@ 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;
@ -327,10 +300,6 @@ public class WorkingNote {
}
}
/**
*
* @param mark truefalse
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -339,13 +308,15 @@ public class WorkingNote {
}
}
/**
* ID
* @param id ID
*/
// 1. 修改 setBgColorId 方法:逻辑是“选了颜色就放弃图片”
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
// [新增手术:清除自定义背景]
mCustomBgUri = "";
mNote.setNoteValue(NoteColumns.CUSTOM_BG_URI, "");
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}
@ -353,10 +324,17 @@ public class WorkingNote {
}
}
/**
*
* @param mode 01
*/
// 2. 确保已添加 Getter/Setter
public void setCustomBgUri(String uri) {
this.mCustomBgUri = uri;
// 立即告诉数据库也要更新这个值
mNote.setNoteValue(NoteColumns.CUSTOM_BG_URI, uri);
}
public String getCustomBgUri() {
return mCustomBgUri;
}
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -367,10 +345,6 @@ public class WorkingNote {
}
}
/**
*
* @param type
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -378,10 +352,6 @@ public class WorkingNote {
}
}
/**
* ID
* @param id ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -389,10 +359,6 @@ public class WorkingNote {
}
}
/**
*
* @param text
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -400,139 +366,80 @@ 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 01
*/
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();
/**
*
* @param date
* @param set
* Called when user set clock
*/
void onClockAlertChanged(long date, boolean set);
/**
*
* Call when user create note from widget
*/
void onWidgetChanged();
/**
*
* @param oldMode
* @param newMode
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}

Loading…
Cancel
Save