Compare commits

..

4 Commits

Author SHA1 Message Date
Ryuki cab648c447 .
2 years ago
Ryuki 8e41221ba1 .
2 years ago
Ryuki 7d4cf94218 all
2 years ago
Ryuki 36148b43e1 注释
2 years ago

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -26,54 +26,29 @@ import org.json.JSONObject;
public class MetaData extends Task { public class MetaData extends Task {
/* TAG
* getSimpleName ()
*/
private final static String TAG = MetaData.class.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) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
//对函数块进行注释
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
/*
* metaInfojsonobject
*/
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
/*
*
*/
} }
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/*
* Gid
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/*
*
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/*
* 使json
* TasksetContentByRemoteJSON ()
*
*/
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
@ -83,9 +58,6 @@ public class MetaData extends Task {
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
/*
*
*/
mRelatedGid = null; mRelatedGid = null;
} }
} }
@ -97,33 +69,14 @@ public class MetaData extends Task {
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
/*
* json
*/
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
/*
*
*/
}
/*
*
*/
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");
} }
/*
*
*/
} }

@ -20,38 +20,32 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/*
*
* abstract
*/
public abstract class Node { public abstract class Node {
//定义了各种用于表征同步状态的常量 public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_NONE = 0;// 本地和云端都无可更新内容(即本地和云端内容一致)
public static final int SYNC_ACTION_ADD_REMOTE = 1;// 需要在远程云端增加内容 public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2;// 需要在本地增加内容 public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;// 需要在远程云端删除内容 public static final int SYNC_ACTION_DEL_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;

@ -14,21 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
/*
* Description便sqlnotedatanote
* SqlData
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
/*
*
*
*
* Made By CuiCan
*/
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
@ -49,30 +36,15 @@ import org.json.JSONObject;
public class SqlData { public class SqlData {
/*
* TAG
* getSimpleName ()
*/
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
private static final int INVALID_ID = -99999;//为mDataId置初始值-99999 private static final int INVALID_ID = -99999;
/*
* NotesDataColumn
*/
// 集合了interface DataColumns中所有SF常量
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
//以下变量作为sql表中5列的编号
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
@ -84,7 +56,7 @@ public class SqlData {
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
//判断是否直接用Content生成是为true否则为false
private boolean mIsCreate; private boolean mIsCreate;
private long mDataId; private long mDataId;
@ -99,13 +71,6 @@ public class SqlData {
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
@ -117,13 +82,6 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -131,12 +89,6 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/*
*
*
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -145,13 +97,7 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/*
*
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
//如果传入的JSONObject对象中有DataColumns.ID这一项则设置否则设为INVALID_ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId);
@ -184,18 +130,11 @@ public class SqlData {
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/*
*
*
*/
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
return null; return null;
} }
//创建JSONObject对象。并将相关数据放入其中并返回。
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId); js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType); js.put(DataColumns.MIME_TYPE, mDataMimeType);
@ -204,9 +143,7 @@ public class SqlData {
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3);
return js; return js;
} }
/*
* commit
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
@ -246,12 +183,6 @@ public class SqlData {
mIsCreate = false; mIsCreate = false;
} }
/*
* id
*
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }

@ -13,10 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* Description便sqldatanotedata
* SqlDataSqlNote
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -40,21 +37,12 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/*
*
*
*/
public class SqlNote { public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
/*
* TAG
* getSimpleName ()
*/
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
// 集合了interface NoteColumns中所有SF常量17个
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -63,7 +51,7 @@ public class SqlNote {
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION NoteColumns.VERSION
}; };
//以下设置17个列的编号
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
@ -97,7 +85,7 @@ public class SqlNote {
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
//以下定义了17个内部的变量其中12个可以由content中获得5个需要初始化为0或者new
private Context mContext; private Context mContext;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
@ -133,12 +121,7 @@ public class SqlNote {
private ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
/*
*
* mIsCreate
*/
//构造函数只有context对所有的变量进行初始化
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -146,9 +129,9 @@ public class SqlNote {
mId = INVALID_ID; mId = INVALID_ID;
mAlertDate = 0; mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();//调用系统函数获得创建时间 mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0; mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();//最后一次修改时间初始化为创建时间 mModifiedDate = System.currentTimeMillis();
mParentId = 0; mParentId = 0;
mSnippet = ""; mSnippet = "";
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE;
@ -159,12 +142,6 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/*
*
* mIsCreate
*/
//构造函数有context和一个数据库的cursor多数变量通过cursor指向的一条记录直接进行初始化
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
@ -176,10 +153,7 @@ public class SqlNote {
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/*
*
* mIsCreate
*/
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -199,10 +173,9 @@ public class SqlNote {
new String[] { new String[] {
String.valueOf(id) String.valueOf(id)
}, null); }, null);
if (c != null) {//通过id获得对应的ContentResolver中的cursor if (c != null) {
c.moveToNext(); c.moveToNext();
loadFromCursor(c);//然后加载数据进行初始化,这样函数 loadFromCursor(c);
//SqlNote(Context context, long id)与SqlNote(Context context, long id)的实现方式基本相同
} else { } else {
Log.w(TAG, "loadFromCursor: cursor = null"); Log.w(TAG, "loadFromCursor: cursor = null");
} }
@ -211,11 +184,8 @@ public class SqlNote {
c.close(); c.close();
} }
} }
/*
*
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
//直接从一条记录中的获得以下变量的初始值
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
@ -229,9 +199,7 @@ public class SqlNote {
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/*
* content
* */
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
@ -257,8 +225,7 @@ public class SqlNote {
c.close(); c.close();
} }
} }
/*
* content*/
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -392,8 +359,6 @@ public class SqlNote {
return true; return true;
} }
/*
* contentnote*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -441,49 +406,40 @@ public class SqlNote {
} }
return null; return null;
} }
/*
* idid*/
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
/*
* idGtaskid*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/*
* idid*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/*
* */
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
/*
* id*/
public long getId() { public long getId() {
return mId; return mId;
} }
/*
* idid*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/*
* 便*/
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
/*
* 便*/
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
/*
* commit*/
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {

@ -35,22 +35,22 @@ import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;//是否完成 private boolean mCompleted;
private String mNotes; private String mNotes;
private JSONObject mMetaInfo;//将在实例中存储数据的类型 private JSONObject mMetaInfo;
private Task mPriorSibling; private Task mPriorSibling;
private TaskList mParent;//所在的任务列表的指针 private TaskList mParent;
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
mNotes = null; mNotes = null;
mPriorSibling = null;//TaskList中当前Task前面的Task的指针 mPriorSibling = null;
mParent = null;//当前Task所在的TaskList mParent = null;
mMetaInfo = null; mMetaInfo = null;
} }

