最终合并的版本

main
helloworld 1 year ago
parent b4151c0eef
commit bd681753da

@ -14,69 +14,101 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class MetaData extends Task { public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName(); /*
* TAG
* getSimpleName ()
*/
private final static String TAG = MetaData.class.getSimpleName();
private String mRelatedGid = null; private String mRelatedGid = null;
/*
*
* JSONObjectput ()TasksetNotes ()setName ()
*
*/
public void setMeta(String gid, JSONObject metaInfo)
{
//对函数块进行注释
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
/*
* metaInfojsonobject
*/
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
/*
*
*/
}
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
}
/*
* Gid
*/
public String getRelatedGid() {
return mRelatedGid;
}
/*
*
*/
public void setMeta(String gid, JSONObject metaInfo) { @Override
try { public boolean isWorthSaving() {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); return getNotes() != null;
} catch (JSONException e) { }
Log.e(TAG, "failed to put related gid"); /*
} * 使json
setNotes(metaInfo.toString()); * TasksetContentByRemoteJSON ()
setName(GTaskStringUtils.META_NOTE_NAME); *
} */
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
/*
* 使json
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/*
* json
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/*
*
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
public String getRelatedGid() { }
return mRelatedGid;
}
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
}

@ -14,88 +14,93 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
public abstract class Node { /*
public static final int SYNC_ACTION_NONE = 0; *
* abstract
*/
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_REMOTE = 1;// 需要在远程云端增加内容
public static final int SYNC_ACTION_ADD_LOCAL = 2; public static final int SYNC_ACTION_ADD_LOCAL = 2;// 需要在本地增加内容
public static final int SYNC_ACTION_DEL_REMOTE = 3; public static final int SYNC_ACTION_DEL_REMOTE = 3;// 需要在远程云端删除内容
public static final int SYNC_ACTION_DEL_LOCAL = 4; 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_REMOTE = 5;// 需要将本地内容更新到远程云端
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 需要将远程云端内容更新到本地
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 同步出现冲突
public static final int SYNC_ACTION_ERROR = 8; public static final int SYNC_ACTION_ERROR = 8;// 同步出现错误
private String mGid; private String mGid;
private String mName; private String mName;
private long mLastModified; private long mLastModified;//记录最后一次修改时间
private boolean mDeleted; private boolean mDeleted;//表征是否被删除
public Node() { public Node() {
mGid = null; mGid = null;
mName = ""; mName = "";
mLastModified = 0; mLastModified = 0;
mDeleted = false; mDeleted = false;
} }
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
} }

@ -14,176 +14,227 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONException;
import org.json.JSONObject; /*
* Description便sqlnotedatanote
* SqlData
public class SqlData { */
private static final String TAG = SqlData.class.getSimpleName();
private static final int INVALID_ID = -99999; public class SqlData {
/*
public static final String[] PROJECTION_DATA = new String[] { * TAG
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, * getSimpleName ()
DataColumns.DATA3
}; */
private static final String TAG = SqlData.class.getSimpleName();
public static final int DATA_ID_COLUMN = 0;
private static final int INVALID_ID = -99999;//为mDataId置初始值-99999
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2; /**
* NotesDataColumn
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; */
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; // 集合了interface DataColumns中所有SF常量
public static final String[] PROJECTION_DATA = new String[] {
private ContentResolver mContentResolver; DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
private boolean mIsCreate; };
private long mDataId; /**
* sql5
private String mDataMimeType; */
public static final int DATA_ID_COLUMN = 0;
private String mDataContent;
public static final int DATA_MIME_TYPE_COLUMN = 1;
private long mDataContentData1;
public static final int DATA_CONTENT_COLUMN = 2;
private String mDataContentData3;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
private ContentValues mDiffDataValues;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
public SqlData(Context context) {
mContentResolver = context.getContentResolver(); private ContentResolver mContentResolver;
mIsCreate = true; //判断是否直接用Content生成是为true否则为false
mDataId = INVALID_ID; private boolean mIsCreate;
mDataMimeType = DataConstants.NOTE;
mDataContent = ""; private long mDataId;
mDataContentData1 = 0;
mDataContentData3 = ""; private String mDataMimeType;
mDiffDataValues = new ContentValues();
} private String mDataContent;
public SqlData(Context context, Cursor c) { private long mDataContentData1;
mContentResolver = context.getContentResolver();
mIsCreate = false; private String mDataContentData3;
loadFromCursor(c);
mDiffDataValues = new ContentValues(); private ContentValues mDiffDataValues;
}
/*
private void loadFromCursor(Cursor c) { *
mDataId = c.getLong(DATA_ID_COLUMN); * mContentResolverContentProvider
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); * mIsCreate
mDataContent = c.getString(DATA_CONTENT_COLUMN); */
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); public SqlData(Context context) {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mContentResolver = context.getContentResolver();
} mIsCreate = true;
mDataId = INVALID_ID;//mDataId置初始值-99999
public void setContent(JSONObject js) throws JSONException { mDataMimeType = DataConstants.NOTE;
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; mDataContent = "";
if (mIsCreate || mDataId != dataId) { mDataContentData1 = 0;
mDiffDataValues.put(DataColumns.ID, dataId); mDataContentData3 = "";
} mDiffDataValues = new ContentValues();
mDataId = dataId; }
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; /*
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { *
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); * mContentResolverContentProvider
} * mIsCreate
mDataMimeType = dataMimeType; */
public SqlData(Context context, Cursor c) {
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; mContentResolver = context.getContentResolver();
if (mIsCreate || !mDataContent.equals(dataContent)) { mIsCreate = false;
mDiffDataValues.put(DataColumns.CONTENT, dataContent); loadFromCursor(c);
} mDiffDataValues = new ContentValues();
mDataContent = dataContent; }
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; /*
if (mIsCreate || mDataContentData1 != dataContentData1) { *
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); *
} */
mDataContentData1 = dataContentData1; private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
} mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
mDataContentData3 = dataContentData3; }
}
public JSONObject getContent() throws JSONException { /*
if (mIsCreate) { *
Log.e(TAG, "it seems that we haven't created this in database yet"); */
return null; public void setContent(JSONObject js) throws JSONException {
} //如果传入的JSONObject对象中有DataColumns.ID这一项则设置否则设为INVALID_ID
JSONObject js = new JSONObject(); long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
js.put(DataColumns.ID, mDataId); if (mIsCreate || mDataId != dataId) {
js.put(DataColumns.MIME_TYPE, mDataMimeType); mDiffDataValues.put(DataColumns.ID, dataId);
js.put(DataColumns.CONTENT, mDataContent); }
js.put(DataColumns.DATA1, mDataContentData1); mDataId = dataId;
js.put(DataColumns.DATA3, mDataContentData3);
return js; String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
} : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
public void commit(long noteId, boolean validateVersion, long version) { mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
}
if (mIsCreate) { mDataMimeType = dataMimeType;
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
} if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); }
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); mDataContent = dataContent;
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1)); long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
} catch (NumberFormatException e) { if (mIsCreate || mDataContentData1 != dataContentData1) {
Log.e(TAG, "Get note id error :" + e.toString()); mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
throw new ActionFailureException("create note failed"); }
} mDataContentData1 = dataContentData1;
} else {
if (mDiffDataValues.size() > 0) { String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
int result = 0; if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
if (!validateVersion) { mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
result = mContentResolver.update(ContentUris.withAppendedId( }
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); mDataContentData3 = dataContentData3;
} else { }
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE /*
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] { *
String.valueOf(noteId), String.valueOf(version) */
}); public JSONObject getContent() throws JSONException {
} if (mIsCreate) {
if (result == 0) { Log.e(TAG, "it seems that we haven't created this in database yet");
Log.w(TAG, "there is no update. maybe user updates note when syncing"); return null;
} }
} //创建JSONObject对象。并将相关数据放入其中并返回。
} JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
mDiffDataValues.clear(); js.put(DataColumns.MIME_TYPE, mDataMimeType);
mIsCreate = false; js.put(DataColumns.CONTENT, mDataContent);
} js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3);
public long getId() { return js;
return mDataId; }
}
} /*
* commit
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
} else {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
}
mDiffDataValues.clear();
mIsCreate = false;
}
/*
* id
*/
public long getId() {
return mDataId;
}
}

File diff suppressed because it is too large Load Diff

