diff --git a/notes/gtask/data/MetaData.java b/notes/gtask/data/MetaData.java index fe7a778..3a2050b 100644 --- a/notes/gtask/data/MetaData.java +++ b/notes/gtask/data/MetaData.java @@ -1,53 +1,54 @@ +/* + * 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.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + + public class MetaData extends Task { - /* - * 功能描述:得到类的简写名称存入字符串TAG中 - * 实现过程:调用getSimpleName ()函数 - */ private final static String TAG = MetaData.class.getSimpleName(); + private String mRelatedGid = null; - /* - * 功能描述:设置数据,即生成元数据库 - * 实现过程:调用JSONObject库函数put (),Task类中的setNotes ()和setName ()函数 - * 参数注解: - */ - public void setMeta(String gid, JSONObject metaInfo) - { - //对函数块进行注释 + + public void setMeta(String gid, JSONObject metaInfo) { try { metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - /* - * 将这对键值放入metaInfo这个jsonobject对象中 - */ } 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数据对象设置元数据内容 - * 实现过程:调用父类Task中的setContentByRemoteJSON ()函数,并 - * 参数注解: - */ + @Override public void setContentByRemoteJSON(JSONObject js) { super.setContentByRemoteJSON(js); @@ -57,48 +58,25 @@ public class MetaData extends Task { 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 - */ } - -} \ No newline at end of file + +} diff --git a/notes/gtask/data/Node.java b/notes/gtask/data/Node.java index db7db78..63950e0 100644 --- a/notes/gtask/data/Node.java +++ b/notes/gtask/data/Node.java @@ -1,90 +1,101 @@ +/* + * 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.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;// 同步出现错误 - + 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;//表征是否被删除 - + + 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; } - -} \ No newline at end of file + +} diff --git a/notes/gtask/data/SqlData.java b/notes/gtask/data/SqlData.java index e69de29..d3ec3be 100644 --- a/notes/gtask/data/SqlData.java +++ b/notes/gtask/data/SqlData.java @@ -0,0 +1,189 @@ +/* + * 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.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; + +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; + +import org.json.JSONException; +import org.json.JSONObject; + + +public class SqlData { + private static final String TAG = SqlData.class.getSimpleName(); + + private static final int INVALID_ID = -99999; + + public static final String[] PROJECTION_DATA = new String[] { + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, + DataColumns.DATA3 + }; + + public static final int DATA_ID_COLUMN = 0; + + public static final int DATA_MIME_TYPE_COLUMN = 1; + + public static final int DATA_CONTENT_COLUMN = 2; + + public static final int DATA_CONTENT_DATA_1_COLUMN = 3; + + public static final int DATA_CONTENT_DATA_3_COLUMN = 4; + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mDataId; + + private String mDataMimeType; + + private String mDataContent; + + private long mDataContentData1; + + private String mDataContentData3; + + private ContentValues mDiffDataValues; + + public SqlData(Context context) { + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = ""; + mDiffDataValues = new ContentValues(); + } + + public SqlData(Context context, Cursor c) { + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } + + private void loadFromCursor(Cursor c) { + mDataId = c.getLong(DATA_ID_COLUMN); + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); + mDataContent = c.getString(DATA_CONTENT_COLUMN); + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); + } + + public void setContent(JSONObject js) throws JSONException { + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; + if (mIsCreate || mDataId != dataId) { + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId; + + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) { + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent; + + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } + + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + JSONObject js = new JSONObject(); + js.put(DataColumns.ID, mDataId); + js.put(DataColumns.MIME_TYPE, mDataMimeType); + js.put(DataColumns.CONTENT, mDataContent); + js.put(DataColumns.DATA1, mDataContentData1); + js.put(DataColumns.DATA3, mDataContentData3); + return js; + } + + public void commit(long noteId, boolean validateVersion, long version) { + + if (mIsCreate) { + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { + mDiffDataValues.remove(DataColumns.ID); + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); + try { + mDataId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed"); + } + } else { + if (mDiffDataValues.size() > 0) { + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else { + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + }); + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + } + + mDiffDataValues.clear(); + mIsCreate = false; + } + + public long getId() { + return mDataId; + } +} diff --git a/notes/gtask/data/SqlNote.java b/notes/gtask/data/SqlNote.java index e69de29..79a4095 100644 --- a/notes/gtask/data/SqlNote.java +++ b/notes/gtask/data/SqlNote.java @@ -0,0 +1,505 @@ +/* + * 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; + + 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; + + public static final int PARENT_ID_COLUMN = 7; + + public static final int SNIPPET_COLUMN = 8; + + public static final int TYPE_COLUMN = 9; + + 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 int LOCAL_MODIFIED_COLUMN = 13; + + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + + public static final int GTASK_ID_COLUMN = 15; + + public static final int VERSION_COLUMN = 16; + + private Context mContext; + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mId; + + private long mAlertDate; + + private int mBgColorId; + + private long mCreatedDate; + + private int mHasAttachment; + + private long mModifiedDate; + + private long mParentId; + + private String mSnippet; + + private int mType; + + private int mWidgetId; + + private int mWidgetType; + + private long mOriginParent; + + private long mVersion; + + private ContentValues mDiffNoteValues; + + private ArrayList mDataList; + + public SqlNote(Context context) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mId = INVALID_ID; + mAlertDate = 0; + mBgColorId = ResourceParser.getDefaultBgId(context); + mCreatedDate = System.currentTimeMillis(); + mHasAttachment = 0; + mModifiedDate = System.currentTimeMillis(); + mParentId = 0; + mSnippet = ""; + mType = Notes.TYPE_NOTE; + mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + mOriginParent = 0; + mVersion = 0; + mDiffNoteValues = new ContentValues(); + mDataList = new ArrayList(); + } + + public SqlNote(Context context, Cursor c) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + } + + public SqlNote(Context context, long id) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(id); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + + } + + 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); + 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) { + mId = c.getLong(ID_COLUMN); + mAlertDate = c.getLong(ALERTED_DATE_COLUMN); + 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); + mParentId = c.getLong(PARENT_ID_COLUMN); + mSnippet = c.getString(SNIPPET_COLUMN); + mType = c.getInt(TYPE_COLUMN); + 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 { + 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 { + 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 + 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; + } + + 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 = new JSONObject(); + if (mType == Notes.TYPE_NOTE) { + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.ALERTED_DATE, mAlertDate); + note.put(NoteColumns.BG_COLOR_ID, mBgColorId); + note.put(NoteColumns.CREATED_DATE, mCreatedDate); + note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); + note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); + note.put(NoteColumns.PARENT_ID, mParentId); + note.put(NoteColumns.SNIPPET, mSnippet); + note.put(NoteColumns.TYPE, mType); + note.put(NoteColumns.WIDGET_ID, mWidgetId); + 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; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + return null; + } + + public void setParentId(long id) { + mParentId = id; + mDiffNoteValues.put(NoteColumns.PARENT_ID, id); + } + + public void setGtaskId(String gid) { + mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); + } + + public void setSyncId(long syncId) { + mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); + } + + public void resetLocalModified() { + mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); + } + + public long getId() { + return mId; + } + + 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 { + 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"); + } + } + + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, validateVersion, mVersion); + } + } + } + + // refresh local info + loadFromCursor(mId); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + + mDiffNoteValues.clear(); + mIsCreate = false; + } +} diff --git a/notes/gtask/data/Task.java b/notes/gtask/data/Task.java index 79610b7..6a19454 100644 --- a/notes/gtask/data/Task.java +++ b/notes/gtask/data/Task.java @@ -1,41 +1,73 @@ +/* + * 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.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 { private static final String TAG = Task.class.getSimpleName(); - - private boolean mCompleted;//是否完成 - + + private boolean mCompleted; + private String mNotes; - - private JSONObject mMetaInfo;//将在实例中存储数据的类型 - - private Task mPriorSibling;//对应的优先兄弟Task的指针(待完善) - - private TaskList mParent;//所在的任务列表的指针 - + + private JSONObject mMetaInfo; + + private Task mPriorSibling; + + private TaskList mParent; + public Task() { super(); mCompleted = false; mNotes = null; - mPriorSibling = null;//TaskList中当前Task前面的Task的指针 - mParent = null;//当前Task所在的TaskList + mPriorSibling = null; + mParent = null; mMetaInfo = null; } - + public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); - + try { // action_type js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - + // action_id js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - + // index js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); - + // entity_delta JSONObject entity = new JSONObject(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); @@ -46,49 +78,45 @@ public class Task extends Node { entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); } js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - + // parent_id - if (mParent!= null) { js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - } - + // dest_parent_type js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - + // list_id - if (mParent!= null) { js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - } - + // prior_sibling_id if (mPriorSibling != null) { js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); } - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to generate task-create jsonobject"); } - + return js; } - + public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); - + try { // action_type js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - + // action_id js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - + // id js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - + // entity_delta JSONObject entity = new JSONObject(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); @@ -97,16 +125,16 @@ public class Task extends Node { } entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to generate task-update jsonobject"); } - + return js; } - + public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -114,27 +142,27 @@ public class Task extends Node { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); } - + // last_modified if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); } - + // name if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); } - + // notes if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); } - + // deleted if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); } - + // completed if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); @@ -146,22 +174,22 @@ public class Task extends Node { } } } - - public void setContentByLocalJSON(JSONObject js) { //��metadata����ʵʩ + + public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); } - + try { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { - Log.e(TAG, "invalid type"); + Log.e(TAG, "invalid type"); return; } - + for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { @@ -169,13 +197,13 @@ public class Task extends Node { break; } } - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } - + public JSONObject getLocalJSONFromContent() { String name = getName(); try { @@ -185,7 +213,7 @@ public class Task extends Node { Log.w(TAG, "the note seems to be an empty one"); return null; } - + JSONObject js = new JSONObject(); JSONObject note = new JSONObject(); JSONArray dataArray = new JSONArray(); @@ -200,7 +228,7 @@ public class Task extends Node { // synced task JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - + for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { @@ -208,7 +236,7 @@ public class Task extends Node { break; } } - + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); return mMetaInfo; } @@ -218,7 +246,7 @@ public class Task extends Node { return null; } } - + public void setMetaInfo(MetaData metaData) { if (metaData != null && metaData.getNotes() != null) { try { @@ -229,30 +257,30 @@ public class Task extends Node { } } } - + public int getSyncAction(Cursor c) { try { JSONObject noteInfo = null; if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); } - + if (noteInfo == null) { Log.w(TAG, "it seems that note meta has been deleted"); return SYNC_ACTION_UPDATE_REMOTE; } - + if (!noteInfo.has(NoteColumns.ID)) { Log.w(TAG, "remote note id seems to be deleted"); return SYNC_ACTION_UPDATE_LOCAL; } - + // validate the note id now if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { Log.w(TAG, "note id doesn't match"); return SYNC_ACTION_UPDATE_LOCAL; } - + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // there is no local update if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { @@ -279,45 +307,45 @@ public class Task extends Node { Log.e(TAG, e.toString()); e.printStackTrace(); } - + return SYNC_ACTION_ERROR; } - + public boolean isWorthSaving() { return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) || (getNotes() != null && getNotes().trim().length() > 0); } - + public void setCompleted(boolean completed) { this.mCompleted = completed; } - + public void setNotes(String notes) { this.mNotes = notes; } - + public void setPriorSibling(Task priorSibling) { this.mPriorSibling = priorSibling; } - + public void setParent(TaskList parent) { this.mParent = parent; } - + public boolean getCompleted() { return this.mCompleted; } - + public String getNotes() { return this.mNotes; } - + public Task getPriorSibling() { return this.mPriorSibling; } - + public TaskList getParent() { return this.mParent; } - -} \ No newline at end of file + +} diff --git a/notes/gtask/data/TaskList.java b/notes/gtask/data/TaskList.java index 276ccc6..4ea21c5 100644 --- a/notes/gtask/data/TaskList.java +++ b/notes/gtask/data/TaskList.java @@ -1,86 +1,108 @@ +/* + * 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.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 { - private static final String TAG = TaskList.class.getSimpleName();//tag标记 - - private int mIndex;//当前TaskList的指针 - - private ArrayList mChildren;//类中主要的保存数据的单元,用来实现一个以Task为元素的ArrayList - + private static final String TAG = TaskList.class.getSimpleName(); + + private int mIndex; + + private ArrayList mChildren; + public TaskList() { super(); mChildren = new ArrayList(); mIndex = 1; } - - /* (non-Javadoc) - * @see net.micode.notes.gtask.data.Node#getCreateAction(int) - * 生成并返回一个包含了一定数据的JSONObject实体 - */ + public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); - + try { // action_type js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - + // action_id js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - + // index js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); - + // entity_delta - JSONObject entity = new JSONObject();//entity实体 + JSONObject entity = new JSONObject(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to generate tasklist-create jsonobject"); } - + return js; } - - /* (non-Javadoc) - * @see net.micode.notes.gtask.data.Node#getUpdateAction(int) - * 生成并返回一个包含了一定数据的JSONObject实体 - */ + public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); - + try { // action_type js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - + // action_id js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - + // id js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - + // entity_delta JSONObject entity = new JSONObject(); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to generate tasklist-update jsonobject"); } - + return js; } - + public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -88,17 +110,17 @@ public class TaskList extends Node { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); } - + // last_modified if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); } - + // name if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); } - + } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); @@ -106,31 +128,22 @@ public class TaskList extends Node { } } } - - public void setContentByLocalJSON(JSONObject js) { - // 判断js是否为空,或者js中是否有GTaskStringUtils.META_HEAD_NOTE + + public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); } - + try { - // 获取js中的JSONObject JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - - // 判断folder的类型是否为folder + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // 获取folder的name String name = folder.getString(NoteColumns.SNIPPET); - // 设置name setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - // 判断folder的id是否为Notes.ID_ROOT_FOLDER if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) - // 设置name setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); - // 判断folder的id是否为Notes.ID_CALL_RECORD_FOLDER else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) - // 设置name setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE); else @@ -143,33 +156,25 @@ public class TaskList extends Node { e.printStackTrace(); } } - - public JSONObject getLocalJSONFromContent() { + + public JSONObject getLocalJSONFromContent() { try { - // 创建一个JSONObject对象 JSONObject js = new JSONObject(); - // 创建一个JSONObject对象,用于存放文件夹信息 JSONObject folder = new JSONObject(); - - // 获取文件夹名 + String folderName = getName(); - // 如果文件夹名以MIUI_FOLDER_PREFFIX开头,则截取文件夹名 if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName.length()); - // 将文件夹名放入JSONObject对象中 folder.put(NoteColumns.SNIPPET, folderName); - // 如果文件夹名是默认文件夹或者电话记录文件夹,则将文件夹类型设置为系统文件夹,否则设置为普通文件夹 if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); else folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); - - // 将文件夹信息放入JSONObject对象中 + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); - - // 返回JSONObject对象 + return js; } catch (JSONException e) { Log.e(TAG, e.toString()); @@ -177,7 +182,7 @@ public class TaskList extends Node { return null; } } - + public int getSyncAction(Cursor c) { try { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { @@ -207,23 +212,14 @@ public class TaskList extends Node { Log.e(TAG, e.toString()); e.printStackTrace(); } - + return SYNC_ACTION_ERROR; } - - /** - * @return - * 功能:获得TaskList的大小,即mChildren的大小 - */ + public int getChildTaskCount() { return mChildren.size(); } - - /** - * @param task - * @return 返回值为是否成功添加任务。 - * 功能:在当前任务表末尾添加新的任务。 - */ + public boolean addChildTask(Task task) { boolean ret = false; if (task != null && !mChildren.contains(task)) { @@ -233,29 +229,21 @@ public class TaskList extends Node { task.setPriorSibling(mChildren.isEmpty() ? null : mChildren .get(mChildren.size() - 1)); task.setParent(this); - //注意:每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改 - //,接下来几个函数都有相关操作 } } return ret; } - - /** - * @param task - * @param index - * @return - * 功能:在当前任务表的指定位置添加新的任务。 - */ + public boolean addChildTask(Task task, int index) { if (index < 0 || index > mChildren.size()) { Log.e(TAG, "add child task: invalid index"); return false; } - + int pos = mChildren.indexOf(task); if (task != null && pos == -1) { mChildren.add(index, task); - + // update the task list Task preTask = null; Task afterTask = null; @@ -263,31 +251,26 @@ public class TaskList extends Node { preTask = mChildren.get(index - 1); if (index != mChildren.size() - 1) afterTask = mChildren.get(index + 1); - + task.setPriorSibling(preTask); if (afterTask != null) afterTask.setPriorSibling(task); } - + return true; } - - /** - * @param task - * @return 返回删除是否成功 - * 功能:删除TaskList中的一个Task - */ + public boolean removeChildTask(Task task) { boolean ret = false; int index = mChildren.indexOf(task); if (index != -1) { ret = mChildren.remove(task); - + if (ret) { // reset prior sibling and parent task.setPriorSibling(null); task.setParent(null); - + // update the task list if (index != mChildren.size()) { mChildren.get(index).setPriorSibling( @@ -297,37 +280,25 @@ public class TaskList extends Node { } return ret; } - - /** - * @param task - * @param index - * @return - * 功能:将当前TaskList中含有的某个Task移到index位置 - */ + public boolean moveChildTask(Task task, int index) { - + if (index < 0 || index >= mChildren.size()) { Log.e(TAG, "move child task: invalid index"); return false; } - + int pos = mChildren.indexOf(task); if (pos == -1) { Log.e(TAG, "move child task: the task should in the list"); return false; } - + if (pos == index) return true; return (removeChildTask(task) && addChildTask(task, index)); - //利用已实现好的功能完成当下功能; } - - /** - * @param gid - * @return返回寻找结果 - * 功能:按gid寻找Task - */ + public Task findChildTaskByGid(String gid) { for (int i = 0; i < mChildren.size(); i++) { Task t = mChildren.get(i); @@ -337,21 +308,11 @@ public class TaskList extends Node { } return null; } - - /** - * @param task - * @return - * 功能:返回指定Task的index - */ + public int getChildTaskIndex(Task task) { return mChildren.indexOf(task); } - - /** - * @param index - * @return - * 功能:返回指定index的Task - */ + public Task getChildTaskByIndex(int index) { if (index < 0 || index >= mChildren.size()) { Log.e(TAG, "getTaskByIndex: invalid index"); @@ -359,32 +320,24 @@ public class TaskList extends Node { } return mChildren.get(index); } - - /** - * @param gid - * @return - * 功能:返回指定gid的Task - */ + public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) {//一种常见的ArrayList的遍历方法(四种,见精读笔记) + for (Task task : mChildren) { if (task.getGid().equals(gid)) return task; } return null; } - - //获取子任务列表 + public ArrayList getChildTaskList() { return this.mChildren; } - - //设置索引 + public void setIndex(int index) { this.mIndex = index; } - - //获取索引 + public int getIndex() { return this.mIndex; } -} \ No newline at end of file +} diff --git a/notes/ui/NoteEditActivity.java b/notes/ui/NoteEditActivity.java index 5a88e7b..116ae53 100644 --- a/notes/ui/NoteEditActivity.java +++ b/notes/ui/NoteEditActivity.java @@ -28,6 +28,7 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Paint; +import android.location.LocationManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.Spannable; @@ -74,6 +75,14 @@ import java.util.regex.Pattern; public class NoteEditActivity extends Activity implements OnClickListener, NoteSettingChangedListener, OnTextViewChangeListener { + + + + + + + + private class HeadViewHolder { public TextView tvModified; @@ -395,6 +404,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; } mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); + local_sel(); } @Override @@ -882,4 +892,167 @@ public class NoteEditActivity extends Activity implements OnClickListener, private void showToast(int resId, int duration) { Toast.makeText(this, resId, duration).show(); } + + private String getLocation(){ + //1、获取位置管理器 + String city = null; + locationManager locationManager = (LocationManager) + getSystemService(Context.LOCATION_SERVICE); + //2.获取位置提供器,GPS 或是 NetWork + List providers = locationManager.getProviders(true); + if (providers.contains(LocationManager.GPS_PROVIDER)) { + //如果是 GPS + locationProvider = LocationManager.GPS_PROVIDER; + Log.v("TAG", "定位方式 GPS"); + } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) { + //如果是 Network + locationProvider = LocationManager.NETWORK_PROVIDER; + Log.v("TAG", "定位方式 Network"); + }else { + Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show(); + return null; + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + //获取权限(如果没有开启权限,会弹出对话框,询问是否开启权限) + if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED || + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) + != PackageManager.PERMISSION_GRANTED) { + //请求权限 + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE); + } else { + //3.获取上次的位置,一般第一次运行,此值为 null + Location location = locationManager.getLastKnownLocation(locationProvider); + if (location != null) { + Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show(); + Log.v("TAG", "获取上次的位置-经纬度:" + location.getLongitude() + " " + location.getLatitude()); + city = getAddress(location); + } else { + //监视地理位置变化,第二个和第三个参数分别为更新的最短时间 minTime 和短距离 minDistace + } + locationManager.requestLocationUpdates(locationProvider, 3000, 1,locationListener); + } + } else { + Location location = locationManager.getLastKnownLocation(locationProvider); + if (location!=null){ + Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show(); + Log.v("TAG", "获取上次的位置-经纬度:"+location.getLongitude()+" "+location.getLatitude()); + city=getAddress(location); + }else{ + //监视地理位置变化,第二个和第三个参数分别为更新的最短时间 minTime 和最短距离 minDistace + locationManager.requestLocationUpdates(locationProvider, 3000, 1,locationListener); + } + } + return city; + } + public LocationListener locationListener = new LocationListener(){ + // Provider 的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数 + public void onStatusChanged(String provider, int status, Bundle extras) { + } + // Provider 被 enable 时触发此函数,比如 GPS 被打开 + public void onProviderEnabled(String provider) { + } + // Provider 被 disable 时触发此函数,比如 GPS 被关闭 + public void onProviderDisabled(String provider) { + } + //当坐标改变时触发此函数,如果 Provider 传进相同的坐标,它就不会被触发 + public void onLocationChanged(Location location) { + if (location != null) { + //如果位置发生变化,重新显示地理位置经纬度 + Toast.makeText(NoteEditActivity.this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show(); + Log.v("TAG", "监视地理位置变化-经纬度:"+location.getLongitude()+" "+location.getLatitude()); + } + } + }; + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + switch (requestCode) { + case LOCATION_CODE: + if(grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED + && grantResults[1] == PackageManager.PERMISSION_GRANTED) { + Toast.makeText(this, "申请权限", Toast.LENGTH_LONG).show(); + try { + List providers = locationManager.getProviders(true); + if (providers.contains(LocationManager.NETWORK_PROVIDER)) { + //如果是 Network + locationProvider = LocationManager.NETWORK_PROVIDER; + }else if (providers.contains(LocationManager.GPS_PROVIDER)) { + //如果是 GPS + locationProvider = LocationManager.GPS_PROVIDER; + } + Location location = + locationManager.getLastKnownLocation(locationProvider); + if (location!=null){ + Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show(); + Log.v("TAG", "获取上次的位置-经纬度: "+location.getLongitude()+" "+location.getLatitude()); + }else{ +// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间 + minTime 和最短距离 minDistace + locationManager.requestLocationUpdates(locationProvider, 0, 0,locationListener); + } + }catch (SecurityException e){ + e.printStackTrace(); + } + } else { + Toast.makeText(this, "缺少权限", Toast.LENGTH_LONG).show(); + finish(); + } + break; + } + } + private String getAddress(Location location) { + List
result = null; + String city = null; + try { + if (location != null) { + Geocoder gc = new Geocoder(this, Locale.getDefault()); + result = gc.getFromLocation(location.getLatitude(),location.getLongitude(), 1); + city = result.get(0).getAddressLine(0).toString(); + Toast.makeText(this, "获取地址信息:"+city, Toast.LENGTH_LONG).show(); + Log.v("TAG", "获取地址信息:"+city); + } + } catch (Exception e) { + e.printStackTrace(); + } + Log.e(TAG, city); + return city; + } + private void local_sel(){ + final Button get_local = findViewById(R.id.location); + get_local.setOnClickListener(new OnClickListener() { + public void onClick(final View v) { + Button local1 = new Button(NoteEditActivity.this); + final Button local2 = new Button(NoteEditActivity.this); + local1.setText("获取地理信息"); + local2.setText("清除地理信息"); + LinearLayout linear = new LinearLayout(NoteEditActivity.this); + linear.setOrientation(LinearLayout.VERTICAL); + linear.addView(local1); + linear.addView(local2); + AlertDialog.Builder builder = new AlertDialog.Builder(NoteEditActivity.this); + builder.setView(linear); + builder.setTitle("请选择功能"); + AlertDialog choose_local = builder.create(); + choose_local.show(); + local1.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + Toast.makeText(NoteEditActivity.this, "获取地理信息", Toast.LENGTH_SHORT).show(); + String city = null; + city = getLocation(); + if(city == null) { + get_local.setText("点击获得地理信息"); + } else{ + get_local.setText(city); + } + } + }); + local2.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + Toast.makeText(NoteEditActivity.this, "清除地理信息", Toast.LENGTH_SHORT).show(); + get_local.setText("点击获得地理信息"); + } + }); + } + }); + } + }