@ -31,11 +31,11 @@ import java.util.ArrayList;
public class TaskList extends Node { public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();//tag标记 private static final String TAG = TaskList.class.getSimpleName();
private int mIndex;//当前TaskList的指针 private int mIndex;
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList private ArrayList<Task> mChildren;
public TaskList() { public TaskList() {
super(); super();
@ -43,7 +43,6 @@ public class TaskList extends Node {
mIndex = 1; mIndex = 1;
} }
//生成并返回一个包含了一定数据的JSONObject实体
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -75,8 +74,6 @@ public class TaskList extends Node {
return js; return js;
} }
//生成并返回一个包含了一定数据的JSONObject实体
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -219,8 +216,6 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
//功能获得TaskList的大小即mChildren的大小
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
@ -238,7 +233,7 @@ public class TaskList extends Node {
} }
return ret; return ret;
} }
//功能:在当前任务表的指定位置添加新的任务
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
@ -265,7 +260,6 @@ public class TaskList extends Node {
return true; return true;
} }
// 功能删除TaskList中的一个Task
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task);
@ -287,7 +281,6 @@ public class TaskList extends Node {
return ret; return ret;
} }
//功能将当前TaskList中含有的某个Task移到index位置
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
@ -305,10 +298,7 @@ public class TaskList extends Node {
return true; return true;
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
//利用已实现好的功能完成当下功能;
// 功能按gid寻找Task
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
@ -318,13 +308,11 @@ public class TaskList extends Node {
} }
return null; return null;
} }
//功能返回指定Task的index
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
//功能返回指定index的Task
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
@ -333,8 +321,6 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
//功能返回指定index的Task
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))

@ -14,24 +14,14 @@
* limitations under the License. * limitations under the License.
*/ */
// 支持小米便签运行过程中的运行异常处理
package net.micode.notes.gtask.exception; 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
*/
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);

@ -13,20 +13,11 @@
* 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.
*/ */
/*
* Description便
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
// serialVersionUID作用是序列化时保持版本的兼容性即在版本升级时反序列化仍保持对象的唯一性。
/*
* JAVA使superthis.
* new
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super();

@ -28,13 +28,6 @@ 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;
/*GTask
*
* private void showNotification(int tickerId, String content)
* protected Integer doInBackground(Void... unused) 线
* protected void onProgressUpdate(String... progress) 使 线
* protected void onPostExecute(Integer result) Handler UI使doInBackground UI
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
@ -64,7 +57,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
public void publishProgess(String message) {// 发布进度单位系统将会调用onProgressUpdate()方法更新这些值 public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
@ -73,29 +66,30 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;// 调用系统自带灯光 notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL; notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent; PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);//如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象 NotesPreferenceActivity.class), 0);
} else { } else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);//如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象 NotesListActivity.class), 0);
} }
// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
// pendingIntent); pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息 mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
// @Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); //进行后台同步具体操作 return mTaskManager.sync(mContext, this);
} }
// @Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
@ -103,8 +97,8 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
} }
//@Override @Override
protected void onPostExecute(Integer result) {//用于在执行完后台任务后更新UI,显示结果 protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));

@ -60,10 +60,7 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/*
* GTASKGTASK
* 使accountManager JSONObject HttpParams authToken Gid
*/
public class GTaskClient { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
@ -105,10 +102,6 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/*
* 使 getInstance()
* mInstance
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();

@ -87,9 +87,9 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
private GTaskManager() { //对象初始化函数 private GTaskManager() {
mSyncing = false; //正在同步,flase代表未执行 mSyncing = false;
mCancelled = false; //全局标识flase代表可以执行 mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>(); mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>(); mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>(); mMetaHashMap = new HashMap<String, MetaData>();
@ -113,7 +113,7 @@ public class GTaskManager {
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress");//创建日志文件调试信息debug Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
mContext = context; mContext = context;
@ -128,7 +128,7 @@ public class GTaskManager {
mNidToGid.clear(); mNidToGid.clear();
try { try {
GTaskClient client = GTaskClient.getInstance();//getInstance即为创建一个实例,client--客户机 GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // login google task
@ -140,7 +140,7 @@ public class GTaskManager {
// get the task list from google // get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList initGTaskList();
// do content sync work // do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
@ -168,17 +168,12 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
/*
*GtaskListGoogleJSONtasklistTaskList
*mMetaListmGTaskListHashMapmGTaskHashMap
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
JSONArray jsTaskLists = client.getTaskLists(); //getInstance即为创建一个实例client应指远端客户机 JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // init meta list first
mMetaList = null; mMetaList = null;
@ -252,8 +247,6 @@ public class GTaskManager {
} }
} }
//功能:本地内容同步操作
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;

@ -42,8 +42,6 @@ public class GTaskSyncService extends Service {
private static String mSyncProgress = ""; private static String mSyncProgress = "";
////开始一个同步的工作
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -67,14 +65,13 @@ public class GTaskSyncService extends Service {
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
}///初始化一个service }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
//两种情况,开始同步或者取消同步
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync();
break; break;
@ -84,7 +81,7 @@ public class GTaskSyncService extends Service {
default: default:
break; break;
} }
return START_STICKY;//等待新的intent来是这个service继续运行 return START_STICKY;
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }

@ -42,11 +42,11 @@ public class Note {
* Create a new note id for adding a new note to databases * Create a new note id for adding a new note to databases
*/ */
public static synchronized long getNewNoteId(Context context, long folderId) { public static synchronized long getNewNoteId(Context context, long folderId) {
//为给定文件夹生成新的笔记ID // Create a new note in the database
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis(); long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);//创建日期 values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);//修改日期 values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId);
@ -71,7 +71,6 @@ public class Note {
} }
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
//此方法设置笔记的值,标记为本地修改
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
@ -80,12 +79,11 @@ public class Note {
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
//为笔记设置文本数据。
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
//setTextDataId、getTextDataId、setCallDataId、setCallData 这些方法处理与笔记相关的文本和通话信息的ID和数据的设置和获取。
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }
@ -101,7 +99,7 @@ public class Note {
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
//根据值和数据的差异检查笔记是否具有本地修改。
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -110,8 +108,6 @@ public class Note {
if (!isLocalModified()) { if (!isLocalModified()) {
return true; return true;
} }
//尝试将笔记与提供的上下文和笔记ID同步。
//如果笔记ID小于或等于0或者没有本地修改则返回true。
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
@ -151,19 +147,17 @@ public class Note {
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
//初始化 mTextDataValues 和 mCallDataValues 为 ContentValues 对象,用于存储文本数据和通话数据。
//初始化 mTextDataId 和 mCallDataId 为 0。
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
//检查文本或通话数据是否有本地修改
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
} }
mTextDataId = id; mTextDataId = id;
} }
//设置文本数据的ID如果提供的ID小于等于0报告异常
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
@ -171,57 +165,52 @@ public class Note {
} }
mCallDataId = id; mCallDataId = id;
} }
//设置通话数据的键值对,并标记笔记为本地修改,更新修改日期
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//设置文本数据的键值对,并标记笔记为本地修改,更新修改日期
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//将数据推送到ContentResolver的方法
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
//检查noteID的有效性如果小于等于0抛出IllegalArgumentException /**
* Check for safety
*/
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
//用于保存ContentProvider操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
//处理文本数据的操作
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
//设置文本数据的关联noteID
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
// 如果mTextDataId为0表示需要插入新的文本数据
if (mTextDataId == 0) { if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
//插入数据并获取新的Uri
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
try { try {
// 解析Uri中的数据获取新插入数据的id并设置给mTextDataId
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// 插入数据失败,记录错误日志并清空数据
Log.e(TAG, "Insert new text data fail with noteId" + noteId); Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear(); mTextDataValues.clear();
return null; return null;
} }
} else { } else {
// mTextDataId不为0表示需要更新已存在的文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues);
operationList.add(builder.build()); operationList.add(builder.build());
} }
// 清空文本数据,以便下一次使用
mTextDataValues.clear(); mTextDataValues.clear();
} }
// 处理通话数据的操作,逻辑类似于文本数据
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) { if (mCallDataId == 0) {
@ -243,20 +232,17 @@ public class Note {
} }
mCallDataValues.clear(); mCallDataValues.clear();
} }
// 如果有待执行的操作将它们应用到ContentResolver
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); Notes.AUTHORITY, operationList);
// 返回插入或更新后的笔记的Uri如果操作失败则返回null
return (results == null || results.length == 0 || results[0] == null) ? null return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { } catch (RemoteException e) {
// 捕获远程异常并记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
// 捕获操作应用异常并记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} }
@ -265,5 +251,3 @@ public class Note {
} }
} }
} }