@ -14,338 +14,343 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;
private String mNotes; public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private JSONObject mMetaInfo;
private boolean mCompleted;//是否完成
private Task mPriorSibling;
private String mNotes;
private TaskList mParent;
private JSONObject mMetaInfo;//将在实例中存储数据的类型
public Task() {
super(); private Task mPriorSibling;//对应的优先兄弟Task的指针待完善
mCompleted = false;
mNotes = null; private TaskList mParent;//所在的任务列表的指针
mPriorSibling = null;
mParent = null; public Task() {
mMetaInfo = null; super();
} mCompleted = false;
mNotes = null;
public JSONObject getCreateAction(int actionId) { mPriorSibling = null;//TaskList中当前Task前面的Task的指针
JSONObject js = new JSONObject(); mParent = null;//当前Task所在的TaskList
mMetaInfo = null;
try { }
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, public JSONObject getCreateAction(int actionId) {
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); JSONObject js = new JSONObject();
// action_id try {
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
// index GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// action_id
// entity_delta js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // index
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK); // entity_delta
if (getNotes() != null) { JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
} entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
// parent_id if (getNotes() != null) {
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
// dest_parent_type js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // parent_id
if (mParent!= null) {
// list_id js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); }
// prior_sibling_id // dest_parent_type
if (mPriorSibling != null) { js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
}
// list_id
} catch (JSONException e) { if (mParent!= null) {
Log.e(TAG, e.toString()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
e.printStackTrace(); }
throw new ActionFailureException("fail to generate task-create jsonobject");
} // prior_sibling_id
if (mPriorSibling != null) {
return js; js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
} }
public JSONObject getUpdateAction(int actionId) { } catch (JSONException e) {
JSONObject js = new JSONObject(); Log.e(TAG, e.toString());
e.printStackTrace();
try { throw new ActionFailureException("fail to generate task-create jsonobject");
// action_type }
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); return js;
}
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); try {
// action_type
// entity_delta js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
JSONObject entity = new JSONObject(); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) { // action_id
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // id
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
} catch (JSONException e) { // entity_delta
Log.e(TAG, e.toString()); JSONObject entity = new JSONObject();
e.printStackTrace(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
throw new ActionFailureException("fail to generate task-update jsonobject"); if (getNotes() != null) {
} entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
return js; entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
} js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
public void setContentByRemoteJSON(JSONObject js) { } catch (JSONException e) {
if (js != null) { Log.e(TAG, e.toString());
try { e.printStackTrace();
// id throw new ActionFailureException("fail to generate task-update jsonobject");
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { }
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} return js;
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { public void setContentByRemoteJSON(JSONObject js) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); if (js != null) {
} try {
// id
// name if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); }
}
// last_modified
// notes if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); }
}
// name
// deleted if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); }
}
// notes
// completed if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); }
}
} catch (JSONException e) { // deleted
Log.e(TAG, e.toString()); if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
e.printStackTrace(); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
throw new ActionFailureException("fail to get task content from jsonobject"); }
}
} // completed
} if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
public void setContentByLocalJSON(JSONObject js) { }
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) } catch (JSONException e) {
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { Log.e(TAG, e.toString());
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); e.printStackTrace();
} throw new ActionFailureException("fail to get task content from jsonobject");
}
try { }
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); }
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
public void setContentByLocalJSON(JSONObject js) { //<2F><>metadata<74><61><EFBFBD><EFBFBD>ʵʩ
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
Log.e(TAG, "invalid type"); || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
return; Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
for (int i = 0; i < dataArray.length(); i++) { try {
JSONObject data = dataArray.getJSONObject(i); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
setName(data.getString(DataColumns.CONTENT));
break; if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
} Log.e(TAG, "invalid type");
} return;
}
} catch (JSONException e) {
Log.e(TAG, e.toString()); for (int i = 0; i < dataArray.length(); i++) {
e.printStackTrace(); JSONObject data = dataArray.getJSONObject(i);
} if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
} setName(data.getString(DataColumns.CONTENT));
break;
public JSONObject getLocalJSONFromContent() { }
String name = getName(); }
try {
if (mMetaInfo == null) { } catch (JSONException e) {
// new task created from web Log.e(TAG, e.toString());
if (name == null) { e.printStackTrace();
Log.w(TAG, "the note seems to be an empty one"); }
return null; }
}
public JSONObject getLocalJSONFromContent() {
JSONObject js = new JSONObject(); String name = getName();
JSONObject note = new JSONObject(); try {
JSONArray dataArray = new JSONArray(); if (mMetaInfo == null) {
JSONObject data = new JSONObject(); // new task created from web
data.put(DataColumns.CONTENT, name); if (name == null) {
dataArray.put(data); Log.w(TAG, "the note seems to be an empty one");
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); return null;
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); }
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; JSONObject js = new JSONObject();
} else { JSONObject note = new JSONObject();
// synced task JSONArray dataArray = new JSONArray();
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject data = new JSONObject();
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); data.put(DataColumns.CONTENT, name);
dataArray.put(data);
for (int i = 0; i < dataArray.length(); i++) { js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
JSONObject data = dataArray.getJSONObject(i); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { js.put(GTaskStringUtils.META_HEAD_NOTE, note);
data.put(DataColumns.CONTENT, getName()); return js;
break; } else {
} // synced task
} JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo; for (int i = 0; i < dataArray.length(); i++) {
} JSONObject data = dataArray.getJSONObject(i);
} catch (JSONException e) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
Log.e(TAG, e.toString()); data.put(DataColumns.CONTENT, getName());
e.printStackTrace(); break;
return null; }
} }
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
public void setMetaInfo(MetaData metaData) { return mMetaInfo;
if (metaData != null && metaData.getNotes() != null) { }
try { } catch (JSONException e) {
mMetaInfo = new JSONObject(metaData.getNotes()); Log.e(TAG, e.toString());
} catch (JSONException e) { e.printStackTrace();
Log.w(TAG, e.toString()); return null;
mMetaInfo = null; }
} }
}
} public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
public int getSyncAction(Cursor c) { try {
try { mMetaInfo = new JSONObject(metaData.getNotes());
JSONObject noteInfo = null; } catch (JSONException e) {
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { Log.w(TAG, e.toString());
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); mMetaInfo = null;
} }
}
if (noteInfo == null) { }
Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE; public int getSyncAction(Cursor c) {
} try {
JSONObject noteInfo = null;
if (!noteInfo.has(NoteColumns.ID)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "remote note id seems to be deleted"); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
return SYNC_ACTION_UPDATE_LOCAL; }
}
if (noteInfo == null) {
// validate the note id now Log.w(TAG, "it seems that note meta has been deleted");
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { return SYNC_ACTION_UPDATE_REMOTE;
Log.w(TAG, "note id doesn't match"); }
return SYNC_ACTION_UPDATE_LOCAL;
} if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted");
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { return SYNC_ACTION_UPDATE_LOCAL;
// there is no local update }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // validate the note id now
return SYNC_ACTION_NONE; if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
} else { Log.w(TAG, "note id doesn't match");
// apply remote to local return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_LOCAL; }
}
} else { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// validate gtask id // there is no local update
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
Log.e(TAG, "gtask id doesn't match"); // no update both side
return SYNC_ACTION_ERROR; return SYNC_ACTION_NONE;
} } else {
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // apply remote to local
// local modification only return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_REMOTE; }
} else { } else {
return SYNC_ACTION_UPDATE_CONFLICT; // validate gtask id
} if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
} Log.e(TAG, "gtask id doesn't match");
} catch (Exception e) { return SYNC_ACTION_ERROR;
Log.e(TAG, e.toString()); }
e.printStackTrace(); if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
} // local modification only
return SYNC_ACTION_UPDATE_REMOTE;
return SYNC_ACTION_ERROR; } else {
} return SYNC_ACTION_UPDATE_CONFLICT;
}
public boolean isWorthSaving() { }
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) } catch (Exception e) {
|| (getNotes() != null && getNotes().trim().length() > 0); Log.e(TAG, e.toString());
} e.printStackTrace();
}
public void setCompleted(boolean completed) {
this.mCompleted = completed; return SYNC_ACTION_ERROR;
} }
public void setNotes(String notes) { public boolean isWorthSaving() {
this.mNotes = notes; return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
} || (getNotes() != null && getNotes().trim().length() > 0);
}
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; public void setCompleted(boolean completed) {
} this.mCompleted = completed;
}
public void setParent(TaskList parent) {
this.mParent = parent; public void setNotes(String notes) {
} this.mNotes = notes;
}
public boolean getCompleted() {
return this.mCompleted; public void setPriorSibling(Task priorSibling) {
} this.mPriorSibling = priorSibling;
}
public String getNotes() {
return this.mNotes; public void setParent(TaskList parent) {
} this.mParent = parent;
}
public Task getPriorSibling() {
return this.mPriorSibling; public boolean getCompleted() {
} return this.mCompleted;
}
public TaskList getParent() {
return this.mParent; public String getNotes() {
} return this.mNotes;
}
}
public Task getPriorSibling() {
return this.mPriorSibling;
}
public TaskList getParent() {
return this.mParent;
}
}

