lidongyang_branch
chenzuiyulianmian 1 year ago
parent be10e0c819
commit 4e8ac3796c

@ -1,69 +0,0 @@
package net.micode.notes.data;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
// 定义一个Contact类
public class Contact {
// 声明一个HashMap类型的静态变量sContactCache
private static HashMap<String, String> sContactCache;
// 声明一个String类型的静态变量TAG
private static final String TAG = "Contact";
// 声明一个String类型的静态变量CALLER_ID_SELECTION
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 定义一个静态方法getContact参数为context和phoneNumber
public static String getContact(Context context, String phoneNumber) {
// 如果sContactCache为空则初始化sContactCache
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存中是否有该号码的联系人
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 查询数据库中是否有该号码的联系人
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 根据电话号码查询联系人
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人名字
String name = cursor.getString(0);
// 将联系人名字存入缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close();
}
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}

@ -1,29 +1,58 @@
package net.micode.notes.gtask.remote;
/*GTask /*
* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* private void showNotification(int tickerId, String content) *
* protected Integer doInBackground(Void... unused) 线 * Licensed under the Apache License, Version 2.0 (the "License");
* protected void onProgressUpdate(String... progress) 使 线 * you may not use this file except in compliance with the License.
* protected void onPostExecute(Integer result) Handler UI使doInBackground UI * 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.
*/ */
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
package net.micode.notes.gtask.remote;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
// 添加中文注释后
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 通知ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 完成监听器
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
// 上下文
private Context mContext; private Context mContext;
// 通知管理器
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
// 任务管理器
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
// 完成监听器
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
// 构造函数
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -32,68 +61,86 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
// 取消同步
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
public void publishProgess(String message) { // 发布进度单位系统将会调用onProgressUpdate()方法更新这些值 // 发布进度
public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
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.flags = Notification.FLAG_AUTO_CANCEL; // 点击清除按钮或点击通知后会自动消失 notification.defaults = Notification.DEFAULT_LIGHTS;
PendingIntent pendingIntent; //一个描述了想要启动一个Activity、Broadcast或是Service的意图 // 设置自动取消
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
// 如果不是成功提示则设置跳转到NotesPreferenceActivity
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);
// 如果是成功提示则设置跳转到NotesListActivity
} 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))); //利用getString,将把 NotesPreferenceActivity.getSyncAccountName(mContext))的字符串内容传进sync_progress_login中 .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) { //instanceof 判断mContext是否是GTaskSyncService的实例 // 如果上下文是GTaskSyncService则发送广播
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
@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()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); //设置最新同步的时间 // 设置上一次同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
// 网络错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
// 内部错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
// 取消同步
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} //几种不同情况下的结果显示 }
// 执行完成回调
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { //这里好像是方法内的一个线程,但是并不太懂什么意思 new Thread(new Runnable() {
public void run() { //完成后的操作使用onComplete()将所有值都重新初始化,相当于完成一次操作 public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }
}).start(); }).start();

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

@ -1,90 +0,0 @@
package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
/**
*
* abstract
*/
public abstract class Node {
//定义了各种用于表征同步状态的常量
public static final int SYNC_ACTION_NONE = 0;// 本地和云端都无可更新内容(即本地和云端内容一致)
public static final int SYNC_ACTION_ADD_REMOTE = 1;// 需要在远程云端增加内容
public static final int SYNC_ACTION_ADD_LOCAL = 2;// 需要在本地增加内容
public static final int SYNC_ACTION_DEL_REMOTE = 3;// 需要在远程云端删除内容
public static final int SYNC_ACTION_DEL_LOCAL = 4;// 需要在本地删除内容
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;// 需要将本地内容更新到远程云端
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 需要将远程云端内容更新到本地
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 同步出现冲突
public static final int SYNC_ACTION_ERROR = 8;// 同步出现错误
private String mGid;
private String mName;
private long mLastModified;//记录最后一次修改时间
private boolean mDeleted;//表征是否被删除
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
public abstract JSONObject getCreateAction(int actionId);
public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js);
public abstract void setContentByLocalJSON(JSONObject js);
public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c);
public void setGid(String gid) {
this.mGid = gid;
}
public void setName(String name) {
this.mName = name;
}
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
public String getGid() {
return this.mGid;
}
public String getName() {
return this.mName;
}
public long getLastModified() {
return this.mLastModified;
}
public boolean getDeleted() {
return this.mDeleted;
}
}