@ -128,11 +128,9 @@ public class WorkingNote {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
// 检查查询结果是否为空
if (cursor != null) { if (cursor != null) {
// 移动到查询结果的第一行(如果有多行数据)
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
// 从查询结果中获取笔记的相关信息并存储到相应的成员变量中
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -140,49 +138,37 @@ public class WorkingNote {
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
} }
// 关闭查询结果的游标
cursor.close(); cursor.close();
} else { } else {
// 如果查询结果为空,则输出错误日志并抛出异常
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
} }
// 调用loadNoteData()方法加载笔记的其他数据
loadNoteData(); loadNoteData();
} }
private void loadNoteData() { private void loadNoteData() {
// 通过内容解析器(ContentResolver)查询笔记的数据信息
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null);
// 检查查询结果是否为空
if (cursor != null) { if (cursor != null) {
// 移动到查询结果的第一行(如果有多行数据)
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
// 获取数据类型
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
// 根据数据类型进行不同的处理
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
// 如果是笔记类型的数据,获取内容和模式,并设置到相应的成员变量中
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) { } else if (DataConstants.CALL_NOTE.equals(type)) {
// 如果是通话笔记类型的数据设置通话数据ID到相应的成员变量中
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else { } else {
// 如果是未知类型的数据,输出调试信息
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
} }
} while (cursor.moveToNext()); } while (cursor.moveToNext());
} }
// 关闭查询结果的游标
cursor.close(); cursor.close();
} else { } else {
// 如果查询结果为空,则输出错误日志并抛出异常
Log.e(TAG, "No data with id:" + mNoteId); Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
} }
@ -202,32 +188,27 @@ public class WorkingNote {
} }
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
// 检查笔记是否值得保存
if (isWorthSaving()) { if (isWorthSaving()) {
// 检查笔记是否存在于数据库中
if (!existInDatabase()) { if (!existInDatabase()) {
// 如果笔记在数据库中不存在尝试创建一个新的笔记ID
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
// 如果创建新的笔记ID失败输出错误日志并返回保存失败
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
} }
} }
// 同步笔记信息到数据库中
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
// 如果存在与该笔记相关的小部件,并且小部件类型有效,并且存在小部件设置状态监听器,则通知小部件内容已更改
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
return true;//保存成功 return true;
} else { } else {
return false;//保存失败 return false;
} }
} }
@ -249,55 +230,38 @@ public class WorkingNote {
} }
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
// 检查传入的日期是否与当前提醒日期不同
if (date != mAlertDate) { if (date != mAlertDate) {
// 如果不同,更新当前提醒日期为传入的日期,并通过 mNote 对象将更新后的提醒日期同步到数据库中
mAlertDate = date; mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
} }
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onClockAlertChanged 方法,通知提醒日期已更改,并传递新的日期和开关状态
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
// 将笔记的删除状态更新为传入的标记值
mIsDeleted = mark; mIsDeleted = mark;
// 检查是否存在与该笔记相关的小部件,并且小部件类型有效,并且存在笔记设置状态监听器
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
// 如果条件满足,调用监听器的 onWidgetChanged 方法,通知小部件内容已更改
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
} }
public void setBgColorId(int id) { public void setBgColorId(int id) {
// 检查传入的颜色ID是否与当前背景颜色ID不同
if (id != mBgColorId) { if (id != mBgColorId) {
// 如果不同更新当前背景颜色ID为传入的颜色ID
mBgColorId = id; mBgColorId = id;
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onBackgroundColorChanged 方法,通知背景颜色已更改
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
} }
// 通过 mNote 对象将更新后的背景颜色ID同步到数据库中
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
// 如果不同,更新当前模式为传入的模式
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onCheckListModeChanged 方法,通知检查清单模式已更改,并传递旧模式和新模式
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
// 将当前模式更新为传入的模式,并通过 mNote 对象将更新后的模式同步到数据库中
mMode = mode; mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
@ -311,23 +275,15 @@ public class WorkingNote {
} }
public void setWidgetId(int id) { public void setWidgetId(int id) {
// 检查传入的小部件类型是否与当前小部件类型不同
if (id != mWidgetId) { if (id != mWidgetId) {
// 如果不同,更新当前小部件类型为传入的小部件类型
mWidgetId = id; mWidgetId = id;
// 通过 mNote 对象将更新后的小部件类型同步到数据库中
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
} }
} }
public void setWorkingText(String text) { public void setWorkingText(String text) {
// 检查传入的文本内容是否与当前内容不同
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
// 如果不同,更新当前内容为传入的文本内容
mContent = text; mContent = text;
// 通过 mNote 对象将更新后的文本内容同步到数据库中
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
} }
} }