@ -14,330 +14,388 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName(); public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();//tag标记
private int mIndex;
private int mIndex;//当前TaskList的指针
private ArrayList<Task> mChildren;
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList
public TaskList() {
super(); public TaskList() {
mChildren = new ArrayList<Task>(); super();
mIndex = 1; mChildren = new ArrayList<Task>();
} mIndex = 1;
}
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); /* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getCreateAction(int)
try { * JSONObject
// action_type */
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, public JSONObject getCreateAction(int actionId) {
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); JSONObject js = new JSONObject();
// action_id try {
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
// index GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// action_id
// entity_delta js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // index
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // entity_delta
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); JSONObject entity = new JSONObject();//entity实体
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
} catch (JSONException e) { entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
Log.e(TAG, e.toString()); entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
e.printStackTrace(); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
throw new ActionFailureException("fail to generate tasklist-create jsonobject"); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
}
} catch (JSONException e) {
return js; Log.e(TAG, e.toString());
} e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject");
public JSONObject getUpdateAction(int actionId) { }
JSONObject js = new JSONObject();
return js;
try { }
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, /* (non-Javadoc)
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); * @see net.micode.notes.gtask.data.Node#getUpdateAction(int)
* JSONObject
// action_id */
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); try {
// action_type
// entity_delta js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
JSONObject entity = new JSONObject(); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // action_id
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
} catch (JSONException e) { // id
Log.e(TAG, e.toString()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); // entity_delta
} JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
return js; entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
} js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
public void setContentByRemoteJSON(JSONObject js) { } catch (JSONException e) {
if (js != null) { Log.e(TAG, e.toString());
try { e.printStackTrace();
// id throw new ActionFailureException("fail to generate tasklist-update jsonobject");
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { }
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} return js;
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { public void setContentByRemoteJSON(JSONObject js) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); if (js != null) {
} try {
// id
// name if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); }
}
// last_modified
} catch (JSONException e) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
Log.e(TAG, e.toString()); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
e.printStackTrace(); }
throw new ActionFailureException("fail to get tasklist content from jsonobject");
} // name
} if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
} setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { } catch (JSONException e) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.e(TAG, e.toString());
} e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject");
try { }
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); }
}
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); public void setContentByLocalJSON(JSONObject js) {
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) }
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) try {
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
Log.e(TAG, "invalid system folder"); String name = folder.getString(NoteColumns.SNIPPET);
} else { setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
Log.e(TAG, "error type"); } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
} if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
} catch (JSONException e) { setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
Log.e(TAG, e.toString()); else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
e.printStackTrace(); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
} + GTaskStringUtils.FOLDER_CALL_NOTE);
} else
Log.e(TAG, "invalid system folder");
public JSONObject getLocalJSONFromContent() { } else {
try { Log.e(TAG, "error type");
JSONObject js = new JSONObject(); }
JSONObject folder = new JSONObject(); } catch (JSONException e) {
Log.e(TAG, e.toString());
String folderName = getName(); e.printStackTrace();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) }
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), }
folderName.length());
folder.put(NoteColumns.SNIPPET, folderName); public JSONObject getLocalJSONFromContent() {
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) try {
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) JSONObject js = new JSONObject();
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); JSONObject folder = new JSONObject();
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length());
return js; folder.put(NoteColumns.SNIPPET, folderName);
} catch (JSONException e) { if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
Log.e(TAG, e.toString()); || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
e.printStackTrace(); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
return null; else
} folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
}
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
public int getSyncAction(Cursor c) {
try { return js;
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { } catch (JSONException e) {
// there is no local update Log.e(TAG, e.toString());
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { e.printStackTrace();
// no update both side return null;
return SYNC_ACTION_NONE; }
} else { }
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL; public int getSyncAction(Cursor c) {
} try {
} else { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// validate gtask id // there is no local update
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
Log.e(TAG, "gtask id doesn't match"); // no update both side
return SYNC_ACTION_ERROR; return SYNC_ACTION_NONE;
} } else {
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // apply remote to local
// local modification only return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_REMOTE; }
} else { } else {
// for folder conflicts, just apply local modification // validate gtask id
return SYNC_ACTION_UPDATE_REMOTE; if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
} Log.e(TAG, "gtask id doesn't match");
} return SYNC_ACTION_ERROR;
} catch (Exception e) { }
Log.e(TAG, e.toString()); if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
e.printStackTrace(); // local modification only
} return SYNC_ACTION_UPDATE_REMOTE;
} else {
return SYNC_ACTION_ERROR; // for folder conflicts, just apply local modification
} return SYNC_ACTION_UPDATE_REMOTE;
}
public int getChildTaskCount() { }
return mChildren.size(); } catch (Exception e) {
} Log.e(TAG, e.toString());
e.printStackTrace();
public boolean addChildTask(Task task) { }
boolean ret = false;
if (task != null && !mChildren.contains(task)) { return SYNC_ACTION_ERROR;
ret = mChildren.add(task); }
if (ret) {
// need to set prior sibling and parent /**
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren * @return
.get(mChildren.size() - 1)); * TaskListmChildren
task.setParent(this); */
} public int getChildTaskCount() {
} return mChildren.size();
return ret; }
}
/**
public boolean addChildTask(Task task, int index) { * @param task
if (index < 0 || index > mChildren.size()) { * @return
Log.e(TAG, "add child task: invalid index"); *
return false; */
} public boolean addChildTask(Task task) {
boolean ret = false;
int pos = mChildren.indexOf(task); if (task != null && !mChildren.contains(task)) {
if (task != null && pos == -1) { ret = mChildren.add(task);
mChildren.add(index, task); if (ret) {
// need to set prior sibling and parent
// update the task list task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
Task preTask = null; .get(mChildren.size() - 1));
Task afterTask = null; task.setParent(this);
if (index != 0) //注意每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改
preTask = mChildren.get(index - 1); //,接下来几个函数都有相关操作
if (index != mChildren.size() - 1) }
afterTask = mChildren.get(index + 1); }
return ret;
task.setPriorSibling(preTask); }
if (afterTask != null)
afterTask.setPriorSibling(task); /**
} * @param task
* @param index
return true; * @return
} *
*/
public boolean removeChildTask(Task task) { public boolean addChildTask(Task task, int index) {
boolean ret = false; if (index < 0 || index > mChildren.size()) {
int index = mChildren.indexOf(task); Log.e(TAG, "add child task: invalid index");
if (index != -1) { return false;
ret = mChildren.remove(task); }
if (ret) { int pos = mChildren.indexOf(task);
// reset prior sibling and parent if (task != null && pos == -1) {
task.setPriorSibling(null); mChildren.add(index, task);
task.setParent(null);
// update the task list
// update the task list Task preTask = null;
if (index != mChildren.size()) { Task afterTask = null;
mChildren.get(index).setPriorSibling( if (index != 0)
index == 0 ? null : mChildren.get(index - 1)); preTask = mChildren.get(index - 1);
} if (index != mChildren.size() - 1)
} afterTask = mChildren.get(index + 1);
}
return ret; task.setPriorSibling(preTask);
} if (afterTask != null)
afterTask.setPriorSibling(task);
public boolean moveChildTask(Task task, int index) { }
if (index < 0 || index >= mChildren.size()) { return true;
Log.e(TAG, "move child task: invalid index"); }
return false;
} /**
* @param task
int pos = mChildren.indexOf(task); * @return
if (pos == -1) { * TaskListTask
Log.e(TAG, "move child task: the task should in the list"); */
return false; public boolean removeChildTask(Task task) {
} boolean ret = false;
int index = mChildren.indexOf(task);
if (pos == index) if (index != -1) {
return true; ret = mChildren.remove(task);
return (removeChildTask(task) && addChildTask(task, index));
} if (ret) {
// reset prior sibling and parent
public Task findChildTaskByGid(String gid) { task.setPriorSibling(null);
for (int i = 0; i < mChildren.size(); i++) { task.setParent(null);
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) { // update the task list
return t; if (index != mChildren.size()) {
} mChildren.get(index).setPriorSibling(
} index == 0 ? null : mChildren.get(index - 1));
return null; }
} }
}
public int getChildTaskIndex(Task task) { return ret;
return mChildren.indexOf(task); }
}
/**
public Task getChildTaskByIndex(int index) { * @param task
if (index < 0 || index >= mChildren.size()) { * @param index
Log.e(TAG, "getTaskByIndex: invalid index"); * @return
return null; * TaskListTaskindex
} */
return mChildren.get(index); public boolean moveChildTask(Task task, int index) {
}
if (index < 0 || index >= mChildren.size()) {
public Task getChilTaskByGid(String gid) { Log.e(TAG, "move child task: invalid index");
for (Task task : mChildren) { return false;
if (task.getGid().equals(gid)) }
return task;
} int pos = mChildren.indexOf(task);
return null; if (pos == -1) {
} Log.e(TAG, "move child task: the task should in the list");
return false;
public ArrayList<Task> getChildTaskList() { }
return this.mChildren;
} if (pos == index)
return true;
public void setIndex(int index) { return (removeChildTask(task) && addChildTask(task, index));
this.mIndex = index; //利用已实现好的功能完成当下功能;
} }
public int getIndex() { /**
return this.mIndex; * @param gid
} * @return
} * gidTask
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) {
return t;
}
}
return null;
}
/**
* @param task
* @return
* Taskindex
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
* @param index
* @return
* indexTask
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
return null;
}
return mChildren.get(index);
}
/**
* @param gid
* @return
* gidTask
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {//一种常见的ArrayList的遍历方法四种见精读笔记
if (task.getGid().equals(gid))
return task;
}
return null;
}
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
public void setIndex(int index) {
this.mIndex = index;
}
public int getIndex() {
return this.mIndex;
}
}

@ -14,20 +14,34 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.exception; /*
* Description便
*/
package net.micode.notes.gtask.exception;
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/*
* serialVersionUIDjava
* serialVersionUID
*/
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
/*
* JAVA使superthis.
* new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public ActionFailureException(String paramString) {
super(paramString);
}
public ActionFailureException(String paramString) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString); super(paramString, paramThrowable);
} }
}
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -14,20 +14,35 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.exception; /*
* Description便
*/
package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
/*
* serialVersionUIDjava
* serialVersionUID
*/
public class NetworkFailureException extends Exception { public NetworkFailureException() {
private static final long serialVersionUID = 2107610287180234136L; super();
}
public NetworkFailureException() { /*
super(); * JAVA使superthis.
} * new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString); super(paramString, paramThrowable);
} }
}
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -15,109 +15,117 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { /*GTask
*
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; * private void showNotification(int tickerId, String content)
* protected Integer doInBackground(Void... unused) 线
public interface OnCompleteListener { * protected void onProgressUpdate(String... progress) 使 线
void onComplete(); * protected void onPostExecute(Integer result) Handler UI使doInBackground UI
} */
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private Context mContext;
private NotificationManager mNotifiManager; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
private GTaskManager mTaskManager; public interface OnCompleteListener {
void onComplete();
private OnCompleteListener mOnCompleteListener; }
public GTaskASyncTask(Context context, OnCompleteListener listener) { private Context mContext;
mContext = context;
mOnCompleteListener = listener; private NotificationManager mNotifiManager;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE); private GTaskManager mTaskManager;
mTaskManager = GTaskManager.getInstance();
} private OnCompleteListener mOnCompleteListener;
public void cancelSync() { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mTaskManager.cancelSync(); mContext = context;
} mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
public void publishProgess(String message) { .getSystemService(Context.NOTIFICATION_SERVICE);
publishProgress(new String[] { mTaskManager = GTaskManager.getInstance();
message }
});
} public void cancelSync() {
mTaskManager.cancelSync();
private void showNotification(int tickerId, String content) { }
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); public void publishProgess(String message) { // 发布进度单位系统将会调用onProgressUpdate()方法更新这些值
notification.defaults = Notification.DEFAULT_LIGHTS; publishProgress(new String[] {
notification.flags = Notification.FLAG_AUTO_CANCEL; message
PendingIntent pendingIntent; });
if (tickerId != R.string.ticker_success) { }
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
} else { .getString(tickerId), System.currentTimeMillis());
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, notification.defaults = Notification.DEFAULT_LIGHTS; // 调用系统自带灯光
NotesListActivity.class), 0); notification.flags = Notification.FLAG_AUTO_CANCEL; // 点击清除按钮或点击通知后会自动消失
} PendingIntent pendingIntent; //一个描述了想要启动一个Activity、Broadcast或是Service的意图
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, if (tickerId != R.string.ticker_success) {
pendingIntent); pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); NotesPreferenceActivity.class), 0); //如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象
}
} else {
@Override pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
protected Integer doInBackground(Void... unused) { NotesListActivity.class), 0); //如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity }
.getSyncAccountName(mContext))); notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
return mTaskManager.sync(mContext, this); pendingIntent);
} mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息
}
@Override
protected void onProgressUpdate(String... progress) { @Override
showNotification(R.string.ticker_syncing, progress[0]); protected Integer doInBackground(Void... unused) {
if (mContext instanceof GTaskSyncService) { publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
((GTaskSyncService) mContext).sendBroadcast(progress[0]); .getSyncAccountName(mContext))); //利用getString,将把 NotesPreferenceActivity.getSyncAccountName(mContext))的字符串内容传进sync_progress_login中
} return mTaskManager.sync(mContext, this); //进行后台同步具体操作
} }
@Override @Override
protected void onPostExecute(Integer result) { protected void onProgressUpdate(String... progress) {
if (result == GTaskManager.STATE_SUCCESS) { showNotification(R.string.ticker_syncing, progress[0]);
showNotification(R.string.ticker_success, mContext.getString( if (mContext instanceof GTaskSyncService) { //instanceof 判断mContext是否是GTaskSyncService的实例
R.string.success_sync_account, mTaskManager.getSyncAccount())); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
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) { @Override
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); protected void onPostExecute(Integer result) { //用于在执行完后台任务后更新UI,显示结果
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_success, mContext.getString(
.getString(R.string.error_sync_cancelled)); R.string.success_sync_account, mTaskManager.getSyncAccount()));
} NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); //设置最新同步的时间
if (mOnCompleteListener != null) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
new Thread(new Runnable() { showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
public void run() { showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
mOnCompleteListener.onComplete(); } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
} showNotification(R.string.ticker_cancel, mContext
}).start(); .getString(R.string.error_sync_cancelled));
} } //几种不同情况下的结果显示
} if (mOnCompleteListener != null) {
} new Thread(new Runnable() { //这里好像是方法内的一个线程,但是并不太懂什么意思
public void run() { //完成后的操作使用onComplete()将所有值都重新初始化,相当于完成一次操作
mOnCompleteListener.onComplete();
}
}).start();
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -13,116 +13,135 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.remote;
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.app.Activity; import android.app.Service;
import android.app.Service; import android.content.Context;
import android.content.Context; import android.content.Intent;
import android.content.Intent; import android.os.Bundle;
import android.os.Bundle; import android.os.IBinder;
import android.os.IBinder;
public class GTaskSyncService extends Service { /*
public final static String ACTION_STRING_NAME = "sync_action_type"; * Service
*
public final static int ACTION_START_SYNC = 0; * private void startSync()
* private void cancelSync()
public final static int ACTION_CANCEL_SYNC = 1; * public void onCreate()
* public int onStartCommand(Intent intent, int flags, int startId) serviceserviceservice
public final static int ACTION_INVALID = 2; * public void onLowMemory() serviceservice
* public IBinder onBind()
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; * public void sendBroadcast(String msg)
* public static void startSync(Activity activity)
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; * public static void cancelSync(Context context)
* public static boolean isSyncing()
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; * public static String getProgressString()
*/
private static GTaskASyncTask mSyncTask = null;
public class GTaskSyncService extends Service {
private static String mSyncProgress = ""; public final static String ACTION_STRING_NAME = "sync_action_type";
private void startSync() { public final static int ACTION_START_SYNC = 0;
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { public final static int ACTION_CANCEL_SYNC = 1;
public void onComplete() {
mSyncTask = null; public final static int ACTION_INVALID = 2;
sendBroadcast("");
stopSelf(); 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";
sendBroadcast("");
mSyncTask.execute(); public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
}
} private static GTaskASyncTask mSyncTask = null;
private void cancelSync() { private static String mSyncProgress = "";
if (mSyncTask != null) {
mSyncTask.cancelSync(); //开始一个同步的工作
} private void startSync() {
} if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@Override public void onComplete() {
public void onCreate() { mSyncTask = null;
mSyncTask = null; sendBroadcast("");
} stopSelf();
}
@Override });
public int onStartCommand(Intent intent, int flags, int startId) { sendBroadcast("");
Bundle bundle = intent.getExtras(); mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { }
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { }
case ACTION_START_SYNC:
startSync();
break; private void cancelSync() {
case ACTION_CANCEL_SYNC: if (mSyncTask != null) {
cancelSync(); mSyncTask.cancelSync();
break; }
default: }
break;
} @Override
return START_STICKY; public void onCreate() { //初始化一个service
} mSyncTask = null;
return super.onStartCommand(intent, flags, startId); }
}
@Override
@Override public int onStartCommand(Intent intent, int flags, int startId) {
public void onLowMemory() { Bundle bundle = intent.getExtras();
if (mSyncTask != null) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
mSyncTask.cancelSync(); switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
} //两种情况,开始同步或者取消同步
} case ACTION_START_SYNC:
startSync();
public IBinder onBind(Intent intent) { break;
return null; case ACTION_CANCEL_SYNC:
} cancelSync();
break;
public void sendBroadcast(String msg) { default:
mSyncProgress = msg; break;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); }
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); return START_STICKY; //等待新的intent来是这个service继续运行
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); }
sendBroadcast(intent); return super.onStartCommand(intent, flags, startId);
} }
public static void startSync(Activity activity) { @Override
GTaskManager.getInstance().setActivityContext(activity); public void onLowMemory() {
Intent intent = new Intent(activity, GTaskSyncService.class); if (mSyncTask != null) {
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); mSyncTask.cancelSync();
activity.startService(intent); }
} }
public static void cancelSync(Context context) { public IBinder onBind(Intent intent) { //不知道干吗用的
Intent intent = new Intent(context, GTaskSyncService.class); return null;
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); }
context.startService(intent);
} public void sendBroadcast(String msg) {
mSyncProgress = msg;
public static boolean isSyncing() { Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent
return mSyncTask != null; intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值
} intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent); //发送这个通知
public static String getProgressString() { }
return mSyncProgress;
} public static void startSync(Activity activity) {//执行一个serviceservice的内容里的同步动作就是开始同步
} GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
}
public static void cancelSync(Context context) {//执行一个serviceservice的内容里的同步动作就是取消同步
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
public static boolean isSyncing() {
return mSyncTask != null;
}
public static String getProgressString() {
return mSyncProgress;
}
}