@ -1,577 +1,245 @@
/* /*
* Description便sqldatanotedata * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* SqlDataSqlNote *
* 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.gtask.data; package net.micode.notes.gtask.data;
/*
*
*
*
* Made By CuiCan
*/
public class SqlNote {
/*
* TAG
* getSimpleName ()
* Made By CuiCan
*/
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
// 集合了interface NoteColumns中所有SF常量17个
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
};
//以下设置17个列的编号
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public static final int HAS_ATTACHMENT_COLUMN = 4; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException;
public static final int MODIFIED_DATE_COLUMN = 5; import org.json.JSONException;
import org.json.JSONObject;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; // 定义一个SqlData类
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
public static final int TYPE_COLUMN = 9; private static final int INVALID_ID = -99999;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int DATA_ID_COLUMN = 0;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; // 数据类型
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int GTASK_ID_COLUMN = 15; // 数据内容
public static final int DATA_CONTENT_COLUMN = 2;
public static final int VERSION_COLUMN = 16; // 数据内容1
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
//一下定义了17个内部的变量其中12个可以由content中获得5个需要初始化为0或者new // 数据内容3
private Context mContext; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
// 内容解析器
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 是否创建
private boolean mIsCreate; private boolean mIsCreate;
private long mId; // 数据ID
private long mDataId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId; // 数据类型
private String mDataMimeType;
private String mSnippet; // 数据内容
private String mDataContent;
private long mDataContentData1;
private int mType; // 数据内容
private String mDataContentData3;
private int mWidgetId; // 差值数据
private ContentValues mDiffDataValues;
private int mWidgetType; public SqlData(Context context) {
//获取内容解析器
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
/*
*
* mIsCreate
*
* Made By CuiCan
*/
//构造函数只有context对所有的变量进行初始化
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
//标识是否创建
mIsCreate = true; mIsCreate = true;
mId = INVALID_ID; //数据ID
mAlertDate = 0; mDataId = INVALID_ID;
mBgColorId = ResourceParser.getDefaultBgId(context); //数据类型
mCreatedDate = System.currentTimeMillis();//调用系统函数获得创建时间 mDataMimeType = DataConstants.NOTE;
mHasAttachment = 0; //数据内容
mModifiedDate = System.currentTimeMillis();//最后一次修改时间初始化为创建时间 mDataContent = "";
mParentId = 0; //数据内容数据1
mSnippet = ""; mDataContentData1 = 0;
mType = Notes.TYPE_NOTE; //数据内容数据3
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mDataContentData3 = "";
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; //差异数据值
mOriginParent = 0; mDiffDataValues = new ContentValues();
mVersion = 0; }
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>(); public SqlData(Context context, Cursor c) {
} //获取内容解析器
/*
*
* mIsCreate
*
* Made By CuiCan
*/
//构造函数有context和一个数据库的cursor多数变量通过cursor指向的一条记录直接进行初始化
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
//标识是否创建
mIsCreate = false; mIsCreate = false;
//从游标中加载数据
loadFromCursor(c); loadFromCursor(c);
mDataList = new ArrayList<SqlData>(); //差异数据值
// mDiffDataValues = new ContentValues();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
} }
/*
*
* mIsCreate
*
* Made By CuiCan
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/*
* id
* Made By CuiCan
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);//通过id获得对应的ContentResolver中的cursor
if (c != null) {
c.moveToNext();
loadFromCursor(c);//然后加载数据进行初始化,这样函数
//SqlNote(Context context, long id)与SqlNote(Context context, long id)的实现方式基本相同
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
/*
*
* Made By CuiCan
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
//直接从一条记录中的获得以下变量的初始值 // 从游标中加载数据
mId = c.getLong(ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); }
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN); public void setContent(JSONObject js) throws JSONException {
mType = c.getInt(TYPE_COLUMN); // 从JSONObject中设置数据
mWidgetId = c.getInt(WIDGET_ID_COLUMN); long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); if (mIsCreate || mDataId != dataId) {
mVersion = c.getLong(VERSION_COLUMN); mDiffDataValues.put(DataColumns.ID, dataId);
} }
mDataId = dataId;
/*
* content // private void initDataMimeType(JSONObject js) {
* // // 从JSONObject中获取MIME_TYPE
* Made By CuiCan String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
*/ : DataConstants.NOTE;
private void loadDataContent() { // // 如果mIsCreate为true或者mDataMimeType不等于dataMimeType
Cursor c = null; if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDataList.clear(); // // 将dataMimeType放入mDiffDataValues中
try { mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, }
"(note_id=?)", new String[] { // // 将dataMimeType赋值给mDataMimeType
String.valueOf(mId) mDataMimeType = dataMimeType;
}, null); // 获取js中的内容
if (c != null) { String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (c.getCount() == 0) { // 判断是否创建或者内容是否改变
Log.w(TAG, "it seems that the note has not data"); if (mIsCreate || !mDataContent.equals(dataContent)) {
return; // 将内容添加到不同的数据值中
} mDiffDataValues.put(DataColumns.CONTENT, dataContent);
while (c.moveToNext()) { }
SqlData data = new SqlData(mContext, c); // 更新数据内容
mDataList.add(data); mDataContent = dataContent;
} // 获取dataContent的data1
} else { long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
Log.w(TAG, "loadDataContent: cursor = null"); // 如果mIsCreate为true或者dataContentData1不等于mDataContentData1则将dataContentData1放入mDiffDataValues中
} if (mIsCreate || mDataContentData1 != dataContentData1) {
} finally { mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
if (c != null) }
c.close(); // 将dataContentData1赋值给mDataContentData1
} mDataContentData1 = dataContentData1;
}
// 获取dataContent的data3
/* String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
* content // 如果mIsCreate为true或者dataContentData3不等于mDataContentData3则将dataContentData3放入mDiffDataValues中
* if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
* Made By CuiCan mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
*/ }
public boolean setContent(JSONObject js) { // 将dataContentData3赋值给mDataContentData3
try { mDataContentData3 = dataContentData3;
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); }
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder"); //获取内容
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { //获取内容
// for folder we can only update the snnipet and type public JSONObject getContent() throws JSONException {
String snippet = note.has(NoteColumns.SNIPPET) ? note //判断是否创建
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
}
mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
}
mCreatedDate = createDate;
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
mOriginParent = originParent;
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
}
}
}
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
sqlData.setContent(data);
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
}
return true;
}
/*
* contentnote
*
* Made By CuiCan
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
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 note = new JSONObject(); JSONObject js = new JSONObject();
if (mType == Notes.TYPE_NOTE) {//类型为note时 //添加ID
note.put(NoteColumns.ID, mId); js.put(DataColumns.ID, mDataId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate); //添加MIME_TYPE
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); js.put(DataColumns.MIME_TYPE, mDataMimeType);
note.put(NoteColumns.CREATED_DATE, mCreatedDate); //添加CONTENT
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); js.put(DataColumns.CONTENT, mDataContent);
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); //添加DATA1
note.put(NoteColumns.PARENT_ID, mParentId); js.put(DataColumns.DATA1, mDataContentData1);
note.put(NoteColumns.SNIPPET, mSnippet); //添加DATA3
note.put(NoteColumns.TYPE, mType); js.put(DataColumns.DATA3, mDataContentData3);
note.put(NoteColumns.WIDGET_ID, mWidgetId); //返回JSONObject
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
if (data != null) {
dataArray.put(data);
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为文件夹或者
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
}
return js; return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return null;
}
/*
* idid
*
* Made By CuiCan
*/
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
/*
* idGtaskid
*
* Made By CuiCan
*/
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
/*
* idid
*
* Made By CuiCan
*/
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
/*
*
*
* Made By CuiCan
*/
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
/*
* id
*
* Made By CuiCan
*/
public long getId() {
return mId;
}
/*
* idid
*
* Made By CuiCan
*/
public long getParentId() {
return mParentId;
} }
/* public void commit(long noteId, boolean validateVersion, long version) {
* 便
*
* Made By CuiCan
*/
public String getSnippet() {
return mSnippet;
}
/*
* 便
*
* Made By CuiCan
*/
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/* // 判断是否是创建操作
* commit
*
* Made By CuiCan
*/
public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { // 如果数据ID为无效ID并且数据值中包含ID
mDiffNoteValues.remove(NoteColumns.ID); if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
// 移除ID
mDiffDataValues.remove(DataColumns.ID);
} }
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); // 添加noteId
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
// 插入数据
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
mId = Long.valueOf(uri.getPathSegments().get(1)); // 获取插入数据的ID
mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {//直接使用sqldata中的实现
sqlData.commit(mId, false, -1);
}
}
} else { } else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { // 更新数据
Log.e(TAG, "No such note"); if (mDiffDataValues.size() > 0) {
throw new IllegalStateException("Try to update note with invalid id");
}
if (mDiffNoteValues.size() > 0) {
mVersion ++;
int result = 0; int result = 0;
if (!validateVersion) {//构造字符串 if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" // 更新数据
+ NoteColumns.ID + "=?)", new String[] { result = mContentResolver.update(ContentUris.withAppendedId(
String.valueOf(mId) Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
});
} else { } else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" // 更新数据,并且检查版本号
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", result = mContentResolver.update(ContentUris.withAppendedId(
new String[] { Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
String.valueOf(mId), String.valueOf(mVersion) " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
}); });
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
}
} }
mDiffDataValues.clear();
mIsCreate = false;
} }
// refresh local info public long getId() {
loadFromCursor(mId); return mDataId;
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues.clear();
mIsCreate = false;
} }
} }