@ -1,3 +1,18 @@
/*
* 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.tool; package net.micode.notes.tool;
@ -23,7 +38,7 @@ import java.io.PrintStream;
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// 单例模式 // Singleton stuff
private static BackupUtils sInstance; private static BackupUtils sInstance;
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
@ -37,15 +52,15 @@ public class BackupUtils {
* Following states are signs to represents backup or restore * Following states are signs to represents backup or restore
* status * status
*/ */
// 当前SD卡未挂载 // Currently, the sdcard is not mounted
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// 备份文件不存在 // The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
//数据格式不正确,可能已被其他程序更改 // The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// 一些运行时异常导致还原或备份失败 // Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// 备份或者还原成功 // Backup or restore success
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
private TextExport mTextExport; private TextExport mTextExport;
@ -122,10 +137,10 @@ public class BackupUtils {
} }
/** /**
* id * Export the folder identified by folder id to text
*/ */
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于此文件夹的便签 // Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
@ -134,11 +149,11 @@ public class BackupUtils {
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// 打印便签的最后修改日期 // Print note's last modified date
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于此便签的数据 // Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
@ -148,7 +163,7 @@ public class BackupUtils {
} }
/** /**
* id便 * Export note identified by id to a print stream
*/ */
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
@ -161,7 +176,7 @@ public class BackupUtils {
do { do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 打印电话号码 // Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
@ -170,11 +185,11 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
} }
// 打印通话日期 // Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), .format(mContext.getString(R.string.format_datetime_mdhm),
callDate))); callDate)));
// 打印通话附件位置 // Print call attachment location
if (!TextUtils.isEmpty(location)) { if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location)); location));
@ -190,7 +205,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// 在便签之间打印一行分隔符 // print a line separator between note
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -225,7 +240,7 @@ public class BackupUtils {
if (folderCursor != null) { if (folderCursor != null) {
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) {
do { do {
// 打印文件夹的名称 // Print folder's name
String folderName = ""; String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name); folderName = mContext.getString(R.string.call_record_folder_name);
@ -255,7 +270,7 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询数据属于此 // Query data belong to this note
String noteId = noteCursor.getString(NOTE_COLUMN_ID); String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext()); } while (noteCursor.moveToNext());
@ -268,7 +283,7 @@ public class BackupUtils {
} }
/** /**
* {@generateExportedTextFile} * Get a print stream pointed to the file {@generateExportedTextFile}
*/ */
private PrintStream getExportToTextPrintStream() { private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
@ -295,7 +310,7 @@ public class BackupUtils {
} }
/** /**
* * Generate the text file to store imported data
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

@ -37,49 +37,39 @@ import java.util.HashSet;
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
// 批量删除笔记的静态方法
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查传入的笔记ID集合是否为空
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true;// 如果为空,返回删除成功 return true;
} }
// 检查传入的笔记ID集合是否为空
if (ids.size() == 0) { if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset"); Log.d(TAG, "no id is in the hashset");
return true;// 如果为空,返回删除成功 return true;
} }
// 创建一个操作列表,用于存储批量操作的删除操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历传入的笔记ID集合为每个ID创建一个删除操作并添加到操作列表中
for (long id : ids) { for (long id : ids) {
// 检查是否为系统文件夹的ID如果是跳过不删除
if(id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root"); Log.e(TAG, "Don't delete system folder root");
continue; continue;
} }
// 创建删除操作的构建器
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 将删除操作添加到操作列表中
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {
// 应用批量操作,删除笔记
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查批量操作结果是否为空或第一个结果是否为空
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;// 如果为空,返回删除失败 return false;
} }
return true;// 返回删除成功 return true;
} catch (RemoteException e) { } catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false;// 返回删除失败 return false;
} }
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
@ -92,34 +82,27 @@ public class DataUtils {
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
// 检查传入的笔记ID集合是否为空
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true;// 如果为空,返回移动成功 return true;
} }
// 创建一个操作列表,用于存储批量操作的更新操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历传入的笔记ID集合为每个ID创建一个更新操作并设置新的父文件夹ID和本地修改标志
for (long id : ids) { for (long id : ids) {
// 创建更新操作的构建器
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 设置更新操作的值包括新的父文件夹ID和本地修改标志
builder.withValue(NoteColumns.PARENT_ID, folderId); builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
// 将更新操作添加到操作列表中
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {
// 应用批量操作更新笔记的父文件夹ID和本地修改标志
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查批量操作结果是否为空或第一个结果是否为空
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;// 如果为空,返回移动失败 return false;
} }
return true;// 返回移动成功 return true;
} catch (RemoteException e) { } catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
@ -132,108 +115,89 @@ public class DataUtils {
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/ */
public static int getUserFolderCount(ContentResolver resolver) { public static int getUserFolderCount(ContentResolver resolver) {
// 查询用户文件夹的数量
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" }, new String[] { "COUNT(*)" },
// 查询条件类型为文件夹且父文件夹ID不是回收站文件夹ID
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null); null);
int count = 0; int count = 0;
if(cursor != null) { if(cursor != null) {
// 如果查询结果非空,移动到第一行
if(cursor.moveToFirst()) { if(cursor.moveToFirst()) {
try { try {
// 获取查询结果中的文件夹数量
count = cursor.getInt(0); count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, "get folder count failed:" + e.toString()); Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
// 关闭游标
cursor.close(); cursor.close();
} }
} }
} }
return count;// 返回文件夹数量 return count;
} }
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询指定笔记ID的可见性
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null,
// 查询条件类型为指定类型且父文件夹ID不是回收站文件夹ID
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)}, new String [] {String.valueOf(type)},
null); null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
// 关闭游标
cursor.close(); cursor.close();
} }
return exist;// 返回是否存在 return exist;
} }
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询指定笔记ID是否存在于笔记数据库中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
// 关闭游标
cursor.close(); cursor.close();
} }
return exist;// 返回是否存在 return exist;
} }
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询指定数据ID是否存在于数据数据库中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
cursor.close(); cursor.close();
} }
return exist;// 返回是否存在 return exist;
} }
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询是否存在具有指定名称的可见文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
// 查询条件类型为文件夹、父文件夹ID不是回收站文件夹ID、且摘要等于指定名称
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
boolean exist = false; boolean exist = false;
if(cursor != null) { if(cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
exist = true; exist = true;
} }
cursor.close(); cursor.close();
} }
return exist; // 返回是否存在 return exist;
} }
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询指定文件夹ID下的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?", NoteColumns.PARENT_ID + "=?",
@ -242,30 +206,25 @@ public class DataUtils {
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null;
if (c != null) { if (c != null) {
// 如果查询结果非空,移动到第一行
if (c.moveToFirst()) { if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>(); set = new HashSet<AppWidgetAttribute>();
do { do {
try { try {
// 创建 AppWidgetAttribute 对象获取小部件ID和小部件类型添加到集合中
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0); widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1); widget.widgetType = c.getInt(1);
set.add(widget); set.add(widget);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
} }
} while (c.moveToNext()); } while (c.moveToNext());
} }
c.close(); c.close();
} }
return set;// 返回包含小部件信息的集合 return set;
} }
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询指定笔记ID对应的通话笔记的电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
@ -274,20 +233,17 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取查询结果中的电话号码
return cursor.getString(0); return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, "Get call number fails " + e.toString()); Log.e(TAG, "Get call number fails " + e.toString());
} finally { } finally {
cursor.close(); cursor.close();
} }
} }
return "";// 如果查询结果为空,返回空字符串 return "";
} }
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询指定电话号码和通话日期对应的通话笔记的笔记ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
@ -296,24 +252,19 @@ public class DataUtils {
null); null);
if (cursor != null) { if (cursor != null) {
// 如果查询结果非空,移动到第一行
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {
// 获取查询结果中的笔记ID
return cursor.getLong(0); return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, "Get call note id fails " + e.toString()); Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
cursor.close(); cursor.close();
} }
return 0; // 如果查询结果为空返回0 return 0;
} }
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询指定笔记ID的摘要信息
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?", NoteColumns.ID + "=?",
@ -321,20 +272,17 @@ public class DataUtils {
null); null);
if (cursor != null) { if (cursor != null) {
// 如果查询结果非空,移动到第一行
String snippet = ""; String snippet = "";
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
// 获取查询结果中的摘要信息
snippet = cursor.getString(0); snippet = cursor.getString(0);
} }
cursor.close(); cursor.close();
return snippet;// 返回摘要信息 return snippet;
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId);
} }
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
// 格式化摘要信息:去除首尾空格,并截取首个换行符之前的内容
if (snippet != null) { if (snippet != null) {
snippet = snippet.trim(); snippet = snippet.trim();
int index = snippet.indexOf('\n'); int index = snippet.indexOf('\n');
@ -342,7 +290,6 @@ public class DataUtils {
snippet = snippet.substring(0, index); snippet = snippet.substring(0, index);
} }
} }
return snippet;// 返回格式化后的摘要信息 return snippet;
} }
} }