@ -14,331 +14,351 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.os.Environment; import android.os.Environment;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.util.Log; import android.util.Log;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
/*
public class BackupUtils { 便
private static final String TAG = "BackupUtils"; 便便
// Singleton stuff 使Android(ContentProvider)便
private static BackupUtils sInstance; 便
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
} //单例对象是一种确保在应用程序中只有一个实例被创建的设计模式
return sInstance; //提供一种全局的访问方式
} //这个类描述备份工具的属性和行为
public class BackupUtils {
/** // 声明一个常量 TAG用于在日志中标识这个类
* Following states are signs to represents backup or restore private static final String TAG = "BackupUtils";
* status // Singleton stuff
*/ // 声明一个私有的静态变量 sInstance保存单例对象
// Currently, the sdcard is not mounted private static BackupUtils sInstance;
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 synchronized BackupUtils getInstance(Context context) {
public static final int STATE_DATA_DESTROIED = 2; if (sInstance == null) {
// Some run-time exception which causes restore or backup fails sInstance = new BackupUtils(context);
public static final int STATE_SYSTEM_ERROR = 3; }
// Backup or restore success return sInstance;
public static final int STATE_SUCCESS = 4; }
private TextExport mTextExport; /**
* Following states are signs to represents backup or restore
private BackupUtils(Context context) { * status
mTextExport = new TextExport(context); */
} // Currently, the sdcard is not mounted
//SD卡没有挂载的状态码
private static boolean externalStorageAvailable() { public static final int STATE_SD_CARD_UNMOUONTED = 0;
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); //备份文件不存在的状态码
} // The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
public int exportToText() { //数据格式不正确,可能被其他程序修改的状态码
return mTextExport.exportToText(); // The data is not well formated, may be changed by other programs
} public static final int STATE_DATA_DESTROIED = 2;
//运行异常导致恢复或者备份失败的状态码
public String getExportedTextFileName() { // Some run-time exception which causes restore or backup fails
return mTextExport.mFileName; public static final int STATE_SYSTEM_ERROR = 3;
} //运行异常导致恢复或者备份成功的状态码
// Backup or restore success
public String getExportedTextFileDir() { public static final int STATE_SUCCESS = 4;
return mTextExport.mFileDirectory; //这个用于导出备份数据到文本文件
} private TextExport mTextExport;
//获取
private static class TextExport { private BackupUtils(Context context) {
private static final String[] NOTE_PROJECTION = { mTextExport = new TextExport(context);
NoteColumns.ID, }
NoteColumns.MODIFIED_DATE, private static boolean externalStorageAvailable() {
NoteColumns.SNIPPET, return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
NoteColumns.TYPE }
};
public int exportToText() {
private static final int NOTE_COLUMN_ID = 0; return mTextExport.exportToText();
}
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
public String getExportedTextFileName() {
private static final int NOTE_COLUMN_SNIPPET = 2; return mTextExport.mFileName;
}
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, public String getExportedTextFileDir() {
DataColumns.MIME_TYPE, return mTextExport.mFileDirectory;
DataColumns.DATA1, }
DataColumns.DATA2,
DataColumns.DATA3, private static class TextExport {
DataColumns.DATA4, private static final String[] NOTE_PROJECTION = {
}; NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
private static final int DATA_COLUMN_CONTENT = 0; NoteColumns.SNIPPET,
NoteColumns.TYPE
private static final int DATA_COLUMN_MIME_TYPE = 1; };
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int NOTE_COLUMN_ID = 0;
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private final String [] TEXT_FORMAT; private static final int NOTE_COLUMN_SNIPPET = 2;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1; private static final String[] DATA_PROJECTION = {
private static final int FORMAT_NOTE_CONTENT = 2; DataColumns.CONTENT,
DataColumns.MIME_TYPE,
private Context mContext; DataColumns.DATA1,
private String mFileName; DataColumns.DATA2,
private String mFileDirectory; DataColumns.DATA3,
DataColumns.DATA4,
public TextExport(Context context) { };
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; private static final int DATA_COLUMN_CONTENT = 0;
mFileName = "";
mFileDirectory = ""; private static final int DATA_COLUMN_MIME_TYPE = 1;
}
private static final int DATA_COLUMN_CALL_DATE = 2;
private String getFormat(int id) {
return TEXT_FORMAT[id]; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
}
private final String [] TEXT_FORMAT;
/** private static final int FORMAT_FOLDER_NAME = 0;
* Export the folder identified by folder id to text private static final int FORMAT_NOTE_DATE = 1;
*/ private static final int FORMAT_NOTE_CONTENT = 2;
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder private Context mContext;
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, private String mFileName;
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { private String mFileDirectory;
folderId
}, null); public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
if (notesCursor != null) { mContext = context;
if (notesCursor.moveToFirst()) { mFileName = "";
do { mFileDirectory = "";
// Print note's last modified date }
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), private String getFormat(int id) {
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); return TEXT_FORMAT[id];
// Query data belong to this note }
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); /**
} while (notesCursor.moveToNext()); * Export the folder identified by folder id to text
} */
notesCursor.close(); 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
* Export note identified by id to a print stream }, null);
*/
private void exportNoteToText(String noteId, PrintStream ps) { if (notesCursor != null) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, if (notesCursor.moveToFirst()) {
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { do {
noteId // Print note's last modified date
}, null); ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
if (dataCursor != null) { notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
if (dataCursor.moveToFirst()) { // Query data belong to this note
do { String noteId = notesCursor.getString(NOTE_COLUMN_ID);
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); exportNoteToText(noteId, ps);
if (DataConstants.CALL_NOTE.equals(mimeType)) { } while (notesCursor.moveToNext());
// Print phone number }
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); notesCursor.close();
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); }
String location = dataCursor.getString(DATA_COLUMN_CONTENT); }
if (!TextUtils.isEmpty(phoneNumber)) { /**
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), * Export note identified by id to a print stream
phoneNumber)); */
} private void exportNoteToText(String noteId, PrintStream ps) {
// Print call date Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
.format(mContext.getString(R.string.format_datetime_mdhm), noteId
callDate))); }, null);
// Print call attachment location
if (!TextUtils.isEmpty(location)) { if (dataCursor != null) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), if (dataCursor.moveToFirst()) {
location)); do {
} String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
} else if (DataConstants.NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) {
String content = dataCursor.getString(DATA_COLUMN_CONTENT); // Print phone number
if (!TextUtils.isEmpty(content)) { String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
content)); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
}
} if (!TextUtils.isEmpty(phoneNumber)) {
} while (dataCursor.moveToNext()); ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
} phoneNumber));
dataCursor.close(); }
} // Print call date
// print a line separator between note ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
try { .format(mContext.getString(R.string.format_datetime_mdhm),
ps.write(new byte[] { callDate)));
Character.LINE_SEPARATOR, Character.LETTER_NUMBER // Print call attachment location
}); if (!TextUtils.isEmpty(location)) {
} catch (IOException e) { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
Log.e(TAG, e.toString()); location));
} }
} } else if (DataConstants.NOTE.equals(mimeType)) {
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
/** if (!TextUtils.isEmpty(content)) {
* Note will be exported as text which is user readable ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
*/ content));
public int exportToText() { }
if (!externalStorageAvailable()) { }
Log.d(TAG, "Media was not mounted"); } while (dataCursor.moveToNext());
return STATE_SD_CARD_UNMOUONTED; }
} dataCursor.close();
}
PrintStream ps = getExportToTextPrintStream(); // print a line separator between note
if (ps == null) { try {
Log.e(TAG, "get print stream error"); ps.write(new byte[] {
return STATE_SYSTEM_ERROR; Character.LINE_SEPARATOR, Character.LETTER_NUMBER
} });
// First export folder and its notes } catch (IOException e) {
Cursor folderCursor = mContext.getContentResolver().query( Log.e(TAG, e.toString());
Notes.CONTENT_NOTE_URI, }
NOTE_PROJECTION, }
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " /**
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); * Note will be exported as text which is user readable
*/
if (folderCursor != null) { public int exportToText() {
if (folderCursor.moveToFirst()) { if (!externalStorageAvailable()) {
do { Log.d(TAG, "Media was not mounted");
// Print folder's name return STATE_SD_CARD_UNMOUONTED;
String folderName = ""; }
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name); PrintStream ps = getExportToTextPrintStream();
} else { if (ps == null) {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); Log.e(TAG, "get print stream error");
} return STATE_SYSTEM_ERROR;
if (!TextUtils.isEmpty(folderName)) { }
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); // First export folder and its notes
} Cursor folderCursor = mContext.getContentResolver().query(
String folderId = folderCursor.getString(NOTE_COLUMN_ID); Notes.CONTENT_NOTE_URI,
exportFolderToText(folderId, ps); NOTE_PROJECTION,
} while (folderCursor.moveToNext()); "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
} + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
folderCursor.close(); + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
}
if (folderCursor != null) {
// Export notes in root's folder if (folderCursor.moveToFirst()) {
Cursor noteCursor = mContext.getContentResolver().query( do {
Notes.CONTENT_NOTE_URI, // Print folder's name
NOTE_PROJECTION, String folderName = "";
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
+ "=0", null, null); folderName = mContext.getString(R.string.call_record_folder_name);
} else {
if (noteCursor != null) { folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
if (noteCursor.moveToFirst()) { }
do { if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
mContext.getString(R.string.format_datetime_mdhm), }
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); String folderId = folderCursor.getString(NOTE_COLUMN_ID);
// Query data belong to this note exportFolderToText(folderId, ps);
String noteId = noteCursor.getString(NOTE_COLUMN_ID); } while (folderCursor.moveToNext());
exportNoteToText(noteId, ps); }
} while (noteCursor.moveToNext()); folderCursor.close();
} }
noteCursor.close();
} // Export notes in root's folder
ps.close(); Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
return STATE_SUCCESS; NOTE_PROJECTION,
} NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
/**
* Get a print stream pointed to the file {@generateExportedTextFile} if (noteCursor != null) {
*/ if (noteCursor.moveToFirst()) {
private PrintStream getExportToTextPrintStream() { do {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
R.string.file_name_txt_format); mContext.getString(R.string.format_datetime_mdhm),
if (file == null) { noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
Log.e(TAG, "create file to exported failed"); // Query data belong to this note
return null; String noteId = noteCursor.getString(NOTE_COLUMN_ID);
} exportNoteToText(noteId, ps);
mFileName = file.getName(); } while (noteCursor.moveToNext());
mFileDirectory = mContext.getString(R.string.file_path); }
PrintStream ps = null; noteCursor.close();
try { }
FileOutputStream fos = new FileOutputStream(file); ps.close();
ps = new PrintStream(fos);
} catch (FileNotFoundException e) { return STATE_SUCCESS;
e.printStackTrace(); }
return null;
} catch (NullPointerException e) { /**
e.printStackTrace(); * Get a print stream pointed to the file {@generateExportedTextFile}
return null; */
} private PrintStream getExportToTextPrintStream() {
return ps; File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
} R.string.file_name_txt_format);
} if (file == null) {
Log.e(TAG, "create file to exported failed");
/** return null;
* Generate the text file to store imported data }
*/ mFileName = file.getName();
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { mFileDirectory = mContext.getString(R.string.file_path);
StringBuilder sb = new StringBuilder(); PrintStream ps = null;
sb.append(Environment.getExternalStorageDirectory()); try {
sb.append(context.getString(filePathResId)); FileOutputStream fos = new FileOutputStream(file);
File filedir = new File(sb.toString()); ps = new PrintStream(fos);
sb.append(context.getString( } catch (FileNotFoundException e) {
fileNameFormatResId, e.printStackTrace();
DateFormat.format(context.getString(R.string.format_date_ymd), return null;
System.currentTimeMillis()))); } catch (NullPointerException e) {
File file = new File(sb.toString()); e.printStackTrace();
return null;
try { }
if (!filedir.exists()) { return ps;
filedir.mkdir(); }
} }
if (!file.exists()) {
file.createNewFile(); /**
} * Generate the text file to store imported data
return file; */
} catch (SecurityException e) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
e.printStackTrace(); StringBuilder sb = new StringBuilder();
} catch (IOException e) { sb.append(Environment.getExternalStorageDirectory());
e.printStackTrace(); sb.append(context.getString(filePathResId));
} File filedir = new File(sb.toString());
sb.append(context.getString(
return null; fileNameFormatResId,
} DateFormat.format(context.getString(R.string.format_date_ymd),
} System.currentTimeMillis())));
File file = new File(sb.toString());
try {
if (!filedir.exists()) {
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

@ -14,282 +14,302 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.OperationApplicationException; import android.content.OperationApplicationException;
import android.database.Cursor; import android.database.Cursor;
import android.os.RemoteException; import android.os.RemoteException;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
public class DataUtils {
public static final String TAG = "DataUtils"; /*
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { DataUtils
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) { 使便
Log.d(TAG, "no id is in the hashset"); 使ContentResolverContentProvider
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); 使
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root"); +
continue; 便
} */
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); public class DataUtils {
operationList.add(builder.build()); public static final String TAG = "DataUtils";
} public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
try { if (ids == null) {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); Log.d(TAG, "the ids is null");
if (results == null || results.length == 0 || results[0] == null) { return true;
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); }
return false; if (ids.size() == 0) {
} Log.d(TAG, "no id is in the hashset");
return true; return true;
} catch (RemoteException e) { }
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); for (long id : ids) {
} if(id == Notes.ID_ROOT_FOLDER) {
return false; Log.e(TAG, "Don't delete system folder root");
} continue;
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { ContentProviderOperation.Builder builder = ContentProviderOperation
ContentValues values = new ContentValues(); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
values.put(NoteColumns.PARENT_ID, desFolderId); operationList.add(builder.build());
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); }
values.put(NoteColumns.LOCAL_MODIFIED, 1); try {
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
} if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, return false;
long folderId) { }
if (ids == null) { return true;
Log.d(TAG, "the ids is null"); } catch (RemoteException e) {
return true; Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} } catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); }
for (long id : ids) { return false;
ContentProviderOperation.Builder builder = ContentProviderOperation }
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId); public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); ContentValues values = new ContentValues();
operationList.add(builder.build()); values.put(NoteColumns.PARENT_ID, desFolderId);
} values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
try { resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); }
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
return false; long folderId) {
} if (ids == null) {
return true; Log.d(TAG, "the ids is null");
} catch (RemoteException e) { return true;
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); }
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
} for (long id : ids) {
return false; ContentProviderOperation.Builder builder = ContentProviderOperation
} .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
/** builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} operationList.add(builder.build());
*/ }
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, try {
new String[] { "COUNT(*)" }, ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", if (results == null || results.length == 0 || results[0] == null) {
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, Log.d(TAG, "delete notes failed, ids:" + ids.toString());
null); return false;
}
int count = 0; return true;
if(cursor != null) { } catch (RemoteException e) {
if(cursor.moveToFirst()) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
try { } catch (OperationApplicationException e) {
count = cursor.getInt(0); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (IndexOutOfBoundsException e) { }
Log.e(TAG, "get folder count failed:" + e.toString()); return false;
} finally { }
cursor.close();
} /**
} * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
} */
return count; public static int getUserFolderCount(ContentResolver resolver) {
} Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null, null);
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)}, int count = 0;
null); if(cursor != null) {
if(cursor.moveToFirst()) {
boolean exist = false; try {
if (cursor != null) { count = cursor.getInt(0);
if (cursor.getCount() > 0) { } catch (IndexOutOfBoundsException e) {
exist = true; Log.e(TAG, "get folder count failed:" + e.toString());
} } finally {
cursor.close(); cursor.close();
} }
return exist; }
} }
return count;
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { }
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
boolean exist = false; null,
if (cursor != null) { NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
if (cursor.getCount() > 0) { new String [] {String.valueOf(type)},
exist = true; null);
}
cursor.close(); boolean exist = false;
} if (cursor != null) {
return exist; if (cursor.getCount() > 0) {
} exist = true;
}
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { cursor.close();
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), }
null, null, null, null); return exist;
}
boolean exist = false;
if (cursor != null) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
if (cursor.getCount() > 0) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
exist = true; null, null, null, null);
}
cursor.close(); boolean exist = false;
} if (cursor != null) {
return exist; if (cursor.getCount() > 0) {
} exist = true;
}
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { cursor.close();
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, }
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + return exist;
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + }
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
boolean exist = false; Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
if(cursor != null) { null, null, null, null);
if(cursor.getCount() > 0) {
exist = true; boolean exist = false;
} if (cursor != null) {
cursor.close(); if (cursor.getCount() > 0) {
} exist = true;
return exist; }
} cursor.close();
}
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { return exist;
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, }
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?", public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
new String[] { String.valueOf(folderId) }, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
null); NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
HashSet<AppWidgetAttribute> set = null; " AND " + NoteColumns.SNIPPET + "=?",
if (c != null) { new String[] { name }, null);
if (c.moveToFirst()) { boolean exist = false;
set = new HashSet<AppWidgetAttribute>(); if(cursor != null) {
do { if(cursor.getCount() > 0) {
try { exist = true;
AppWidgetAttribute widget = new AppWidgetAttribute(); }
widget.widgetId = c.getInt(0); cursor.close();
widget.widgetType = c.getInt(1); }
set.add(widget); return exist;
} catch (IndexOutOfBoundsException e) { }
Log.e(TAG, e.toString());
} public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
} while (c.moveToNext()); Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
} new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
c.close(); NoteColumns.PARENT_ID + "=?",
} new String[] { String.valueOf(folderId) },
return set; null);
}
HashSet<AppWidgetAttribute> set = null;
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { if (c != null) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, if (c.moveToFirst()) {
new String [] { CallNote.PHONE_NUMBER }, set = new HashSet<AppWidgetAttribute>();
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", do {
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, try {
null); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
if (cursor != null && cursor.moveToFirst()) { widget.widgetType = c.getInt(1);
try { set.add(widget);
return cursor.getString(0); } catch (IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) { Log.e(TAG, e.toString());
Log.e(TAG, "Get call number fails " + e.toString()); }
} finally { } while (c.moveToNext());
cursor.close(); }
} c.close();
} }
return ""; return set;
} }
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.PHONE_NUMBER },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
+ CallNote.PHONE_NUMBER + ",?)", new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, null);
null);
if (cursor != null && cursor.moveToFirst()) {
if (cursor != null) { try {
if (cursor.moveToFirst()) { return cursor.getString(0);
try { } catch (IndexOutOfBoundsException e) {
return cursor.getLong(0); Log.e(TAG, "Get call number fails " + e.toString());
} catch (IndexOutOfBoundsException e) { } finally {
Log.e(TAG, "Get call note id fails " + e.toString()); cursor.close();
} }
} }
cursor.close(); return "";
} }
return 0;
} public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
public static String getSnippetById(ContentResolver resolver, long noteId) { new String [] { CallNote.NOTE_ID },
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
new String [] { NoteColumns.SNIPPET }, + CallNote.PHONE_NUMBER + ",?)",
NoteColumns.ID + "=?", new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
new String [] { String.valueOf(noteId)}, null);
null);
if (cursor != null) {
if (cursor != null) { if (cursor.moveToFirst()) {
String snippet = ""; try {
if (cursor.moveToFirst()) { return cursor.getLong(0);
snippet = cursor.getString(0); } catch (IndexOutOfBoundsException e) {
} Log.e(TAG, "Get call note id fails " + e.toString());
cursor.close(); }
return snippet; }
} cursor.close();
throw new IllegalArgumentException("Note is not found with id: " + noteId); }
} return 0;
}
public static String getFormattedSnippet(String snippet) {
if (snippet != null) { public static String getSnippetById(ContentResolver resolver, long noteId) {
snippet = snippet.trim(); Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
int index = snippet.indexOf('\n'); new String [] { NoteColumns.SNIPPET },
if (index != -1) { NoteColumns.ID + "=?",
snippet = snippet.substring(0, index); new String [] { String.valueOf(noteId)},
} null);
}
return snippet; if (cursor != null) {
} String snippet = "";
} if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);
}
}
return snippet;
}
}