@ -0,0 +1,669 @@
/*
* 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.gtask.data;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
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.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
};
public static final int ID_COLUMN = 0;
// 警报日期列
public static final int ALERTED_DATE_COLUMN = 1;
// 背景颜色ID列
public static final int BG_COLOR_ID_COLUMN = 2;
// 创建日期列
public static final int CREATED_DATE_COLUMN = 3;
// 是否有附件列
public static final int HAS_ATTACHMENT_COLUMN = 4;
// 修改日期列
public static final int MODIFIED_DATE_COLUMN = 5;
// 注释计数列
public static final int NOTES_COUNT_COLUMN = 6;
// 父ID列
public static final int PARENT_ID_COLUMN = 7;
// 片段列
public static final int SNIPPET_COLUMN = 8;
// 类型列
public static final int TYPE_COLUMN = 9;
// 小部件ID列
public static final int WIDGET_ID_COLUMN = 10;
// 小部件类型列
public static final int WIDGET_TYPE_COLUMN = 11;
// 同步ID列
public static final int SYNC_ID_COLUMN =12;
// 本地修改时间列
public static final int LOCAL_MODIFIED_COLUMN = 13;
// 父ID列
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
// 任务ID列
public static final int GTASK_ID_COLUMN = 15;
// 版本列
public static final int VERSION_COLUMN = 16;
// 上下文
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 是否创建
private boolean mIsCreate;
// ID
private long mId;
// 警报日期
private long mAlertDate;
// 背景颜色ID
private int mBgColorId;
private long mCreatedDate;
// 0 = no, 1 = yes
private int mHasAttachment;
// 0 = no, 1 = yes
private long mModifiedDate;
// parent id
private long mParentId;
// 160 characters max
private String mSnippet;
// 0 = note, 1 = task, 2 = both
private int mType;
// widget id
private int mWidgetId;
// widget type
private int mWidgetType;
// origin parent id
private long mOriginParent;
// version
private long mVersion;
private ContentValues mDiffNoteValues;
// 用于存储SqlData对象的列表
private ArrayList<SqlData> mDataList;
// 构造函数,传入上下文
// 创建SqlNote对象并初始化
public SqlNote(Context context) {
mContext = context;
//获取上下文
mContentResolver = context.getContentResolver();
//获取内容解析器
mIsCreate = true;
//是否创建
mId = INVALID_ID;
//ID
mAlertDate = 0;
//警报日期
mBgColorId = ResourceParser.getDefaultBgId(context);
//背景颜色ID
mCreatedDate = System.currentTimeMillis();
//创建日期
mHasAttachment = 0;
//是否有附件
mModifiedDate = System.currentTimeMillis();
//修改日期
mParentId = 0;
//父ID
mSnippet = "";
//摘要
mType = Notes.TYPE_NOTE;
//类型
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
//小部件ID
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
//小部件类型
mOriginParent = 0;
//来源父
mVersion = 0;
//版本
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
// 创建SqlNote对象从Cursor中加载数据
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
// 创建SqlNote对象传入上下文和id
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
private void loadFromCursor(long id) {
Cursor c = null;
try {
// 根据id查询Notes表中的数据
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);
if (c != null) {
// 将查询到的数据加载到当前对象中
c.moveToNext();
loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
private void loadFromCursor(Cursor c) {
// 从游标中获取ID
mId = c.getLong(ID_COLUMN);
// 从游标中获取提示日期
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
// 从游标中获取背景颜色ID
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
// 从游标中获取创建日期
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
// 从游标中获取是否有附件
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
// 从游标中获取修改日期
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
// 从游标中获取父ID
mParentId = c.getLong(PARENT_ID_COLUMN);
// 从游标中获取摘要
mSnippet = c.getString(SNIPPET_COLUMN);
// 从游标中获取类型
mType = c.getInt(TYPE_COLUMN);
// 从游标中获取小部件ID
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
// 从游标中获取小部件类型
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
// 从游标中获取版本
mVersion = c.getLong(VERSION_COLUMN);
}
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
try {
// 根据note_id查询数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
}, null);
if (c != null) {
// 判断是否有数据
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
// 遍历查询到的数据
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
}
} else {
Log.w(TAG, "loadDataContent: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
public boolean setContent(JSONObject js) {
try {
// 获取js中的meta_head_note对象
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 判断note的类型是否为系统文件夹
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 判断note的类型是否为文件夹
// for folder we can only update the snnipet and type
// 获取note中的snippet
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
// 判断是否为创建或者mSnippet是否与note中的snippet不同
if (mIsCreate || !mSnippet.equals(snippet)) {
// 将mSnippet与note中的snippet进行比较不同的值放入mDiffNoteValues中
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
// 将note中的snippet赋值给mSnippet
mSnippet = snippet;
// 获取note中的type
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
// 判断是否为创建或者mType是否与note中的type不同
if (mIsCreate || mType != type) {
// 将mType与note中的type进行比较不同的值放入mDiffNoteValues中
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
// 将note中的type赋值给mType
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
// 获取JSONArray类型的dataArray
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 获取note中的id
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
// 判断是否是创建操作或者mId和id不相等
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
// 获取note中的alertDate
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
// 判断是否是创建操作或者mAlertDate和alertDate不相等
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
}
mAlertDate = alertDate;
// 获取note中的bgColorId
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
// 判断是否是创建操作或者mBgColorId和bgColorId不相等
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
// 获取note中的createDate
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
// 判断是否是创建操作或者mCreatedDate和createDate不相等
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
}
mCreatedDate = createDate;
// 获取是否有附件
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
// 如果创建或者有附件改变
if (mIsCreate || mHasAttachment != hasAttachment) {
// 将附件改变添加到不同的值
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
// 获取修改日期
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
// 如果创建或者修改日期改变
if (mIsCreate || mModifiedDate != modifiedDate) {
// 将修改日期改变添加到不同的值
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
// 获取父ID
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
// 如果创建或者父ID改变
if (mIsCreate || mParentId != parentId) {
// 将父ID改变添加到不同的值
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
// 判断是否创建或者是否修改了摘要
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
// 获取类型
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
// 判断是否创建或者是否修改了类型
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
// 获取note中的widgetId
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
// 如果mIsCreate为true或者mWidgetId不等于widgetId则将widgetId添加到mDiffNoteValues中
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
// 将widgetId赋值给mWidgetId
mWidgetId = widgetId;
// 获取note中的widgetType
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
// 如果mIsCreate为true或者mWidgetType不等于widgetType则将widgetType添加到mDiffNoteValues中
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
// 将widgetType赋值给mWidgetType
mWidgetType = widgetType;
// 获取note中的originParent
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
// 如果mIsCreate为true或者mOriginParent不等于originParent则将originParent添加到mDiffNoteValues中
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
// 将originParent赋值给mOriginParent
mOriginParent = originParent;
// 遍历dataArray中的每一个JSONObject
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
// 判断data中是否有ID字段
if (data.has(DataColumns.ID)) {
// 获取ID字段的值
long dataId = data.getLong(DataColumns.ID);
// 遍历mDataList中的每一个SqlData
for (SqlData temp : mDataList) {
// 如果ID字段的值和SqlData的ID值相等
if (dataId == temp.getId()) {
// 将temp赋值给sqlData
sqlData = temp;
}
}
}
// 如果sqlData为null则创建一个新的SqlData
if (sqlData == null) {
sqlData = new SqlData(mContext);
// 将sqlData添加到mDataList中
mDataList.add(sqlData);
}
// 设置SqlData的内容
sqlData.setContent(data);
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
}
return true;
}
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
// 检查是否已经创建
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
// 创建一个JSONObject对象note
JSONObject note = new JSONObject();
// 如果mType等于Notes.TYPE_NOTE
if (mType == Notes.TYPE_NOTE) {
// 将mId放入note中
note.put(NoteColumns.ID, mId);
// 将mAlertDate放入note中
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
// 将mBgColorId放入note中
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
// 将mCreatedDate放入note中
note.put(NoteColumns.CREATED_DATE, mCreatedDate);
// 将mHasAttachment放入note中
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
// 将mModifiedDate放入note中
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
// 将mParentId放入note中
note.put(NoteColumns.PARENT_ID, mParentId);
// 将mSnippet放入note中
note.put(NoteColumns.SNIPPET, mSnippet);
// 将mType放入note中
note.put(NoteColumns.TYPE, mType);
// 将mWidgetId放入note中
note.put(NoteColumns.WIDGET_ID, mWidgetId);
// 将mWidgetType放入note中
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
// 将mOriginParent放入note中
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
// 将note放入js中
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 创建一个JSONArray对象dataArray
JSONArray dataArray = new JSONArray();
// 遍历mDataList
for (SqlData sqlData : mDataList) {
// 获取sqlData的content
JSONObject data = sqlData.getContent();
// 如果data不为空
if (data != null) {
// 将data放入dataArray中
dataArray.put(data);
}
}
// 将dataArray放入js中
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
// 如果mType等于Notes.TYPE_FOLDER或者mType等于Notes.TYPE_SYSTEM
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
// 将mId放入note中
note.put(NoteColumns.ID, mId);
// 将mType放入note中
note.put(NoteColumns.TYPE, mType);
// 将mSnippet放入note中
note.put(NoteColumns.SNIPPET, mSnippet);
// 将note放入js中
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
}
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return null;
}
// 设置父id
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
// 设置GtaskId
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
// 设置同步id
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
// 重置本地修改时间
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
// 获取id
public long getId() {
return mId;
}
//获取父ID
public long getParentId() {
return mParentId;
}
//获取摘要
public String getSnippet() {
return mSnippet;
}
//判断是否为笔记类型
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
//提交
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try {
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
// 检查mId是否有效
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
}
// 检查是否有更新
if (mDiffNoteValues.size() > 0) {
// 更新版本号
mVersion ++;
int result = 0;
// 检查是否是同步更新
if (!validateVersion) {
// 更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
});
} else {
// 更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
// 检查是否更新成功
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
// 判断mType是否为Notes.TYPE_NOTE
if (mType == Notes.TYPE_NOTE) {
// 遍历mDataList
for (SqlData sqlData : mDataList) {
// 提交数据
sqlData.commit(mId, validateVersion, mVersion);
}
}
}
// refresh local info
// 从游标中加载数据
loadFromCursor(mId);
// 判断mType是否为Notes.TYPE_NOTE
if (mType == Notes.TYPE_NOTE)
// 加载数据内容
loadDataContent();
// 清除mDiffNoteValues
mDiffNoteValues.clear();
// 设置mIsCreate为false
mIsCreate = false;
}
}

@ -1,28 +1,61 @@
/*
* 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.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
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;//对应的优先兄弟Task的指针待完善 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;
} }
public JSONObject getCreateAction(int actionId) { //获取创建动作
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
@ -46,20 +79,15 @@ public class Task extends Node {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id // parent_id
if (mParent!= null) {
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
}
// dest_parent_type // dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id // list_id
if (mParent!= null) {
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
}
// prior_sibling_id // prior_sibling_id
if (mPriorSibling != null) { if (mPriorSibling != null) {
@ -98,7 +126,7 @@ public class Task extends Node {
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { }catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject");
@ -131,15 +159,19 @@ public class Task extends Node {
} }
// deleted // deleted
// 判断js中是否有GTaskStringUtils.GTASK_JSON_DELETED属性
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
// 设置deleted属性
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// completed // completed
// 判断js中是否有GTaskStringUtils.GTASK_JSON_COMPLETED属性
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
// 设置completed属性
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
} catch (JSONException e) { }catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject"); throw new ActionFailureException("fail to get task content from jsonobject");
@ -147,25 +179,31 @@ public class Task extends Node {
} }
} }
public void setContentByLocalJSON(JSONObject js) { //<2F><>metadata<74><61><EFBFBD><EFBFBD>ʵʩ public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
// 获取JSONObject中的note和dataArray
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 判断note的类型是否为Notes.TYPE_NOTE
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");
return; return;
} }
// 遍历dataArray数组
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
// 获取dataArray数组中的每一个JSONObject
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
// 判断data中MIME_TYPE字段的值是否为NOTE
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
// 设置name字段
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT));
// 跳出循环
break; break;
} }
} }
@ -187,20 +225,30 @@ public class Task extends Node {
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
// 创建一个JSONObject对象用于存储JSON数据
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
// 创建一个JSONObject对象用于存储JSON数据
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
// 创建一个JSONArray对象用于存储JSON数据
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
// 创建一个JSONObject对象用于存储JSON数据
data.put(DataColumns.CONTENT, name); data.put(DataColumns.CONTENT, name);
// 将name的值放入data中
dataArray.put(data); dataArray.put(data);
// 将data放入dataArray中
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
// 将dataArray放入js中
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
// 将Notes.TYPE_NOTE放入note中
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 将note放入js中
return js; return js;
} else { } else {
// synced task // synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 遍历dataArray找到mime_type为NOTE的data并将其content设置为getName()
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -209,6 +257,7 @@ public class Task extends Node {
} }
} }
// 将note的type设置为NOTE
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo; return mMetaInfo;
} }
@ -219,7 +268,8 @@ public class Task extends Node {
} }
} }
public void setMetaInfo(MetaData metaData) { //设置元数据
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes());
@ -232,29 +282,41 @@ public class Task extends Node {
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
// 获取JSONObject
JSONObject noteInfo = null; JSONObject noteInfo = null;
// 如果mMetaInfo不为空并且mMetaInfo中有META_HEAD_NOTE
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
// 获取JSONObject
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
} }
// 如果noteInfo为空
if (noteInfo == null) { if (noteInfo == null) {
// 打印日志
Log.w(TAG, "it seems that note meta has been deleted"); Log.w(TAG, "it seems that note meta has been deleted");
// 返回更新远程的同步动作
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
// 如果noteInfo中没有ID
if (!noteInfo.has(NoteColumns.ID)) { if (!noteInfo.has(NoteColumns.ID)) {
// 打印日志
Log.w(TAG, "remote note id seems to be deleted"); Log.w(TAG, "remote note id seems to be deleted");
// 返回更新远程的同步动作
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// validate the note id now // validate the note id now
// 检查note的ID是否与noteInfo中的ID匹配
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// 检查本地修改时间
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // there is no local update
// 检查同步ID是否与本地修改时间匹配
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
@ -263,15 +325,17 @@ public class Task extends Node {
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // validate gtaskid
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
// 比较本地和远程的修改时间
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// remote modification only
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT;
} }
} }
@ -283,40 +347,48 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
// 判断是否需要保存
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
// 设置是否完成
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
// 设置备注
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
//设置前一个兄弟节点
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
//设置父节点
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
//获取是否完成
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
//获取备注
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
public Task getPriorSibling() { public Task getPriorSibling() {
// 获取前一个兄弟节点
return this.mPriorSibling; return this.mPriorSibling;
} }
public TaskList getParent() { public TaskList getParent() {
// 获取父节点
return this.mParent; return this.mParent;
} }

@ -1,11 +1,41 @@
/*
* 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.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
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();
@ -13,10 +43,6 @@ public class TaskList extends Node {
mIndex = 1; mIndex = 1;
} }
/* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getCreateAction(int)
* JSONObject
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -32,7 +58,7 @@ public class TaskList extends Node {
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta // entity_delta
JSONObject entity = new JSONObject();//entity实体 JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
@ -48,11 +74,8 @@ public class TaskList extends Node {
return js; return js;
} }
/* (non-Javadoc) //获取更新操作的JSONObject
* @see net.micode.notes.gtask.data.Node#getUpdateAction(int) public JSONObject getUpdateAction(int actionId) {
* JSONObject
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
@ -71,7 +94,6 @@ public class TaskList extends Node {
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -116,12 +138,18 @@ public class TaskList extends Node {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 获取文件夹的摘要
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
// 设置文件夹的名称
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 判断文件夹的ID是否为根文件夹
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
// 设置文件夹的名称
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
// 判断文件夹的ID是否为通话记录文件夹
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
// 设置文件夹的名称
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE); + GTaskStringUtils.FOLDER_CALL_NOTE);
else else
@ -130,6 +158,7 @@ public class TaskList extends Node {
Log.e(TAG, "error type"); Log.e(TAG, "error type");
} }
} catch (JSONException e) { } catch (JSONException e) {
// public void error(String e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
@ -140,19 +169,24 @@ public class TaskList extends Node {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
// 获取文件夹名
String folderName = getName(); String folderName = getName();
// 如果文件夹名以MIUI_FOLDER_PREFFIX开头则截取文件夹名
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length());
// 将文件夹名放入folder中
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
// 如果文件夹名等于FOLDER_DEFAULT或者FOLDER_CALL_NOTE则将文件夹类型设置为Notes.TYPE_SYSTEM
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
// 否则将文件夹类型设置为Notes.TYPE_FOLDER
else else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
// 将文件夹放入js中
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js; return js;
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -163,13 +197,17 @@ public class TaskList extends Node {
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
// 判断本地修改列是否为0
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // there is no local update
// 判断远程更新列是否等于最后修改时间
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // no update both side
// 没有本地更新和远程更新,返回无操作
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // apply remote to local
// 将远程更新应用到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
@ -191,63 +229,58 @@ public class TaskList extends Node {
e.printStackTrace(); e.printStackTrace();
} }
// 返回同步操作错误
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/** // 获取子任务的数量
* @return
* TaskListmChildren
*/
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
/** // 添加子任务
* @param task
* @return
*
*/
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
if (ret) { if (ret) {
// need to set prior sibling and parent // need to set prior sibling and parent
// 设置前一个兄弟和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
//注意每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改
//,接下来几个函数都有相关操作
} }
} }
return ret; return ret;
} }
/** //添加中文注释后
* @param task public boolean addChildTask(Task task, int index) {
* @param index //检查索引是否有效
* @return
*
*/
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");
return false; return false;
} }
//检查任务是否已经存在
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);
if (task != null && pos == -1) { if (task != null && pos == -1) {
//添加任务
mChildren.add(index, task); mChildren.add(index, task);
// update the task list // update the task list
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
// 判断当前节点是否是第一个节点
if (index != 0) if (index != 0)
preTask = mChildren.get(index - 1); preTask = mChildren.get(index - 1);
// 判断当前节点是否是最后一个节点
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1);
// 设置当前节点的前一个节点
task.setPriorSibling(preTask); task.setPriorSibling(preTask);
// 设置当前节点的后一个节点
if (afterTask != null) if (afterTask != null)
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task);
} }
@ -255,11 +288,6 @@ public class TaskList extends Node {
return true; return true;
} }
/**
* @param task
* @return
* TaskListTask
*/
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);
@ -280,37 +308,27 @@ public class TaskList extends Node {
} }
return ret; return ret;
} }
/**
* @param task
* @param index
* @return
* TaskListTaskindex
*/
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
//检查index是否越界
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index");
return false; return false;
} }
//检查task是否在mChildren中
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);
if (pos == -1) { if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list");
return false; return false;
} }
//如果task的索引和index相等则不需要移动
if (pos == index) if (pos == index)
return true; return true;
//从mChildren中移除task并将其添加到指定位置
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
//利用已实现好的功能完成当下功能;
} }
/**
* @param gid
* @return
* gidTask
*/
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);
@ -321,20 +339,12 @@ public class TaskList extends Node {
return null; return null;
} }
/** //获取子任务索引
* @param task public int getChildTaskIndex(Task task) {
* @return
* Taskindex
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
/** //根据索引获取子任务
* @param index
* @return
* indexTask
*/
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");
@ -343,13 +353,9 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
/** //根据GID获取子任务
* @param gid
* @return
* gidTask
*/
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {//一种常见的ArrayList的遍历方法四种见精读笔记 for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
return task; return task;
} }
@ -360,10 +366,12 @@ public class TaskList extends Node {
return this.mChildren; return this.mChildren;
} }
//设置索引
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
//获取索引
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }

Loading…
Cancel
Save