@ -66,19 +66,15 @@ public class ResourceParser {
} }
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
// 获取默认背景ID
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 如果用户已设置背景颜色则返回随机选择的编辑界面背景资源ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else { } else {
// 如果用户未设置背景颜色则返回默认颜色的背景资源ID
return BG_DEFAULT_COLOR; return BG_DEFAULT_COLOR;
} }
} }
public static class NoteItemBgResources { public static class NoteItemBgResources {
// 定义笔记列表项背景资源数组
private final static int [] BG_FIRST_RESOURCES = new int [] { private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up, R.drawable.list_yellow_up,
R.drawable.list_blue_up, R.drawable.list_blue_up,

@ -12,40 +12,56 @@ import android.widget.Toast;
import net.micode.notes.R; import net.micode.notes.R;
//继承自 Activity 类,提供用户界面删除已设置的密码
public class DeletingPassword extends Activity { public class DeletingPassword extends Activity {
//定义 EditText 成员变量获取用户输入的密码
EditText Dt_password; EditText Dt_password;
//定义 Button 成员变量,用户点击后确认删除密码
Button Acknowledged; Button Acknowledged;
// Activity 的 onCreate()方法
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_delete_password); setContentView(R.layout.activity_delete_password);
//设置软键盘行为
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//关联至布局文件中的 EditText 组件(用于输入密码)
Dt_password=(EditText) findViewById(R.id.thepassword); Dt_password=(EditText) findViewById(R.id.thepassword);
//关联至布局文件中的 Button 组件(确认删除按钮)
Acknowledged=(Button)findViewById(R.id.Dt_Acknowledged); Acknowledged=(Button)findViewById(R.id.Dt_Acknowledged);
//设置确认删除按钮的点击监听器
Acknowledged.setOnClickListener(new View.OnClickListener() { Acknowledged.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
//获取用户输入的密码
String text02 = Dt_password.getText().toString(); String text02 = Dt_password.getText().toString();
if(text02.equals("")==true) //检查密码是否为空
Toast.makeText(DeletingPassword.this, "密码不能为空", if(text02.equals("")==true) {
Toast.LENGTH_SHORT).show(); Toast.makeText(DeletingPassword.this, "密码不能为空", Toast.LENGTH_SHORT).show();
return; //为空则直接返回不进行后续操作
}
//获取 SharedPreferences 中保存的密码
SharedPreferences pref=getSharedPreferences("user management",MODE_PRIVATE); SharedPreferences pref=getSharedPreferences("user management",MODE_PRIVATE);
String password = pref.getString("password",""); String password = pref.getString("password","");
//如果存储密码不为空,且与用户输入密码匹配
if(password.equals("")==false&&password.equals(text02)==true){ if(password.equals("")==false&&password.equals(text02)==true){
//获取 SharedPreferences 编辑器以删除密码
SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit(); SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit();
editor.putBoolean("user",false);//false 表示已经设置登录密码 editor.putBoolean("user",false);//false 表示登录密码已被设置
editor.putString("password",""); editor.putString("password",""); //清除密码
editor.apply(); editor.apply(); //应用更改
Toast.makeText(DeletingPassword.this, "已经删除登录密码", //显示已删除登录密码的提示信息
Toast.LENGTH_SHORT).show(); Toast.makeText(DeletingPassword.this, "已经删除登录密码", Toast.LENGTH_SHORT).show();
Intent intent=new //跳回便签列表界面
Intent(DeletingPassword.this,NotesListActivity.class); Intent intent=new Intent(DeletingPassword.this,NotesListActivity.class);
startActivity(intent); startActivity(intent);
finish(); finish(); //结束当前 Activity
} }
else{ else{
//如果输入的密码不正确,显示错误信息
Toast.makeText(DeletingPassword.this, "密码错误", Toast.makeText(DeletingPassword.this, "密码错误",
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
Dt_password.setText("");//把密码框内输入过的错误密码清空 Dt_password.setText("");//把密码框内输入过的错误密码清空
@ -53,6 +69,8 @@ public class DeletingPassword extends Activity {
} }
}); });
} }
//重写 onBackPressed 方法,用于用户按下返回键的行为
@Override @Override
public void onBackPressed() { public void onBackPressed() {
Intent intent=new Intent(DeletingPassword.this,NotesListActivity.class); Intent intent=new Intent(DeletingPassword.this,NotesListActivity.class);

@ -27,34 +27,39 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
//DropdownMenu类用来创建和显示一个下拉菜单
public class DropdownMenu { public class DropdownMenu {
private Button mButton; private Button mButton;//按钮成员变量,用于触发下拉菜单
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu;//弹出菜单的成员变量,用于显示菜单项
private Menu mMenu; private Menu mMenu;//菜单成员变量,包含了具体的菜单项
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;//将传入的按钮引用赋值给mButton
mButton.setBackgroundResource(R.drawable.dropdown_icon); mButton.setBackgroundResource(R.drawable.dropdown_icon);//设置这个按钮的背景为下拉图标
mPopupMenu = new PopupMenu(context, mButton); mPopupMenu = new PopupMenu(context, mButton);//初始化PopupMenu
mMenu = mPopupMenu.getMenu(); mMenu = mPopupMenu.getMenu();//获取PopupMenu关联的Menu对象
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); mPopupMenu.getMenuInflater().inflate(menuId, mMenu);//使用传入的menuId资源填充Menu
mButton.setOnClickListener(new OnClickListener() { mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mPopupMenu.show(); mPopupMenu.show();
} }//显示菜单
}); });
} }
//设置菜单项点击监听器
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
//查找具体的菜单项
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); return mMenu.findItem(id);
} }
//设置按钮的标题文字
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); mButton.setText(title);
} }

@ -24,57 +24,66 @@ import android.widget.CursorAdapter;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import net.micode.notes.R; import net.micode.notes.R;//引入资源文件
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;//引入与Notes相关的数据处理类
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;//引入NOte数据表中的字段
//FoldersListAdapter 类是CursorAdapter的一个子类用于提供文件夹数据的视图
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
//定义查询结果的列这里只用到ID和SNIPET列
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
//定义列的索引,方便读取数据时使用
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
//该类的构造函数
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
//必须重写的newView方法用于创建新的列表项视图
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); return new FolderListItem(context);//创建一个新的FoldersListItem实例
} }
//用于将数据绑定到视图上
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {//检查视图类型是否正确
//根据ID列判断是否根文件夹是则使用预定义字符串否则使用数据库中的名字
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName); ((FolderListItem) view).bind(folderName);//调用FolderListItem的bind方法绑定文件夹名称
} }
} }
//辅助方法,根据位置获取文件夹名称
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);//获取对应位置的游标
//同样根据ID列判断文件夹名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
//FolderListItem是LinearLayout的一个内部子类用于表示每一项文件夹
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
private TextView mName; private TextView mName;//文件夹名称的Textview
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);//调用父类构造函数
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);//填充布局
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name);//获取布局中的TextView
} }
public void bind(String name) { public void bind(String name) {
mName.setText(name); mName.setText(name);
} }//设置文件夹名称到Textview
} }
} }