@ -1,7 +1,39 @@
//简介定义了很多的静态字符串目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范 /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
便
ContentResolverAndroid
ContentProvider
使ContentResolverContentProvider(Android)
使便
使
*/
package net.micode.notes.tool; package net.micode.notes.tool;
//这个类就是定义了一堆static string实际就是为jsonObject提供Key把这些定义全部写到一个类里方便查看管理是一个非常好的编程习惯
public class GTaskStringUtils { public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";

@ -1,20 +1,36 @@
package net.micode.notes.tool; /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
/*使 *
* R.java * Licensed under the Apache License, Version 2.0 (the "License");
* R.id * you may not use this file except in compliance with the License.
* R.drawable 使 * You may obtain a copy of the License at
* R.layout *
* R.menu * http://www.apache.org/licenses/LICENSE-2.0
* R.String
* R.style 使
* idgetXXX
* *
* * Unless required by applicable law or agreed to in writing, software
* @BG_DEFAULT_COLOR * distributed under the License is distributed on an "AS IS" BASIS,
* BG_DEFAULT_FONT_SIZE * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
/**
使
便使使
使
*/
package net.micode.notes.tool;
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
public class ResourceParser { public class ResourceParser {
public static final int YELLOW = 0; public static final int YELLOW = 0;
@ -57,7 +73,7 @@ public class ResourceParser {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
//直接获取默认的背景颜色。看不太懂这个PREFERENCE_SET_BG_COLOR_KEY是个final string,也就是说getBoolean肯定执行else为什么要这么写
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -155,7 +171,6 @@ public class ResourceParser {
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
//这里有一个容错的函数防止输入的id大于资源总量若如此则自动返回默认的设置结果
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.
@ -173,4 +188,3 @@ public class ResourceParser {
} }
} }
} }

