diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..1b24acb 100644 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java @@ -17,103 +17,79 @@ package net.micode.notes.gtask.remote; import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; +import android.app.Service; import android.content.Context; -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.data.MetaData; -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.SqlNote; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - - +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; public class GTaskManager { private static final String TAG = GTaskManager.class.getSimpleName(); - public static final int STATE_SUCCESS = 0; - public static final int STATE_NETWORK_ERROR = 1; - public static final int STATE_INTERNAL_ERROR = 2; - public static final int STATE_SYNC_IN_PROGRESS = 3; - public static final int STATE_SYNC_CANCELLED = 4; - private static GTaskManager mInstance = null; private Activity mActivity; - private Context mContext; - private ContentResolver mContentResolver; - private boolean mSyncing; - private boolean mCancelled; - private HashMap mGTaskListHashMap; - private HashMap mGTaskHashMap; - private HashMap mMetaHashMap; - private TaskList mMetaList; - private HashSet mLocalDeleteIdMap; - private HashMap mGidToNid; - private HashMap mNidToGid; - private GTaskManager() { - mSyncing = false; - mCancelled = false; - mGTaskListHashMap = new HashMap(); + private GTaskManager() { //对象初始化函数 + mSyncing = false; //正在同步,flase代表未执行 + mCancelled = false; //全局标识,flase代表可以执行 + mGTaskListHashMap = new HashMap(); //<>代表Java的泛型,就是创建一个用类型作为参数的类。 mGTaskHashMap = new HashMap(); mMetaHashMap = new HashMap(); mMetaList = null; mLocalDeleteIdMap = new HashSet(); - mGidToNid = new HashMap(); - mNidToGid = new HashMap(); + mGidToNid = new HashMap(); //GoogleID to NodeID?? + mNidToGid = new HashMap(); //NodeID to GoogleID???通过hashmap散列表建立映射 } - public static synchronized GTaskManager getInstance() { + /** + * 包含关键字synchronized,语言级同步,指明该函数可能运行在多线程的环境下。 + * 功能:类初始化函数 + * @author TTS + * @return GtaskManger + */ + public static synchronized GTaskManager getInstance() { //可能运行在多线程环境下,使用语言级同步--synchronized if (mInstance == null) { mInstance = new GTaskManager(); } return mInstance; } + /** + * 包含关键字synchronized,语言级同步,指明该函数可能运行在多线程的环境下。 + * @author TTS + * @param activity + */ public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken + // used for getting auth token mActivity = activity; } - public int sync(Context context, GTaskASyncTask asyncTask) { + /** + * 核心函数 + * 功能:实现了本地同步操作和远端同步操作 + * @author TTS + * @param context-----获取上下文 + * @param asyncTask-------用于同步的异步操作类 + * @return int + */ + public int sync(Context context, GTaskASyncTask asyncTask) { //核心函数 if (mSyncing) { - Log.d(TAG, "Sync is in progress"); + Log.d(TAG, "Sync is in progress"); //创建日志文件(调试信息),debug return STATE_SYNC_IN_PROGRESS; } mContext = context; @@ -128,8 +104,8 @@ public class GTaskManager { mNidToGid.clear(); try { - GTaskClient client = GTaskClient.getInstance(); - client.resetUpdateArray(); + GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例,client--客户机 + client.resetUpdateArray(); //JSONArray类型,reset即置为NULL // login google task if (!mCancelled) { @@ -140,15 +116,15 @@ public class GTaskManager { // get the task list from google asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - initGTaskList(); + initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList // do content sync work asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); syncContent(); - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); + } catch (NetworkFailureException e) { //分为两种异常,此类异常为网络异常 + Log.e(TAG, e.toString()); //创建日志文件(调试信息),error return STATE_NETWORK_ERROR; - } catch (ActionFailureException e) { + } catch (ActionFailureException e) { //此类异常为操作异常 Log.e(TAG, e.toString()); return STATE_INTERNAL_ERROR; } catch (Exception e) { @@ -168,32 +144,41 @@ public class GTaskManager { return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + /** + *功能:初始化GtaskList,获取Google上的JSONtasklist转为本地TaskList。 + *获得的数据存储在mMetaList,mGTaskListHashMap,mGTaskHashMap + *@author TTS + *@exception NetworkFailureException + *@return void + */ private void initGTaskList() throws NetworkFailureException { if (mCancelled) return; - GTaskClient client = GTaskClient.getInstance(); + GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例,client应指远端客户机 try { - JSONArray jsTaskLists = client.getTaskLists(); + //Json对象是Name Value对(即子元素)的无序集合,相当于一个Map对象。JsonObject类是bantouyan-json库对Json对象的抽象,提供操纵Json对象的各种方法。 + //其格式为{"key1":value1,"key2",value2....};key 必须是字符串。 + //因为ajax请求不刷新页面,但配合js可以实现局部刷新,因此json常常被用来作为异步请求的返回对象使用。 + JSONArray jsTaskLists = client.getTaskLists(); //原注释为get task list------lists??? // init meta list first - mMetaList = null; + mMetaList = null; //TaskList类型 for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); + JSONObject object = jsTaskLists.getJSONObject(i); //JSONObject与JSONArray一个为对象,一个为数组。此处取出单个JASONObject String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { - mMetaList = new TaskList(); - mMetaList.setContentByRemoteJSON(object); + if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + mMetaList = new TaskList(); //MetaList意为元表,Tasklist类型,此处为初始化 + mMetaList.setContentByRemoteJSON(object); //将JSON中部分数据复制到自己定义的对象中相对应的数据:name->mname... // load meta data - JSONArray jsMetas = client.getTaskList(gid); + JSONArray jsMetas = client.getTaskList(gid); //原注释为get action_list------list??? for (int j = 0; j < jsMetas.length(); j++) { object = (JSONObject) jsMetas.getJSONObject(j); - MetaData metaData = new MetaData(); + MetaData metaData = new MetaData(); //继承自Node metaData.setContentByRemoteJSON(object); - if (metaData.isWorthSaving()) { + if (metaData.isWorthSaving()) { //if not worth to save,metadata将不加入mMetaList mMetaList.addChildTask(metaData); if (metaData.getGid() != null) { mMetaHashMap.put(metaData.getRelatedGid(), metaData); @@ -214,16 +199,16 @@ public class GTaskManager { // init task list for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); //通过getString函数传入本地某个标志数据的名称,获取其在远端的名称。 String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - TaskList tasklist = new TaskList(); + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList(); //继承自Node tasklist.setContentByRemoteJSON(object); mGTaskListHashMap.put(gid, tasklist); - mGTaskHashMap.put(gid, tasklist); + mGTaskHashMap.put(gid, tasklist); //为什么加两遍??? // load tasks JSONArray jsTasks = client.getTaskList(gid); @@ -247,13 +232,18 @@ public class GTaskManager { } } - private void syncContent() throws NetworkFailureException { + /** + * 功能:本地内容同步操作 + * @throws NetworkFailureException + * @return 无返回值 + */ + private void syncContent() throws NetworkFailureException { //本地内容同步操作 int syncType; - Cursor c = null; - String gid; - Node node; + Cursor c = null; //数据库指针 + String gid; //GoogleID?? + Node node; //Node包含Sync_Action的不同类型 - mLocalDeleteIdMap.clear(); + mLocalDeleteIdMap.clear(); //HashSet类型 if (mCancelled) { return; @@ -301,8 +291,8 @@ public class GTaskManager { node = mGTaskHashMap.get(gid); if (node != null) { mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); //通过hashmap建立联系 + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); //通过hashmap建立联系 syncType = node.getSyncAction(c); } else { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { @@ -327,14 +317,14 @@ public class GTaskManager { } // go through remaining items - Iterator> iter = mGTaskHashMap.entrySet().iterator(); + Iterator> iter = mGTaskHashMap.entrySet().iterator(); //Iterator迭代器 while (iter.hasNext()) { Map.Entry entry = iter.next(); node = entry.getValue(); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); } - // mCancelled can be set by another thread, so we neet to check one by + // mCancelled can be set by another thread, so we neet to check one by //thread----线程 // one // clear local delete table if (!mCancelled) { @@ -351,6 +341,11 @@ public class GTaskManager { } + /** + * 功能: + * @author TTS + * @throws NetworkFailureException + */ private void syncFolder() throws NetworkFailureException { Cursor c = null; String gid; @@ -394,7 +389,7 @@ public class GTaskManager { try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) }, null); if (c != null) { if (c.moveToNext()) { @@ -476,6 +471,14 @@ public class GTaskManager { GTaskClient.getInstance().commitUpdate(); } + /** + * 功能:syncType分类,addLocalNode,addRemoteNode,deleteNode,updateLocalNode,updateRemoteNode + * @author TTS + * @param syncType + * @param node + * @param c + * @throws NetworkFailureException + */ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -522,6 +525,12 @@ public class GTaskManager { } } + /** + * 功能:本地增加Node + * @author TTS + * @param node + * @throws NetworkFailureException + */ private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return; @@ -596,6 +605,15 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 功能:update本地node + * @author TTS + * @param node + * ----同步操作的基础数据类型 + * @param c + * ----Cursor + * @throws NetworkFailureException + */ private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -619,12 +637,22 @@ public class GTaskManager { updateRemoteMeta(node.getGid(), sqlNote); } + /** + * 功能:远程增加Node + * 需要updateRemoteMeta + * @author TTS + * @param node + * ----同步操作的基础数据类型 + * @param c + * --Cursor + * @throws NetworkFailureException + */ private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; } - SqlNote sqlNote = new SqlNote(mContext, c); + SqlNote sqlNote = new SqlNote(mContext, c); //从本地mContext中获取内容 Node n; // update remotely @@ -634,11 +662,12 @@ public class GTaskManager { String parentGid = mNidToGid.get(sqlNote.getParentId()); if (parentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); + Log.e(TAG, "cannot find task's parent tasklist"); //调试信息 throw new ActionFailureException("cannot add remote task"); } - mGTaskListHashMap.get(parentGid).addChildTask(task); + mGTaskListHashMap.get(parentGid).addChildTask(task); //在本地生成的GTaskList中增加子结点 + //登录远程服务器,创建Task GTaskClient.getInstance().createTask(task); n = (Node) task; @@ -656,6 +685,7 @@ public class GTaskManager { else folderName += sqlNote.getSnippet(); + //iterator迭代器,通过统一的接口迭代所有的map元素 Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -687,11 +717,20 @@ public class GTaskManager { sqlNote.resetLocalModified(); sqlNote.commit(true); - // gid-id mapping + // gid-id mapping //创建id间的映射 mGidToNid.put(n.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), n.getGid()); } + /** + * 功能:更新远端的Node,包含meta更新(updateRemoteMeta) + * @author TTS + * @param node + * ----同步操作的基础数据类型 + * @param c + * --Cursor + * @throws NetworkFailureException + */ private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { if (mCancelled) { return; @@ -701,7 +740,7 @@ public class GTaskManager { // update remotely node.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(node); + GTaskClient.getInstance().addUpdateNode(node); //GTaskClient用途为从本地登陆远端服务器 // update meta updateRemoteMeta(node.getGid(), sqlNote); @@ -710,15 +749,19 @@ public class GTaskManager { if (sqlNote.isNoteType()) { Task task = (Task) node; TaskList preParentList = task.getParent(); + //preParentList为通过node获取的父节点列表 String curParentGid = mNidToGid.get(sqlNote.getParentId()); + //curParentGid为通过光标在数据库中找到sqlNote的mParentId,再通过mNidToGid由long类型转为String类型的Gid + if (curParentGid == null) { Log.e(TAG, "cannot find task's parent tasklist"); throw new ActionFailureException("cannot update remote task"); } TaskList curParentList = mGTaskListHashMap.get(curParentGid); + //通过HashMap找到对应Gid的TaskList - if (preParentList != curParentList) { + if (preParentList != curParentList) { //????????????? preParentList.removeChildTask(task); curParentList.addChildTask(task); GTaskClient.getInstance().moveTask(task, preParentList, curParentList); @@ -727,9 +770,19 @@ public class GTaskManager { // clear local modified flag sqlNote.resetLocalModified(); + //commit到本地数据库 sqlNote.commit(true); } + /** + * 功能:升级远程meta。 meta---元数据----计算机文件系统管理数据---管理数据的数据。 + * @author TTS + * @param gid + * ---GoogleID为String类型 + * @param sqlNote + * ---同步前的数据库操作,故使用类SqlNote + * @throws NetworkFailureException + */ private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { if (sqlNote != null && sqlNote.isNoteType()) { MetaData metaData = mMetaHashMap.get(gid); @@ -746,12 +799,18 @@ public class GTaskManager { } } + /** + * 功能:刷新本地,给sync的ID对应上最后更改过的对象 + * @author TTS + * @return void + * @throws NetworkFailureException + */ private void refreshLocalSyncId() throws NetworkFailureException { if (mCancelled) { return; } - // get the latest gtask list + // get the latest gtask list //获取最近的(最晚的)gtask list mGTaskHashMap.clear(); mGTaskListHashMap.clear(); mMetaHashMap.clear(); @@ -762,16 +821,16 @@ public class GTaskManager { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(type<>? AND parent_id<>?)", new String[] { String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); + }, NoteColumns.TYPE + " DESC"); //query语句:五个参数,NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。new String[] {String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)}------为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE--------应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri if (c != null) { while (c.moveToNext()) { String gid = c.getString(SqlNote.GTASK_ID_COLUMN); Node node = mGTaskHashMap.get(gid); if (node != null) { mGTaskHashMap.remove(gid); - ContentValues values = new ContentValues(); + ContentValues values = new ContentValues(); //在ContentValues中创建键值对。准备通过contentResolver写入数据 values.put(NoteColumns.SYNC_ID, node.getLastModified()); - mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, //进行批量更改,选择参数为NULL,应该可以用insert替换,参数分别为表名和需要更新的value对象。 c.getLong(SqlNote.ID_COLUMN)), values, null, null); } else { Log.e(TAG, "something is missed"); @@ -790,11 +849,20 @@ public class GTaskManager { } } + /** + * 功能:获取同步账号,mAccount.name + * @author TTS + * @return String + */ public String getSyncAccount() { return GTaskClient.getInstance().getSyncAccount().name; } + /** + * 功能:取消同步,置mCancelled为true + * @author TTS + */ public void cancelSync() { mCancelled = true; } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..882b059 100644 --- a/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -23,6 +23,24 @@ import android.content.Intent; import android.os.Bundle; import android.os.IBinder; +package net.micode.notes.gtask.remote; + +/* + * Service是在一段不定的时间运行在后台,不和用户交互的应用组件 + * 主要方法: + * private void startSync() 启动一个同步工作 + * private void cancelSync() 取消同步 + * public void onCreate() + * public int onStartCommand(Intent intent, int flags, int startId) service生命周期的组成部分,相当于重启service(比如在被暂停之后),而不是创建一个新的service + * public void onLowMemory() 在没有内存的情况下如果存在service则结束掉这的service + * public IBinder onBind() + * public void sendBroadcast(String msg) 发送同步的相关通知 + * public static void startSync(Activity activity) + * public static void cancelSync(Context context) + * public static boolean isSyncing() 判读是否在进行同步 + * public static String getProgressString() 获取当前进度的信息 + */ + public class GTaskSyncService extends Service { public final static String ACTION_STRING_NAME = "sync_action_type"; @@ -42,6 +60,7 @@ public class GTaskSyncService extends Service { private static String mSyncProgress = ""; + //开始一个同步的工作 private void startSync() { if (mSyncTask == null) { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { @@ -52,10 +71,11 @@ public class GTaskSyncService extends Service { } }); sendBroadcast(""); - mSyncTask.execute(); + mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行 } } + private void cancelSync() { if (mSyncTask != null) { mSyncTask.cancelSync(); @@ -63,7 +83,7 @@ public class GTaskSyncService extends Service { } @Override - public void onCreate() { + public void onCreate() { //初始化一个service mSyncTask = null; } @@ -72,6 +92,7 @@ public class GTaskSyncService extends Service { Bundle bundle = intent.getExtras(); if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + //两种情况,开始同步或者取消同步 case ACTION_START_SYNC: startSync(); break; @@ -81,7 +102,7 @@ public class GTaskSyncService extends Service { default: break; } - return START_STICKY; + return START_STICKY; //等待新的intent来是这个service继续运行 } return super.onStartCommand(intent, flags, startId); } @@ -93,26 +114,26 @@ public class GTaskSyncService extends Service { } } - public IBinder onBind(Intent intent) { + public IBinder onBind(Intent intent) { //不知道干吗用的 return null; } public void sendBroadcast(String msg) { mSyncProgress = msg; - Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值 intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); - sendBroadcast(intent); + sendBroadcast(intent); //发送这个通知 } - public static void startSync(Activity activity) { + public static void startSync(Activity activity) {//执行一个service,service的内容里的同步动作就是开始同步 GTaskManager.getInstance().setActivityContext(activity); Intent intent = new Intent(activity, GTaskSyncService.class); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); activity.startService(intent); } - public static void cancelSync(Context context) { + public static void cancelSync(Context context) {//执行一个service,service的内容里的同步动作就是取消同步 Intent intent = new Intent(context, GTaskSyncService.class); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); context.startService(intent); @@ -125,4 +146,4 @@ public class GTaskSyncService extends Service { public static String getProgressString() { return mSyncProgress; } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/model/Note.java b/src/main/java/net/micode/notes/model/Note.java index 6706cf6..3f0bffe 100644 --- a/src/main/java/net/micode/notes/model/Note.java +++ b/src/main/java/net/micode/notes/model/Note.java @@ -15,29 +15,29 @@ */ package net.micode.notes.model; -import android.content.ContentProviderOperation; -import android.content.ContentProviderResult; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.OperationApplicationException; -import android.net.Uri; -import android.os.RemoteException; -import android.util.Log; import net.micode.notes.data.Notes; +import android.content.ContentProviderOperation;//批量的更新、插入、删除数据。 +import android.content.ContentProviderResult;//操作的结果 +import android.content.ContentUris;//用于添加和获取Uri后面的ID +import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制 +import android.content.Context;//需要用该类来弄清楚调用者的实例 +import android.content.OperationApplicationException;//操作应用程序容错 +import android.net.Uri;//表示待操作的数据 +import android.os.RemoteException;//远程容错 +import android.util.Log;//输出日志,比如说出错、警告等 import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.TextNote; - import java.util.ArrayList; - public class Note { - private ContentValues mNoteDiffValues; + // private ContentValues mNoteDiffValues; + ContentValues mNoteDiffValues;// private NoteData mNoteData; private static final String TAG = "Note"; + /** * Create a new note id for adding a new note to databases */ @@ -49,16 +49,17 @@ public class Note { values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.LOCAL_MODIFIED, 1); - values.put(NoteColumns.PARENT_ID, folderId); + values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格 Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); - + //ContentResolver()主要是实现外部应用对ContentProvider中的数据 + //进行添加、删除、修改和查询操作 long noteId = 0; try { noteId = Long.valueOf(uri.getPathSegments().get(1)); } catch (NumberFormatException e) { Log.e(TAG, "Get note id error :" + e.toString()); noteId = 0; - } + }//try-catch异常处理 if (noteId == -1) { throw new IllegalStateException("Wrong note id:" + noteId); } @@ -68,37 +69,37 @@ public class Note { public Note() { mNoteDiffValues = new ContentValues(); mNoteData = new NoteData(); - } + }//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容 public void setNoteValue(String key, String value) { mNoteDiffValues.put(key, value); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); - } + }//设置数据库表格的标签属性数据 public void setTextData(String key, String value) { mNoteData.setTextData(key, value); - } + }//设置数据库表格的标签文本内容的数据 public void setTextDataId(long id) { mNoteData.setTextDataId(id); - } + }//设置文本数据的ID public long getTextDataId() { return mNoteData.mTextDataId; - } + }//得到文本数据的ID public void setCallDataId(long id) { mNoteData.setCallDataId(id); - } + }//设置电话号码数据的ID public void setCallData(String key, String value) { mNoteData.setCallData(key, value); - } + }//得到电话号码数据的ID public boolean isLocalModified() { return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); - } + }//判断是否是本地修改 public boolean syncNote(Context context, long noteId) { if (noteId <= 0) { @@ -128,16 +129,16 @@ public class Note { } return true; - } + }//判断数据是否同步 - private class NoteData { + private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据 private long mTextDataId; - private ContentValues mTextDataValues; + private ContentValues mTextDataValues;//文本数据 private long mCallDataId; - private ContentValues mCallDataValues; + private ContentValues mCallDataValues;//电话号码数据 private static final String TAG = "NoteData"; @@ -147,7 +148,7 @@ public class Note { mTextDataId = 0; mCallDataId = 0; } - + //下面是上述几个函数的具体实现 boolean isLocalModified() { return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; } @@ -177,17 +178,17 @@ public class Note { mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); } - + //下面函数的作用是将新的数据通过Uri的操作存储到数据库 Uri pushIntoContentResolver(Context context, long noteId) { /** * Check for safety */ if (noteId <= 0) { throw new IllegalArgumentException("Wrong note id:" + noteId); - } + }//判断数据是否合法 ArrayList operationList = new ArrayList(); - ContentProviderOperation.Builder builder = null; + ContentProviderOperation.Builder builder = null;//数据库的操作列表 if(mTextDataValues.size() > 0) { mTextDataValues.put(DataColumns.NOTE_ID, noteId); @@ -209,7 +210,7 @@ public class Note { operationList.add(builder.build()); } mTextDataValues.clear(); - } + }//把文本数据存入DataColumns if(mCallDataValues.size() > 0) { mCallDataValues.put(DataColumns.NOTE_ID, noteId); @@ -231,7 +232,7 @@ public class Note { operationList.add(builder.build()); } mCallDataValues.clear(); - } + }//把电话号码数据存入DataColumns if (operationList.size() > 0) { try { @@ -246,8 +247,8 @@ public class Note { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); return null; } - } + }//存储过程中的异常处理 return null; } } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/model/WorkingNote.java b/src/main/java/net/micode/notes/model/WorkingNote.java index be081e4..e625572 100644 --- a/src/main/java/net/micode/notes/model/WorkingNote.java +++ b/src/main/java/net/micode/notes/model/WorkingNote.java @@ -31,7 +31,6 @@ import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.TextNote; import net.micode.notes.tool.ResourceParser.NoteBgResources; - public class WorkingNote { // Note for the working note private Note mNote; @@ -43,17 +42,11 @@ public class WorkingNote { private int mMode; private long mAlertDate; - private long mModifiedDate; - private int mBgColorId; - private int mWidgetId; - private int mWidgetType; - private long mFolderId; - private Context mContext; private static final String TAG = "WorkingNote"; @@ -62,6 +55,7 @@ public class WorkingNote { private NoteSettingChangedListener mNoteSettingStatusListener; + // 声明 DATA_PROJECTION字符串数组 public static final String[] DATA_PROJECTION = new String[] { DataColumns.ID, DataColumns.CONTENT, @@ -72,6 +66,7 @@ public class WorkingNote { DataColumns.DATA4, }; + // 声明 NOTE_PROJECTION字符串数组 public static final String[] NOTE_PROJECTION = new String[] { NoteColumns.PARENT_ID, NoteColumns.ALERTED_DATE, @@ -82,27 +77,18 @@ public class WorkingNote { }; private static final int DATA_ID_COLUMN = 0; - private static final int DATA_CONTENT_COLUMN = 1; - private static final int DATA_MIME_TYPE_COLUMN = 2; - private static final int DATA_MODE_COLUMN = 3; - private static final int NOTE_PARENT_ID_COLUMN = 0; - private static final int NOTE_ALERTED_DATE_COLUMN = 1; - private static final int NOTE_BG_COLOR_ID_COLUMN = 2; - private static final int NOTE_WIDGET_ID_COLUMN = 3; - private static final int NOTE_WIDGET_TYPE_COLUMN = 4; - private static final int NOTE_MODIFIED_DATE_COLUMN = 5; // New note construct - private WorkingNote(Context context, long folderId) { + public WorkingNote(Context context, long folderId) { mContext = context; mAlertDate = 0; mModifiedDate = System.currentTimeMillis(); @@ -114,6 +100,7 @@ public class WorkingNote { mWidgetType = Notes.TYPE_WIDGET_INVALIDE; } + // WorkingNote的构造函数 // Existing note construct private WorkingNote(Context context, long noteId, long folderId) { mContext = context; @@ -124,11 +111,14 @@ public class WorkingNote { loadNote(); } + // 加载Note + // 通过数据库调用query函数找到第一个条目 private void loadNote() { Cursor cursor = mContext.getContentResolver().query( ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, null, null); + // 若存在,储存相应信息 if (cursor != null) { if (cursor.moveToFirst()) { mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); @@ -139,6 +129,7 @@ public class WorkingNote { mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); } cursor.close(); + // 若不存在,报错 } else { Log.e(TAG, "No note with id:" + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId); @@ -146,14 +137,16 @@ public class WorkingNote { loadNoteData(); } + // 加载NoteData private void loadNoteData() { Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - String.valueOf(mNoteId) + String.valueOf(mNoteId) }, null); if (cursor != null) { - if (cursor.moveToFirst()) { + // 查到信息不为空 + if (cursor.moveToFirst()) { // 查看第一项是否存在 do { String type = cursor.getString(DATA_MIME_TYPE_COLUMN); if (DataConstants.NOTE.equals(type)) { @@ -165,7 +158,7 @@ public class WorkingNote { } else { Log.d(TAG, "Wrong note type with type:" + type); } - } while (cursor.moveToNext()); + } while (cursor.moveToNext());//查阅所有项,直到为空 } cursor.close(); } else { @@ -174,9 +167,12 @@ public class WorkingNote { } } + // 创建空的Note + // 传参:context,文件夹id,widget,背景颜色 public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, - int widgetType, int defaultBgColorId) { + int widgetType, int defaultBgColorId) { WorkingNote note = new WorkingNote(context, folderId); + // 设定相关属性 note.setBgColorId(defaultBgColorId); note.setWidgetId(widgetId); note.setWidgetType(widgetType); @@ -187,9 +183,10 @@ public class WorkingNote { return new WorkingNote(context, id, 0); } + // 保存Note public synchronized boolean saveNote() { - if (isWorthSaving()) { - if (!existInDatabase()) { + if (isWorthSaving()) { //是否值得保存 + if (!existInDatabase()) { // 是否存在数据库中 if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { Log.e(TAG, "Create new note fail with id:" + mNoteId); return false; @@ -212,11 +209,14 @@ public class WorkingNote { } } + // 是否在数据库中存在 public boolean existInDatabase() { return mNoteId > 0; } + // 是否值得保存 private boolean isWorthSaving() { + // 被删除,或(不在数据库中 内容为空),或 本地已保存过 if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) || (existInDatabase() && !mNote.isLocalModified())) { return false; @@ -225,10 +225,14 @@ public class WorkingNote { } } + + // 设置mNoteSettingStatusListener public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { mNoteSettingStatusListener = l; } + // 设置AlertDate + // 若 mAlertDate与data不同,则更改mAlertDate并设定NoteValue public void setAlertDate(long date, boolean set) { if (date != mAlertDate) { mAlertDate = date; @@ -239,16 +243,20 @@ public class WorkingNote { } } + // 设定删除标记 public void markDeleted(boolean mark) { + // 设定标记 mIsDeleted = mark; if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { - mNoteSettingStatusListener.onWidgetChanged(); + mNoteSettingStatusListener.onWidgetChanged(); + // 调用mNoteSettingStatusListener的 onWidgetChanged方法 } } + // 设定背景颜色 public void setBgColorId(int id) { - if (id != mBgColorId) { + if (id != mBgColorId) { //设定条件 id != mBgColorId mBgColorId = id; if (mNoteSettingStatusListener != null) { mNoteSettingStatusListener.onBackgroundColorChanged(); @@ -257,8 +265,10 @@ public class WorkingNote { } } + // 设定检查列表模式 + // 参数:mode public void setCheckListMode(int mode) { - if (mMode != mode) { + if (mMode != mode) { //设定条件 mMode != mode if (mNoteSettingStatusListener != null) { mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); } @@ -267,81 +277,108 @@ public class WorkingNote { } } + + // 设定WidgetType + // 参数:type public void setWidgetType(int type) { - if (type != mWidgetType) { + if (type != mWidgetType) {//设定条件 type != mWidgetType mWidgetType = type; mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + // 调用Note的setNoteValue方法更改WidgetType } } + // 设定WidgetId + // 参数:id public void setWidgetId(int id) { - if (id != mWidgetId) { + if (id != mWidgetId) {//设定条件 id != mWidgetId mWidgetId = id; mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + // 调用Note的setNoteValue方法更改WidgetId } } + // 设定WorkingTex + // 参数:更改的text public void setWorkingText(String text) { - if (!TextUtils.equals(mContent, text)) { + if (!TextUtils.equals(mContent, text)) {//设定条件 mContent, text内容不同 mContent = text; mNote.setTextData(DataColumns.CONTENT, mContent); + // 调用Note的setTextData方法更改WorkingText } } + // 转变mNote的CallData及CallNote信息 + // 参数:String phoneNumber, long callDate public void convertToCallNote(String phoneNumber, long callDate) { mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); } + // 判断是否有时钟题型 public boolean hasClockAlert() { return (mAlertDate > 0 ? true : false); } + // 获取Content public String getContent() { return mContent; } + // 获取AlertDate public long getAlertDate() { return mAlertDate; } + // 获取ModifiedDate public long getModifiedDate() { return mModifiedDate; } + // 获取背景颜色来源id public int getBgColorResId() { return NoteBgResources.getNoteBgResource(mBgColorId); } + // 获取背景颜色id public int getBgColorId() { return mBgColorId; } + // 获取标题背景颜色id public int getTitleBgResId() { return NoteBgResources.getNoteTitleBgResource(mBgColorId); } + // 获取CheckListMode public int getCheckListMode() { return mMode; } + // 获取便签id public long getNoteId() { return mNoteId; } + // 获取文件夹id public long getFolderId() { return mFolderId; } + // 获取WidgetId public int getWidgetId() { return mWidgetId; } + // 获取WidgetType public int getWidgetType() { return mWidgetType; } + // 创建接口 NoteSettingChangedListener,便签更新监视 + // 为NoteEditActivity提供接口 + // 提供函数有 public interface NoteSettingChangedListener { /** * Called when the background color of current note has just changed @@ -365,4 +402,4 @@ public class WorkingNote { */ void onCheckListModeChanged(int oldMode, int newMode); } -} +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/tool/BackupUtils.java b/src/main/java/net/micode/notes/tool/BackupUtils.java index 39f6ec4..df99224 100644 --- a/src/main/java/net/micode/notes/tool/BackupUtils.java +++ b/src/main/java/net/micode/notes/tool/BackupUtils.java @@ -35,14 +35,17 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; - public class BackupUtils { private static final String TAG = "BackupUtils"; // Singleton stuff - private static BackupUtils sInstance; + private static BackupUtils sInstance; //类里面为什么可以定义自身类的对象? public static synchronized BackupUtils getInstance(Context context) { + //ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A) + //运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法(或者该类的其他同步方法),有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。 + //它包括两种用法:synchronized 方法和 synchronized 块。 if (sInstance == null) { + //如果当前备份不存在,则新声明一个 sInstance = new BackupUtils(context); } return sInstance; @@ -52,24 +55,24 @@ public class BackupUtils { * Following states are signs to represents backup or restore * status */ - // Currently, the sdcard is not mounted + // Currently, the sdcard is not mounted SD卡没有被装入手机 public static final int STATE_SD_CARD_UNMOUONTED = 0; - // The backup file not exist + // The backup file not exist 备份文件夹不存在 public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - // The data is not well formated, may be changed by other programs + // The data is not well formated, may be changed by other programs 数据已被破坏,可能被修改 public static final int STATE_DATA_DESTROIED = 2; - // Some run-time exception which causes restore or backup fails + // Some run-time exception which causes restore or backup fails 超时异常 public static final int STATE_SYSTEM_ERROR = 3; - // Backup or restore success + // Backup or restore success 成功存储 public static final int STATE_SUCCESS = 4; private TextExport mTextExport; - private BackupUtils(Context context) { + private BackupUtils(Context context) { //初始化函数 mTextExport = new TextExport(context); } - private static boolean externalStorageAvailable() { + private static boolean externalStorageAvailable() { //外部存储功能是否可用 return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } @@ -128,11 +131,11 @@ public class BackupUtils { public TextExport(Context context) { TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); mContext = context; - mFileName = ""; + mFileName = ""; //为什么为空? mFileDirectory = ""; } - private String getFormat(int id) { + private String getFormat(int id) { //获取文本的组成部分 return TEXT_FORMAT[id]; } @@ -140,22 +143,22 @@ public class BackupUtils { * Export the folder identified by folder id to text */ private void exportFolderToText(String folderId, PrintStream ps) { - // Query notes belong to this folder + // Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { - folderId + folderId }, null); if (notesCursor != null) { if (notesCursor.moveToFirst()) { do { - // Print note's last modified date + // Print note's last modified date ps里面保存有这份note的日期 ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( mContext.getString(R.string.format_datetime_mdhm), notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // Query data belong to this note String noteId = notesCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); + exportNoteToText(noteId, ps); //将文件导出到text } while (notesCursor.moveToNext()); } notesCursor.close(); @@ -168,10 +171,10 @@ public class BackupUtils { private void exportNoteToText(String noteId, PrintStream ps) { Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { - noteId + noteId }, null); - if (dataCursor != null) { + if (dataCursor != null) { //利用光标来扫描内容,区别为callnote和note两种,靠ps.printline输出 if (dataCursor.moveToFirst()) { do { String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); @@ -181,7 +184,7 @@ public class BackupUtils { long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); String location = dataCursor.getString(DATA_COLUMN_CONTENT); - if (!TextUtils.isEmpty(phoneNumber)) { + if (!TextUtils.isEmpty(phoneNumber)) { //判断是否为空字符 ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber)); } @@ -218,7 +221,7 @@ public class BackupUtils { /** * Note will be exported as text which is user readable */ - public int exportToText() { + public int exportToText() { //总函数,调用上面的exportFolder和exportNote if (!externalStorageAvailable()) { Log.d(TAG, "Media was not mounted"); return STATE_SD_CARD_UNMOUONTED; @@ -229,7 +232,7 @@ public class BackupUtils { Log.e(TAG, "get print stream error"); return STATE_SYSTEM_ERROR; } - // First export folder and its notes + // First export folder and its notes 导出文件夹,就是导出里面包含的便签 Cursor folderCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -257,7 +260,7 @@ public class BackupUtils { folderCursor.close(); } - // Export notes in root's folder + // Export notes in root's folder 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出) Cursor noteCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -297,7 +300,7 @@ public class BackupUtils { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(file); - ps = new PrintStream(fos); + ps = new PrintStream(fos); //将ps输出流输出到特定的文件,目的就是导出到文件,而不是直接输出 } catch (FileNotFoundException e) { e.printStackTrace(); return null; @@ -314,16 +317,16 @@ public class BackupUtils { */ private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { StringBuilder sb = new StringBuilder(); - sb.append(Environment.getExternalStorageDirectory()); - sb.append(context.getString(filePathResId)); - File filedir = new File(sb.toString()); + sb.append(Environment.getExternalStorageDirectory()); //外部(SD卡)的存储路径 + sb.append(context.getString(filePathResId)); //文件的存储路径 + File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息 sb.append(context.getString( fileNameFormatResId, DateFormat.format(context.getString(R.string.format_date_ymd), System.currentTimeMillis()))); File file = new File(sb.toString()); - try { + try { //如果这些文件不存在,则新建 if (!filedir.exists()) { filedir.mkdir(); } @@ -336,9 +339,7 @@ public class BackupUtils { } catch (IOException e) { e.printStackTrace(); } - +// try catch 异常处理 return null; } } - - diff --git a/src/main/java/net/micode/notes/tool/DataUtils.java b/src/main/java/net/micode/notes/tool/DataUtils.java index 2a14982..191d589 100644 --- a/src/main/java/net/micode/notes/tool/DataUtils.java +++ b/src/main/java/net/micode/notes/tool/DataUtils.java @@ -34,10 +34,9 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import java.util.ArrayList; import java.util.HashSet; - public class DataUtils { public static final String TAG = "DataUtils"; - public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { //直接删除多个笔记 if (ids == null) { Log.d(TAG, "the ids is null"); return true; @@ -47,18 +46,19 @@ public class DataUtils { return true; } - ArrayList operationList = new ArrayList(); + ArrayList operationList = new ArrayList(); //提供一个任务列表 for (long id : ids) { if(id == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Don't delete system folder root"); continue; - } + } //如果发现是根文件夹,则不删除 ContentProviderOperation.Builder builder = ContentProviderOperation - .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); - operationList.add(builder.build()); + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //用newDelete实现删除功能 + operationList.add(builder.build()); // } try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//主机名(或叫Authority)用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。 + //数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行 if (results == null || results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; @@ -77,11 +77,11 @@ public class DataUtils { values.put(NoteColumns.PARENT_ID, desFolderId); values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); values.put(NoteColumns.LOCAL_MODIFIED, 1); - resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); //对需要移动的便签进行数据更新,然后用update实现 } public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, - long folderId) { + long folderId) { if (ids == null) { Log.d(TAG, "the ids is null"); return true; @@ -90,14 +90,14 @@ public class DataUtils { ArrayList operationList = new ArrayList(); for (long id : ids) { ContentProviderOperation.Builder builder = ContentProviderOperation - .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //通过withAppendedId方法,为该Uri加上ID builder.withValue(NoteColumns.PARENT_ID, folderId); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); operationList.add(builder.build()); - } + }//将ids里包含的每一列的数据逐次加入到operationList中,等待最后的批量处理 try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); //applyBatch一次性处理一个操作列表 if (results == null || results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; @@ -119,7 +119,7 @@ public class DataUtils { new String[] { "COUNT(*)" }, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, - null); + null); //筛选条件:源文件不为trash folder int count = 0; if(cursor != null) { @@ -137,15 +137,15 @@ public class DataUtils { } public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), //通过withAppendedId方法,为该Uri加上ID null, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, new String [] {String.valueOf(type)}, - null); + null); //查询条件:type符合,且不属于垃圾文件夹 boolean exist = false; if (cursor != null) { - if (cursor.getCount() > 0) { + if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空 exist = true; } cursor.close(); @@ -184,9 +184,10 @@ public class DataUtils { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + - " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + - " AND " + NoteColumns.SNIPPET + "=?", + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", new String[] { name }, null); + //通过名字查询文件是否存在 boolean exist = false; if(cursor != null) { if(cursor.getCount() > 0) { @@ -202,7 +203,7 @@ public class DataUtils { new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, NoteColumns.PARENT_ID + "=?", new String[] { String.valueOf(folderId) }, - null); + null); //查询条件:父ID是传入的folderId; HashSet set = null; if (c != null) { @@ -211,13 +212,13 @@ public class DataUtils { do { try { AppWidgetAttribute widget = new AppWidgetAttribute(); - widget.widgetId = c.getInt(0); - widget.widgetType = c.getInt(1); + widget.widgetId = c.getInt(0); //0对应的NoteColumns.WIDGET_ID + widget.widgetType = c.getInt(1); //1对应的NoteColumns.WIDGET_TYPE set.add(widget); } catch (IndexOutOfBoundsException e) { Log.e(TAG, e.toString()); } - } while (c.moveToNext()); + } while (c.moveToNext()); //查询下一条 } c.close(); } @@ -247,14 +248,15 @@ public class DataUtils { Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, new String [] { CallNote.NOTE_ID }, CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" - + CallNote.PHONE_NUMBER + ",?)", + + CallNote.PHONE_NUMBER + ",?)", new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, null); + //通过数据库操作,查询条件是(callDate和phoneNumber匹配传入参数的值) if (cursor != null) { if (cursor.moveToFirst()) { try { - return cursor.getLong(0); + return cursor.getLong(0); //0对应的CallNote.NOTE_ID } catch (IndexOutOfBoundsException e) { Log.e(TAG, "Get call note id fails " + e.toString()); } @@ -269,7 +271,7 @@ public class DataUtils { new String [] { NoteColumns.SNIPPET }, NoteColumns.ID + "=?", new String [] { String.valueOf(noteId)}, - null); + null);//查询条件:noteId if (cursor != null) { String snippet = ""; @@ -281,8 +283,7 @@ public class DataUtils { } 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) { snippet = snippet.trim(); int index = snippet.indexOf('\n'); @@ -292,4 +293,5 @@ public class DataUtils { } return snippet; } -} + +} \ No newline at end of file diff --git a/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java index 666b729..8f82926 100644 --- a/src/main/java/net/micode/notes/tool/GTaskStringUtils.java +++ b/src/main/java/net/micode/notes/tool/GTaskStringUtils.java @@ -14,8 +14,10 @@ * limitations under the License. */ +//简介:定义了很多的静态字符串,目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范 package net.micode.notes.tool; +//这个类就是定义了一堆static string,实际就是为jsonObject提供Key,把这些定义全部写到一个类里,方便查看管理,是一个非常好的编程习惯 public class GTaskStringUtils { public final static String GTASK_JSON_ACTION_ID = "action_id"; @@ -110,4 +112,4 @@ public class GTaskStringUtils { public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; -} +} \ No newline at end of file