@ -12,36 +12,52 @@ import android.app.Activity;
import net.micode.notes.R; import net.micode.notes.R;
//LoginActivity 类继承自Activity 类,用于管理登录页面的行为
public class LoginActivity extends Activity{ public class LoginActivity extends Activity{
//定义EditText 成员变量用于获取用户输入的密码
EditText lgn_password; EditText lgn_password;
//定义Button成员变量用于用户点击登录
Button lgn_login; Button lgn_login;
//Activity 的 onCreate()方法在创建loginActivity 时被调用
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//获取名为 "user management" 的 SharedPreferences 对象,用于读取或存储轻量级的键值对数据
SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE); SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE);
//从 SharedPreferences 对象中获取名为 "user" 的布尔值,检查用户是否设置了密码
boolean User_boolean = pref.getBoolean("user", false); //检查用户是否设置了密码 boolean User_boolean = pref.getBoolean("user", false); //检查用户是否设置了密码
if (!User_boolean) { //如果用户没有设置密码,则直接跳转到便签主界面 if (!User_boolean) { //如果用户没有设置密码,则直接跳转到便签主界面
Intent intent = new Intent(LoginActivity.this, NotesListActivity.class); Intent intent = new Intent(LoginActivity.this, NotesListActivity.class);
startActivity(intent); startActivity(intent);
finish(); finish(); //结束当前 Activity
} }
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_login); setContentView(R.layout.activity_login);
//设置软键盘行为,这里设置的是在输入框获取焦点时显示软键盘并调整布局大小以适应键盘
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//关联变量 lgn_password 至布局文件中的 EditText 组件
lgn_password = (EditText)findViewById(R.id.lgn_password); lgn_password = (EditText)findViewById(R.id.lgn_password);
//关联变量lgn_login 至布局文件中的 Button 组件
lgn_login = (Button) findViewById(R.id.login); lgn_login = (Button) findViewById(R.id.login);
//设置登录按钮的点击监听器
lgn_login.setOnClickListener(new View.OnClickListener() { lgn_login.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
//再次或者SharedPreferences 对象
SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE); SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE);
//获取 SharedPreferences 中存储的密码字符串,若不存在则返回空字符串
String password = pref.getString("password", ""); String password = pref.getString("password", "");
//比较存储的密码和用户输入的密码是否相同
if (password.equals(" ") == false && password.equals(lgn_password.getText().toString()) == true) { if (password.equals(" ") == false && password.equals(lgn_password.getText().toString()) == true) {
//如果密码匹配,跳转至便签列表界面
Intent intent = new Intent(LoginActivity.this, NotesListActivity.class); Intent intent = new Intent(LoginActivity.this, NotesListActivity.class);
startActivity(intent); startActivity(intent);
finish(); finish(); //结束当前 Activity
} else { } else {
//如果密码不匹配,显示 Toast 提醒用户密码错误,并清空密码输入框
Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show(); Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
lgn_password.setText(""); //清空密码框内的输入 lgn_password.setText(""); //清空密码框内的输入
} }

@ -78,7 +78,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder { private class HeadViewHolder {
public TextView tvModified; // public TextView tvModified;
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
@ -498,12 +498,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
//如果点击的是设置背景颜色按钮,则显示颜色选择器 //如果点击的是设置背景颜色按钮,则显示颜色选择器
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.VISIBLE);
-View.VISIBLE);
//更改背景颜色或字体大小的逻辑 //更改背景颜色或字体大小的逻辑
} else if (sBgSelectorBtnsMap.containsKey(id)) { } else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.GONE);
View.GONE);
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
} else if (sFontSizeBtnsMap.containsKey(id)) { } else if (sFontSizeBtnsMap.containsKey(id)) {
@ -1013,17 +1011,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
final ImageButton add_img_btn = (ImageButton) findViewById(R.id.add_img_btn); // final ImageButton add_img_btn = (ImageButton) findViewById(R.id.add_img_btn);
add_img_btn.setOnClickListener(new View.OnClickListener() { // add_img_btn.setOnClickListener(new View.OnClickListener() {
@Override // @Override
public void onClick(View view) { // public void onClick(View view) {
log.d(TAG, "onClick: click add image button"); // log.d(TAG, "onClick: click add image button");
Intent loadImage = new Intent(Intent.ACTION_GET_CONTENT); // Intent loadImage = new Intent(Intent.ACTION_GET_CONTENT);
loadImage.addCategory(Intent.CATEGORY_OPENABLE); // loadImage.addCategory(Intent.CATEGORY_OPENABLE);
loadImage.setType("image/*"); // loadImage.setType("image/*");
startActivityForResult(loadImage, PHOTO_REQUESt); // startActivityForResult(loadImage, PHOTO_REQUESt);
} // }
}); // });
} }

@ -25,8 +25,9 @@ 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;
//NoteItemData 类的定义,用于封装便签应用中的便签项的数据。
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,
@ -42,6 +43,7 @@ public class NoteItemData {
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;
@ -55,28 +57,31 @@ public class NoteItemData {
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 mAlertDate; private long mId; //笔记项ID
private int mBgColorId; private long mAlertDate; //提醒日期
private long mCreatedDate; private int mBgColorId; //背景颜色ID
private boolean mHasAttachment; private long mCreatedDate; //创建日期
private long mModifiedDate; private boolean mHasAttachment; //是否有附件
private int mNotesCount; private long mModifiedDate; //修改日期
private long mParentId; private int mNotesCount; //子项个数
private String mSnippet; private long mParentId; //父项Id
private int mType; private String mSnippet; //笔记摘要
private int mWidgetId; private int mType; //笔记类型
private int mWidgetType; private int mWidgetId; //小工具ID
private String mName; private int mWidgetType; //小工具类型
private String mPhoneNumber; private String mName; //联系人名称
private String mPhoneNumber; //联系人电话
private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsLastItem; //是否为最后一项
private boolean mIsOnlyOneItem; private boolean mIsFirstItem; //是否为第一项
private boolean mIsOneNoteFollowingFolder; private boolean mIsOnlyOneItem; //是否只有一项
private boolean mIsMultiNotesFollowingFolder; private boolean mIsOneNoteFollowingFolder; //是否仅有一个笔记跟随文件夹
private boolean mIsMultiNotesFollowingFolder; //是否有多个笔记跟随文件夹
//构造器从提供的有表数据创建NoteItemData 对象
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);
@ -94,6 +99,7 @@ public class NoteItemData {
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);
@ -106,9 +112,11 @@ public class NoteItemData {
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
//调用该方法来判断笔记项在游标中的位置
checkPostion(cursor); checkPostion(cursor);
} }
//判断当前位于游标中的位置情况,如是否是第一个,最后一个等,并相应地设置布尔标记位
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
@ -116,6 +124,7 @@ public class NoteItemData {
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()) {
@ -128,12 +137,14 @@ public class NoteItemData {
} }
} }
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");
} }
} }
} }
} }
//为了获取NoteItemData对象内容的公共访问方法
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
@ -218,6 +229,7 @@ public class NoteItemData {
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);
} }