@ -14,214 +14,215 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import net.micode.notes.data.Contact; import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT, NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3; private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5; private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6; private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7; private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8; private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
private long mId; private long mId;
private long mAlertDate; private long mAlertDate;
private int mBgColorId; private int mBgColorId;
private long mCreatedDate; private long mCreatedDate;
private boolean mHasAttachment; private boolean mHasAttachment;
private long mModifiedDate; private long mModifiedDate;
private int mNotesCount; private int mNotesCount;
private long mParentId; private long mParentId;
private String mSnippet; private String mSnippet;
private int mType; private int mType;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
private boolean mIsLastItem; private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
// 构造函数,用于初始化笔记项数据 // 构造函数,用于初始化笔记项数据
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = ""; mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) { if (mName == null) {
mName = mPhoneNumber; mName = mPhoneNumber;
} }
} }
} }
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
checkPostion(cursor); checkPostion(cursor);
} }
// 检查笔记项在Cursor中的位置设置一些标志 // 检查笔记项在Cursor中的位置设置一些标志
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
// 检查是否是最后一项 // 检查是否是最后一项
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
// 检查是否是第一项 // 检查是否是第一项
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
// 检查笔记项是否在文件夹后有多个笔记 // 检查笔记项是否在文件夹后有多个笔记
int position = cursor.getPosition(); int position = cursor.getPosition();
if (cursor.moveToPrevious()) { if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) { if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true; mIsMultiNotesFollowingFolder = true;
} else { } else {
mIsOneNoteFollowingFolder = true; mIsOneNoteFollowingFolder = true;
} }
} }
if (!cursor.moveToNext()) { if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back"); throw new IllegalStateException("cursor move to previous but can't move back");
} }
} }
} }
} }
// 检查笔记项是否在文件夹后有一个笔记 // 检查笔记项是否在文件夹后有一个笔记
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
// 检查笔记项是否在文件夹后有多个笔记 // 检查笔记项是否在文件夹后有多个笔记
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
// 检查笔记项是否是最后一项 // 检查笔记项是否是最后一项
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
public String getCallName() { public String getCallName() {
return mName; return mName;
} }
// 检查笔记项是否是第一项 // 检查笔记项是否是第一项
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
public long getId() { public long getId() {
return mId; return mId;
} }
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }
public int getType() { public int getType() {
return mType; return mType;
} }
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); return (mAlertDate > 0);
} }
public boolean isCallRecord() { public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
@ -77,9 +61,14 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
//主界面,一进入就是这个界面
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { /**
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; * @author k
*
*/
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { //没有用特定的标签加注释。。。感觉没有什么用
// 定义一些常量和枚举类型
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
@ -89,41 +78,41 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; //单行超过80个字符
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
}; };
private ListEditState mState; private ListEditState mState; // 当前列表的编辑状态
private BackgroundQueryHandler mBackgroundQueryHandler; private BackgroundQueryHandler mBackgroundQueryHandler; // 异步查询处理器
private NotesListAdapter mNotesListAdapter; private NotesListAdapter mNotesListAdapter; // 笔记列表的适配器
private ListView mNotesListView; private ListView mNotesListView; // 笔记列表视图
private Button mAddNewNote; private Button mAddNewNote; // 添加新笔记的按钮
private boolean mDispatch; private boolean mDispatch; // 是否分发事件
private int mOriginY; private int mOriginY; // 原始Y坐标
private int mDispatchY; private int mDispatchY; // 分发Y坐标
private TextView mTitleBar; private TextView mTitleBar; // 标题栏
private long mCurrentFolderId; private long mCurrentFolderId; // 当前文件夹的ID
private ContentResolver mContentResolver; private ContentResolver mContentResolver; // 内容解析器
private ModeCallback mModeCallBack; private ModeCallback mModeCallBack; // 模式回调
private static final String TAG = "NotesListActivity"; private static final String TAG = "NotesListActivity";
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
private NoteItemData mFocusNoteDataItem; private NoteItemData mFocusNoteDataItem; // 当前焦点笔记的数据项
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
@ -136,38 +125,49 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { // 创建类
super.onCreate(savedInstanceState); protected void onCreate(final Bundle savedInstanceState) { //需要是final类型 根据程序上下文环境Java关键字final有“这是无法改变的”或者“终态的”含义它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变设计或效率。
// final类不能被继承没有子类final类中的方法默认是final的。
//final方法不能被子类的方法覆盖但可以被继承。
//final成员变量表示常量只能被赋值一次赋值后值不再改变。
//final不能用于修饰构造方法。
super.onCreate(savedInstanceState); // 调用父类的onCreate函数
setContentView(R.layout.note_list); setContentView(R.layout.note_list);
initResources(); initResources();
/** /**
* Insert an introduction when user firstly use this application * Insert an introduction when user firstly use this application
*/ */
setAppInfoFromRawRes(); setAppInfoFromRawRes();// 初始化应用信息
} }
@Override @Override
// 返回一些子模块完成的数据交给主Activity处理
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK // 结果值 和 要求值 符合要求
if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null); mNotesListAdapter.changeCursor(null);
} else { } else {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
// 调用 Activity 的onActivityResult
} }
} }
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {
// Android平台给我们提供了一个SharedPreferences类它是一个轻量级的存储类特别适合用于保存软件配置参数。
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {// 判断是否已添加介绍
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream in = null; InputStream in = null;
try { try {
in = getResources().openRawResource(R.raw.introduction); // 把资源文件放到应用程序的/raw/raw下那么就可以在应用中使用getResources获取资源后,
if (in != null) { // 以openRawResource方法不带后缀的资源文件名打开这个文件。
in = getResources().openRawResource(R.raw.introduction);
if (in != null) {// 读取原始资源文件中的介绍内容
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024]; char [] buf = new char[1024]; // 自行定义的数值,使用者不知道有什么意义
int len = 0; int len = 0;
while ((len = br.read(buf)) > 0) { while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len); sb.append(buf, 0, len);
@ -180,7 +180,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
e.printStackTrace(); e.printStackTrace();
return; return;
} finally { } finally {
if(in != null) { if (in != null) {
try { try {
in.close(); in.close();
} catch (IOException e) { } catch (IOException e) {
@ -190,11 +190,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
// 创建空的WorkingNote
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED); ResourceParser.RED); // 创建一个新的工作笔记
note.setWorkingText(sb.toString()); note.setWorkingText(sb.toString()); // 设置工作笔记的内容为读取到的介绍内容
if (note.saveNote()) { if (note.saveNote()) { // 保存工作笔记
// 更新保存note的信息
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "Save introduction note error");
@ -209,18 +211,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
// 初始化资源
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver(); // 获取应用程序的数据,得到类似数据表的东西
// 初始化BackgroundQueryHandler
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mNotesListView = (ListView) findViewById(R.id.notes_list);
// findViewById 是安卓编程的定位函数,主要是引用.R文件里的引用名
mNotesListView = (ListView) findViewById(R.id.notes_list); // 绑定XML中的ListView作为Item的容器
// 将尾部视图添加到列表视图
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false); null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this); mNotesListView.setOnItemLongClickListener(this);
mNotesListAdapter = new NotesListAdapter(this); mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter); mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote = (Button) findViewById(R.id.btn_new_note);// 在activity中要获取该按钮
mAddNewNote.setOnClickListener(this); mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false; mDispatch = false;
@ -231,11 +238,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
// 继承自ListView.MultiChoiceModeListener 和 OnMenuItemClickListener
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu; private DropdownMenu mDropDownMenu;
private ActionMode mActionMode; private ActionMode mActionMode;
private MenuItem mMoveMenu; private MenuItem mMoveMenu;
// 创建ActionMode时触发
public boolean onCreateActionMode(ActionMode mode, Menu menu) { public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu); getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this); menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
@ -251,7 +259,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mNotesListAdapter.setChoiceMode(true); mNotesListAdapter.setChoiceMode(true);
mNotesListView.setLongClickable(false); mNotesListView.setLongClickable(false);
mAddNewNote.setVisibility(View.GONE); mAddNewNote.setVisibility(View.GONE);
// 初始化下拉菜单
View customView = LayoutInflater.from(NotesListActivity.this).inflate( View customView = LayoutInflater.from(NotesListActivity.this).inflate(
R.layout.note_list_dropdown_menu, null); R.layout.note_list_dropdown_menu, null);
mode.setCustomView(customView); mode.setCustomView(customView);
@ -259,9 +267,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(final MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu(); updateMenu();// 更新菜单
return true; return true;
} }
@ -269,11 +277,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
// 更新菜单
private void updateMenu() { private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu // Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount); String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format); mDropDownMenu.setTitle(format); // 更改标题
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) { if (item != null) {
if (mNotesListAdapter.isAllSelected()) { if (mNotesListAdapter.isAllSelected()) {
@ -295,7 +304,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
// 销毁ActionMode时触发
public void onDestroyActionMode(ActionMode mode) { public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false); mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true); mNotesListView.setLongClickable(true);
@ -305,13 +314,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public void finishActionMode() { public void finishActionMode() {
mActionMode.finish(); mActionMode.finish();
} }
// 当选择的项发生变化时触发
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) { boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked); mNotesListAdapter.setCheckedItem(position, checked);
updateMenu(); updateMenu();
} }
// 菜单项点击事件处理
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
if (mNotesListAdapter.getSelectedCount() == 0) { if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
@ -321,6 +330,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.delete: case R.id.delete:
// 弹出删除对话框
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
@ -337,7 +347,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show(); builder.show();
break; break;
case R.id.move: case R.id.move:
startQueryDestinationFolders(); startQueryDestinationFolders();// 查询目标文件夹
break; break;
default: default:
return false; return false;
@ -366,7 +376,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** /**
* HACKME:When click the transparent part of "New Note" button, dispatch * HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of * the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel * "New Note" button could be expressed by formula y=-0.12x+94nit:pixel<EFBFBD>
* and the line top of the button. The coordinate based on left of the "New * and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part. * Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should * Notice that, if the background of the button changes, the formula should
@ -409,14 +419,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}; };
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {
// 构建查询语句的selection根据当前文件夹id选择不同的查询条件
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION; : NORMAL_SELECTION;
// 调用异步查询处理器进行数据库查询
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId) String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
// 异步查询处理器类
private final class BackgroundQueryHandler extends AsyncQueryHandler { private final class BackgroundQueryHandler extends AsyncQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) { public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver); super(contentResolver);
@ -426,10 +438,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
protected void onQueryComplete(int token, Object cookie, Cursor cursor) { protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) { switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN: case FOLDER_NOTE_LIST_QUERY_TOKEN:
// 查询完成后更新列表适配器的Cursor数据源
mNotesListAdapter.changeCursor(cursor); mNotesListAdapter.changeCursor(cursor);
break; break;
case FOLDER_LIST_QUERY_TOKEN: case FOLDER_LIST_QUERY_TOKEN:
if (cursor != null && cursor.getCount() > 0) { if (cursor != null && cursor.getCount() > 0) {
// 如果查询到了文件夹列表,则显示文件夹选择菜单
showFolderListMenu(cursor); showFolderListMenu(cursor);
} else { } else {
Log.e(TAG, "Query folder failed"); Log.e(TAG, "Query folder failed");
@ -440,7 +454,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
} }
// 显示文件夹选择菜单
private void showFolderListMenu(Cursor cursor) { private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
@ -448,6 +462,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setAdapter(adapter, new DialogInterface.OnClickListener() { builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 点击菜单项后进行相应操作,这里是批量移动笔记到选中的文件夹
DataUtils.batchMoveToFolder(mContentResolver, DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText( Toast.makeText(
@ -461,19 +476,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
builder.show(); builder.show();
} }
// 创建新的笔记
private void createNewNote() { private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
} }
// 批量删除操作
private void batchDelete() { private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
// 获取选中笔记对应的小部件信息
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) { if (!isSyncMode()) {
// 如果不是同步模式,则直接删除选中的笔记
// if not synced, delete notes directly // if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) { .getSelectedItemIds())) {
@ -532,7 +549,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
} }
// 打开笔记详情界面
private void openNode(NoteItemData data) { private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
@ -541,6 +558,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private void openFolder(NoteItemData data) { private void openFolder(NoteItemData data) {
// 更新当前文件夹id并进行异步查询笔记列表
mCurrentFolderId = data.getId(); mCurrentFolderId = data.getId();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
@ -560,85 +578,88 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public void onClick(View v) { public void onClick(View v) {
switch (v.getId()) { switch (v.getId()) {
case R.id.btn_new_note: case R.id.btn_new_note:
// 点击新建笔记按钮,触发创建新的笔记操作
createNewNote(); createNewNote();
break; break;
default: default:
break; break;
} }
} }
// 显示输入法软键盘
private void showSoftInput() { private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) { if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
} }
} }
// 隐藏输入法软键盘
private void hideSoftInput(View view) { private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
} }
//显示创建或修改文件夹的对话框
private void showCreateOrModifyFolderDialog(final boolean create) { private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);// 创建对话框构建器
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);//加载布局文件
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);// 获取输入框
showSoftInput(); showSoftInput();// 显示软键盘
if (!create) { if (!create) { // 如果是修改文件夹
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) { // 如果有选中的文件夹
etName.setText(mFocusNoteDataItem.getSnippet()); etName.setText(mFocusNoteDataItem.getSnippet()); // 设置输入框文字为文件夹名称
builder.setTitle(getString(R.string.menu_folder_change_name)); builder.setTitle(getString(R.string.menu_folder_change_name)); // 设置对话框标题为"更改文件夹名称"
} else { } else {
Log.e(TAG, "The long click data item is null"); Log.e(TAG, "The long click data item is null"); // 输出错误日志
return; return;
} }
} else { } else { // 如果是创建文件夹
etName.setText(""); etName.setText(""); // 清空输入框
builder.setTitle(this.getString(R.string.menu_create_folder)); builder.setTitle(this.getString(R.string.menu_create_folder)); // 设置对话框标题为"创建文件夹"
} }
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null); // 设置确定按钮,暂不处理点击事件
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName); hideSoftInput(etName); // 隐藏软键盘
} }
}); }); // 设置取消按钮,点击时隐藏软键盘
final Dialog dialog = builder.setView(view).show(); final Dialog dialog = builder.setView(view).show(); // 创建对话框并显示
final Button positive = (Button)dialog.findViewById(android.R.id.button1); final Button positive = (Button)dialog.findViewById(android.R.id.button1); // 获取确定按钮
positive.setOnClickListener(new OnClickListener() { positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
hideSoftInput(etName); hideSoftInput(etName); // 隐藏软键盘
String name = etName.getText().toString(); String name = etName.getText().toString(); // 获取输入的文件夹名称
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { // 检查文件夹名称是否可见
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
Toast.LENGTH_LONG).show(); Toast.LENGTH_LONG).show(); // 显示提示信息,文件夹已存在
etName.setSelection(0, etName.length()); etName.setSelection(0, etName.length()); // 选中输入框中的文字
return; return;
} }
if (!create) {
if (!TextUtils.isEmpty(name)) { if (!create) { // 如果是修改文件夹
if (!TextUtils.isEmpty(name)) { // 如果文件夹名称不为空
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name); // 更新文件夹名称
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型为文件夹
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地修改
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] { + "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId()) String.valueOf(mFocusNoteDataItem.getId())
}); }); // 更新数据库中的文件夹信息
} }
} else if (!TextUtils.isEmpty(name)) { } else if (!TextUtils.isEmpty(name)) { // 如果是创建文件夹且文件夹名称不为空
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name); // 设置文件夹名称
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型为文件夹
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); // 插入数据库中
} }
dialog.dismiss();
dialog.dismiss(); // 关闭对话框
} }
}); });
if (TextUtils.isEmpty(etName.getText())) { // 如果输入框内容为空
if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); // 禁用确定按钮
positive.setEnabled(false);
} }
/** /**
* When the name edit text is null, disable the positive button * When the name edit text is null, disable the positive button
@ -664,9 +685,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
} }
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*
*/
@Override @Override
public void onBackPressed() { public void onBackPressed() { switch (mState) {
switch (mState) {
case SUB_FOLDER: case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST;
@ -688,6 +712,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
* @param appWidgetId
* @param appWidgetType
* widgetintent
*/
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) { if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -707,6 +736,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
/**
*
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
@ -726,6 +758,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
super.onContextMenuClosed(menu); super.onContextMenuClosed(menu);
} }
/* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
* menu
*/
@Override @Override
public boolean onContextItemSelected(MenuItem item) { public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) { if (mFocusNoteDataItem == null) {
@ -734,10 +770,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
switch (item.getItemId()) { switch (item.getItemId()) {
case MENU_FOLDER_VIEW: case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem); openFolder(mFocusNoteDataItem);//打开对应文件
break; break;
case MENU_FOLDER_DELETE: case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);//设置确认是否删除的对话框
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder));
@ -748,7 +784,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();//显示对话框
break; break;
case MENU_FOLDER_CHANGE_NAME: case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false); showCreateOrModifyFolderDialog(false);
@ -763,54 +799,55 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear(); menu.clear();
if (mState == ListEditState.NOTE_LIST) { if (mState == ListEditState.NOTE_LIST) { // 如果当前状态是便签列表
getMenuInflater().inflate(R.menu.note_list, menu); getMenuInflater().inflate(R.menu.note_list, menu); // 加载便签列表的菜单布局
// set sync or sync_cancel // 设置同步或取消同步选项的标题
menu.findItem(R.id.menu_sync).setTitle( menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
} else if (mState == ListEditState.SUB_FOLDER) { } else if (mState == ListEditState.SUB_FOLDER) { // 如果当前状态是子文件夹
getMenuInflater().inflate(R.menu.sub_folder, menu); getMenuInflater().inflate(R.menu.sub_folder, menu); // 加载子文件夹的菜单布局
} else if (mState == ListEditState.CALL_RECORD_FOLDER) { } else if (mState == ListEditState.CALL_RECORD_FOLDER) { // 如果当前状态是通话记录文件夹
getMenuInflater().inflate(R.menu.call_record_folder, menu); getMenuInflater().inflate(R.menu.call_record_folder, menu); // 加载通话记录文件夹的菜单布局
} else { } else {
Log.e(TAG, "Wrong state:" + mState); Log.e(TAG, "Wrong state:" + mState); // 如果状态不匹配,则输出错误日志
} }
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_folder: { case R.id.menu_new_folder: { // 如果选择了新建文件夹选项
showCreateOrModifyFolderDialog(true); showCreateOrModifyFolderDialog(true); // 显示创建或修改文件夹对话框
break; break;
} }
case R.id.menu_export_text: { case R.id.menu_export_text: { // 如果选择了导出文本选项
exportNoteToText(); exportNoteToText(); // 导出便签到文本
break; break;
} }
case R.id.menu_sync: { case R.id.menu_sync: { // 如果选择了同步选项
if (isSyncMode()) { if (isSyncMode()) { // 如果处于同步模式
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
GTaskSyncService.startSync(this); GTaskSyncService.startSync(this); // 启动同步服务
} else { } else {
GTaskSyncService.cancelSync(this); GTaskSyncService.cancelSync(this); // 取消同步服务
} }
} else { } else {
startPreferenceActivity(); startPreferenceActivity(); // 跳转到设置界面
} }
break; break;
} }
case R.id.menu_setting: { case R.id.menu_setting: { // 如果选择了设置选项
startPreferenceActivity(); startPreferenceActivity(); // 跳转到设置界面
break; break;
} }
case R.id.menu_new_note: { case R.id.menu_new_note: { // 如果选择了新建便签选项
createNewNote(); createNewNote(); // 创建新的便签
break; break;
} }
case R.id.menu_search: case R.id.menu_search:
onSearchRequested(); onSearchRequested(); // 执行搜索操作
break; break;
default: default:
break; break;
@ -818,46 +855,53 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/* (non-Javadoc)
* @see android.app.Activity#onSearchRequested()
* startSearch
*/
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false); startSearch(null, false, null /* appData */, false);
return true; return true;
} }
/**
* 便
*/
private void exportNoteToText() { private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() { new AsyncTask<Void, Void, Integer>() {
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
return backup.exportToText(); return backup.exportToText(); // 调用备份工具类的导出便签到文本方法
} }
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { // 如果SD卡未挂载
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); .getString(R.string.failed_sdcard_export)); // 设置对话框标题为导出失败
builder.setMessage(NotesListActivity.this builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted)); .getString(R.string.error_sdcard_unmounted)); // 设置对话框内容为SD卡未挂载
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) { } else if (result == BackupUtils.STATE_SUCCESS) { // 如果导出成功
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.success_sdcard_export)); .getString(R.string.success_sdcard_export)); // 设置对话框标题为导出成功
builder.setMessage(NotesListActivity.this.getString( builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir())); .getExportedTextFileName(), backup.getExportedTextFileDir())); // 设置对话框内容为导出文件的位置
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) { } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { // 如果系统错误
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); .getString(R.string.failed_sdcard_export)); // 设置对话框标题为导出失败
builder.setMessage(NotesListActivity.this builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export)); .getString(R.string.error_sdcard_export)); // 设置对话框内容为导出错误
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} }
@ -866,26 +910,37 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
/**
* @return
*
*/
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
/**
* PreferenceActivity
*/
private void startPreferenceActivity() { private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
/**
* @author k
* 便
*/
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData(); NoteItemData item = ((NotesListItem) view).getItemData(); // 获取点击项的数据
if (mNotesListAdapter.isInChoiceMode()) { if (mNotesListAdapter.isInChoiceMode()) { // 如果处于选择模式
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
position = position - mNotesListView.getHeaderViewsCount(); position = position - mNotesListView.getHeaderViewsCount();
mModeCallBack.onItemCheckedStateChanged(null, position, id, mModeCallBack.onItemCheckedStateChanged(null, position, id,
!mNotesListAdapter.isSelectedItem(position)); !mNotesListAdapter.isSelectedItem(position)); // 更新选择状态
} }
return; return;
} }
@ -894,9 +949,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
case NOTE_LIST: case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) { || item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item); openFolder(item); // 打开文件夹
} else if (item.getType() == Notes.TYPE_NOTE) { } else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); openNode(item); // 打开便签
} else { } else {
Log.e(TAG, "Wrong note type in NOTE_LIST"); Log.e(TAG, "Wrong note type in NOTE_LIST");
} }
@ -904,7 +959,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
case SUB_FOLDER: case SUB_FOLDER:
case CALL_RECORD_FOLDER: case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); openNode(item); // 打开便签
} else { } else {
Log.e(TAG, "Wrong note type in SUB_FOLDER"); Log.e(TAG, "Wrong note type in SUB_FOLDER");
} }
@ -917,6 +972,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
/**
*
*/
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection:
@ -935,18 +993,24 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
NoteColumns.MODIFIED_DATE + " DESC"); NoteColumns.MODIFIED_DATE + " DESC");
} }
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemLongClickListener#onItemLongClick(android.widget.AdapterView, android.view.View, int, long)
*
* 便ActionModeContextMenu
* ActionMOdeContextMenu
*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData(); mFocusNoteDataItem = ((NotesListItem) view).getItemData();// 获取当前长按项的数据
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
if (mNotesListView.startActionMode(mModeCallBack) != null) { if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mModeCallBack.onItemCheckedStateChanged(null, position, id, true);// 更改选择状态
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
} else { } else {
Log.e(TAG, "startActionMode fails"); Log.e(TAG, "startActionMode fails");
} }
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);// 设置创建上下文菜单监听器
} }
} }
return false; return false;

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -23,6 +7,7 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import java.util.Collection; import java.util.Collection;
@ -31,55 +16,94 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
/*
* 便CursorAdaptercursorListView
* NotesListAdapter便
*/
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; private int mNotesCount; //便签数
private boolean mChoiceMode; private boolean mChoiceMode; //选择模式标记
/*
* widget
*/
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
/*
* 便
*
*/
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null); //父类对象置空
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>(); //新建选项下标的hash表
mContext = context; mContext = context;
mNotesCount = 0; mNotesCount = 0;
} }
@Override @Override
/*
*
* 使NotesListItem
*/
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
/*
*
*
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
//若view是NotesListItem的一个实例
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
//则新建一个项目选项并且用bind跟将view和鼠标内容便签数据捆绑在一起
} }
} }
/*
*
*
*/
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
//根据定位和是否勾选设置下标
notifyDataSetChanged(); notifyDataSetChanged();
//在修改后刷新activity
} }
/*
*
*/
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
/*
*
* mode
*/
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
/*
*
*
*/
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
//获取光标位置
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
@ -87,30 +111,47 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
//遍历所有光标可用的位置在判断为便签类型之后勾选单项框
} }
/*
*
*
*/
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
//建立hash表
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
//遍历所有的关键
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
//若光标位置可用
Long id = getItemId(position); Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {
//原文件不需要添加
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); itemSet.add(id);
} }
//则将id该下标假如选项集合中
} }
} }
return itemSet; return itemSet;
} }
/*
* Widget
*
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position); Cursor c = (Cursor) getItem(position);
//以上4句和getSelectedItemIds一样不再重复
if (c != null) { if (c != null) {
//光标位置可用的话就建立新的Widget属性并编辑下标和类型最后添加到选项集中
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c); NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); widget.widgetId = item.getWidgetId();
@ -128,26 +169,42 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/*
*
*
*/
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
//首先获取选项下标的值
if (null == values) { if (null == values) {
return 0; return 0;
} }
Iterator<Boolean> iter = values.iterator(); Iterator<Boolean> iter = values.iterator();
//初始化叠加器
int count = 0; int count = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
if (true == iter.next()) { if (true == iter.next()) {
//若value值为真计数+1
count++; count++;
} }
} }
return count; return count;
} }
/*
*
*
*/
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
//获取选项数看是否等于便签的个数
} }
/*
*
*
*/
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -156,29 +213,45 @@ public class NotesListAdapter extends CursorAdapter {
} }
@Override @Override
/*
* activity便
*
*/
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
//执行基类函数
calcNotesCount(); calcNotesCount();
} }
@Override @Override
/*
* activity便
*/
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
//执行基类函数
calcNotesCount(); calcNotesCount();
} }
/*
* 便
*
*/
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
//获取总数同时遍历
Cursor c = (Cursor) getItem(i); Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; mNotesCount++;
//若该位置不为空并且文本类型为便签就+1
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "Invalid cursor");
return; return;
} }
//否则报错
} }
} }
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -30,37 +14,43 @@ import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
//创建便签列表项目选项
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert;//闹钟图片
private TextView mTitle; private TextView mTitle; //标题
private TextView mTime; private TextView mTime; //时间
private TextView mCallName; private TextView mCallName; //
private NoteItemData mItemData; private NoteItemData mItemData; //标签数据
private CheckBox mCheckBox; private CheckBox mCheckBox; //打钩框
/*初始化基本信息*/
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context); //super()它的主要作用是调整调用父类构造函数的顺序
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);//Inflate可用于将一个xml中定义的布局控件找出来,这里的xml是r。layout
//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定;
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title); mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time); mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name); mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
///根据data的属性对各个控件的属性的控制主要是可见性Visibility内容setText格式setTextAppearance
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE); ///设置可见行为可见
mCheckBox.setChecked(checked); mCheckBox.setChecked(checked); ///格子打钩
} else { } else {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE);
} }
mItemData = data; mItemData = data;
///设置控件属性一共三种情况由data的id和父id是否与保存到文件夹的id一致来决定
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
//设置该textview的style
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
//settext为设置内容
mTitle.setText(context.getString(R.string.call_record_folder_name) mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); mAlert.setImageResource(R.drawable.call_record);
@ -69,8 +59,9 @@ public class NotesListItem extends LinearLayout {
mCallName.setText(data.getCallName()); mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
///关于闹钟的设置
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);//图片来源的设置
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
@ -78,7 +69,7 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
///设置title格式
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
@ -87,35 +78,38 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);///设置图片来源
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); ///设置内容获取相关时间从data里编辑的日期中获取
mTime. setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data); setBackground(data);
} }
//根据data的文件属性来设置背景
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
//单个数据并且只有一个子文件夹
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) { } else if (data.isLast()) {//是最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) { } else if (data.isFirst() || data.isMultiFollowingFolder()) {//是一个数据并有多个子文件夹
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else { } else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { } else {
//若不是note直接调用文件夹的背景来源
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
@ -47,66 +31,92 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
/*
*NotesPreferenceActivity便
* PreferenceActivityActivity
*/
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
//优先名
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
//同步账号
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
//同步时间
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
//同步密码
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
//本地密码
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
//账户分组
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
//同步任务接收器
private Account[] mOriAccounts; private Account[] mOriAccounts;
//账户
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
//账户的hash标记
@Override @Override
/*
*activity
*Bundle icicle activity
*
*/
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
//先执行父类的创建函数
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
//给左上角图标的左边加上一个返回的图标
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
//添加xml来源并显示 xml
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
//根据同步账户关键码来初始化分组
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
//初始化同步组件
mOriAccounts = null; mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
//获取listvivewListView的作用:用于列出所有选择
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
//在listview组件上方添加其他组件
} }
@Override @Override
/*
* activity
*
*/
protected void onResume() { protected void onResume() {
//先执行父类 的交互实现
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // need to set sync account automatically if user has added a new
// account // account
if (mHasAddedAccount) { if (mHasAddedAccount) {
//若用户新加了账户则自动设置同步账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
//获取google同步账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) { //若原账户不为空且当前账户有增加
for (Account accountNew : accounts) {
boolean found = false; boolean found = false;
for (Account accountOld : mOriAccounts) { for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) { if (TextUtils.equals(accountOld.name, accountNew.name)) {
//更新账户
found = true; found = true;
break; break;
} }
} }
if (!found) { if (!found) {
setSyncAccount(accountNew.name); setSyncAccount(accountNew.name);
//若是没有找到旧的账户,那么同步账号中就只添加新账户
break; break;
} }
} }
@ -114,35 +124,52 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
refreshUI(); refreshUI();
//刷新标签界面
} }
@Override @Override
/*
* activity
*
*/
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
//注销接收器
} }
super.onDestroy(); super.onDestroy();
//执行父类的销毁动作
} }
/*
*
*
*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
//销毁所有的分组
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
//建立首选项
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setSummary(getString(R.string.preferences_account_summary));
//设置首选项的大标题和小标题
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
//建立监听器
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // the first time to set account
//若是第一次建立账户显示选择账户提示对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // if the account has already been set, we need to promp
// user about the risk // user about the risk
//若是已经建立则显示修改对话框并进行修改操作
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
//若在没有同步的情况下则在toast中显示不能修改
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
@ -151,21 +178,29 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
//根据新建首选项编辑新的账户分组
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
/*
*
*
*/
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取同步按钮控件和最终同步时间的的窗口
// set button state // set button state
//设置按钮的状态
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
//若是在同步状态下
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
} }
}); });
//设置按钮显示的文本为“取消同步”以及监听器
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
@ -173,50 +208,67 @@ public class NotesPreferenceActivity extends PreferenceActivity {
GTaskSyncService.startSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
//设置按键可用还是不可用
// set last sync time // set last sync time
// 设置最终同步时间
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
//若是在同步的情况下
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
// 根据当前同步服务器设置时间显示框的文本以及可见性
} else { } else {
//若是非同步情况
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
//则根据最后同步时间的信息来编辑时间显示框的文本内容和可见性
} else { } else {
//若时间为空直接设置为不可见状态
lastSyncTimeView.setVisibility(View.GONE); lastSyncTimeView.setVisibility(View.GONE);
} }
} }
} }
/*
*
*
*/
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
/*
*
*
*/
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
//设置标题以及子标题的内容
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); dialogBuilder.setPositiveButton(null, null);
//设置对话框的自定义标题建立一个YES的按钮
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);
//获取同步账户信息
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) {
//若账户不为空
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
int checkedItem = -1; int checkedItem = -1;
@ -224,83 +276,119 @@ public class NotesPreferenceActivity extends PreferenceActivity {
for (Account account : accounts) { for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) { if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index; checkedItem = index;
//在账户列表中查询到所需账户
} }
items[index++] = account.name; items[index++] = account.name;
} }
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
//在对话框建立一个单选的复选框
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); setSyncAccount(itemMapping[which].toString());
dialog.dismiss(); dialog.dismiss();
//取消对话框
refreshUI(); refreshUI();
} }
//设置点击后执行的事件,包括检录新同步账户和刷新标签界面
}); });
//建立对话框网络版的监听器
} }
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
//给新加账户对话框设置自定义样式
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
//显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; mHasAddedAccount = true;
//将新加账户的hash置true
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
//建立网络建立组件
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls" "gmail-ls"
}); });
startActivityForResult(intent, -1); startActivityForResult(intent, -1);
//跳回上一个选项
dialog.dismiss(); dialog.dismiss();
} }
}); });
//建立新加账户对话框的监听器
} }
/*
*
*
*/
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this))); getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
//根据同步修改的账户信息设置标题以及子标题的内容
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
//设置对话框的自定义标题
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
}; };
//定义一些标记字符串
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
//设置对话框要显示的一个list用于显示几个命令时,即changeremovecancel
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
//按键功能由which来决定
if (which == 0) { if (which == 0) {
//进入账户选择对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
//删除账户并且跟新便签界面
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
} }
}); });
dialogBuilder.show(); dialogBuilder.show();
//显示对话框
} }
/*
*
*
*/
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
/*
*
*
*/
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
//假如该账号不在同步账号列表中
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
//编辑共享的首选项
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
//将该账号加入到首选项中
editor.commit(); editor.commit();
//提交修改的数据
// clean up last sync time
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
//将最后同步时间清零
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
@ -311,23 +399,33 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
//重置当地同步任务的信息
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
//将toast的文本信息置为“设置账户成功”并显示出来
} }
} }
/*
*
*
*/
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
//假如当前首选项中有账户就删除
} }
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
//删除当前首选项中有账户时间
} }
editor.commit(); editor.commit();
//提交更新后的数据
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
@ -338,51 +436,79 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
//重置当地同步任务的信息
} }
/*
*
*
*/
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
/*
*
*
*/
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
// 从共享首选项中找到相关账户并获取其编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); editor.commit();
//编辑最终同步时间并提交更新
} }
/*
*
*
*/
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
/*
*
* BroadcastReceiver
*/
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); //获取随广播而来的Intent中的同步服务的数据
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
//通过获取的数据在设置系统的状态
} }
} }
} }
/*
*
*
* :MenuItem
*/
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
//根据选项的id选择这里只有一个主页
case android.R.id.home: case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
return true; return true;
//在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
default: default:
return false; return false;
} }
} }
} }