@ -795,6 +795,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
createNewNote(); createNewNote();
} else if (itemId == R.id.menu_search) { } else if (itemId == R.id.menu_search) {
onSearchRequested(); onSearchRequested();
} else if (itemId == R.id.menu_weather) {
startWeatherActivity();
} }
return true; return true;
} }
@ -857,6 +859,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
private void startWeatherActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, WeatherActivity.class);
from.startActivity(intent);
}
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) {

@ -30,19 +30,22 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
//NoteListAdapter 类用于将数据从Cursor绑定到ListView的每个项
//定义了列表适配器的主要功能,如创建新视图进行绑定、处理项的选择状态、统计选中的项数等
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";//用于日志记录的TAG
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;//是否选择模式
//AppEidgetAttribute 是一个静态内部类,用于存储小部件属性
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>();
@ -50,38 +53,47 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0; mNotesCount = 0;
} }
//为给定数据创建新的ListsItem视图
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
//将数据绑定到给定的视图上
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
//创建一个NoteItemData对象用于从Cursor提取数据
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()));
} }
} }
//设置指定位置的项是否被选中
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
notifyDataSetChanged(); notifyDataSetChanged();
} }
//返回是否处于选择模式
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
//设置选择模式
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
//选择或取消选择所有便签项
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
//仅选择便签类型的项
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked); setCheckedItem(i, checked);
} }
@ -89,8 +101,10 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
//获取选中项的ID集合
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
//遍历mSelectedIndex查找选中的项目
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);
@ -105,8 +119,10 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
//获取选中的小部件集合
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
//同样遍历选中的项但是这一次获取widgetId和widgetType
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);
@ -128,6 +144,7 @@ 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) {
@ -143,11 +160,13 @@ public class NotesListAdapter extends CursorAdapter {
return count; return count;
} }
//检查是否所有项都被选中了
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
} }
//检查指定位置的项是否被转中
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -155,18 +174,21 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position); return mSelectedIndex.get(position);
} }
//当内容改变时更新便签数量
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount();
} }
//更改cursor时同样更新便签数量
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount();
} }
//计算便签的数量,只计算类型为便签的项
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {

@ -29,18 +29,21 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
//定义NotesListItem 类扩展了LinearLayout 类,用于表示一个笔记的布局
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert; //用于显示警告图标
private TextView mTitle; private TextView mTitle; //显示笔记标题
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);
//从布局文件 note_item.xml中加载布局
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);
//通过findViewById 方法获取对应的控件对象
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);
@ -48,7 +51,9 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
//绑定数据到当前的笔记项,设置显示内容和样式
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);
@ -56,8 +61,11 @@ public class NotesListItem extends LinearLayout {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE);
} }
//保存数据到成员变量中
mItemData = data; mItemData = data;
//根据笔记的类型分别设置不同的显示方式
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
//如果是通话记录文件夹
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
@ -65,6 +73,7 @@ public class NotesListItem extends LinearLayout {
+ 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);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
//如果笔记是通话记录文件夹中的一项
mCallName.setVisibility(View.VISIBLE); mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName()); mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
@ -76,15 +85,18 @@ public class NotesListItem extends LinearLayout {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} else { } else {
//如果笔记既不是通话记录也不是通话记录文件夹中的一项
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
//如果笔记为文件夹类型
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
data.getNotesCount())); data.getNotesCount()));
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} 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);
@ -94,13 +106,17 @@ public class NotesListItem extends LinearLayout {
} }
} }
} }
//设置显示笔记最后修改时间,格式化为相对时间(如"5分钟前")
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
//根据数据设置背景图案
setBackground(data); setBackground(data);
} }
//设置背景图案的私有方法
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
//根据笔记类型和位置(身处列表中的位置),选择不同的背景
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
@ -112,10 +128,12 @@ public class NotesListItem extends LinearLayout {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { } else {
//如果是文件夹,则使用文件夹的背景资源
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
//获取当前笔记项的数据
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -49,6 +49,7 @@ import net.micode.notes.gtask.remote.GTaskSyncService;
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";
@ -61,29 +62,33 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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;
//存储原始的Google账号数组用于比较之后是否有变化
private Account[] mOriAccounts; private Account[] mOriAccounts;
//标志变量,记录是否添加了新账户
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ //启用向上导航使用应用程序图标
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
//从Preferences.xml资源文件添加偏好设置项到这个活动
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
//通过键找到偏好设置分类,准备后续添加账户选项
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
//实例化广播接收器并注册,以便再同步服务发送广播时接收
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
//初始化账户数组为null
mOriAccounts = null; mOriAccounts = null;
//为设置列表添加表头View
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
@ -92,8 +97,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new //用户添加了新账户,自动设置同步账户
// account //通过比较原始账号和当前账户,确定新账户,并设置同步
if (mHasAddedAccount) { if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -112,12 +117,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
} }
//刷新UI界面可能涉及到帐号显示的更新
refreshUI(); refreshUI();
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
//注销广播接收器
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
} }
@ -125,8 +131,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
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));
@ -154,117 +162,150 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
//用于初始化并设置同步按钮的状态和功能的私有方法
private void loadSyncButton() { private void loadSyncButton() {
// 通过 ID 查找同步按钮,它是一个 Button 对象
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
// 通过 ID 查找表示上次同步时间的 TextView 对象
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state //检查是否当前正在同步中,根据同步状态来设置按钮的文本和点击事件
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
// 如果正在同步,设置按钮文本为“取消同步”并添加取消同步的点击事件
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
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() {
public void onClick(View v) { public void onClick(View v) {
//当按钮被点击时,启动同步
GTaskSyncService.startSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
} }
// 设置按钮的可用性,如果没有设置同步账户名称则按钮不可用
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // 根据同步情况设置同步状态文本和其可见性
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
//如果正在同步,展示当前同步进度
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
} 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);
//获取当前设备上的 Google 账户列表
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;
int index = 0; int index = 0;
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) {
// 当用户选择一个账户时设置该账户为同步账户并刷新UI
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;
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"
}); });
// 启动活动,请求码设置为-1可能表示这个启动是特殊的或者不需要处理返回结果
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),
@ -272,100 +313,138 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}; };
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 当用户在列表中选择选项时,根据选择执行相应操作
if (which == 0) { if (which == 0) {
// 如果选择“更改账户”,显示选择账户的对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
//如果选择“移除账户”移除同步账户并刷新UI
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
// 没有必要处理取消选项,因为点击会自动关闭对话框
} }
}); });
// 显示对话框
dialogBuilder.show(); dialogBuilder.show();
} }
// 获取设备中所有Google账户的数组
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
// 通过AccountManager获取账户管理实例
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
//调用getAccountsByType方法获取类型为"com.google"的所有账户即Google账户
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的实例来存储偏好设置
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
//创建一个SharedPreferences.Editor进行编辑
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
//如果传入账号不是null将其存储到SharedPreferences
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
// 如果是null则存储空字符串""
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
// 将更改提交到SharedPreferences
editor.commit(); editor.commit();
// clean up last sync time // 将最后同步时间设置为0清空
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // 在新线程中清空与同步相关的本地信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
//创建ContentValues以存储需要更新的值
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.SYNC_ID, 0); // 设置SYNC_ID为0
// 调用ContentResolver以更新数据库中的信息
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
// 显示提示信息,告知用户同步账号设置成功
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
} }
// 移除同步账号
private void removeSyncAccount() { private void removeSyncAccount() {
// 获取SharedPreferences的实例来存储偏好设置
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
// 创建一个SharedPreferences.Editor进行编辑
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);
} }
// 将更改提交到SharedPreferences
editor.commit(); editor.commit();
// clean up local gtask related info // 在新线程中清空与同步相关的本地信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
// 创建ContentValues以存储需要更新的值
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.SYNC_ID, 0); // 设置SYNC_ID为0
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的实例来存储偏好设置
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的实例来存储偏好设置
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
// 创建一个SharedPreferences.Editor进行编辑
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
// 将同步时间设置为传入的time
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
// 将更改提交到SharedPreferences
editor.commit(); editor.commit();
} }
// 获取最后同步时间
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
// 获取SharedPreferences的实例来存储偏好设置
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
// 返回存储的最后同步时间如果没有则返回0
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
// 内部类,广播接收器,用于接收同步状态变更的广播
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 刷新界面显示
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
// 找到同步状态的TextView并设置显示文本
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); 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));
@ -374,9 +453,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 处理选项菜单的项被选择的事件
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// 根据菜单项的ID进行不同的操作
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
// 如果是home项创建意图启动NotesListActivity
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);

@ -14,38 +14,52 @@ import android.widget.Toast;
import net.micode.notes.R; import net.micode.notes.R;
//继承自 Activity 类,用于管理设置密码的页面行为
public class SettingPassword extends Activity { public class SettingPassword extends Activity {
//定义两个 EditText 成员变量用于获取用户输入的密码以及确认密码
EditText password; EditText password;
EditText password_ack; EditText password_ack;
//定义 Button 成员变量用于用户完成密码输入时点击确认
Button acknowledge; Button acknowledge;
//Activity 的 onCreate()方法,创建 SettingPassword时被调用
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_set_loginpassword); setContentView(R.layout.activity_set_loginpassword);
//设置软键盘的行为
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//关联至 EditText 组件(用于输入密码)
password = (EditText) findViewById(R.id.password); password = (EditText) findViewById(R.id.password);
//关联至 EditText 组件(用于确认密码)
password_ack = (EditText) findViewById(R.id.password_ack); password_ack = (EditText) findViewById(R.id.password_ack);
//关联 acknowledge 至Button 组件(确认按钮)
acknowledge = (Button)findViewById(R.id.acknowledge); acknowledge = (Button)findViewById(R.id.acknowledge);
//设置确认按钮的监听器
acknowledge.setOnClickListener(new View.OnClickListener() { acknowledge.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
//获取用户输入的密码和确认密码
String text02 = password.getText().toString(); String text02 = password.getText().toString();
String text03 = password_ack.getText().toString(); String text03 = password_ack.getText().toString();
//检查密码是否为空
if(text02.equals("")==true) { if(text02.equals("")==true) {
Toast.makeText(SettingPassword.this, "密码不能为空", Toast.LENGTH_SHORT).show(); Toast.makeText(SettingPassword.this, "密码不能为空", Toast.LENGTH_SHORT).show();
} }
//检查输入的密码和确认密码是否相同
else if (text02.equals(text03) == false) { else if (text02.equals(text03) == false) {
Toast.makeText(SettingPassword.this, "密码错误,请重新输入密码 ", Toast.LENGTH_SHORT).show(); Toast.makeText(SettingPassword.this, "密码错误,请重新输入密码 ", Toast.LENGTH_SHORT).show();
password_ack.setText(""); password_ack.setText(""); //不同则清空确认密码框
} }
//若输入的密码和确认密码相同
else if (text02.equals(text03) == true){ else if (text02.equals(text03) == true){
SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit(); SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit();
editor.putBoolean("user",true); //true 表示已经设置登录密码 editor.putBoolean("user",true); //true 表示已经设置登录密码
editor.putString("password",text02); editor.putString("password",text02); //保存密码
editor.apply(); editor.apply(); //应用更改
Log.d("RegisterLoginPassword","password is "+text02); Log.d("RegisterLoginPassword","password is "+text02);
Toast.makeText(SettingPassword.this, "密码设置成功", Toast.makeText(SettingPassword.this, "密码设置成功",
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
@ -57,8 +71,11 @@ public class SettingPassword extends Activity {
} }
}); });
} }
//重写 onBackPressed 方法,用于在按下返回键时的操作
@Override @Override
public void onBackPressed() { public void onBackPressed() {
//创建跳转到便签列表界面的 Intent
Intent intent=new Intent(SettingPassword.this,NotesListActivity.class); Intent intent=new Intent(SettingPassword.this,NotesListActivity.class);
startActivity(intent); startActivity(intent);
finish(); finish();

@ -0,0 +1,127 @@
package net.micode.notes.ui;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import net.micode.notes.R;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
public class WeatherActivity extends Activity
{
private String responseData;
private TextView temperature; // 声明为成员变量
private TextView location;
private TextView wea;
private TextView date;
private TextView humidity;
private TextView win;
private TextView pressure;
private TextView pm25;
private TextView airlevel; // 声明为成员变量
OkHttpClient client = new OkHttpClient();//新建一个OkHttpClient对象
//api地址http://tianqiapi.com/index/doc?version=day
//注册后获取参数拼接在url上
private static String weatherUrl = "https://v1.yiketianqi.com/free/day?appid=94339557&version=v61&appsecret=9bIWWwDL&unescape=1";
@SuppressLint("StaticFieldLeak")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_weather);
temperature = this.findViewById(R.id.temperature_tv);
location = this.findViewById(R.id.location_tv);
wea= this.findViewById(R.id.weather_tv);
date= this.findViewById(R.id.date_tv);
humidity= this.findViewById(R.id.humidity_tv);
win= this.findViewById(R.id.win_tv);
pressure= this.findViewById(R.id.pressure_tv);
pm25= this.findViewById(R.id.pm2_5_tv);
airlevel= this.findViewById(R.id.airlevel_tv);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(weatherUrl)
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
Log.d("NetworkData", responseData);
return responseData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String responseData) {
// if (responseData != null) {
// Gson gson = new Gson();
// HashMap map = gson.fromJson(responseData, HashMap.class);
// temperature.setText("温度:"+(CharSequence) map.get("tem"));
// location.setText("城市:"+(CharSequence) map.get("city"));
// wea.setText("天气:"+map.get("wea").toString());
// date.setText("日期:"+map.get("date").toString());
// humidity.setText("湿度:"+map.get("humidity").toString());
// win.setText("风向:"+map.get("win").toString());
// pressure.setText("气压:"+map.get("pressure").toString());
// pm25.setText("PM2.5"+map.get("air_pm25").toString());
// airlevel.setText("空气等级:"+map.get("air_level").toString());
// }
if (responseData != null) {
Gson gson = new Gson();
HashMap map = gson.fromJson(responseData, HashMap.class);
// 在此之后,检查 map 中每个键对应的值是否为 null
if (map.get("tem") != null) {
temperature.setText("温度: " + map.get("tem").toString());
}
if (map.get("city") != null) {
location.setText("城市: " + map.get("city").toString());
}
// 对其他字段也做相同的检查
if (map.get("wea") != null) {
wea.setText("天气: " + map.get("wea").toString());
}
if (map.get("date") != null) {
date.setText("日期: " + map.get("date").toString());
}
if (map.get("humidity") != null) {
humidity.setText("湿度: " + map.get("humidity").toString());
}
if (map.get("win") != null) {
win.setText("风向: " + map.get("win").toString());
}
if (map.get("pressure") != null) {
pressure.setText("气压: " + map.get("pressure").toString());
}
if (map.get("air_pm25") != null) {
pm25.setText("PM2.5 " + map.get("air_pm25").toString());
}
if (map.get("air_level") != null) {
airlevel.setText("空气等级: " + map.get("air_level").toString());
}
}
}
}.execute();
}
}

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/location_tv"
android:layout_width="114dp"
android:layout_height="45dp"
android:text="武汉" />
<TextView
android:id="@+id/date_tv"
android:layout_width="114dp"
android:layout_height="46dp"
android:text="日期"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/temperature_tv"
android:layout_width="114dp"
android:layout_height="46dp"
android:text="0"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/weather_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="天气"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/humidity_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="湿度"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/win_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="风向"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/pressure_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="气压"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/pm2.5_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="pm2.5"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/airlevel_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="空气等级"
android:textColor="#FF6200EE" />
</LinearLayout>

@ -45,7 +45,8 @@
android:cacheColorHint="@null" android:cacheColorHint="@null"
android:listSelector="@android:color/transparent" android:listSelector="@android:color/transparent"
android:divider="@null" android:divider="@null"
android:fadingEdge="@null" /> android:fadingEdge="@null"/>
</LinearLayout> </LinearLayout>
<Button <Button

@ -36,4 +36,9 @@
<item <item
android:id="@+id/menu_search" android:id="@+id/menu_search"
android:title="@string/menu_search"/> android:title="@string/menu_search"/>
<item
android:id="@+id/menu_weather"
android:title="查询天气"/>
</menu> </menu>

Loading…
Cancel
Save