@ -14,39 +14,161 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.content.Context; import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import net.micode.notes.R; import android.content.Context;
import net.micode.notes.data.Notes; import android.content.Intent;
import net.micode.notes.tool.ResourceParser; import android.database.Cursor;
import android.util.Log;
// NoteWidgetProvider_2x 类是 NoteWidgetProvider 的子类,用于特定类型的小部件 import android.widget.RemoteViews;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
import net.micode.notes.R;
@Override import net.micode.notes.data.Notes;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { import net.micode.notes.data.Notes.NoteColumns;
// 调用父类的 update 方法以执行小部件更新操作 import net.micode.notes.tool.ResourceParser;
super.update(context, appWidgetManager, appWidgetIds); import net.micode.notes.ui.NoteEditActivity;
} import net.micode.notes.ui.NotesListActivity;
// 获取小部件的布局资源 ID public abstract class NoteWidgetProvider extends AppWidgetProvider {
@Override public static final String [] PROJECTION = new String [] {
protected int getLayoutId() { NoteColumns.ID,
return R.layout.widget_2x; NoteColumns.BG_COLOR_ID,
} NoteColumns.SNIPPET
};
// 获取与小部件类型相关的背景资源 ID
@Override public static final int COLUMN_ID = 0;
protected int getBgResourceId(int bgId) { public static final int COLUMN_BG_COLOR_ID = 1;
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); public static final int COLUMN_SNIPPET = 2;
}
private static final String TAG = "NoteWidgetProvider";
// 获取小部件的类型,此处返回 Notes.TYPE_WIDGET_2X
@Override @Override
protected int getWidgetType() { // 当小部件从主屏幕中被删除时调用的方法
return Notes.TYPE_WIDGET_2X; public void onDeleted(Context context, int[] appWidgetIds) {
} // 创建 ContentValues 对象,用于存储更新数据库的数值
} ContentValues values = new ContentValues();
// 将 NoteColumns.WIDGET_ID 的值设置为无效的小部件 IDAppWidgetManager.INVALID_APPWIDGET_ID
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历传入的小部件 ID 数组
for (int i = 0; i < appWidgetIds.length; i++) {
// 使用 ContentResolver 更新 Notes 数据库中的相应小部件 ID 的记录
context.getContentResolver().update(
Notes.CONTENT_NOTE_URI, // 更新的数据表的 URI
values, // 更新的数值
NoteColumns.WIDGET_ID + "=?", // 更新的条件,匹配小部件 ID
new String[] { String.valueOf(appWidgetIds[i]) } // 匹配条件的参数,传入当前小部件 ID
);
}
}
// 获取与小部件相关的笔记信息的方法
// 参数 context上下文对象用于访问内容提供程序
// 参数 widgetId要获取信息的小部件的唯一标识符
// 返回值:包含笔记信息的游标对象
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
// 使用内容解析器查询 Notes 数据库中的记录
// 查询的条件是NoteColumns.WIDGET_ID 等于给定 widgetId同时 NoteColumns.PARENT_ID 不等于垃圾箱的 IDNotes.ID_TRASH_FOLER
// 查询的列是由 PROJECTION 常量指定的列数组
return context.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 查询的数据表的 URI
PROJECTION, // 查询的列数组
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询的条件
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, // 查询条件的参数
null // 不排序
);
}
// update 方法的重载,用于执行小部件更新操作
// 参数 context上下文对象用于访问资源和小部件管理器
// 参数 appWidgetManager小部件管理器用于更新小部件
// 参数 appWidgetIds包含要更新的小部件 ID 的数组
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用 update 方法的重载版本,传入默认参数 false
update(context, appWidgetManager, appWidgetIds, false);
}
// update 方法,用于更新小部件
// 参数 context上下文对象用于访问资源和小部件管理器
// 参数 appWidgetManager小部件管理器用于更新小部件
// 参数 appWidgetIds包含要更新的小部件 ID 的数组
// 参数 privacyMode一个布尔值表示小部件是否处于隐私模式
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 获取默认背景 ID
int bgId = ResourceParser.getDefaultBgId(context);
// 初始化一个空字符串用于存储文本片段
String snippet = "";
// 创建一个意图,用于打开 NoteEditActivity
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
// 查询与当前小部件相关的笔记信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) {
// 如果查询结果中有多于一个记录,记录错误并返回
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with the same widget id:" + appWidgetIds[i]);
c.close();
return;
}
// 从查询结果中获取文本片段和背景颜色 ID
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
// 设置 intent 中的额外数据,包括笔记的唯一标识符和操作类型
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
} else {
// 如果没有查询到相关信息,使用默认文本片段和插入/编辑操作类型
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}
if (c != null) {
c.close();
}
// 创建远程视图对象,用于配置小部件的外观
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
// 设置 intent 中的额外数据,包括背景 ID
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
// 生成用于启动小部件的挂起意图
PendingIntent pendingIntent = null;
if (privacyMode) {
// 如果小部件处于隐私模式,设置文本为特定文本并创建 NotesListActivity 的意图
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// 如果不是隐私模式,将文本设置为笔记片段,并创建打开笔记编辑界面的意图
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 设置小部件的点击行为
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId();
protected abstract int getWidgetType();
}
Loading…
Cancel
Save