();
+ }
+
+ // 如果缓存中已存在该电话号码的联系人,则直接返回其名称
+ if(sContactCache.containsKey(phoneNumber)) {
+ return sContactCache.get(phoneNumber);
+ }
+
+ // 替换CALLER_ID_SELECTION中的"+"为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) {
+ // 获取联系人名称出错,记录日志并返回null
+ Log.e(TAG, " Cursor get string error " + e.toString());
+ return null;
+ } finally {
+ // 关闭游标
+ cursor.close();
+ }
+ } else {
+ // 查询结果为空,记录日志并返回null
+ Log.d(TAG, "No contact matched with number:" + phoneNumber);
+ return null;
+ }
+ }
+}
+/*这个类主要用于根据电话号码查询联系人名称。在查询过程中,会将查询到的联系人名称缓存在一个HashMap中,以便于下次查询时直接从缓存中获取。*/
\ No newline at end of file
diff --git a/doc/data/Notes.java b/doc/data/Notes.java
new file mode 100644
index 0000000..f240604
--- /dev/null
+++ b/doc/data/Notes.java
@@ -0,0 +1,279 @@
+/*
+ * 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.data;
+
+import android.net.Uri;
+public class Notes {
+ public static final String AUTHORITY = "micode_notes";
+ public static final String TAG = "Notes";
+ public static final int TYPE_NOTE = 0;
+ public static final int TYPE_FOLDER = 1;
+ public static final int TYPE_SYSTEM = 2;
+
+ /**
+ * Following IDs are system folders' identifiers
+ * {@link Notes#ID_ROOT_FOLDER } is default folder
+ * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
+ * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
+ */
+ public static final int ID_ROOT_FOLDER = 0;
+ public static final int ID_TEMPARAY_FOLDER = -1;
+ public static final int ID_CALL_RECORD_FOLDER = -2;
+ public static final int ID_TRASH_FOLER = -3;
+
+ public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
+ public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
+ public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
+ public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
+ public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
+ public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
+
+ public static final int TYPE_WIDGET_INVALIDE = -1;
+ public static final int TYPE_WIDGET_2X = 0;
+ public static final int TYPE_WIDGET_4X = 1;
+
+ public static class DataConstants {
+ public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
+ public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
+ }
+
+ /**
+ * Uri to query all notes and folders
+ */
+ public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
+
+ /**
+ * Uri to query data
+ */
+ public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
+
+ public interface NoteColumns {
+ /**
+ * The unique ID for a row
+ * Type: INTEGER (long)
+ */
+ public static final String ID = "_id";
+
+ /**
+ * The parent's id for note or folder
+ * Type: INTEGER (long)
+ */
+ public static final String PARENT_ID = "parent_id";
+
+ /**
+ * Created data for note or folder
+ * Type: INTEGER (long)
+ */
+ public static final String CREATED_DATE = "created_date";
+
+ /**
+ * Latest modified date
+ * Type: INTEGER (long)
+ */
+ public static final String MODIFIED_DATE = "modified_date";
+
+
+ /**
+ * Alert date
+ * Type: INTEGER (long)
+ */
+ public static final String ALERTED_DATE = "alert_date";
+
+ /**
+ * Folder's name or text content of note
+ * Type: TEXT
+ */
+ public static final String SNIPPET = "snippet";
+
+ /**
+ * Note's widget id
+ * Type: INTEGER (long)
+ */
+ public static final String WIDGET_ID = "widget_id";
+
+ /**
+ * Note's widget type
+ * Type: INTEGER (long)
+ */
+ public static final String WIDGET_TYPE = "widget_type";
+
+ /**
+ * Note's background color's id
+ * Type: INTEGER (long)
+ */
+ public static final String BG_COLOR_ID = "bg_color_id";
+
+ /**
+ * For text note, it doesn't has attachment, for multi-media
+ * note, it has at least one attachment
+ * Type: INTEGER
+ */
+ public static final String HAS_ATTACHMENT = "has_attachment";
+
+ /**
+ * Folder's count of notes
+ * Type: INTEGER (long)
+ */
+ public static final String NOTES_COUNT = "notes_count";
+
+ /**
+ * The file type: folder or note
+ * Type: INTEGER
+ */
+ public static final String TYPE = "type";
+
+ /**
+ * The last sync id
+ * Type: INTEGER (long)
+ */
+ public static final String SYNC_ID = "sync_id";
+
+ /**
+ * Sign to indicate local modified or not
+ * Type: INTEGER
+ */
+ public static final String LOCAL_MODIFIED = "local_modified";
+
+ /**
+ * Original parent id before moving into temporary folder
+ * Type : INTEGER
+ */
+ public static final String ORIGIN_PARENT_ID = "origin_parent_id";
+
+ /**
+ * The gtask id
+ * Type : TEXT
+ */
+ public static final String GTASK_ID = "gtask_id";
+
+ /**
+ * The version code
+ * Type : INTEGER (long)
+ */
+ public static final String VERSION = "version";
+ }
+
+ public interface DataColumns {
+ /**
+ * The unique ID for a row
+ * Type: INTEGER (long)
+ */
+ public static final String ID = "_id";
+
+ /**
+ * The MIME type of the item represented by this row.
+ * Type: Text
+ */
+ public static final String MIME_TYPE = "mime_type";
+
+ /**
+ * The reference id to note that this data belongs to
+ * Type: INTEGER (long)
+ */
+ public static final String NOTE_ID = "note_id";
+
+ /**
+ * Created data for note or folder
+ * Type: INTEGER (long)
+ */
+ public static final String CREATED_DATE = "created_date";
+
+ /**
+ * Latest modified date
+ * Type: INTEGER (long)
+ */
+ public static final String MODIFIED_DATE = "modified_date";
+
+ /**
+ * Data's content
+ * Type: TEXT
+ */
+ public static final String CONTENT = "content";
+
+
+ /**
+ * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
+ * integer data type
+ * Type: INTEGER
+ */
+ public static final String DATA1 = "data1";
+
+ /**
+ * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
+ * integer data type
+ * Type: INTEGER
+ */
+ public static final String DATA2 = "data2";
+
+ /**
+ * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
+ * TEXT data type
+ * Type: TEXT
+ */
+ public static final String DATA3 = "data3";
+
+ /**
+ * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
+ * TEXT data type
+ * Type: TEXT
+ */
+ public static final String DATA4 = "data4";
+
+ /**
+ * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
+ * TEXT data type
+ * Type: TEXT
+ */
+ public static final String DATA5 = "data5";
+ }
+
+ public static final class TextNote implements DataColumns {
+ /**
+ * Mode to indicate the text in check list mode or not
+ * Type: Integer 1:check list mode 0: normal mode
+ */
+ public static final String MODE = DATA1;
+
+ public static final int MODE_CHECK_LIST = 1;
+
+ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
+
+ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
+
+ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
+ }
+
+ public static final class CallNote implements DataColumns {
+ /**
+ * Call date for this record
+ * Type: INTEGER (long)
+ */
+ public static final String CALL_DATE = DATA1;
+
+ /**
+ * Phone number for this record
+ * Type: TEXT
+ */
+ public static final String PHONE_NUMBER = DATA3;
+
+ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
+
+ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
+
+ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
+ }
+}
diff --git a/doc/data/NotesDatabaseHelper.java b/doc/data/NotesDatabaseHelper.java
new file mode 100644
index 0000000..ffe5d57
--- /dev/null
+++ b/doc/data/NotesDatabaseHelper.java
@@ -0,0 +1,362 @@
+/*
+ * 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.data;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.util.Log;
+
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.DataConstants;
+import net.micode.notes.data.Notes.NoteColumns;
+
+
+public class NotesDatabaseHelper extends SQLiteOpenHelper {
+ private static final String DB_NAME = "note.db";
+
+ private static final int DB_VERSION = 4;
+
+ public interface TABLE {
+ public static final String NOTE = "note";
+
+ public static final String DATA = "data";
+ }
+
+ private static final String TAG = "NotesDatabaseHelper";
+
+ private static NotesDatabaseHelper mInstance;
+
+ private static final String CREATE_NOTE_TABLE_SQL =
+ "CREATE TABLE " + TABLE.NOTE + "(" +
+ NoteColumns.ID + " INTEGER PRIMARY KEY," +
+ NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
+ NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
+ NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
+ NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
+ NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
+ NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
+ ")";
+
+ private static final String CREATE_DATA_TABLE_SQL =
+ "CREATE TABLE " + TABLE.DATA + "(" +
+ DataColumns.ID + " INTEGER PRIMARY KEY," +
+ DataColumns.MIME_TYPE + " TEXT NOT NULL," +
+ DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
+ NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
+ NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
+ DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
+ DataColumns.DATA1 + " INTEGER," +
+ DataColumns.DATA2 + " INTEGER," +
+ DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
+ DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
+ DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
+ ")";
+
+ private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
+ "CREATE INDEX IF NOT EXISTS note_id_index ON " +
+ TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
+
+ /**
+ * Increase folder's note count when move note to the folder
+ */
+ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
+ "CREATE TRIGGER increase_folder_count_on_update "+
+ " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
+ " BEGIN " +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
+ " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
+ " END";
+
+ /**
+ * Decrease folder's note count when move note from folder
+ */
+ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
+ "CREATE TRIGGER decrease_folder_count_on_update " +
+ " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
+ " BEGIN " +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
+ " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
+ " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
+ " END";
+
+ /**
+ * Increase folder's note count when insert new note to the folder
+ */
+ private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
+ "CREATE TRIGGER increase_folder_count_on_insert " +
+ " AFTER INSERT ON " + TABLE.NOTE +
+ " BEGIN " +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
+ " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
+ " END";
+
+ /**
+ * Decrease folder's note count when delete note from the folder
+ */
+ private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
+ "CREATE TRIGGER decrease_folder_count_on_delete " +
+ " AFTER DELETE ON " + TABLE.NOTE +
+ " BEGIN " +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
+ " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
+ " AND " + NoteColumns.NOTES_COUNT + ">0;" +
+ " END";
+
+ /**
+ * Update note's content when insert data with type {@link DataConstants#NOTE}
+ */
+ private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
+ "CREATE TRIGGER update_note_content_on_insert " +
+ " AFTER INSERT ON " + TABLE.DATA +
+ " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
+ " BEGIN" +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
+ " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
+ " END";
+
+ /**
+ * Update note's content when data with {@link DataConstants#NOTE} type has changed
+ */
+ private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
+ "CREATE TRIGGER update_note_content_on_update " +
+ " AFTER UPDATE ON " + TABLE.DATA +
+ " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
+ " BEGIN" +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
+ " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
+ " END";
+
+ /**
+ * Update note's content when data with {@link DataConstants#NOTE} type has deleted
+ */
+ private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
+ "CREATE TRIGGER update_note_content_on_delete " +
+ " AFTER delete ON " + TABLE.DATA +
+ " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
+ " BEGIN" +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.SNIPPET + "=''" +
+ " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
+ " END";
+
+ /**
+ * Delete datas belong to note which has been deleted
+ */
+ private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
+ "CREATE TRIGGER delete_data_on_delete " +
+ " AFTER DELETE ON " + TABLE.NOTE +
+ " BEGIN" +
+ " DELETE FROM " + TABLE.DATA +
+ " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
+ " END";
+
+ /**
+ * Delete notes belong to folder which has been deleted
+ */
+ private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
+ "CREATE TRIGGER folder_delete_notes_on_delete " +
+ " AFTER DELETE ON " + TABLE.NOTE +
+ " BEGIN" +
+ " DELETE FROM " + TABLE.NOTE +
+ " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
+ " END";
+
+ /**
+ * Move notes belong to folder which has been moved to trash folder
+ */
+ private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
+ "CREATE TRIGGER folder_move_notes_on_trash " +
+ " AFTER UPDATE ON " + TABLE.NOTE +
+ " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
+ " BEGIN" +
+ " UPDATE " + TABLE.NOTE +
+ " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
+ " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
+ " END";
+
+ public NotesDatabaseHelper(Context context) {
+ super(context, DB_NAME, null, DB_VERSION);
+ }
+
+ public void createNoteTable(SQLiteDatabase db) {
+ db.execSQL(CREATE_NOTE_TABLE_SQL);
+ reCreateNoteTableTriggers(db);
+ createSystemFolder(db);
+ Log.d(TAG, "note table has been created");
+ }
+
+ private void reCreateNoteTableTriggers(SQLiteDatabase db) {
+ db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
+ db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
+ db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
+ db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
+ db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
+ db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
+ db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
+
+ db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
+ db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
+ db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
+ db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
+ db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
+ db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
+ db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
+ }
+
+ private void createSystemFolder(SQLiteDatabase db) {
+ ContentValues values = new ContentValues();
+
+ /**
+ * call record foler for call notes
+ */
+ values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
+ values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ db.insert(TABLE.NOTE, null, values);
+
+ /**
+ * root folder which is default folder
+ */
+ values.clear();
+ values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
+ values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ db.insert(TABLE.NOTE, null, values);
+
+ /**
+ * temporary folder which is used for moving note
+ */
+ values.clear();
+ values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
+ values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ db.insert(TABLE.NOTE, null, values);
+
+ /**
+ * create trash folder
+ */
+ values.clear();
+ values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
+ values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ db.insert(TABLE.NOTE, null, values);
+ }
+
+ public void createDataTable(SQLiteDatabase db) {
+ db.execSQL(CREATE_DATA_TABLE_SQL);
+ reCreateDataTableTriggers(db);
+ db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
+ Log.d(TAG, "data table has been created");
+ }
+
+ private void reCreateDataTableTriggers(SQLiteDatabase db) {
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
+
+ db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
+ db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
+ db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
+ }
+
+ static synchronized NotesDatabaseHelper getInstance(Context context) {
+ if (mInstance == null) {
+ mInstance = new NotesDatabaseHelper(context);
+ }
+ return mInstance;
+ }
+
+ @Override
+ public void onCreate(SQLiteDatabase db) {
+ createNoteTable(db);
+ createDataTable(db);
+ }
+
+ @Override
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+ boolean reCreateTriggers = false;
+ boolean skipV2 = false;
+
+ if (oldVersion == 1) {
+ upgradeToV2(db);
+ skipV2 = true; // this upgrade including the upgrade from v2 to v3
+ oldVersion++;
+ }
+
+ if (oldVersion == 2 && !skipV2) {
+ upgradeToV3(db);
+ reCreateTriggers = true;
+ oldVersion++;
+ }
+
+ if (oldVersion == 3) {
+ upgradeToV4(db);
+ oldVersion++;
+ }
+
+ if (reCreateTriggers) {
+ reCreateNoteTableTriggers(db);
+ reCreateDataTableTriggers(db);
+ }
+
+ if (oldVersion != newVersion) {
+ throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ + "fails");
+ }
+ }
+
+ private void upgradeToV2(SQLiteDatabase db) {
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
+ createNoteTable(db);
+ createDataTable(db);
+ }
+
+ private void upgradeToV3(SQLiteDatabase db) {
+ // drop unused triggers
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
+ db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
+ // add a column for gtask id
+ db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ + " TEXT NOT NULL DEFAULT ''");
+ // add a trash system folder
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
+ values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ db.insert(TABLE.NOTE, null, values);
+ }
+
+ private void upgradeToV4(SQLiteDatabase db) {
+ db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ + " INTEGER NOT NULL DEFAULT 0");
+ }
+}
diff --git a/doc/data/NotesProvider.java b/doc/data/NotesProvider.java
new file mode 100644
index 0000000..edb0a60
--- /dev/null
+++ b/doc/data/NotesProvider.java
@@ -0,0 +1,305 @@
+/*
+ * 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.data;
+
+
+import android.app.SearchManager;
+import android.content.ContentProvider;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Intent;
+import android.content.UriMatcher;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.net.Uri;
+import android.text.TextUtils;
+import android.util.Log;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.data.NotesDatabaseHelper.TABLE;
+
+
+public class NotesProvider extends ContentProvider {
+ private static final UriMatcher mMatcher;
+
+ private NotesDatabaseHelper mHelper;
+
+ private static final String TAG = "NotesProvider";
+
+ private static final int URI_NOTE = 1;
+ private static final int URI_NOTE_ITEM = 2;
+ private static final int URI_DATA = 3;
+ private static final int URI_DATA_ITEM = 4;
+
+ private static final int URI_SEARCH = 5;
+ private static final int URI_SEARCH_SUGGEST = 6;
+
+ static {
+ mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+ mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
+ mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
+ mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
+ mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
+ mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
+ mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
+ mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
+ }
+
+ /**
+ * x'0A' represents the '\n' character in sqlite. For title and content in the search result,
+ * we will trim '\n' and white space in order to show more information.
+ */
+ private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
+
+ private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ + " FROM " + TABLE.NOTE
+ + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
+
+ @Override
+ public boolean onCreate() {
+ mHelper = NotesDatabaseHelper.getInstance(getContext());
+ return true;
+ }
+
+ @Override
+ public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+ String sortOrder) {
+ Cursor c = null;
+ SQLiteDatabase db = mHelper.getReadableDatabase();
+ String id = null;
+ switch (mMatcher.match(uri)) {
+ case URI_NOTE:
+ c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
+ sortOrder);
+ break;
+ case URI_NOTE_ITEM:
+ id = uri.getPathSegments().get(1);
+ c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ + parseSelection(selection), selectionArgs, null, null, sortOrder);
+ break;
+ case URI_DATA:
+ c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
+ sortOrder);
+ break;
+ case URI_DATA_ITEM:
+ id = uri.getPathSegments().get(1);
+ c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ + parseSelection(selection), selectionArgs, null, null, sortOrder);
+ break;
+ case URI_SEARCH:
+ case URI_SEARCH_SUGGEST:
+ if (sortOrder != null || projection != null) {
+ throw new IllegalArgumentException(
+ "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
+ }
+
+ String searchString = null;
+ if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
+ if (uri.getPathSegments().size() > 1) {
+ searchString = uri.getPathSegments().get(1);
+ }
+ } else {
+ searchString = uri.getQueryParameter("pattern");
+ }
+
+ if (TextUtils.isEmpty(searchString)) {
+ return null;
+ }
+
+ try {
+ searchString = String.format("%%%s%%", searchString);
+ c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
+ new String[] { searchString });
+ } catch (IllegalStateException ex) {
+ Log.e(TAG, "got exception: " + ex.toString());
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown URI " + uri);
+ }
+ if (c != null) {
+ c.setNotificationUri(getContext().getContentResolver(), uri);
+ }
+ return c;
+ }
+
+ @Override
+ public Uri insert(Uri uri, ContentValues values) {
+ SQLiteDatabase db = mHelper.getWritableDatabase();
+ long dataId = 0, noteId = 0, insertedId = 0;
+ switch (mMatcher.match(uri)) {
+ case URI_NOTE:
+ insertedId = noteId = db.insert(TABLE.NOTE, null, values);
+ break;
+ case URI_DATA:
+ if (values.containsKey(DataColumns.NOTE_ID)) {
+ noteId = values.getAsLong(DataColumns.NOTE_ID);
+ } else {
+ Log.d(TAG, "Wrong data format without note id:" + values.toString());
+ }
+ insertedId = dataId = db.insert(TABLE.DATA, null, values);
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown URI " + uri);
+ }
+ // Notify the note uri
+ if (noteId > 0) {
+ getContext().getContentResolver().notifyChange(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
+ }
+
+ // Notify the data uri
+ if (dataId > 0) {
+ getContext().getContentResolver().notifyChange(
+ ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
+ }
+
+ return ContentUris.withAppendedId(uri, insertedId);
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ int count = 0;
+ String id = null;
+ SQLiteDatabase db = mHelper.getWritableDatabase();
+ boolean deleteData = false;
+ switch (mMatcher.match(uri)) {
+ case URI_NOTE:
+ selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
+ count = db.delete(TABLE.NOTE, selection, selectionArgs);
+ break;
+ case URI_NOTE_ITEM:
+ id = uri.getPathSegments().get(1);
+ /**
+ * ID that smaller than 0 is system folder which is not allowed to
+ * trash
+ */
+ long noteId = Long.valueOf(id);
+ if (noteId <= 0) {
+ break;
+ }
+ count = db.delete(TABLE.NOTE,
+ NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
+ break;
+ case URI_DATA:
+ count = db.delete(TABLE.DATA, selection, selectionArgs);
+ deleteData = true;
+ break;
+ case URI_DATA_ITEM:
+ id = uri.getPathSegments().get(1);
+ count = db.delete(TABLE.DATA,
+ DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
+ deleteData = true;
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown URI " + uri);
+ }
+ if (count > 0) {
+ if (deleteData) {
+ getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
+ }
+ getContext().getContentResolver().notifyChange(uri, null);
+ }
+ return count;
+ }
+
+ @Override
+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ int count = 0;
+ String id = null;
+ SQLiteDatabase db = mHelper.getWritableDatabase();
+ boolean updateData = false;
+ switch (mMatcher.match(uri)) {
+ case URI_NOTE:
+ increaseNoteVersion(-1, selection, selectionArgs);
+ count = db.update(TABLE.NOTE, values, selection, selectionArgs);
+ break;
+ case URI_NOTE_ITEM:
+ id = uri.getPathSegments().get(1);
+ increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
+ count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ + parseSelection(selection), selectionArgs);
+ break;
+ case URI_DATA:
+ count = db.update(TABLE.DATA, values, selection, selectionArgs);
+ updateData = true;
+ break;
+ case URI_DATA_ITEM:
+ id = uri.getPathSegments().get(1);
+ count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ + parseSelection(selection), selectionArgs);
+ updateData = true;
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown URI " + uri);
+ }
+
+ if (count > 0) {
+ if (updateData) {
+ getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
+ }
+ getContext().getContentResolver().notifyChange(uri, null);
+ }
+ return count;
+ }
+
+ private String parseSelection(String selection) {
+ return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
+ }
+
+ private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
+ StringBuilder sql = new StringBuilder(120);
+ sql.append("UPDATE ");
+ sql.append(TABLE.NOTE);
+ sql.append(" SET ");
+ sql.append(NoteColumns.VERSION);
+ sql.append("=" + NoteColumns.VERSION + "+1 ");
+
+ if (id > 0 || !TextUtils.isEmpty(selection)) {
+ sql.append(" WHERE ");
+ }
+ if (id > 0) {
+ sql.append(NoteColumns.ID + "=" + String.valueOf(id));
+ }
+ if (!TextUtils.isEmpty(selection)) {
+ String selectString = id > 0 ? parseSelection(selection) : selection;
+ for (String args : selectionArgs) {
+ selectString = selectString.replaceFirst("\\?", args);
+ }
+ sql.append(selectString);
+ }
+
+ mHelper.getWritableDatabase().execSQL(sql.toString());
+ }
+
+ @Override
+ public String getType(Uri uri) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/other/06_江一阳_代码标注/gtask/data/MetaData.java b/doc/gtask/data/MetaData.java
similarity index 71%
rename from other/06_江一阳_代码标注/gtask/data/MetaData.java
rename to doc/gtask/data/MetaData.java
index 01afbd2..3a2050b 100644
--- a/other/06_江一阳_代码标注/gtask/data/MetaData.java
+++ b/doc/gtask/data/MetaData.java
@@ -16,7 +16,6 @@
package net.micode.notes.gtask.data;
-// 导入所需的类和包
import android.database.Cursor;
import android.util.Log;
@@ -25,70 +24,56 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
-// MetaData类继承自Task类,用于处理与Google任务相关的元数据
+
public class MetaData extends Task {
- // 定义类的TAG,用于日志记录
private final static String TAG = MetaData.class.getSimpleName();
- // 定义一个变量用于存储与Google任务相关的ID
+
private String mRelatedGid = null;
- // 设置元数据方法,接收一个gid和一个metaInfo JSONObject对象
public void setMeta(String gid, JSONObject metaInfo) {
try {
- // 将gid存储在metaInfo的JSON对象中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
- // 记录错误日志
Log.e(TAG, "failed to put related gid");
}
- // 记录错误日志
setNotes(metaInfo.toString());
- // 设置元数据任务的名称
setName(GTaskStringUtils.META_NOTE_NAME);
}
- // 获取与Google任务相关的ID的方法
public String getRelatedGid() {
return mRelatedGid;
}
- // 重写isWorthSaving方法,判断是否值得保存
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
- // 从远程JSON设置内容
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
- // 解析notes中的JSON字符串
JSONObject metaInfo = new JSONObject(getNotes().trim());
- // 从JSON对象中获取与Google任务相关的ID
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
- // 记录警告日志
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
- // 从本地JSON设置内容,但是不应该被调用,因此抛出异常
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
- // 从内容获取本地JSON,但是不应该被调用,因此抛出异常
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
- // 获取同步操作,但是不应该被调用,因此抛出异常
+
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
diff --git a/other/06_江一阳_代码标注/gtask/data/Node.java b/doc/gtask/data/Node.java
similarity index 77%
rename from other/06_江一阳_代码标注/gtask/data/Node.java
rename to doc/gtask/data/Node.java
index f205cdf..63950e0 100644
--- a/other/06_江一阳_代码标注/gtask/data/Node.java
+++ b/doc/gtask/data/Node.java
@@ -16,14 +16,11 @@
package net.micode.notes.gtask.data;
-// 导入所需的类和包
import android.database.Cursor;
import org.json.JSONObject;
-// 定义一个抽象类Node,用于表示各种数据节点
public abstract class Node {
- // 定义同步操作的常量
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;
@@ -41,7 +38,7 @@ public abstract class Node {
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
- // 定义节点的基本属性
+
private String mGid;
private String mName;
@@ -50,7 +47,6 @@ public abstract class Node {
private boolean mDeleted;
- // 构造方法,初始化节点的属性
public Node() {
mGid = null;
mName = "";
@@ -58,25 +54,18 @@ public abstract class Node {
mDeleted = false;
}
- // 定义抽象方法,用于获取创建操作的JSON对象
public abstract JSONObject getCreateAction(int actionId);
- // 定义抽象方法,用于获取更新操作的JSON对象
public abstract JSONObject getUpdateAction(int actionId);
- // 定义抽象方法,用于根据远程JSON设置节点的内容
public abstract void setContentByRemoteJSON(JSONObject js);
- // 定义抽象方法,用于根据本地JSON设置节点的内容
public abstract void setContentByLocalJSON(JSONObject js);
- // 定义抽象方法,用于根据内容获取本地JSON
public abstract JSONObject getLocalJSONFromContent();
- // 定义抽象方法,用于获取同步操作类型
public abstract int getSyncAction(Cursor c);
- // 定义setter方法,用于设置节点的属性
public void setGid(String gid) {
this.mGid = gid;
}
@@ -93,7 +82,6 @@ public abstract class Node {
this.mDeleted = deleted;
}
- // 定义getter方法,用于获取节点的属性
public String getGid() {
return this.mGid;
}
diff --git a/other/06_江一阳_代码标注/gtask/data/SqlData.java b/doc/gtask/data/SqlData.java
similarity index 93%
rename from other/06_江一阳_代码标注/gtask/data/SqlData.java
rename to doc/gtask/data/SqlData.java
index 2685b8a..d3ec3be 100644
--- a/other/06_江一阳_代码标注/gtask/data/SqlData.java
+++ b/doc/gtask/data/SqlData.java
@@ -15,7 +15,7 @@
*/
package net.micode.notes.gtask.data;
-// 导入所需的类和包
+
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
@@ -34,13 +34,12 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
-// 定义一个名为SqlData的类,用于表示SQL数据
+
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
@@ -55,7 +54,7 @@ public class SqlData {
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;
@@ -71,7 +70,7 @@ public class SqlData {
private String mDataContentData3;
private ContentValues mDiffDataValues;
- // 构造方法,初始化类的属性
+
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@@ -82,14 +81,14 @@ public class SqlData {
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}
- // 基于现有的游标创建SqlData实例
+
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);
@@ -97,7 +96,7 @@ public class SqlData {
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
- // 从JSONObject设置内容
+
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
@@ -130,7 +129,7 @@ public class SqlData {
}
mDataContentData3 = dataContentData3;
}
- // 获取内容并将其转换为JSONObject
+
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@@ -144,7 +143,7 @@ public class SqlData {
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}
- // 提交更改到数据库
+
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@@ -183,7 +182,7 @@ public class SqlData {
mDiffDataValues.clear();
mIsCreate = false;
}
- // 获取数据ID
+
public long getId() {
return mDataId;
}
diff --git a/other/06_江一阳_代码标注/gtask/data/SqlNote.java b/doc/gtask/data/SqlNote.java
similarity index 95%
rename from other/06_江一阳_代码标注/gtask/data/SqlNote.java
rename to doc/gtask/data/SqlNote.java
index ddcb8a1..79a4095 100644
--- a/other/06_江一阳_代码标注/gtask/data/SqlNote.java
+++ b/doc/gtask/data/SqlNote.java
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-// 导入相关类和包
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
@@ -38,13 +37,12 @@ import org.json.JSONObject;
import java.util.ArrayList;
-// 定义 SqlNote 类
+
public class SqlNote {
- // 定义日志标签,用于调试和输出日志信息
private static final String TAG = SqlNote.class.getSimpleName();
- // 定义一个无效的 ID 常量
+
private static final int INVALID_ID = -99999;
- // 定义 PROJECTION_NOTE 数组,用于查询数据库时指定需要的列
+
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,
@@ -124,7 +122,6 @@ public class SqlNote {
private ArrayList mDataList;
- // 构造方法:用于创建新的笔记对象
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -146,7 +143,6 @@ public class SqlNote {
mDataList = new ArrayList();
}
- // 构造方法:用于从数据库的 Cursor 加载笔记对象
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -158,7 +154,6 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
- // 构造方法:通过笔记 ID 从数据库加载笔记对象
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@@ -171,13 +166,12 @@ public class SqlNote {
}
- // 通过笔记 ID 从数据库加载笔记数据
private void loadFromCursor(long id) {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
- String.valueOf(id)
+ String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
@@ -191,7 +185,6 @@ public class SqlNote {
}
}
- // 从 Cursor 加载 SqlNote 对象的数据
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@@ -207,14 +200,13 @@ public class SqlNote {
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)
+ String.valueOf(mId)
}, null);
if (c != null) {
if (c.getCount() == 0) {
@@ -236,7 +228,6 @@ public class SqlNote {
public boolean setContent(JSONObject js) {
try {
- // 获取包含笔记信息的 JSON 对象
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
@@ -477,14 +468,13 @@ public class SqlNote {
throw new IllegalStateException("Try to update note with invalid id");
}
if (mDiffNoteValues.size() > 0) {
- mVersion++;
+ mVersion ++;
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
- + NoteColumns.ID + "=?)",
- new String[] {
- String.valueOf(mId)
- });
+ + NoteColumns.ID + "=?)", new String[] {
+ String.valueOf(mId)
+ });
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
diff --git a/doc/gtask/data/Task.java b/doc/gtask/data/Task.java
new file mode 100644
index 0000000..1c6ef20
--- /dev/null
+++ b/doc/gtask/data/Task.java
@@ -0,0 +1,351 @@
+/*
+ * 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.
+ */
+/*ceshi*/
+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 String mNotes;
+
+ private JSONObject mMetaInfo;
+
+ private Task mPriorSibling;
+
+ private TaskList mParent;
+
+ public Task() {
+ super();
+ mCompleted = false;
+ mNotes = null;
+ 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());
+ entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
+ entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
+ GTaskStringUtils.GTASK_JSON_TYPE_TASK);
+ if (getNotes() != null) {
+ entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
+ }
+ js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
+
+ // parent_id
+ 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
+ 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());
+ if (getNotes() != null) {
+ entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
+ }
+ 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 {
+ // id
+ 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));
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to get task content from jsonobject");
+ }
+ }
+ }
+
+ 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");
+ return;
+ }
+
+ for (int i = 0; i < dataArray.length(); i++) {
+ JSONObject data = dataArray.getJSONObject(i);
+ if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
+ setName(data.getString(DataColumns.CONTENT));
+ break;
+ }
+ }
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+ }
+
+ public JSONObject getLocalJSONFromContent() {
+ String name = getName();
+ try {
+ if (mMetaInfo == null) {
+ // new task created from web
+ if (name == null) {
+ 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();
+ JSONObject data = new JSONObject();
+ data.put(DataColumns.CONTENT, name);
+ dataArray.put(data);
+ js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
+ note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
+ js.put(GTaskStringUtils.META_HEAD_NOTE, note);
+ return js;
+ } else {
+ // 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)) {
+ data.put(DataColumns.CONTENT, getName());
+ break;
+ }
+ }
+
+ note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
+ return mMetaInfo;
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public void setMetaInfo(MetaData metaData) {
+ if (metaData != null && metaData.getNotes() != null) {
+ try {
+ mMetaInfo = new JSONObject(metaData.getNotes());
+ } catch (JSONException e) {
+ Log.w(TAG, e.toString());
+ mMetaInfo = null;
+ }
+ }
+ }
+
+ 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()) {
+ // no update both side
+ return SYNC_ACTION_NONE;
+ } else {
+ // apply remote to local
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+ } else {
+ // validate gtask id
+ if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
+ Log.e(TAG, "gtask id doesn't match");
+ return SYNC_ACTION_ERROR;
+ }
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // local modification only
+ return SYNC_ACTION_UPDATE_REMOTE;
+ } else {
+ return SYNC_ACTION_UPDATE_CONFLICT;
+ }
+ }
+ } catch (Exception e) {
+ 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;
+ }
+
+}
diff --git a/doc/gtask/data/TaskList.java b/doc/gtask/data/TaskList.java
new file mode 100644
index 0000000..4ea21c5
--- /dev/null
+++ b/doc/gtask/data/TaskList.java
@@ -0,0 +1,343 @@
+/*
+ * 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();
+
+ private int mIndex;
+
+ private ArrayList mChildren;
+
+ public TaskList() {
+ super();
+ mChildren = new ArrayList();
+ mIndex = 1;
+ }
+
+ 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.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;
+ }
+
+ 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 {
+ // id
+ 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();
+ throw new ActionFailureException("fail to get tasklist content from jsonobject");
+ }
+ }
+ }
+
+ public void setContentByLocalJSON(JSONObject js) {
+ if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
+ Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
+ }
+
+ try {
+ JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+
+ if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
+ String name = folder.getString(NoteColumns.SNIPPET);
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
+ } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
+ if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
+ else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_CALL_NOTE);
+ else
+ Log.e(TAG, "invalid system folder");
+ } else {
+ Log.e(TAG, "error type");
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+ }
+
+ public JSONObject getLocalJSONFromContent() {
+ try {
+ JSONObject js = new JSONObject();
+ JSONObject folder = new JSONObject();
+
+ String folderName = getName();
+ if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
+ folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
+ folderName.length());
+ 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);
+
+ js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
+
+ return js;
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public int getSyncAction(Cursor c) {
+ try {
+ if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
+ // there is no local update
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // no update both side
+ return SYNC_ACTION_NONE;
+ } else {
+ // apply remote to local
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+ } else {
+ // validate gtask id
+ if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
+ Log.e(TAG, "gtask id doesn't match");
+ return SYNC_ACTION_ERROR;
+ }
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // local modification only
+ return SYNC_ACTION_UPDATE_REMOTE;
+ } else {
+ // for folder conflicts, just apply local modification
+ return SYNC_ACTION_UPDATE_REMOTE;
+ }
+ }
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+
+ return SYNC_ACTION_ERROR;
+ }
+
+ public int getChildTaskCount() {
+ return mChildren.size();
+ }
+
+ public boolean addChildTask(Task task) {
+ boolean ret = false;
+ if (task != null && !mChildren.contains(task)) {
+ ret = mChildren.add(task);
+ if (ret) {
+ // need to set prior sibling and parent
+ task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
+ .get(mChildren.size() - 1));
+ task.setParent(this);
+ }
+ }
+ return ret;
+ }
+
+ 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;
+ if (index != 0)
+ 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;
+ }
+
+ 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(
+ index == 0 ? null : mChildren.get(index - 1));
+ }
+ }
+ }
+ return ret;
+ }
+
+ 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));
+ }
+
+ public Task findChildTaskByGid(String gid) {
+ for (int i = 0; i < mChildren.size(); i++) {
+ Task t = mChildren.get(i);
+ if (t.getGid().equals(gid)) {
+ return t;
+ }
+ }
+ return null;
+ }
+
+ public int getChildTaskIndex(Task task) {
+ return mChildren.indexOf(task);
+ }
+
+ public Task getChildTaskByIndex(int index) {
+ if (index < 0 || index >= mChildren.size()) {
+ Log.e(TAG, "getTaskByIndex: invalid index");
+ return null;
+ }
+ return mChildren.get(index);
+ }
+
+ public Task getChilTaskByGid(String gid) {
+ 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;
+ }
+}
diff --git a/doc/gtask/exception/ActionFailureException.java b/doc/gtask/exception/ActionFailureException.java
new file mode 100644
index 0000000..15504be
--- /dev/null
+++ b/doc/gtask/exception/ActionFailureException.java
@@ -0,0 +1,33 @@
+/*
+ * 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.exception;
+
+public class ActionFailureException extends RuntimeException {
+ private static final long serialVersionUID = 4425249765923293627L;
+
+ public ActionFailureException() {
+ super();
+ }
+
+ public ActionFailureException(String paramString) {
+ super(paramString);
+ }
+
+ public ActionFailureException(String paramString, Throwable paramThrowable) {
+ super(paramString, paramThrowable);
+ }
+}
diff --git a/doc/gtask/exception/NetworkFailureException.java b/doc/gtask/exception/NetworkFailureException.java
new file mode 100644
index 0000000..b08cfb1
--- /dev/null
+++ b/doc/gtask/exception/NetworkFailureException.java
@@ -0,0 +1,33 @@
+/*
+ * 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.exception;
+
+public class NetworkFailureException extends Exception {
+ private static final long serialVersionUID = 2107610287180234136L;
+
+ public NetworkFailureException() {
+ super();
+ }
+
+ public NetworkFailureException(String paramString) {
+ super(paramString);
+ }
+
+ public NetworkFailureException(String paramString, Throwable paramThrowable) {
+ super(paramString, paramThrowable);
+ }
+}
diff --git a/doc/gtask/remote/GTaskASyncTask.java b/doc/gtask/remote/GTaskASyncTask.java
new file mode 100644
index 0000000..529639f
--- /dev/null
+++ b/doc/gtask/remote/GTaskASyncTask.java
@@ -0,0 +1,123 @@
+
+/*
+ * 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.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 {
+
+ private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
+
+ public interface OnCompleteListener {
+ void onComplete();
+ }
+
+ private Context mContext;
+
+ private NotificationManager mNotifiManager;
+
+ private GTaskManager mTaskManager;
+
+ private OnCompleteListener mOnCompleteListener;
+
+ public GTaskASyncTask(Context context, OnCompleteListener listener) {
+ mContext = context;
+ mOnCompleteListener = listener;
+ mNotifiManager = (NotificationManager) mContext
+ .getSystemService(Context.NOTIFICATION_SERVICE);
+ mTaskManager = GTaskManager.getInstance();
+ }
+
+ public void cancelSync() {
+ mTaskManager.cancelSync();
+ }
+
+ public void publishProgess(String message) {
+ publishProgress(new String[] {
+ message
+ });
+ }
+
+ private void showNotification(int tickerId, String content) {
+ Notification notification = new Notification(R.drawable.notification, mContext
+ .getString(tickerId), System.currentTimeMillis());
+ notification.defaults = Notification.DEFAULT_LIGHTS;
+ notification.flags = Notification.FLAG_AUTO_CANCEL;
+ PendingIntent pendingIntent;
+ if (tickerId != R.string.ticker_success) {
+ pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
+ NotesPreferenceActivity.class), 0);
+
+ } else {
+ pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
+ NotesListActivity.class), 0);
+ }
+ /*notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
+ pendingIntent);*/
+ mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
+ }
+
+ @Override
+ protected Integer doInBackground(Void... unused) {
+ publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
+ .getSyncAccountName(mContext)));
+ return mTaskManager.sync(mContext, this);
+ }
+
+ @Override
+ protected void onProgressUpdate(String... progress) {
+ showNotification(R.string.ticker_syncing, progress[0]);
+ if (mContext instanceof GTaskSyncService) {
+ ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
+ }
+ }
+
+ @Override
+ protected void onPostExecute(Integer result) {
+ if (result == GTaskManager.STATE_SUCCESS) {
+ showNotification(R.string.ticker_success, mContext.getString(
+ R.string.success_sync_account, mTaskManager.getSyncAccount()));
+ NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
+ } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
+ showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
+ } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
+ showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
+ } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
+ showNotification(R.string.ticker_cancel, mContext
+ .getString(R.string.error_sync_cancelled));
+ }
+ if (mOnCompleteListener != null) {
+ new Thread(new Runnable() {
+
+ public void run() {
+ mOnCompleteListener.onComplete();
+ }
+ }).start();
+ }
+ }
+}
diff --git a/doc/gtask/remote/GTaskClient.java b/doc/gtask/remote/GTaskClient.java
new file mode 100644
index 0000000..c67dfdf
--- /dev/null
+++ b/doc/gtask/remote/GTaskClient.java
@@ -0,0 +1,585 @@
+/*
+ * 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.remote;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.accounts.AccountManagerFuture;
+import android.app.Activity;
+import android.os.Bundle;
+import android.text.TextUtils;
+import android.util.Log;
+
+import net.micode.notes.gtask.data.Node;
+import net.micode.notes.gtask.data.Task;
+import net.micode.notes.gtask.data.TaskList;
+import net.micode.notes.gtask.exception.ActionFailureException;
+import net.micode.notes.gtask.exception.NetworkFailureException;
+import net.micode.notes.tool.GTaskStringUtils;
+import net.micode.notes.ui.NotesPreferenceActivity;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.cookie.Cookie;
+import org.apache.http.impl.client.BasicCookieStore;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.HttpProtocolParams;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.Inflater;
+import java.util.zip.InflaterInputStream;
+
+
+public class GTaskClient {
+ private static final String TAG = GTaskClient.class.getSimpleName();
+
+ private static final String GTASK_URL = "https://mail.google.com/tasks/";
+
+ private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
+
+ private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
+
+ private static GTaskClient mInstance = null;
+
+ private DefaultHttpClient mHttpClient;
+
+ private String mGetUrl;
+
+ private String mPostUrl;
+
+ private long mClientVersion;
+
+ private boolean mLoggedin;
+
+ private long mLastLoginTime;
+
+ private int mActionId;
+
+ private Account mAccount;
+
+ private JSONArray mUpdateArray;
+
+ private GTaskClient() {
+ mHttpClient = null;
+ mGetUrl = GTASK_GET_URL;
+ mPostUrl = GTASK_POST_URL;
+ mClientVersion = -1;
+ mLoggedin = false;
+ mLastLoginTime = 0;
+ mActionId = 1;
+ mAccount = null;
+ mUpdateArray = null;
+ }
+
+ public static synchronized GTaskClient getInstance() {
+ if (mInstance == null) {
+ mInstance = new GTaskClient();
+ }
+ return mInstance;
+ }
+
+ public boolean login(Activity activity) {
+ // we suppose that the cookie would expire after 5 minutes
+ // then we need to re-login
+ final long interval = 1000 * 60 * 5;
+ if (mLastLoginTime + interval < System.currentTimeMillis()) {
+ mLoggedin = false;
+ }
+
+ // need to re-login after account switch
+ if (mLoggedin
+ && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
+ .getSyncAccountName(activity))) {
+ mLoggedin = false;
+ }
+
+ if (mLoggedin) {
+ Log.d(TAG, "already logged in");
+ return true;
+ }
+
+ mLastLoginTime = System.currentTimeMillis();
+ String authToken = loginGoogleAccount(activity, false);
+ if (authToken == null) {
+ Log.e(TAG, "login google account failed");
+ return false;
+ }
+
+ // login with custom domain if necessary
+ if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
+ .endsWith("googlemail.com"))) {
+ StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
+ int index = mAccount.name.indexOf('@') + 1;
+ String suffix = mAccount.name.substring(index);
+ url.append(suffix + "/");
+ mGetUrl = url.toString() + "ig";
+ mPostUrl = url.toString() + "r/ig";
+
+ if (tryToLoginGtask(activity, authToken)) {
+ mLoggedin = true;
+ }
+ }
+
+ // try to login with google official url
+ if (!mLoggedin) {
+ mGetUrl = GTASK_GET_URL;
+ mPostUrl = GTASK_POST_URL;
+ if (!tryToLoginGtask(activity, authToken)) {
+ return false;
+ }
+ }
+
+ mLoggedin = true;
+ return true;
+ }
+
+ private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
+ String authToken;
+ AccountManager accountManager = AccountManager.get(activity);
+ Account[] accounts = accountManager.getAccountsByType("com.google");
+
+ if (accounts.length == 0) {
+ Log.e(TAG, "there is no available google account");
+ return null;
+ }
+
+ String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
+ Account account = null;
+ for (Account a : accounts) {
+ if (a.name.equals(accountName)) {
+ account = a;
+ break;
+ }
+ }
+ if (account != null) {
+ mAccount = account;
+ } else {
+ Log.e(TAG, "unable to get an account with the same name in the settings");
+ return null;
+ }
+
+ // get the token now
+ AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,
+ "goanna_mobile", null, activity, null, null);
+ try {
+ Bundle authTokenBundle = accountManagerFuture.getResult();
+ authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
+ if (invalidateToken) {
+ accountManager.invalidateAuthToken("com.google", authToken);
+ loginGoogleAccount(activity, false);
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "get auth token failed");
+ authToken = null;
+ }
+
+ return authToken;
+ }
+
+ private boolean tryToLoginGtask(Activity activity, String authToken) {
+ if (!loginGtask(authToken)) {
+ // maybe the auth token is out of date, now let's invalidate the
+ // token and try again
+ authToken = loginGoogleAccount(activity, true);
+ if (authToken == null) {
+ Log.e(TAG, "login google account failed");
+ return false;
+ }
+
+ if (!loginGtask(authToken)) {
+ Log.e(TAG, "login gtask failed");
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean loginGtask(String authToken) {
+ int timeoutConnection = 10000;
+ int timeoutSocket = 15000;
+ HttpParams httpParameters = new BasicHttpParams();
+ HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
+ HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
+ mHttpClient = new DefaultHttpClient(httpParameters);
+ BasicCookieStore localBasicCookieStore = new BasicCookieStore();
+ mHttpClient.setCookieStore(localBasicCookieStore);
+ HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
+
+ // login gtask
+ try {
+ String loginUrl = mGetUrl + "?auth=" + authToken;
+ HttpGet httpGet = new HttpGet(loginUrl);
+ HttpResponse response = null;
+ response = mHttpClient.execute(httpGet);
+
+ // get the cookie now
+ List cookies = mHttpClient.getCookieStore().getCookies();
+ boolean hasAuthCookie = false;
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().contains("GTL")) {
+ hasAuthCookie = true;
+ }
+ }
+ if (!hasAuthCookie) {
+ Log.w(TAG, "it seems that there is no auth cookie");
+ }
+
+ // get the client version
+ String resString = getResponseContent(response.getEntity());
+ String jsBegin = "_setup(";
+ String jsEnd = ")}";
+ int begin = resString.indexOf(jsBegin);
+ int end = resString.lastIndexOf(jsEnd);
+ String jsString = null;
+ if (begin != -1 && end != -1 && begin < end) {
+ jsString = resString.substring(begin + jsBegin.length(), end);
+ }
+ JSONObject js = new JSONObject(jsString);
+ mClientVersion = js.getLong("v");
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return false;
+ } catch (Exception e) {
+ // simply catch all exceptions
+ Log.e(TAG, "httpget gtask_url failed");
+ return false;
+ }
+
+ return true;
+ }
+
+ private int getActionId() {
+ return mActionId++;
+ }
+
+ private HttpPost createHttpPost() {
+ HttpPost httpPost = new HttpPost(mPostUrl);
+ httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+ httpPost.setHeader("AT", "1");
+ return httpPost;
+ }
+
+ private String getResponseContent(HttpEntity entity) throws IOException {
+ String contentEncoding = null;
+ if (entity.getContentEncoding() != null) {
+ contentEncoding = entity.getContentEncoding().getValue();
+ Log.d(TAG, "encoding: " + contentEncoding);
+ }
+
+ InputStream input = entity.getContent();
+ if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
+ input = new GZIPInputStream(entity.getContent());
+ } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
+ Inflater inflater = new Inflater(true);
+ input = new InflaterInputStream(entity.getContent(), inflater);
+ }
+
+ try {
+ InputStreamReader isr = new InputStreamReader(input);
+ BufferedReader br = new BufferedReader(isr);
+ StringBuilder sb = new StringBuilder();
+
+ while (true) {
+ String buff = br.readLine();
+ if (buff == null) {
+ return sb.toString();
+ }
+ sb = sb.append(buff);
+ }
+ } finally {
+ input.close();
+ }
+ }
+
+ private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
+ if (!mLoggedin) {
+ Log.e(TAG, "please login first");
+ throw new ActionFailureException("not logged in");
+ }
+
+ HttpPost httpPost = createHttpPost();
+ try {
+ LinkedList list = new LinkedList();
+ list.add(new BasicNameValuePair("r", js.toString()));
+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
+ httpPost.setEntity(entity);
+
+ // execute the post
+ HttpResponse response = mHttpClient.execute(httpPost);
+ String jsString = getResponseContent(response.getEntity());
+ return new JSONObject(jsString);
+
+ } catch (ClientProtocolException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new NetworkFailureException("postRequest failed");
+ } catch (IOException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new NetworkFailureException("postRequest failed");
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("unable to convert response content to jsonobject");
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("error occurs when posting request");
+ }
+ }
+
+ public void createTask(Task task) throws NetworkFailureException {
+ commitUpdate();
+ try {
+ JSONObject jsPost = new JSONObject();
+ JSONArray actionList = new JSONArray();
+
+ // action_list
+ actionList.put(task.getCreateAction(getActionId()));
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ // post
+ JSONObject jsResponse = postRequest(jsPost);
+ JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
+ GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
+ task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("create task: handing jsonobject failed");
+ }
+ }
+
+ public void createTaskList(TaskList tasklist) throws NetworkFailureException {
+ commitUpdate();
+ try {
+ JSONObject jsPost = new JSONObject();
+ JSONArray actionList = new JSONArray();
+
+ // action_list
+ actionList.put(tasklist.getCreateAction(getActionId()));
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ // post
+ JSONObject jsResponse = postRequest(jsPost);
+ JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
+ GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
+ tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("create tasklist: handing jsonobject failed");
+ }
+ }
+
+ public void commitUpdate() throws NetworkFailureException {
+ if (mUpdateArray != null) {
+ try {
+ JSONObject jsPost = new JSONObject();
+
+ // action_list
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
+
+ // client_version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ postRequest(jsPost);
+ mUpdateArray = null;
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("commit update: handing jsonobject failed");
+ }
+ }
+ }
+
+ public void addUpdateNode(Node node) throws NetworkFailureException {
+ if (node != null) {
+ // too many update items may result in an error
+ // set max to 10 items
+ if (mUpdateArray != null && mUpdateArray.length() > 10) {
+ commitUpdate();
+ }
+
+ if (mUpdateArray == null)
+ mUpdateArray = new JSONArray();
+ mUpdateArray.put(node.getUpdateAction(getActionId()));
+ }
+ }
+
+ public void moveTask(Task task, TaskList preParent, TaskList curParent)
+ throws NetworkFailureException {
+ commitUpdate();
+ try {
+ JSONObject jsPost = new JSONObject();
+ JSONArray actionList = new JSONArray();
+ JSONObject action = new JSONObject();
+
+ // action_list
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
+ action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
+ if (preParent == curParent && task.getPriorSibling() != null) {
+ // put prioring_sibing_id only if moving within the tasklist and
+ // it is not the first one
+ action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
+ }
+ action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
+ action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
+ if (preParent != curParent) {
+ // put the dest_list only if moving between tasklists
+ action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
+ }
+ actionList.put(action);
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ postRequest(jsPost);
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("move task: handing jsonobject failed");
+ }
+ }
+
+ public void deleteNode(Node node) throws NetworkFailureException {
+ commitUpdate();
+ try {
+ JSONObject jsPost = new JSONObject();
+ JSONArray actionList = new JSONArray();
+
+ // action_list
+ node.setDeleted(true);
+ actionList.put(node.getUpdateAction(getActionId()));
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ postRequest(jsPost);
+ mUpdateArray = null;
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("delete node: handing jsonobject failed");
+ }
+ }
+
+ public JSONArray getTaskLists() throws NetworkFailureException {
+ if (!mLoggedin) {
+ Log.e(TAG, "please login first");
+ throw new ActionFailureException("not logged in");
+ }
+
+ try {
+ HttpGet httpGet = new HttpGet(mGetUrl);
+ HttpResponse response = null;
+ response = mHttpClient.execute(httpGet);
+
+ // get the task list
+ String resString = getResponseContent(response.getEntity());
+ String jsBegin = "_setup(";
+ String jsEnd = ")}";
+ int begin = resString.indexOf(jsBegin);
+ int end = resString.lastIndexOf(jsEnd);
+ String jsString = null;
+ if (begin != -1 && end != -1 && begin < end) {
+ jsString = resString.substring(begin + jsBegin.length(), end);
+ }
+ JSONObject js = new JSONObject(jsString);
+ return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
+ } catch (ClientProtocolException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new NetworkFailureException("gettasklists: httpget failed");
+ } catch (IOException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new NetworkFailureException("gettasklists: httpget failed");
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("get task lists: handing jasonobject failed");
+ }
+ }
+
+ public JSONArray getTaskList(String listGid) throws NetworkFailureException {
+ commitUpdate();
+ try {
+ JSONObject jsPost = new JSONObject();
+ JSONArray actionList = new JSONArray();
+ JSONObject action = new JSONObject();
+
+ // action_list
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
+ action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
+ action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
+ actionList.put(action);
+ jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
+ jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
+
+ JSONObject jsResponse = postRequest(jsPost);
+ return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("get task list: handing jsonobject failed");
+ }
+ }
+
+ public Account getSyncAccount() {
+ return mAccount;
+ }
+
+ public void resetUpdateArray() {
+ mUpdateArray = null;
+ }
+}
diff --git a/doc/gtask/remote/GTaskManager.java b/doc/gtask/remote/GTaskManager.java
new file mode 100644
index 0000000..d2b4082
--- /dev/null
+++ b/doc/gtask/remote/GTaskManager.java
@@ -0,0 +1,800 @@
+/*
+ * 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.remote;
+
+import android.app.Activity;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.util.Log;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.gtask.data.MetaData;
+import net.micode.notes.gtask.data.Node;
+import net.micode.notes.gtask.data.SqlNote;
+import net.micode.notes.gtask.data.Task;
+import net.micode.notes.gtask.data.TaskList;
+import net.micode.notes.gtask.exception.ActionFailureException;
+import net.micode.notes.gtask.exception.NetworkFailureException;
+import net.micode.notes.tool.DataUtils;
+import net.micode.notes.tool.GTaskStringUtils;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+
+
+public class GTaskManager {
+ private static final String TAG = GTaskManager.class.getSimpleName();
+
+ public static final int STATE_SUCCESS = 0;
+
+ public static final int STATE_NETWORK_ERROR = 1;
+
+ public static final int STATE_INTERNAL_ERROR = 2;
+
+ public static final int STATE_SYNC_IN_PROGRESS = 3;
+
+ public static final int STATE_SYNC_CANCELLED = 4;
+
+ private static GTaskManager mInstance = null;
+
+ private Activity mActivity;
+
+ private Context mContext;
+
+ private ContentResolver mContentResolver;
+
+ private boolean mSyncing;
+
+ private boolean mCancelled;
+
+ private HashMap mGTaskListHashMap;
+
+ private HashMap mGTaskHashMap;
+
+ private HashMap mMetaHashMap;
+
+ private TaskList mMetaList;
+
+ private HashSet mLocalDeleteIdMap;
+
+ private HashMap mGidToNid;
+
+ private HashMap mNidToGid;
+
+ private GTaskManager() {
+ mSyncing = false;
+ mCancelled = false;
+ mGTaskListHashMap = new HashMap();
+ mGTaskHashMap = new HashMap();
+ mMetaHashMap = new HashMap();
+ mMetaList = null;
+ mLocalDeleteIdMap = new HashSet();
+ mGidToNid = new HashMap();
+ mNidToGid = new HashMap();
+ }
+
+ public static synchronized GTaskManager getInstance() {
+ if (mInstance == null) {
+ mInstance = new GTaskManager();
+ }
+ return mInstance;
+ }
+
+ public synchronized void setActivityContext(Activity activity) {
+ // used for getting authtoken
+ mActivity = activity;
+ }
+
+ public int sync(Context context, GTaskASyncTask asyncTask) {
+ if (mSyncing) {
+ Log.d(TAG, "Sync is in progress");
+ return STATE_SYNC_IN_PROGRESS;
+ }
+ mContext = context;
+ mContentResolver = mContext.getContentResolver();
+ mSyncing = true;
+ mCancelled = false;
+ mGTaskListHashMap.clear();
+ mGTaskHashMap.clear();
+ mMetaHashMap.clear();
+ mLocalDeleteIdMap.clear();
+ mGidToNid.clear();
+ mNidToGid.clear();
+
+ try {
+ GTaskClient client = GTaskClient.getInstance();
+ client.resetUpdateArray();
+
+ // login google task
+ if (!mCancelled) {
+ if (!client.login(mActivity)) {
+ throw new NetworkFailureException("login google task failed");
+ }
+ }
+
+ // get the task list from google
+ asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
+ initGTaskList();
+
+ // do content sync work
+ asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
+ syncContent();
+ } catch (NetworkFailureException e) {
+ Log.e(TAG, e.toString());
+ return STATE_NETWORK_ERROR;
+ } catch (ActionFailureException e) {
+ Log.e(TAG, e.toString());
+ return STATE_INTERNAL_ERROR;
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return STATE_INTERNAL_ERROR;
+ } finally {
+ mGTaskListHashMap.clear();
+ mGTaskHashMap.clear();
+ mMetaHashMap.clear();
+ mLocalDeleteIdMap.clear();
+ mGidToNid.clear();
+ mNidToGid.clear();
+ mSyncing = false;
+ }
+
+ return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
+ }
+
+ private void initGTaskList() throws NetworkFailureException {
+ if (mCancelled)
+ return;
+ GTaskClient client = GTaskClient.getInstance();
+ try {
+ JSONArray jsTaskLists = client.getTaskLists();
+
+ // init meta list first
+ mMetaList = null;
+ for (int i = 0; i < jsTaskLists.length(); i++) {
+ JSONObject object = jsTaskLists.getJSONObject(i);
+ String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
+ String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
+
+ if (name
+ .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
+ mMetaList = new TaskList();
+ mMetaList.setContentByRemoteJSON(object);
+
+ // load meta data
+ JSONArray jsMetas = client.getTaskList(gid);
+ for (int j = 0; j < jsMetas.length(); j++) {
+ object = (JSONObject) jsMetas.getJSONObject(j);
+ MetaData metaData = new MetaData();
+ metaData.setContentByRemoteJSON(object);
+ if (metaData.isWorthSaving()) {
+ mMetaList.addChildTask(metaData);
+ if (metaData.getGid() != null) {
+ mMetaHashMap.put(metaData.getRelatedGid(), metaData);
+ }
+ }
+ }
+ }
+ }
+
+ // create meta list if not existed
+ if (mMetaList == null) {
+ mMetaList = new TaskList();
+ mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_META);
+ GTaskClient.getInstance().createTaskList(mMetaList);
+ }
+
+ // init task list
+ for (int i = 0; i < jsTaskLists.length(); i++) {
+ JSONObject object = jsTaskLists.getJSONObject(i);
+ String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
+ String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
+
+ if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
+ && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_META)) {
+ TaskList tasklist = new TaskList();
+ tasklist.setContentByRemoteJSON(object);
+ mGTaskListHashMap.put(gid, tasklist);
+ mGTaskHashMap.put(gid, tasklist);
+
+ // load tasks
+ JSONArray jsTasks = client.getTaskList(gid);
+ for (int j = 0; j < jsTasks.length(); j++) {
+ object = (JSONObject) jsTasks.getJSONObject(j);
+ gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
+ Task task = new Task();
+ task.setContentByRemoteJSON(object);
+ if (task.isWorthSaving()) {
+ task.setMetaInfo(mMetaHashMap.get(gid));
+ tasklist.addChildTask(task);
+ mGTaskHashMap.put(gid, task);
+ }
+ }
+ }
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("initGTaskList: handing JSONObject failed");
+ }
+ }
+
+ private void syncContent() throws NetworkFailureException {
+ int syncType;
+ Cursor c = null;
+ String gid;
+ Node node;
+
+ mLocalDeleteIdMap.clear();
+
+ if (mCancelled) {
+ return;
+ }
+
+ // for local deleted note
+ try {
+ c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
+ "(type<>? AND parent_id=?)", new String[] {
+ String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
+ }, null);
+ if (c != null) {
+ while (c.moveToNext()) {
+ gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
+ }
+
+ mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
+ }
+ } else {
+ Log.w(TAG, "failed to query trash folder");
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+
+ // sync folder first
+ syncFolder();
+
+ // for note existing in database
+ try {
+ c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
+ "(type=? AND parent_id<>?)", new String[] {
+ String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
+ }, NoteColumns.TYPE + " DESC");
+ if (c != null) {
+ while (c.moveToNext()) {
+ gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
+ mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
+ syncType = node.getSyncAction(c);
+ } else {
+ if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
+ // local add
+ syncType = Node.SYNC_ACTION_ADD_REMOTE;
+ } else {
+ // remote delete
+ syncType = Node.SYNC_ACTION_DEL_LOCAL;
+ }
+ }
+ doContentSync(syncType, node, c);
+ }
+ } else {
+ Log.w(TAG, "failed to query existing note in database");
+ }
+
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+
+ // go through remaining items
+ Iterator> iter = mGTaskHashMap.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry = iter.next();
+ node = entry.getValue();
+ doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
+ }
+
+ // mCancelled can be set by another thread, so we neet to check one by
+ // one
+ // clear local delete table
+ if (!mCancelled) {
+ if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
+ throw new ActionFailureException("failed to batch-delete local deleted notes");
+ }
+ }
+
+ // refresh local sync id
+ if (!mCancelled) {
+ GTaskClient.getInstance().commitUpdate();
+ refreshLocalSyncId();
+ }
+
+ }
+
+ private void syncFolder() throws NetworkFailureException {
+ Cursor c = null;
+ String gid;
+ Node node;
+ int syncType;
+
+ if (mCancelled) {
+ return;
+ }
+
+ // for root folder
+ try {
+ c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
+ Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
+ if (c != null) {
+ c.moveToNext();
+ gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
+ mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
+ // for system folder, only update remote name if necessary
+ if (!node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
+ doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
+ } else {
+ doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
+ }
+ } else {
+ Log.w(TAG, "failed to query root folder");
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+
+ // for call-note folder
+ try {
+ c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
+ new String[] {
+ String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
+ }, null);
+ if (c != null) {
+ if (c.moveToNext()) {
+ gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
+ mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
+ // for system folder, only update remote name if
+ // necessary
+ if (!node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_CALL_NOTE))
+ doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
+ } else {
+ doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
+ }
+ }
+ } else {
+ Log.w(TAG, "failed to query call note folder");
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+
+ // for local existing folders
+ try {
+ c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
+ "(type=? AND parent_id<>?)", new String[] {
+ String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
+ }, NoteColumns.TYPE + " DESC");
+ if (c != null) {
+ while (c.moveToNext()) {
+ gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
+ mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
+ syncType = node.getSyncAction(c);
+ } else {
+ if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
+ // local add
+ syncType = Node.SYNC_ACTION_ADD_REMOTE;
+ } else {
+ // remote delete
+ syncType = Node.SYNC_ACTION_DEL_LOCAL;
+ }
+ }
+ doContentSync(syncType, node, c);
+ }
+ } else {
+ Log.w(TAG, "failed to query existing folder");
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+
+ // for remote add folders
+ Iterator> iter = mGTaskListHashMap.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry = iter.next();
+ gid = entry.getKey();
+ node = entry.getValue();
+ if (mGTaskHashMap.containsKey(gid)) {
+ mGTaskHashMap.remove(gid);
+ doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
+ }
+ }
+
+ if (!mCancelled)
+ GTaskClient.getInstance().commitUpdate();
+ }
+
+ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ MetaData meta;
+ switch (syncType) {
+ case Node.SYNC_ACTION_ADD_LOCAL:
+ addLocalNode(node);
+ break;
+ case Node.SYNC_ACTION_ADD_REMOTE:
+ addRemoteNode(node, c);
+ break;
+ case Node.SYNC_ACTION_DEL_LOCAL:
+ meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
+ if (meta != null) {
+ GTaskClient.getInstance().deleteNode(meta);
+ }
+ mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
+ break;
+ case Node.SYNC_ACTION_DEL_REMOTE:
+ meta = mMetaHashMap.get(node.getGid());
+ if (meta != null) {
+ GTaskClient.getInstance().deleteNode(meta);
+ }
+ GTaskClient.getInstance().deleteNode(node);
+ break;
+ case Node.SYNC_ACTION_UPDATE_LOCAL:
+ updateLocalNode(node, c);
+ break;
+ case Node.SYNC_ACTION_UPDATE_REMOTE:
+ updateRemoteNode(node, c);
+ break;
+ case Node.SYNC_ACTION_UPDATE_CONFLICT:
+ // merging both modifications maybe a good idea
+ // right now just use local update simply
+ updateRemoteNode(node, c);
+ break;
+ case Node.SYNC_ACTION_NONE:
+ break;
+ case Node.SYNC_ACTION_ERROR:
+ default:
+ throw new ActionFailureException("unkown sync action type");
+ }
+ }
+
+ private void addLocalNode(Node node) throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ SqlNote sqlNote;
+ if (node instanceof TaskList) {
+ if (node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
+ sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
+ } else if (node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
+ sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
+ } else {
+ sqlNote = new SqlNote(mContext);
+ sqlNote.setContent(node.getLocalJSONFromContent());
+ sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
+ }
+ } else {
+ sqlNote = new SqlNote(mContext);
+ JSONObject js = node.getLocalJSONFromContent();
+ try {
+ if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
+ JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ if (note.has(NoteColumns.ID)) {
+ long id = note.getLong(NoteColumns.ID);
+ if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
+ // the id is not available, have to create a new one
+ note.remove(NoteColumns.ID);
+ }
+ }
+ }
+
+ if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
+ JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
+ for (int i = 0; i < dataArray.length(); i++) {
+ JSONObject data = dataArray.getJSONObject(i);
+ if (data.has(DataColumns.ID)) {
+ long dataId = data.getLong(DataColumns.ID);
+ if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
+ // the data id is not available, have to create
+ // a new one
+ data.remove(DataColumns.ID);
+ }
+ }
+ }
+
+ }
+ } catch (JSONException e) {
+ Log.w(TAG, e.toString());
+ e.printStackTrace();
+ }
+ sqlNote.setContent(js);
+
+ Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
+ if (parentId == null) {
+ Log.e(TAG, "cannot find task's parent id locally");
+ throw new ActionFailureException("cannot add local node");
+ }
+ sqlNote.setParentId(parentId.longValue());
+ }
+
+ // create the local node
+ sqlNote.setGtaskId(node.getGid());
+ sqlNote.commit(false);
+
+ // update gid-nid mapping
+ mGidToNid.put(node.getGid(), sqlNote.getId());
+ mNidToGid.put(sqlNote.getId(), node.getGid());
+
+ // update meta
+ updateRemoteMeta(node.getGid(), sqlNote);
+ }
+
+ private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ SqlNote sqlNote;
+ // update the note locally
+ sqlNote = new SqlNote(mContext, c);
+ sqlNote.setContent(node.getLocalJSONFromContent());
+
+ Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
+ : new Long(Notes.ID_ROOT_FOLDER);
+ if (parentId == null) {
+ Log.e(TAG, "cannot find task's parent id locally");
+ throw new ActionFailureException("cannot update local node");
+ }
+ sqlNote.setParentId(parentId.longValue());
+ sqlNote.commit(true);
+
+ // update meta info
+ updateRemoteMeta(node.getGid(), sqlNote);
+ }
+
+ private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ SqlNote sqlNote = new SqlNote(mContext, c);
+ Node n;
+
+ // update remotely
+ if (sqlNote.isNoteType()) {
+ Task task = new Task();
+ task.setContentByLocalJSON(sqlNote.getContent());
+
+ String parentGid = mNidToGid.get(sqlNote.getParentId());
+ if (parentGid == null) {
+ Log.e(TAG, "cannot find task's parent tasklist");
+ throw new ActionFailureException("cannot add remote task");
+ }
+ mGTaskListHashMap.get(parentGid).addChildTask(task);
+
+ GTaskClient.getInstance().createTask(task);
+ n = (Node) task;
+
+ // add meta
+ updateRemoteMeta(task.getGid(), sqlNote);
+ } else {
+ TaskList tasklist = null;
+
+ // we need to skip folder if it has already existed
+ String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
+ if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
+ folderName += GTaskStringUtils.FOLDER_DEFAULT;
+ else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
+ folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
+ else
+ folderName += sqlNote.getSnippet();
+
+ Iterator> iter = mGTaskListHashMap.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry = iter.next();
+ String gid = entry.getKey();
+ TaskList list = entry.getValue();
+
+ if (list.getName().equals(folderName)) {
+ tasklist = list;
+ if (mGTaskHashMap.containsKey(gid)) {
+ mGTaskHashMap.remove(gid);
+ }
+ break;
+ }
+ }
+
+ // no match we can add now
+ if (tasklist == null) {
+ tasklist = new TaskList();
+ tasklist.setContentByLocalJSON(sqlNote.getContent());
+ GTaskClient.getInstance().createTaskList(tasklist);
+ mGTaskListHashMap.put(tasklist.getGid(), tasklist);
+ }
+ n = (Node) tasklist;
+ }
+
+ // update local note
+ sqlNote.setGtaskId(n.getGid());
+ sqlNote.commit(false);
+ sqlNote.resetLocalModified();
+ sqlNote.commit(true);
+
+ // gid-id mapping
+ mGidToNid.put(n.getGid(), sqlNote.getId());
+ mNidToGid.put(sqlNote.getId(), n.getGid());
+ }
+
+ private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ SqlNote sqlNote = new SqlNote(mContext, c);
+
+ // update remotely
+ node.setContentByLocalJSON(sqlNote.getContent());
+ GTaskClient.getInstance().addUpdateNode(node);
+
+ // update meta
+ updateRemoteMeta(node.getGid(), sqlNote);
+
+ // move task if necessary
+ if (sqlNote.isNoteType()) {
+ Task task = (Task) node;
+ TaskList preParentList = task.getParent();
+
+ String curParentGid = mNidToGid.get(sqlNote.getParentId());
+ if (curParentGid == null) {
+ Log.e(TAG, "cannot find task's parent tasklist");
+ throw new ActionFailureException("cannot update remote task");
+ }
+ TaskList curParentList = mGTaskListHashMap.get(curParentGid);
+
+ if (preParentList != curParentList) {
+ preParentList.removeChildTask(task);
+ curParentList.addChildTask(task);
+ GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
+ }
+ }
+
+ // clear local modified flag
+ sqlNote.resetLocalModified();
+ sqlNote.commit(true);
+ }
+
+ private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
+ if (sqlNote != null && sqlNote.isNoteType()) {
+ MetaData metaData = mMetaHashMap.get(gid);
+ if (metaData != null) {
+ metaData.setMeta(gid, sqlNote.getContent());
+ GTaskClient.getInstance().addUpdateNode(metaData);
+ } else {
+ metaData = new MetaData();
+ metaData.setMeta(gid, sqlNote.getContent());
+ mMetaList.addChildTask(metaData);
+ mMetaHashMap.put(gid, metaData);
+ GTaskClient.getInstance().createTask(metaData);
+ }
+ }
+ }
+
+ private void refreshLocalSyncId() throws NetworkFailureException {
+ if (mCancelled) {
+ return;
+ }
+
+ // get the latest gtask list
+ mGTaskHashMap.clear();
+ mGTaskListHashMap.clear();
+ mMetaHashMap.clear();
+ initGTaskList();
+
+ Cursor c = null;
+ try {
+ c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
+ "(type<>? AND parent_id<>?)", new String[] {
+ String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
+ }, NoteColumns.TYPE + " DESC");
+ if (c != null) {
+ while (c.moveToNext()) {
+ String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
+ Node node = mGTaskHashMap.get(gid);
+ if (node != null) {
+ mGTaskHashMap.remove(gid);
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.SYNC_ID, node.getLastModified());
+ mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
+ c.getLong(SqlNote.ID_COLUMN)), values, null, null);
+ } else {
+ Log.e(TAG, "something is missed");
+ throw new ActionFailureException(
+ "some local items don't have gid after sync");
+ }
+ }
+ } else {
+ Log.w(TAG, "failed to query local note to refresh sync id");
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ c = null;
+ }
+ }
+ }
+
+ public String getSyncAccount() {
+ return GTaskClient.getInstance().getSyncAccount().name;
+ }
+
+ public void cancelSync() {
+ mCancelled = true;
+ }
+}
diff --git a/doc/gtask/remote/GTaskSyncService.java b/doc/gtask/remote/GTaskSyncService.java
new file mode 100644
index 0000000..cca36f7
--- /dev/null
+++ b/doc/gtask/remote/GTaskSyncService.java
@@ -0,0 +1,128 @@
+/*
+ * 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.remote;
+
+import android.app.Activity;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.IBinder;
+
+public class GTaskSyncService extends Service {
+ public final static String ACTION_STRING_NAME = "sync_action_type";
+
+ public final static int ACTION_START_SYNC = 0;
+
+ public final static int ACTION_CANCEL_SYNC = 1;
+
+ public final static int ACTION_INVALID = 2;
+
+ public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
+
+ public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
+
+ public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
+
+ private static GTaskASyncTask mSyncTask = null;
+
+ private static String mSyncProgress = "";
+
+ private void startSync() {
+ if (mSyncTask == null) {
+ mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
+ public void onComplete() {
+ mSyncTask = null;
+ sendBroadcast("");
+ stopSelf();
+ }
+ });
+ sendBroadcast("");
+ mSyncTask.execute();
+ }
+ }
+
+ private void cancelSync() {
+ if (mSyncTask != null) {
+ mSyncTask.cancelSync();
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ mSyncTask = null;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ Bundle bundle = intent.getExtras();
+ if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
+ switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
+ case ACTION_START_SYNC:
+ startSync();
+ break;
+ case ACTION_CANCEL_SYNC:
+ cancelSync();
+ break;
+ default:
+ break;
+ }
+ return START_STICKY;
+ }
+ return super.onStartCommand(intent, flags, startId);
+ }
+
+ @Override
+ public void onLowMemory() {
+ if (mSyncTask != null) {
+ mSyncTask.cancelSync();
+ }
+ }
+
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ public void sendBroadcast(String msg) {
+ mSyncProgress = msg;
+ Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
+ intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
+ intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
+ sendBroadcast(intent);
+ }
+
+ public static void startSync(Activity activity) {
+ GTaskManager.getInstance().setActivityContext(activity);
+ Intent intent = new Intent(activity, GTaskSyncService.class);
+ intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
+ activity.startService(intent);
+ }
+
+ public static void cancelSync(Context context) {
+ Intent intent = new Intent(context, GTaskSyncService.class);
+ intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
+ context.startService(intent);
+ }
+
+ public static boolean isSyncing() {
+ return mSyncTask != null;
+ }
+
+ public static String getProgressString() {
+ return mSyncProgress;
+ }
+}
diff --git a/doc/model/Note.java b/doc/model/Note.java
new file mode 100644
index 0000000..6706cf6
--- /dev/null
+++ b/doc/model/Note.java
@@ -0,0 +1,253 @@
+/*
+ * 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.model;
+import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.OperationApplicationException;
+import android.net.Uri;
+import android.os.RemoteException;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.CallNote;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.data.Notes.TextNote;
+
+import java.util.ArrayList;
+
+
+public class Note {
+ private ContentValues mNoteDiffValues;
+ private NoteData mNoteData;
+ private static final String TAG = "Note";
+ /**
+ * Create a new note id for adding a new note to databases
+ */
+ public static synchronized long getNewNoteId(Context context, long folderId) {
+ // Create a new note in the database
+ ContentValues values = new ContentValues();
+ long createdTime = System.currentTimeMillis();
+ values.put(NoteColumns.CREATED_DATE, createdTime);
+ values.put(NoteColumns.MODIFIED_DATE, createdTime);
+ values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
+ values.put(NoteColumns.LOCAL_MODIFIED, 1);
+ values.put(NoteColumns.PARENT_ID, folderId);
+ Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
+
+ long noteId = 0;
+ try {
+ noteId = Long.valueOf(uri.getPathSegments().get(1));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Get note id error :" + e.toString());
+ noteId = 0;
+ }
+ if (noteId == -1) {
+ throw new IllegalStateException("Wrong note id:" + noteId);
+ }
+ return noteId;
+ }
+
+ public Note() {
+ mNoteDiffValues = new ContentValues();
+ mNoteData = new NoteData();
+ }
+
+ public void setNoteValue(String key, String value) {
+ mNoteDiffValues.put(key, value);
+ mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
+ mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
+ }
+
+ public void setTextData(String key, String value) {
+ mNoteData.setTextData(key, value);
+ }
+
+ public void setTextDataId(long id) {
+ mNoteData.setTextDataId(id);
+ }
+
+ public long getTextDataId() {
+ return mNoteData.mTextDataId;
+ }
+
+ public void setCallDataId(long id) {
+ mNoteData.setCallDataId(id);
+ }
+
+ public void setCallData(String key, String value) {
+ mNoteData.setCallData(key, value);
+ }
+
+ public boolean isLocalModified() {
+ return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
+ }
+
+ public boolean syncNote(Context context, long noteId) {
+ if (noteId <= 0) {
+ throw new IllegalArgumentException("Wrong note id:" + noteId);
+ }
+
+ if (!isLocalModified()) {
+ return true;
+ }
+
+ /**
+ * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
+ * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
+ * note data info
+ */
+ if (context.getContentResolver().update(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
+ null) == 0) {
+ Log.e(TAG, "Update note error, should not happen");
+ // Do not return, fall through
+ }
+ mNoteDiffValues.clear();
+
+ if (mNoteData.isLocalModified()
+ && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private class NoteData {
+ private long mTextDataId;
+
+ private ContentValues mTextDataValues;
+
+ private long mCallDataId;
+
+ private ContentValues mCallDataValues;
+
+ private static final String TAG = "NoteData";
+
+ public NoteData() {
+ mTextDataValues = new ContentValues();
+ mCallDataValues = new ContentValues();
+ mTextDataId = 0;
+ mCallDataId = 0;
+ }
+
+ boolean isLocalModified() {
+ return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
+ }
+
+ void setTextDataId(long id) {
+ if(id <= 0) {
+ throw new IllegalArgumentException("Text data id should larger than 0");
+ }
+ mTextDataId = id;
+ }
+
+ void setCallDataId(long id) {
+ if (id <= 0) {
+ throw new IllegalArgumentException("Call data id should larger than 0");
+ }
+ mCallDataId = id;
+ }
+
+ void setCallData(String key, String value) {
+ mCallDataValues.put(key, value);
+ mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
+ mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
+ }
+
+ void setTextData(String key, String value) {
+ mTextDataValues.put(key, value);
+ mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
+ mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
+ }
+
+ Uri pushIntoContentResolver(Context context, long noteId) {
+ /**
+ * Check for safety
+ */
+ if (noteId <= 0) {
+ throw new IllegalArgumentException("Wrong note id:" + noteId);
+ }
+
+ ArrayList operationList = new ArrayList();
+ ContentProviderOperation.Builder builder = null;
+
+ if(mTextDataValues.size() > 0) {
+ mTextDataValues.put(DataColumns.NOTE_ID, noteId);
+ if (mTextDataId == 0) {
+ mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
+ Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
+ mTextDataValues);
+ try {
+ setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Insert new text data fail with noteId" + noteId);
+ mTextDataValues.clear();
+ return null;
+ }
+ } else {
+ builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
+ Notes.CONTENT_DATA_URI, mTextDataId));
+ builder.withValues(mTextDataValues);
+ operationList.add(builder.build());
+ }
+ mTextDataValues.clear();
+ }
+
+ if(mCallDataValues.size() > 0) {
+ mCallDataValues.put(DataColumns.NOTE_ID, noteId);
+ if (mCallDataId == 0) {
+ mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
+ Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
+ mCallDataValues);
+ try {
+ setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Insert new call data fail with noteId" + noteId);
+ mCallDataValues.clear();
+ return null;
+ }
+ } else {
+ builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
+ Notes.CONTENT_DATA_URI, mCallDataId));
+ builder.withValues(mCallDataValues);
+ operationList.add(builder.build());
+ }
+ mCallDataValues.clear();
+ }
+
+ if (operationList.size() > 0) {
+ try {
+ ContentProviderResult[] results = context.getContentResolver().applyBatch(
+ Notes.AUTHORITY, operationList);
+ return (results == null || results.length == 0 || results[0] == null) ? null
+ : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
+ } catch (RemoteException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ return null;
+ } catch (OperationApplicationException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ return null;
+ }
+ }
+ return null;
+ }
+ }
+}
diff --git a/doc/model/WorkingNote.java b/doc/model/WorkingNote.java
new file mode 100644
index 0000000..be081e4
--- /dev/null
+++ b/doc/model/WorkingNote.java
@@ -0,0 +1,368 @@
+/*
+ * 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.model;
+
+import android.appwidget.AppWidgetManager;
+import android.content.ContentUris;
+import android.content.Context;
+import android.database.Cursor;
+import android.text.TextUtils;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.CallNote;
+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.Notes.TextNote;
+import net.micode.notes.tool.ResourceParser.NoteBgResources;
+
+
+public class WorkingNote {
+ // Note for the working note
+ private Note mNote;
+ // Note Id
+ private long mNoteId;
+ // Note content
+ private String mContent;
+ // Note mode
+ private int mMode;
+
+ private long mAlertDate;
+
+ private long mModifiedDate;
+
+ private int mBgColorId;
+
+ private int mWidgetId;
+
+ private int mWidgetType;
+
+ private long mFolderId;
+
+ private Context mContext;
+
+ private static final String TAG = "WorkingNote";
+
+ private boolean mIsDeleted;
+
+ private NoteSettingChangedListener mNoteSettingStatusListener;
+
+ public static final String[] DATA_PROJECTION = new String[] {
+ DataColumns.ID,
+ DataColumns.CONTENT,
+ DataColumns.MIME_TYPE,
+ DataColumns.DATA1,
+ DataColumns.DATA2,
+ DataColumns.DATA3,
+ DataColumns.DATA4,
+ };
+
+ public static final String[] NOTE_PROJECTION = new String[] {
+ NoteColumns.PARENT_ID,
+ NoteColumns.ALERTED_DATE,
+ NoteColumns.BG_COLOR_ID,
+ NoteColumns.WIDGET_ID,
+ NoteColumns.WIDGET_TYPE,
+ NoteColumns.MODIFIED_DATE
+ };
+
+ private static final int DATA_ID_COLUMN = 0;
+
+ private static final int DATA_CONTENT_COLUMN = 1;
+
+ private static final int DATA_MIME_TYPE_COLUMN = 2;
+
+ private static final int DATA_MODE_COLUMN = 3;
+
+ private static final int NOTE_PARENT_ID_COLUMN = 0;
+
+ private static final int NOTE_ALERTED_DATE_COLUMN = 1;
+
+ private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
+
+ private static final int NOTE_WIDGET_ID_COLUMN = 3;
+
+ private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
+
+ private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
+
+ // New note construct
+ private WorkingNote(Context context, long folderId) {
+ mContext = context;
+ mAlertDate = 0;
+ mModifiedDate = System.currentTimeMillis();
+ mFolderId = folderId;
+ mNote = new Note();
+ mNoteId = 0;
+ mIsDeleted = false;
+ mMode = 0;
+ mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
+ }
+
+ // Existing note construct
+ private WorkingNote(Context context, long noteId, long folderId) {
+ mContext = context;
+ mNoteId = noteId;
+ mFolderId = folderId;
+ mIsDeleted = false;
+ mNote = new Note();
+ loadNote();
+ }
+
+ private void loadNote() {
+ Cursor cursor = mContext.getContentResolver().query(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
+ null, null);
+
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
+ mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
+ mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
+ mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
+ mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
+ mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
+ }
+ cursor.close();
+ } else {
+ Log.e(TAG, "No note with id:" + mNoteId);
+ throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
+ }
+ loadNoteData();
+ }
+
+ private void loadNoteData() {
+ Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
+ DataColumns.NOTE_ID + "=?", new String[] {
+ String.valueOf(mNoteId)
+ }, null);
+
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ do {
+ String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
+ if (DataConstants.NOTE.equals(type)) {
+ mContent = cursor.getString(DATA_CONTENT_COLUMN);
+ mMode = cursor.getInt(DATA_MODE_COLUMN);
+ mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
+ } else if (DataConstants.CALL_NOTE.equals(type)) {
+ mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
+ } else {
+ Log.d(TAG, "Wrong note type with type:" + type);
+ }
+ } while (cursor.moveToNext());
+ }
+ cursor.close();
+ } else {
+ Log.e(TAG, "No data with id:" + mNoteId);
+ throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
+ }
+ }
+
+ public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
+ int widgetType, int defaultBgColorId) {
+ WorkingNote note = new WorkingNote(context, folderId);
+ note.setBgColorId(defaultBgColorId);
+ note.setWidgetId(widgetId);
+ note.setWidgetType(widgetType);
+ return note;
+ }
+
+ public static WorkingNote load(Context context, long id) {
+ return new WorkingNote(context, id, 0);
+ }
+
+ public synchronized boolean saveNote() {
+ if (isWorthSaving()) {
+ if (!existInDatabase()) {
+ if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
+ Log.e(TAG, "Create new note fail with id:" + mNoteId);
+ return false;
+ }
+ }
+
+ mNote.syncNote(mContext, mNoteId);
+
+ /**
+ * Update widget content if there exist any widget of this note
+ */
+ if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
+ && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
+ && mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onWidgetChanged();
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean existInDatabase() {
+ return mNoteId > 0;
+ }
+
+ private boolean isWorthSaving() {
+ if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
+ || (existInDatabase() && !mNote.isLocalModified())) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
+ mNoteSettingStatusListener = l;
+ }
+
+ public void setAlertDate(long date, boolean set) {
+ if (date != mAlertDate) {
+ mAlertDate = date;
+ mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
+ }
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onClockAlertChanged(date, set);
+ }
+ }
+
+ public void markDeleted(boolean mark) {
+ mIsDeleted = mark;
+ if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
+ && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onWidgetChanged();
+ }
+ }
+
+ public void setBgColorId(int id) {
+ if (id != mBgColorId) {
+ mBgColorId = id;
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onBackgroundColorChanged();
+ }
+ mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
+ }
+ }
+
+ public void setCheckListMode(int mode) {
+ if (mMode != mode) {
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
+ }
+ mMode = mode;
+ mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
+ }
+ }
+
+ public void setWidgetType(int type) {
+ if (type != mWidgetType) {
+ mWidgetType = type;
+ mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
+ }
+ }
+
+ public void setWidgetId(int id) {
+ if (id != mWidgetId) {
+ mWidgetId = id;
+ mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
+ }
+ }
+
+ public void setWorkingText(String text) {
+ if (!TextUtils.equals(mContent, text)) {
+ mContent = text;
+ mNote.setTextData(DataColumns.CONTENT, mContent);
+ }
+ }
+
+ public void convertToCallNote(String phoneNumber, long callDate) {
+ mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
+ mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
+ mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
+ }
+
+ public boolean hasClockAlert() {
+ return (mAlertDate > 0 ? true : false);
+ }
+
+ public String getContent() {
+ return mContent;
+ }
+
+ public long getAlertDate() {
+ return mAlertDate;
+ }
+
+ public long getModifiedDate() {
+ return mModifiedDate;
+ }
+
+ public int getBgColorResId() {
+ return NoteBgResources.getNoteBgResource(mBgColorId);
+ }
+
+ public int getBgColorId() {
+ return mBgColorId;
+ }
+
+ public int getTitleBgResId() {
+ return NoteBgResources.getNoteTitleBgResource(mBgColorId);
+ }
+
+ public int getCheckListMode() {
+ return mMode;
+ }
+
+ public long getNoteId() {
+ return mNoteId;
+ }
+
+ public long getFolderId() {
+ return mFolderId;
+ }
+
+ public int getWidgetId() {
+ return mWidgetId;
+ }
+
+ public int getWidgetType() {
+ return mWidgetType;
+ }
+
+ public interface NoteSettingChangedListener {
+ /**
+ * Called when the background color of current note has just changed
+ */
+ void onBackgroundColorChanged();
+
+ /**
+ * Called when user set clock
+ */
+ void onClockAlertChanged(long date, boolean set);
+
+ /**
+ * Call when user create note from widget
+ */
+ void onWidgetChanged();
+
+ /**
+ * Call when switch between check list mode and normal mode
+ * @param oldMode is previous mode before change
+ * @param newMode is new mode
+ */
+ void onCheckListModeChanged(int oldMode, int newMode);
+ }
+}
diff --git a/doc/tool/BackupUtils.java b/doc/tool/BackupUtils.java
new file mode 100644
index 0000000..39f6ec4
--- /dev/null
+++ b/doc/tool/BackupUtils.java
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.tool;
+
+import android.content.Context;
+import android.database.Cursor;
+import android.os.Environment;
+import android.text.TextUtils;
+import android.text.format.DateFormat;
+import android.util.Log;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.DataConstants;
+import net.micode.notes.data.Notes.NoteColumns;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+
+public class BackupUtils {
+ private static final String TAG = "BackupUtils";
+ // Singleton stuff
+ private static BackupUtils sInstance;
+
+ public static synchronized BackupUtils getInstance(Context context) {
+ if (sInstance == null) {
+ sInstance = new BackupUtils(context);
+ }
+ return sInstance;
+ }
+
+ /**
+ * Following states are signs to represents backup or restore
+ * status
+ */
+ // Currently, the sdcard is not mounted
+ public static final int STATE_SD_CARD_UNMOUONTED = 0;
+ // The backup file not exist
+ public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
+ // The data is not well formated, may be changed by other programs
+ public static final int STATE_DATA_DESTROIED = 2;
+ // Some run-time exception which causes restore or backup fails
+ public static final int STATE_SYSTEM_ERROR = 3;
+ // Backup or restore success
+ public static final int STATE_SUCCESS = 4;
+
+ private TextExport mTextExport;
+
+ private BackupUtils(Context context) {
+ mTextExport = new TextExport(context);
+ }
+
+ private static boolean externalStorageAvailable() {
+ return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
+ }
+
+ public int exportToText() {
+ return mTextExport.exportToText();
+ }
+
+ public String getExportedTextFileName() {
+ return mTextExport.mFileName;
+ }
+
+ public String getExportedTextFileDir() {
+ return mTextExport.mFileDirectory;
+ }
+
+ private static class TextExport {
+ private static final String[] NOTE_PROJECTION = {
+ NoteColumns.ID,
+ NoteColumns.MODIFIED_DATE,
+ NoteColumns.SNIPPET,
+ NoteColumns.TYPE
+ };
+
+ private static final int NOTE_COLUMN_ID = 0;
+
+ private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
+
+ private static final int NOTE_COLUMN_SNIPPET = 2;
+
+ private static final String[] DATA_PROJECTION = {
+ DataColumns.CONTENT,
+ DataColumns.MIME_TYPE,
+ DataColumns.DATA1,
+ DataColumns.DATA2,
+ DataColumns.DATA3,
+ DataColumns.DATA4,
+ };
+
+ private static final int DATA_COLUMN_CONTENT = 0;
+
+ private static final int DATA_COLUMN_MIME_TYPE = 1;
+
+ private static final int DATA_COLUMN_CALL_DATE = 2;
+
+ private static final int DATA_COLUMN_PHONE_NUMBER = 4;
+
+ private final String [] TEXT_FORMAT;
+ private static final int FORMAT_FOLDER_NAME = 0;
+ private static final int FORMAT_NOTE_DATE = 1;
+ private static final int FORMAT_NOTE_CONTENT = 2;
+
+ private Context mContext;
+ private String mFileName;
+ private String mFileDirectory;
+
+ public TextExport(Context context) {
+ TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
+ mContext = context;
+ mFileName = "";
+ mFileDirectory = "";
+ }
+
+ private String getFormat(int id) {
+ return TEXT_FORMAT[id];
+ }
+
+ /**
+ * Export the folder identified by folder id to text
+ */
+ private void exportFolderToText(String folderId, PrintStream ps) {
+ // Query notes belong to this folder
+ Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
+ NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
+ folderId
+ }, null);
+
+ if (notesCursor != null) {
+ if (notesCursor.moveToFirst()) {
+ do {
+ // Print note's last modified date
+ ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
+ mContext.getString(R.string.format_datetime_mdhm),
+ notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
+ // Query data belong to this note
+ String noteId = notesCursor.getString(NOTE_COLUMN_ID);
+ exportNoteToText(noteId, ps);
+ } while (notesCursor.moveToNext());
+ }
+ notesCursor.close();
+ }
+ }
+
+ /**
+ * Export note identified by id to a print stream
+ */
+ private void exportNoteToText(String noteId, PrintStream ps) {
+ Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
+ DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
+ noteId
+ }, null);
+
+ if (dataCursor != null) {
+ if (dataCursor.moveToFirst()) {
+ do {
+ String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
+ if (DataConstants.CALL_NOTE.equals(mimeType)) {
+ // Print phone number
+ String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
+ long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
+ String location = dataCursor.getString(DATA_COLUMN_CONTENT);
+
+ if (!TextUtils.isEmpty(phoneNumber)) {
+ ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
+ phoneNumber));
+ }
+ // Print call date
+ ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
+ .format(mContext.getString(R.string.format_datetime_mdhm),
+ callDate)));
+ // Print call attachment location
+ if (!TextUtils.isEmpty(location)) {
+ ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
+ location));
+ }
+ } else if (DataConstants.NOTE.equals(mimeType)) {
+ String content = dataCursor.getString(DATA_COLUMN_CONTENT);
+ if (!TextUtils.isEmpty(content)) {
+ ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
+ content));
+ }
+ }
+ } while (dataCursor.moveToNext());
+ }
+ dataCursor.close();
+ }
+ // print a line separator between note
+ try {
+ ps.write(new byte[] {
+ Character.LINE_SEPARATOR, Character.LETTER_NUMBER
+ });
+ } catch (IOException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ /**
+ * Note will be exported as text which is user readable
+ */
+ public int exportToText() {
+ if (!externalStorageAvailable()) {
+ Log.d(TAG, "Media was not mounted");
+ return STATE_SD_CARD_UNMOUONTED;
+ }
+
+ PrintStream ps = getExportToTextPrintStream();
+ if (ps == null) {
+ Log.e(TAG, "get print stream error");
+ return STATE_SYSTEM_ERROR;
+ }
+ // First export folder and its notes
+ Cursor folderCursor = mContext.getContentResolver().query(
+ Notes.CONTENT_NOTE_URI,
+ NOTE_PROJECTION,
+ "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
+
+ if (folderCursor != null) {
+ if (folderCursor.moveToFirst()) {
+ do {
+ // Print folder's name
+ String folderName = "";
+ if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
+ folderName = mContext.getString(R.string.call_record_folder_name);
+ } else {
+ folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
+ }
+ if (!TextUtils.isEmpty(folderName)) {
+ ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
+ }
+ String folderId = folderCursor.getString(NOTE_COLUMN_ID);
+ exportFolderToText(folderId, ps);
+ } while (folderCursor.moveToNext());
+ }
+ folderCursor.close();
+ }
+
+ // Export notes in root's folder
+ Cursor noteCursor = mContext.getContentResolver().query(
+ Notes.CONTENT_NOTE_URI,
+ NOTE_PROJECTION,
+ NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ + "=0", null, null);
+
+ if (noteCursor != null) {
+ if (noteCursor.moveToFirst()) {
+ do {
+ ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
+ mContext.getString(R.string.format_datetime_mdhm),
+ noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
+ // Query data belong to this note
+ String noteId = noteCursor.getString(NOTE_COLUMN_ID);
+ exportNoteToText(noteId, ps);
+ } while (noteCursor.moveToNext());
+ }
+ noteCursor.close();
+ }
+ ps.close();
+
+ return STATE_SUCCESS;
+ }
+
+ /**
+ * Get a print stream pointed to the file {@generateExportedTextFile}
+ */
+ private PrintStream getExportToTextPrintStream() {
+ File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
+ R.string.file_name_txt_format);
+ if (file == null) {
+ Log.e(TAG, "create file to exported failed");
+ return null;
+ }
+ mFileName = file.getName();
+ mFileDirectory = mContext.getString(R.string.file_path);
+ PrintStream ps = null;
+ try {
+ FileOutputStream fos = new FileOutputStream(file);
+ ps = new PrintStream(fos);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ return null;
+ } catch (NullPointerException e) {
+ e.printStackTrace();
+ return null;
+ }
+ return ps;
+ }
+ }
+
+ /**
+ * Generate the text file to store imported data
+ */
+ private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(Environment.getExternalStorageDirectory());
+ sb.append(context.getString(filePathResId));
+ File filedir = new File(sb.toString());
+ sb.append(context.getString(
+ fileNameFormatResId,
+ DateFormat.format(context.getString(R.string.format_date_ymd),
+ System.currentTimeMillis())));
+ File file = new File(sb.toString());
+
+ try {
+ if (!filedir.exists()) {
+ filedir.mkdir();
+ }
+ if (!file.exists()) {
+ file.createNewFile();
+ }
+ return file;
+ } catch (SecurityException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+}
+
+
diff --git a/doc/tool/DataUtils.java b/doc/tool/DataUtils.java
new file mode 100644
index 0000000..2a14982
--- /dev/null
+++ b/doc/tool/DataUtils.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.tool;
+
+import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.OperationApplicationException;
+import android.database.Cursor;
+import android.os.RemoteException;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.CallNote;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+
+
+public class DataUtils {
+ public static final String TAG = "DataUtils";
+ public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) {
+ if (ids == null) {
+ Log.d(TAG, "the ids is null");
+ return true;
+ }
+ if (ids.size() == 0) {
+ Log.d(TAG, "no id is in the hashset");
+ return true;
+ }
+
+ ArrayList operationList = new ArrayList();
+ for (long id : ids) {
+ if(id == Notes.ID_ROOT_FOLDER) {
+ Log.e(TAG, "Don't delete system folder root");
+ continue;
+ }
+ ContentProviderOperation.Builder builder = ContentProviderOperation
+ .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
+ operationList.add(builder.build());
+ }
+ try {
+ ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
+ if (results == null || results.length == 0 || results[0] == null) {
+ Log.d(TAG, "delete notes failed, ids:" + ids.toString());
+ return false;
+ }
+ return true;
+ } catch (RemoteException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ } catch (OperationApplicationException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ }
+ return false;
+ }
+
+ public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.PARENT_ID, desFolderId);
+ values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
+ values.put(NoteColumns.LOCAL_MODIFIED, 1);
+ resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
+ }
+
+ public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids,
+ long folderId) {
+ if (ids == null) {
+ Log.d(TAG, "the ids is null");
+ return true;
+ }
+
+ ArrayList operationList = new ArrayList();
+ for (long id : ids) {
+ ContentProviderOperation.Builder builder = ContentProviderOperation
+ .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
+ builder.withValue(NoteColumns.PARENT_ID, folderId);
+ builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
+ operationList.add(builder.build());
+ }
+
+ try {
+ ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
+ if (results == null || results.length == 0 || results[0] == null) {
+ Log.d(TAG, "delete notes failed, ids:" + ids.toString());
+ return false;
+ }
+ return true;
+ } catch (RemoteException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ } catch (OperationApplicationException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ }
+ return false;
+ }
+
+ /**
+ * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
+ */
+ public static int getUserFolderCount(ContentResolver resolver) {
+ Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
+ new String[] { "COUNT(*)" },
+ NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
+ new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
+ null);
+
+ int count = 0;
+ if(cursor != null) {
+ if(cursor.moveToFirst()) {
+ try {
+ count = cursor.getInt(0);
+ } catch (IndexOutOfBoundsException e) {
+ Log.e(TAG, "get folder count failed:" + e.toString());
+ } finally {
+ cursor.close();
+ }
+ }
+ }
+ return count;
+ }
+
+ public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
+ Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
+ null,
+ NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
+ new String [] {String.valueOf(type)},
+ null);
+
+ boolean exist = false;
+ if (cursor != null) {
+ if (cursor.getCount() > 0) {
+ exist = true;
+ }
+ cursor.close();
+ }
+ return exist;
+ }
+
+ public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
+ Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
+ null, null, null, null);
+
+ boolean exist = false;
+ if (cursor != null) {
+ if (cursor.getCount() > 0) {
+ exist = true;
+ }
+ cursor.close();
+ }
+ return exist;
+ }
+
+ public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
+ Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
+ null, null, null, null);
+
+ boolean exist = false;
+ if (cursor != null) {
+ if (cursor.getCount() > 0) {
+ exist = true;
+ }
+ cursor.close();
+ }
+ return exist;
+ }
+
+ public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
+ Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
+ NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
+ " AND " + NoteColumns.SNIPPET + "=?",
+ new String[] { name }, null);
+ boolean exist = false;
+ if(cursor != null) {
+ if(cursor.getCount() > 0) {
+ exist = true;
+ }
+ cursor.close();
+ }
+ return exist;
+ }
+
+ public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) {
+ Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
+ new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
+ NoteColumns.PARENT_ID + "=?",
+ new String[] { String.valueOf(folderId) },
+ null);
+
+ HashSet set = null;
+ if (c != null) {
+ if (c.moveToFirst()) {
+ set = new HashSet();
+ do {
+ try {
+ AppWidgetAttribute widget = new AppWidgetAttribute();
+ widget.widgetId = c.getInt(0);
+ widget.widgetType = c.getInt(1);
+ set.add(widget);
+ } catch (IndexOutOfBoundsException e) {
+ Log.e(TAG, e.toString());
+ }
+ } while (c.moveToNext());
+ }
+ c.close();
+ }
+ return set;
+ }
+
+ public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
+ Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
+ new String [] { CallNote.PHONE_NUMBER },
+ CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
+ new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
+ null);
+
+ if (cursor != null && cursor.moveToFirst()) {
+ try {
+ return cursor.getString(0);
+ } catch (IndexOutOfBoundsException e) {
+ Log.e(TAG, "Get call number fails " + e.toString());
+ } finally {
+ cursor.close();
+ }
+ }
+ return "";
+ }
+
+ public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
+ Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
+ new String [] { CallNote.NOTE_ID },
+ CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ + CallNote.PHONE_NUMBER + ",?)",
+ new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
+ null);
+
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ try {
+ return cursor.getLong(0);
+ } catch (IndexOutOfBoundsException e) {
+ Log.e(TAG, "Get call note id fails " + e.toString());
+ }
+ }
+ cursor.close();
+ }
+ return 0;
+ }
+
+ public static String getSnippetById(ContentResolver resolver, long noteId) {
+ Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
+ new String [] { NoteColumns.SNIPPET },
+ NoteColumns.ID + "=?",
+ new String [] { String.valueOf(noteId)},
+ null);
+
+ if (cursor != null) {
+ String snippet = "";
+ if (cursor.moveToFirst()) {
+ snippet = cursor.getString(0);
+ }
+ cursor.close();
+ return snippet;
+ }
+ throw new IllegalArgumentException("Note is not found with id: " + noteId);
+ }
+
+ public static String getFormattedSnippet(String snippet) {
+ if (snippet != null) {
+ snippet = snippet.trim();
+ int index = snippet.indexOf('\n');
+ if (index != -1) {
+ snippet = snippet.substring(0, index);
+ }
+ }
+ return snippet;
+ }
+}
diff --git a/doc/tool/GTaskStringUtils.java b/doc/tool/GTaskStringUtils.java
new file mode 100644
index 0000000..666b729
--- /dev/null
+++ b/doc/tool/GTaskStringUtils.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.tool;
+
+public class GTaskStringUtils {
+
+ public final static String GTASK_JSON_ACTION_ID = "action_id";
+
+ public final static String GTASK_JSON_ACTION_LIST = "action_list";
+
+ public final static String GTASK_JSON_ACTION_TYPE = "action_type";
+
+ public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
+
+ public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
+
+ public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
+
+ public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
+
+ public final static String GTASK_JSON_CREATOR_ID = "creator_id";
+
+ public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
+
+ public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
+
+ public final static String GTASK_JSON_COMPLETED = "completed";
+
+ public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
+
+ public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
+
+ public final static String GTASK_JSON_DELETED = "deleted";
+
+ public final static String GTASK_JSON_DEST_LIST = "dest_list";
+
+ public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
+
+ public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
+
+ public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
+
+ public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
+
+ public final static String GTASK_JSON_GET_DELETED = "get_deleted";
+
+ public final static String GTASK_JSON_ID = "id";
+
+ public final static String GTASK_JSON_INDEX = "index";
+
+ public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
+
+ public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
+
+ public final static String GTASK_JSON_LIST_ID = "list_id";
+
+ public final static String GTASK_JSON_LISTS = "lists";
+
+ public final static String GTASK_JSON_NAME = "name";
+
+ public final static String GTASK_JSON_NEW_ID = "new_id";
+
+ public final static String GTASK_JSON_NOTES = "notes";
+
+ public final static String GTASK_JSON_PARENT_ID = "parent_id";
+
+ public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
+
+ public final static String GTASK_JSON_RESULTS = "results";
+
+ public final static String GTASK_JSON_SOURCE_LIST = "source_list";
+
+ public final static String GTASK_JSON_TASKS = "tasks";
+
+ public final static String GTASK_JSON_TYPE = "type";
+
+ public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
+
+ public final static String GTASK_JSON_TYPE_TASK = "TASK";
+
+ public final static String GTASK_JSON_USER = "user";
+
+ public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
+
+ public final static String FOLDER_DEFAULT = "Default";
+
+ public final static String FOLDER_CALL_NOTE = "Call_Note";
+
+ public final static String FOLDER_META = "METADATA";
+
+ public final static String META_HEAD_GTASK_ID = "meta_gid";
+
+ public final static String META_HEAD_NOTE = "meta_note";
+
+ public final static String META_HEAD_DATA = "meta_data";
+
+ public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
+
+}
diff --git a/doc/tool/ResourceParser.java b/doc/tool/ResourceParser.java
new file mode 100644
index 0000000..1ad3ad6
--- /dev/null
+++ b/doc/tool/ResourceParser.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.tool;
+
+import android.content.Context;
+import android.preference.PreferenceManager;
+
+import net.micode.notes.R;
+import net.micode.notes.ui.NotesPreferenceActivity;
+
+public class ResourceParser {
+
+ public static final int YELLOW = 0;
+ public static final int BLUE = 1;
+ public static final int WHITE = 2;
+ public static final int GREEN = 3;
+ public static final int RED = 4;
+
+ public static final int BG_DEFAULT_COLOR = YELLOW;
+
+ public static final int TEXT_SMALL = 0;
+ public static final int TEXT_MEDIUM = 1;
+ public static final int TEXT_LARGE = 2;
+ public static final int TEXT_SUPER = 3;
+
+ public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
+
+ public static class NoteBgResources {
+ private final static int [] BG_EDIT_RESOURCES = new int [] {
+ R.drawable.edit_yellow,
+ R.drawable.edit_blue,
+ R.drawable.edit_white,
+ R.drawable.edit_green,
+ R.drawable.edit_red
+ };
+
+ private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
+ R.drawable.edit_title_yellow,
+ R.drawable.edit_title_blue,
+ R.drawable.edit_title_white,
+ R.drawable.edit_title_green,
+ R.drawable.edit_title_red
+ };
+
+ public static int getNoteBgResource(int id) {
+ return BG_EDIT_RESOURCES[id];
+ }
+
+ public static int getNoteTitleBgResource(int id) {
+ return BG_EDIT_TITLE_RESOURCES[id];
+ }
+ }
+
+ public static int getDefaultBgId(Context context) {
+ if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
+ NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
+ return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
+ } else {
+ return BG_DEFAULT_COLOR;
+ }
+ }
+
+ public static class NoteItemBgResources {
+ private final static int [] BG_FIRST_RESOURCES = new int [] {
+ R.drawable.list_yellow_up,
+ R.drawable.list_blue_up,
+ R.drawable.list_white_up,
+ R.drawable.list_green_up,
+ R.drawable.list_red_up
+ };
+
+ private final static int [] BG_NORMAL_RESOURCES = new int [] {
+ R.drawable.list_yellow_middle,
+ R.drawable.list_blue_middle,
+ R.drawable.list_white_middle,
+ R.drawable.list_green_middle,
+ R.drawable.list_red_middle
+ };
+
+ private final static int [] BG_LAST_RESOURCES = new int [] {
+ R.drawable.list_yellow_down,
+ R.drawable.list_blue_down,
+ R.drawable.list_white_down,
+ R.drawable.list_green_down,
+ R.drawable.list_red_down,
+ };
+
+ private final static int [] BG_SINGLE_RESOURCES = new int [] {
+ R.drawable.list_yellow_single,
+ R.drawable.list_blue_single,
+ R.drawable.list_white_single,
+ R.drawable.list_green_single,
+ R.drawable.list_red_single
+ };
+
+ public static int getNoteBgFirstRes(int id) {
+ return BG_FIRST_RESOURCES[id];
+ }
+
+ public static int getNoteBgLastRes(int id) {
+ return BG_LAST_RESOURCES[id];
+ }
+
+ public static int getNoteBgSingleRes(int id) {
+ return BG_SINGLE_RESOURCES[id];
+ }
+
+ public static int getNoteBgNormalRes(int id) {
+ return BG_NORMAL_RESOURCES[id];
+ }
+
+ public static int getFolderBgRes() {
+ return R.drawable.list_folder;
+ }
+ }
+
+ public static class WidgetBgResources {
+ private final static int [] BG_2X_RESOURCES = new int [] {
+ R.drawable.widget_2x_yellow,
+ R.drawable.widget_2x_blue,
+ R.drawable.widget_2x_white,
+ R.drawable.widget_2x_green,
+ R.drawable.widget_2x_red,
+ };
+
+ public static int getWidget2xBgResource(int id) {
+ return BG_2X_RESOURCES[id];
+ }
+
+ private final static int [] BG_4X_RESOURCES = new int [] {
+ R.drawable.widget_4x_yellow,
+ R.drawable.widget_4x_blue,
+ R.drawable.widget_4x_white,
+ R.drawable.widget_4x_green,
+ R.drawable.widget_4x_red
+ };
+
+ public static int getWidget4xBgResource(int id) {
+ return BG_4X_RESOURCES[id];
+ }
+ }
+
+ public static class TextAppearanceResources {
+ private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
+ R.style.TextAppearanceNormal,
+ R.style.TextAppearanceMedium,
+ R.style.TextAppearanceLarge,
+ R.style.TextAppearanceSuper
+ };
+
+ public static int getTexAppearanceResource(int id) {
+ /**
+ * HACKME: Fix bug of store the resource id in shared preference.
+ * The id may larger than the length of resources, in this case,
+ * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
+ */
+ if (id >= TEXTAPPEARANCE_RESOURCES.length) {
+ return BG_DEFAULT_FONT_SIZE;
+ }
+ return TEXTAPPEARANCE_RESOURCES[id];
+ }
+
+ public static int getResourcesSize() {
+ return TEXTAPPEARANCE_RESOURCES.length;
+ }
+ }
+}
diff --git a/doc/ui/AlarmAlertActivity.java b/doc/ui/AlarmAlertActivity.java
new file mode 100644
index 0000000..85723be
--- /dev/null
+++ b/doc/ui/AlarmAlertActivity.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.ui;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.DialogInterface.OnDismissListener;
+import android.content.Intent;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.media.RingtoneManager;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.PowerManager;
+import android.provider.Settings;
+import android.view.Window;
+import android.view.WindowManager;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.tool.DataUtils;
+
+import java.io.IOException;
+
+
+public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
+ private long mNoteId;
+ private String mSnippet;
+ private static final int SNIPPET_PREW_MAX_LEN = 60;
+ MediaPlayer mPlayer;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
+
+ final Window win = getWindow();
+ win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+
+ if (!isScreenOn()) {
+ win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+ | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
+ | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
+ | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
+ }
+
+ Intent intent = getIntent();
+
+ try {
+ mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
+ mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
+ mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
+ SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
+ : mSnippet;
+ } catch (IllegalArgumentException e) {
+ e.printStackTrace();
+ return;
+ }
+
+ mPlayer = new MediaPlayer();
+ if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
+ showActionDialog();
+ playAlarmSound();
+ } else {
+ finish();
+ }
+ }
+
+ private boolean isScreenOn() {
+ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
+ return pm.isScreenOn();
+ }
+
+ private void playAlarmSound() {
+ Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
+
+ int silentModeStreams = Settings.System.getInt(getContentResolver(),
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
+
+ if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
+ mPlayer.setAudioStreamType(silentModeStreams);
+ } else {
+ mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
+ }
+ try {
+ mPlayer.setDataSource(this, url);
+ mPlayer.prepare();
+ mPlayer.setLooping(true);
+ mPlayer.start();
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (SecurityException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalStateException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ private void showActionDialog() {
+ AlertDialog.Builder dialog = new AlertDialog.Builder(this);
+ dialog.setTitle(R.string.app_name);
+ dialog.setMessage(mSnippet);
+ dialog.setPositiveButton(R.string.notealert_ok, this);
+ if (isScreenOn()) {
+ dialog.setNegativeButton(R.string.notealert_enter, this);
+ }
+ dialog.show().setOnDismissListener(this);
+ }
+
+ public void onClick(DialogInterface dialog, int which) {
+ switch (which) {
+ case DialogInterface.BUTTON_NEGATIVE:
+ Intent intent = new Intent(this, NoteEditActivity.class);
+ intent.setAction(Intent.ACTION_VIEW);
+ intent.putExtra(Intent.EXTRA_UID, mNoteId);
+ startActivity(intent);
+ break;
+ default:
+ break;
+ }
+ }
+
+ public void onDismiss(DialogInterface dialog) {
+ stopAlarmSound();
+ finish();
+ }
+
+ private void stopAlarmSound() {
+ if (mPlayer != null) {
+ mPlayer.stop();
+ mPlayer.release();
+ mPlayer = null;
+ }
+ }
+}
diff --git a/doc/ui/AlarmInitReceiver.java b/doc/ui/AlarmInitReceiver.java
new file mode 100644
index 0000000..f221202
--- /dev/null
+++ b/doc/ui/AlarmInitReceiver.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.ui;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ContentUris;
+import android.content.Context;
+import android.content.Intent;
+import android.database.Cursor;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.NoteColumns;
+
+
+public class AlarmInitReceiver extends BroadcastReceiver {
+
+ private static final String [] PROJECTION = new String [] {
+ NoteColumns.ID,
+ NoteColumns.ALERTED_DATE
+ };
+
+ private static final int COLUMN_ID = 0;
+ private static final int COLUMN_ALERTED_DATE = 1;
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ long currentDate = System.currentTimeMillis();
+ Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
+ PROJECTION,
+ NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
+ new String[] { String.valueOf(currentDate) },
+ null);
+
+ if (c != null) {
+ if (c.moveToFirst()) {
+ do {
+ long alertDate = c.getLong(COLUMN_ALERTED_DATE);
+ Intent sender = new Intent(context, AlarmReceiver.class);
+ sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
+ PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
+ AlarmManager alermManager = (AlarmManager) context
+ .getSystemService(Context.ALARM_SERVICE);
+ alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
+ } while (c.moveToNext());
+ }
+ c.close();
+ }
+ }
+}
diff --git a/other/06_凌子杰_代码标注/ui/AlarmReceiver.java b/doc/ui/AlarmReceiver.java
similarity index 69%
rename from other/06_凌子杰_代码标注/ui/AlarmReceiver.java
rename to doc/ui/AlarmReceiver.java
index d0f90e6..54e503b 100644
--- a/other/06_凌子杰_代码标注/ui/AlarmReceiver.java
+++ b/doc/ui/AlarmReceiver.java
@@ -24,16 +24,7 @@ public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent.setClass(context, AlarmAlertActivity.class);
- //启动AlarmAlertActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- //activity要存在于activity的栈中,而非activity的途径启动activity时必然不存在一个activity的栈
- //所以要新起一个栈装入启动的activity
context.startActivity(intent);
}
}
-//这是实现alarm这个功能最接近用户层的包,基于上面的两个包,
-<<<<<<< remotes/origin/lzj_branch
-//作用还需要深究但是对于setClass和addFlags的
-=======
-//作用还需要深究但是对于setClass和addFlags的
->>>>>>> local
diff --git a/other/06_凌子杰_代码标注/ui/DateTimePicker.java b/doc/ui/DateTimePicker.java
similarity index 85%
rename from other/06_凌子杰_代码标注/ui/DateTimePicker.java
rename to doc/ui/DateTimePicker.java
index 30ccd1e..496b0cd 100644
--- a/other/06_凌子杰_代码标注/ui/DateTimePicker.java
+++ b/doc/ui/DateTimePicker.java
@@ -14,9 +14,22 @@
* limitations under the License.
*/
+package net.micode.notes.ui;
+
+import java.text.DateFormatSymbols;
+import java.util.Calendar;
+
+import net.micode.notes.R;
+
+
+import android.content.Context;
+import android.text.format.DateFormat;
+import android.view.View;
+import android.widget.FrameLayout;
+import android.widget.NumberPicker;
+
public class DateTimePicker extends FrameLayout {
- //FrameLayout是布局模板之一
- //所有的子元素全部在屏幕的右上方
+
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12;
@@ -32,15 +45,13 @@ public class DateTimePicker extends FrameLayout {
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
- //初始化控件
+
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
- //NumberPicker是数字选择器
- //这里定义的四个变量全部是在设置闹钟时需要选择的变量(如日期、时、分、上午或者下午)
private Calendar mDate;
- //定义了Calendar类型的变量mDate,用于操作时间
+
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
@@ -60,50 +71,41 @@ public class DateTimePicker extends FrameLayout {
updateDateControl();
onDateTimeChanged();
}
- };//OnValueChangeListener,这是时间改变监听器,这里主要是对日期的监听
- //将现在日期的值传递给mDate;updateDateControl是同步操作
+ };
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
- //这里是对 小时(Hour) 的监听
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
- //声明一个Calendar的变量cal,便于后续的操作
if (!mIs24HourView) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
- //这里是对于12小时制时,晚上11点和12点交替时对日期的更改
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
- //这里是对于12小时制时,凌晨11点和12点交替时对日期的更改
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
- //这里是对于12小时制时,中午11点和12点交替时对AM和PM的更改
} else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
- //这里是对于24小时制时,晚上11点和12点交替时对日期的更改
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
- }//这里是对于12小时制时,凌晨11点和12点交替时对日期的更改
+ }
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
- //通过数字选择器对newHour的赋值
mDate.set(Calendar.HOUR_OF_DAY, newHour);
- //通过set函数将新的Hour值传给mDate
onDateTimeChanged();
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
@@ -115,19 +117,15 @@ public class DateTimePicker extends FrameLayout {
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
- //这里是对 分钟(Minute)改变的监听
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
- //设置offset,作为小时改变的一个记录数据
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
- //如果原值为59,新值为0,则offset加1
- //如果原值为0,新值为59,则offset减1
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
@@ -147,7 +145,6 @@ public class DateTimePicker extends FrameLayout {
};
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
- //对AM和PM的监听
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
@@ -169,20 +166,18 @@ public class DateTimePicker extends FrameLayout {
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
- //通过对数据库的访问,获取当前的系统时间
+
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
- }//上面函数的得到的是一个天文数字(1970至今的秒数),需要DateFormat将其变得有意义
+ }
public DateTimePicker(Context context, long date, boolean is24HourView) {
- super(context);//获取系统时间
+ super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this);
- //如果当前Activity里用到别的layout,比如对话框layout
- //还要设置这个layout上的其他组件的内容,就必须用inflate()方法先将对话框的layout找出来
- //然后再用findViewById()找到它上面的其它组件
+
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
@@ -231,9 +226,7 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
- //存在疑问:setEnabled的作用
- //下面的代码通过原程序的注释已经比较清晰,另外可以通过函数名来判断
- //下面的各函数主要是对上面代码引用到的各函数功能的实现
+
@Override
public boolean isEnabled() {
return mIsEnabled;
@@ -247,7 +240,6 @@ public class DateTimePicker extends FrameLayout {
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
- //实现函数——得到当前的秒数
/**
* Set the current date
@@ -259,7 +251,7 @@ public class DateTimePicker extends FrameLayout {
cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
- }//实现函数功能——设置当前的时间,参数是date
+ }
/**
* Set the current date
@@ -277,14 +269,13 @@ public class DateTimePicker extends FrameLayout {
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
- }//实现函数功能——设置当前的时间,参数是各详细的变量
+ }
/**
* Get current year
*
* @return The current year
*/
- //下面是得到year、month、day等值
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
@@ -455,7 +446,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
- }// 对于星期几的算法
+ }
private void updateAmPmControl() {
if (mIs24HourView) {
@@ -465,7 +456,7 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
- }// 对于上下午操作的算法
+ }
private void updateHourControl() {
if (mIs24HourView) {
@@ -475,7 +466,7 @@ public class DateTimePicker extends FrameLayout {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
- }// 对于小时的算法
+ }
/**
* Set the callback that indicates the 'Set' button has been pressed.
@@ -492,4 +483,3 @@ public class DateTimePicker extends FrameLayout {
}
}
}
-
diff --git a/other/06_凌子杰_代码标注/ui/DateTimePickerDialog.java b/doc/ui/DateTimePickerDialog.java
similarity index 78%
rename from other/06_凌子杰_代码标注/ui/DateTimePickerDialog.java
rename to doc/ui/DateTimePickerDialog.java
index 3df9568..2c47ba4 100644
--- a/other/06_凌子杰_代码标注/ui/DateTimePickerDialog.java
+++ b/doc/ui/DateTimePickerDialog.java
@@ -32,24 +32,18 @@ import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance();
- //创建一个Calendar类型的变量 mDate,方便时间的操作
private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener;
- //声明一个时间日期滚动选择控件 mOnDateTimeSetListener
private DateTimePicker mDateTimePicker;
- //DateTimePicker控件,控件一般用于让用户可以从日期列表中选择单个值。
- //运行时,单击控件边上的下拉箭头,会显示为两个部分:一个下拉列表,一个用于选择日期的
+
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
public DateTimePickerDialog(Context context, long date) {
- //对该界面对话框的实例化
super(context);
- //对数据库的操作
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
- //添加一个子视图
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
@@ -58,20 +52,15 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
- //将视图中的各选项设置为系统当前时间
updateTitle(mDate.getTimeInMillis());
}
});
mDate.setTimeInMillis(date);
- //得到系统时间
mDate.set(Calendar.SECOND, 0);
- //将秒数设置为0
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
- //设置按钮
set24HourView(DateFormat.is24HourFormat(this.getContext()));
- //时间标准化打印
updateTitle(mDate.getTimeInMillis());
}
@@ -81,7 +70,7 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
- }//将时间日期滚动选择控件实例化
+ }
private void updateTitle(long date) {
int flag =
@@ -90,13 +79,12 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
- }//android开发中常见日期管理工具类(API)——DateUtils:按照上下午显示时间
+ }
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
- }//第一个参数arg0是接收到点击事件的对话框
- //第二个参数arg1是该对话框上的按钮
+ }
}
\ No newline at end of file
diff --git a/other/06_凌子杰_代码标注/ui/DropdownMenu.java b/doc/ui/DropdownMenu.java
similarity index 85%
rename from other/06_凌子杰_代码标注/ui/DropdownMenu.java
rename to doc/ui/DropdownMenu.java
index 7a4e0da..613dc74 100644
--- a/other/06_凌子杰_代码标注/ui/DropdownMenu.java
+++ b/doc/ui/DropdownMenu.java
@@ -30,18 +30,14 @@ import net.micode.notes.R;
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
- //声明一个下拉菜单
private Menu mMenu;
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
mButton.setBackgroundResource(R.drawable.dropdown_icon);
- //设置这个view的背景
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
- //MenuInflater是用来实例化Menu目录下的Menu布局文件
- //根据ID来确认menu的内容选项
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@@ -52,16 +48,14 @@ public class DropdownMenu {
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
- }//设置菜单的监听
+ }
}
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
- //对于菜单选项的初始化,根据索引搜索菜单需要的选项
public void setTitle(CharSequence title) {
mButton.setText(title);
}
- //布局文件,设置标题
}
diff --git a/other/06_凌子杰_代码标注/ui/FoldersListAdapter.java b/doc/ui/FoldersListAdapter.java
similarity index 81%
rename from other/06_凌子杰_代码标注/ui/FoldersListAdapter.java
rename to doc/ui/FoldersListAdapter.java
index ab83701..96b77da 100644
--- a/other/06_凌子杰_代码标注/ui/FoldersListAdapter.java
+++ b/doc/ui/FoldersListAdapter.java
@@ -30,14 +30,10 @@ import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter {
- //CursorAdapter是Cursor和ListView的接口
- //FoldersListAdapter继承了CursorAdapter的类
- //主要作用是便签数据库和用户的交互
- //这里就是用folder(文件夹)的形式展现给用户
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
- };//调用数据库中便签的ID和片段
+ };
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
@@ -45,13 +41,12 @@ public class FoldersListAdapter extends CursorAdapter {
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
- }//数据库操作
+ }
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
- //ViewGroup是容器
return new FolderListItem(context);
- }//创建一个文件夹,对于各文件夹中子标签的初始化
+ }
@Override
public void bindView(View view, Context context, Cursor cursor) {
@@ -60,22 +55,20 @@ public class FoldersListAdapter extends CursorAdapter {
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName);
}
- }//将各个布局文件绑定起来
+ }
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
- }//根据数据库中标签的ID得到标签的各项内容
+ }
private class FolderListItem extends LinearLayout {
private TextView mName;
public FolderListItem(Context context) {
super(context);
- //操作数据库
inflate(context, R.layout.folder_list_item, this);
- //根据布局文件的名字等信息将其找出来
mName = (TextView) findViewById(R.id.tv_folder_name);
}
diff --git a/other/06_凌子杰_代码标注/ui/NoteEditActivity.java b/doc/ui/NoteEditActivity.java
similarity index 77%
rename from other/06_凌子杰_代码标注/ui/NoteEditActivity.java
rename to doc/ui/NoteEditActivity.java
index 8ba7ee3..96a9ff8 100644
--- a/other/06_凌子杰_代码标注/ui/NoteEditActivity.java
+++ b/doc/ui/NoteEditActivity.java
@@ -74,8 +74,6 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
- //该类主要是针对标签的编辑
- //继承了系统内部许多和监听有关的类
private class HeadViewHolder {
public TextView tvModified;
@@ -85,7 +83,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public ImageView ibSetBgColor;
}
- //使用Map实现数据存储
+
private static final Map sBgSelectorBtnsMap = new HashMap();
static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
@@ -93,7 +91,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
- //put函数是将指定值和指定键相连
}
private static final Map sBgSelectorSelectionMap = new HashMap();
@@ -103,7 +100,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
- //put函数是将指定值和指定键相连
}
private static final Map sFontSizeBtnsMap = new HashMap();
@@ -112,7 +108,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
- //put函数是将指定值和指定键相连
}
private static final Map sFontSelectorSelectionMap = new HashMap();
@@ -121,7 +116,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
- //put函数是将指定值和指定键相连
}
private static final String TAG = "NoteEditActivity";
@@ -129,23 +123,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private HeadViewHolder mNoteHeaderHolder;
private View mHeadViewPanel;
- //私有化一个界面操作mHeadViewPanel,对表头的操作
+
private View mNoteBgColorSelector;
- //私有化一个界面操作mNoteBgColorSelector,对背景颜色的操作
+
private View mFontSizeSelector;
- //私有化一个界面操作mFontSizeSelector,对标签字体的操作
+
private EditText mNoteEditor;
- //声明编辑控件,对文本操作
+
private View mNoteEditorPanel;
- //私有化一个界面操作mNoteEditorPanel,文本编辑的控制板
- //private WorkingNote mWorkingNote;
+
private WorkingNote mWorkingNote;
- //对模板WorkingNote的初始化
+
private SharedPreferences mSharedPrefs;
- //私有化SharedPreferences的数据存储方式
- //它的本质是基于XML文件存储key-value键值对数据
private int mFontSizeId;
- //用于操作字体的大小
+
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
@@ -154,7 +145,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
private LinearLayout mEditTextList;
- //线性布局
+
private String mUserQuery;
private Pattern mPattern;
@@ -162,7 +153,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit);
- //对数据库的访问操作
+
if (savedInstanceState == null && !initActivityState(getIntent())) {
finish();
return;
@@ -185,7 +176,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return;
}
Log.d(TAG, "Restoring from killed activity");
- }//为防止内存不足时程序的终止,在这里有一个保存现场的函数
+ }
}
private boolean initActivityState(Intent intent) {
@@ -197,41 +188,34 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = "";
- //如果用户实例化标签时,系统并未给出标签ID
+
/**
* Starting from the searched result
*/
- //根据键值查找ID
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
}
- //如果ID在数据库中未找到
+
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
Intent jump = new Intent(this, NotesListActivity.class);
startActivity(jump);
- //程序将跳转到上面声明的intent——jump
showToast(R.string.error_note_not_exist);
finish();
return false;
- }//ID在数据库中找到
- else {
+ } else {
mWorkingNote = WorkingNote.load(this, noteId);
if (mWorkingNote == null) {
Log.e(TAG, "load note failed with note id" + noteId);
- //打印出红色的错误信息
finish();
return false;
}
}
- //setSoftInputMode——软键盘输入模式
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// New note
- // 大多用于broadcast发送广播时给机制(intent)设置一个action,就是一个字符串
- // 用户可以通过receive(接受)intent,通过 getAction得到的字符串,来决定做什么
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
@@ -239,7 +223,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Notes.TYPE_WIDGET_INVALIDE);
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this));
- // intent.getInt(Long、String)Extra是对各变量的语法分析
+
// Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
@@ -255,7 +239,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.e(TAG, "load call note failed with note id" + noteId);
finish();
return false;
- }//将电话号码与手机的号码簿相关
+ }
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
widgetType, bgResId);
@@ -264,7 +248,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId);
- }//创建一个新的WorkingNote
+ }
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
@@ -285,10 +269,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
private void initNoteScreen() {
- //对界面的初始化操作
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));
- //设置外观
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
switchToListMode(mWorkingNote.getContent());
} else {
@@ -312,21 +294,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
*/
showAlertHeader();
}
- //设置闹钟的显示
+
private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis();
if (time > mWorkingNote.getAlertDate()) {
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);
- } //如果系统时间大于了闹钟设置的时间,那么闹钟失效
- else {
+ } else {
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));
}
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);
- } //显示闹钟开启的图标
- else {
+ } else {
mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
};
@@ -349,29 +329,26 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (!mWorkingNote.existInDatabase()) {
saveNote();
}
- //在创建一个新的标签时,先在数据库中匹配
- //如果不存在,那么先在数据库中存储
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
}
@Override
- //MotionEvent是对屏幕触控的传递机制
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE);
return true;
- }//颜色选择器在屏幕上可见
+ }
if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE);
return true;
- }//字体大小选择器在屏幕上可见
+ }
return super.dispatchTouchEvent(ev);
}
- //对屏幕触控的坐标进行操作
+
private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2];
view.getLocationOnScreen(location);
@@ -380,9 +357,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (ev.getX() < x
|| ev.getX() > (x + view.getWidth())
|| ev.getY() < y
- || ev.getY() > (y + view.getHeight()))
- //如果触控的位置超出了给定的范围,返回false
- {
+ || ev.getY() > (y + view.getHeight())) {
return false;
}
return true;
@@ -402,13 +377,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
for (int id : sBgSelectorBtnsMap.keySet()) {
ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this);
- }//对标签各项属性内容的初始化
+ }
mFontSizeSelector = findViewById(R.id.font_size_selector);
for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id);
view.setOnClickListener(this);
- };//对字体大小的选择
+ };
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/**
@@ -430,7 +405,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
clearSettingState();
}
- //和桌面小工具的同步
+
private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
@@ -475,7 +450,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
mFontSizeSelector.setVisibility(View.GONE);
}
- }//************************存在问题
+ }
@Override
public void onBackPressed() {
@@ -506,7 +481,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
@Override
- //对选择菜单的准备
public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) {
return true;
@@ -515,7 +489,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
menu.clear();
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_note_edit, menu);
- // MenuInflater是用来实例化Menu目录下的Menu布局文件的
} else {
getMenuInflater().inflate(R.menu.note_edit, menu);
}
@@ -535,65 +508,43 @@ public class NoteEditActivity extends Activity implements OnClickListener,
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
- //根据菜单的id来编剧相关项目
case R.id.menu_new_note:
- //创建一个新的便签
createNewNote();
break;
case R.id.menu_delete:
- //删除便签
AlertDialog.Builder builder = new AlertDialog.Builder(this);
- //创建关于删除操作的对话框
builder.setTitle(getString(R.string.alert_title_delete));
- // 设置标签的标题为alert_title_delete
builder.setIcon(android.R.drawable.ic_dialog_alert);
- //设置对话框图标
builder.setMessage(getString(R.string.alert_message_delete_note));
- //设置对话框内容
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
- //建立按键监听器
public void onClick(DialogInterface dialog, int which) {
- //点击所触发事件
deleteCurrentNote();
- // 删除单签便签
finish();
}
});
- //添加“YES”按钮
builder.setNegativeButton(android.R.string.cancel, null);
- //添加“NO”的按钮
builder.show();
- //显示对话框
break;
case R.id.menu_font_size:
- //字体大小的编辑
mFontSizeSelector.setVisibility(View.VISIBLE);
- // 将字体选择器置为可见1
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
- // 通过id找到相应的大小
break;
case R.id.menu_list_mode:
- //选择列表模式
mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?
TextNote.MODE_CHECK_LIST : 0);
break;
case R.id.menu_share:
- //菜单共享
getWorkingText();
sendTo(this, mWorkingNote.getContent());
- // 用sendto函数将运行文本发送到遍历的本文内
break;
case R.id.menu_send_to_desktop:
- //发送到桌面
sendToDesktop();
break;
case R.id.menu_alert:
- //创建提醒器
setReminder();
break;
case R.id.menu_delete_remind:
- //删除日期提醒
mWorkingNote.setAlertDate(0, false);
break;
default:
@@ -601,161 +552,112 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
return true;
}
- /*
- * 函数功能:建立事件提醒器
- * 函数实现:如下注释
- */
+
private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
- // 建立修改时间日期的对话框
d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
public void OnDateTimeSet(AlertDialog dialog, long date) {
mWorkingNote.setAlertDate(date , true);
- //选择提醒的日期
}
});
- //建立时间日期的监听器
d.show();
- //显示对话框
}
/**
* Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type
*/
- /*
- * 函数功能:共享便签
- * 函数实现:如下注释
- */
private void sendTo(Context context, String info) {
Intent intent = new Intent(Intent.ACTION_SEND);
- //建立intent链接选项
intent.putExtra(Intent.EXTRA_TEXT, info);
- //将需要传递的便签信息放入text文件中
intent.setType("text/plain");
- //编辑连接器的类型
context.startActivity(intent);
- //在acti中进行链接
}
private void createNewNote() {
// Firstly, save current editing notes
- //保存当前便签
saveNote();
// For safety, start a new NoteEditActivity
finish();
Intent intent = new Intent(this, NoteEditActivity.class);
- //设置链接器
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
- //该活动定义为创建或编辑
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());
- //将运行便签的id添加到INTENT_EXTRA_FOLDER_ID标记中
startActivity(intent);
- //开始activity并链接
}
- /*
- * 函数功能:删除当前便签
- * 函数实现:如下注释
- */
+
private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) {
- //假如当前运行的便签内存有数据
HashSet ids = new HashSet();
long id = mWorkingNote.getNoteId();
if (id != Notes.ID_ROOT_FOLDER) {
ids.add(id);
- //如果不是头文件夹建立一个hash表把便签id存起来
} else {
Log.d(TAG, "Wrong note id, should not happen");
- //否则报错
}
if (!isSyncMode()) {
- //在非同步模式情况下
- //删除操作
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
Log.e(TAG, "Delete Note error");
}
} else {
- //同步模式
- //移动至垃圾文件夹的操作
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {
Log.e(TAG, "Move notes to trash folder error, should not happens");
}
}
}
mWorkingNote.markDeleted(true);
- //将这些标签的删除标记置为true
}
- /*
- * 函数功能:判断是否为同步模式
- * 函数实现:直接看NotesPreferenceActivity中同步名称是否为空
- */
+
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
- /*
- * 函数功能:设置提醒时间
- * 函数实现:如下注释
- */
+
public void onClockAlertChanged(long date, boolean set) {
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) {
- //首先保存已有的便签
saveNote();
}
if (mWorkingNote.getNoteId() > 0) {
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
- //若有有运行的便签就是建立一个链接器将标签id都存在uri中
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
- //设置提醒管理器
showAlertHeader();
if(!set) {
alarmManager.cancel(pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
}
- //如果用户设置了时间,就通过提醒管理器设置一个监听事项
} else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
- //没有运行的便签就报错
Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock);
}
}
- /*
- * 函数功能:Widget发生改变的所触发的事件
- */
+
public void onWidgetChanged() {
updateWidget();
}
- /*
- * 函数功能: 删除编辑文本框所触发的事件
- * 函数实现:如下注释
- */
+
public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount();
if (childCount == 1) {
return;
}
- //没有编辑框的话直接返回
+
for (int i = index + 1; i < childCount; i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1);
- //通过id把编辑框存在便签编辑框中
}
mEditTextList.removeViewAt(index);
- //删除特定位置的视图
NoteEditText edit = null;
if(index == 0) {
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
@@ -764,94 +666,69 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text);
}
- //通过id把编辑框存在空的NoteEditText中
int length = edit.length();
edit.append(text);
- edit.requestFocus();//请求优先完成该此 编辑
- edit.setSelection(length);//定位到length位置处的条目
+ edit.requestFocus();
+ edit.setSelection(length);
}
- /*
- * 函数功能:进入编辑文本框所触发的事件
- * 函数实现:如下注释
- */
+
public void onEditTextEnter(int index, String text) {
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
- //越界把偶偶
}
View view = getListItem(text, index);
mEditTextList.addView(view, index);
- //建立一个新的视图并添加到编辑文本框内
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
- edit.requestFocus();//请求优先操作
- edit.setSelection(0);//定位到起始位置
+ edit.requestFocus();
+ edit.setSelection(0);
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i);
- //遍历子文本框并设置对应对下标
}
}
- /*
- * 函数功能:切换至列表模式
- * 函数实现:如下注释
- */
+
private void switchToListMode(String text) {
mEditTextList.removeAllViews();
String[] items = text.split("\n");
int index = 0;
- //清空所有视图,初始化下标
for (String item : items) {
if(!TextUtils.isEmpty(item)) {
mEditTextList.addView(getListItem(item, index));
index++;
- //遍历所有文本单元并添加到文本框中
}
}
mEditTextList.addView(getListItem("", index));
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
- //优先请求此操作
- mNoteEditor.setVisibility(View.GONE);//便签编辑器不可见
- mEditTextList.setVisibility(View.VISIBLE); //将文本编辑框置为可见
+
+ mNoteEditor.setVisibility(View.GONE);
+ mEditTextList.setVisibility(View.VISIBLE);
}
- /*
- * 函数功能:获取高亮效果的反馈情况
- * 函数实现:如下注释
- */
+
private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
- //新建一个效果选项
if (!TextUtils.isEmpty(userQuery)) {
mPattern = Pattern.compile(userQuery);
- //将用户的询问进行解析
Matcher m = mPattern.matcher(fullText);
- //建立一个状态机检查Pattern并进行匹配
int start = 0;
while (m.find(start)) {
spannable.setSpan(
new BackgroundColorSpan(this.getResources().getColor(
R.color.user_query_highlight)), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
- //设置背景颜色
start = m.end();
- //跟新起始位置
}
}
return spannable;
}
- /*
- * 函数功能:获取列表项
- * 函数实现:如下注释
- */
+
private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
- //创建一个视图
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
- //创建一个文本编辑框并设置可见性
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
@@ -862,14 +739,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
}
});
- //建立一个打钩框并设置监听器
+
if (item.startsWith(TAG_CHECKED)) {
- //选择勾选
cb.setChecked(true);
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
item = item.substring(TAG_CHECKED.length(), item.length()).trim();
} else if (item.startsWith(TAG_UNCHECKED)) {
- //选择不勾选
cb.setChecked(false);
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
@@ -878,90 +753,61 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setOnTextViewChangeListener(this);
edit.setIndex(index);
edit.setText(getHighlightQueryResult(item, mUserQuery));
- //运行编辑框的监听器对该行为作出反应,并设置下标及文本内容
return view;
}
- /*
- * 函数功能:便签内容发生改变所 触发的事件
- * 函数实现:如下注释
- */
+
public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen");
return;
- //越界报错
}
if(hasText) {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
} else {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
}
- //如果内容不为空则将其子编辑框可见性置为可见,否则不可见
}
- /*
- * 函数功能:检查模式和列表模式的切换
- * 函数实现:如下注释
- */
+
public void onCheckListModeChanged(int oldMode, int newMode) {
if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString());
- //检查模式切换到列表模式
} else {
if (!getWorkingText()) {
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
""));
}
- //若是获取到文本就改变其检查标记
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
mEditTextList.setVisibility(View.GONE);
mNoteEditor.setVisibility(View.VISIBLE);
- //修改文本编辑器的内容和可见性
}
}
- /*
- * 函数功能:设置勾选选项表并返回是否勾选的标记
- * 函数实现:如下注释
- */
+
private boolean getWorkingText() {
boolean hasChecked = false;
- //初始化check标记
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
- //若模式为CHECK_LIST
StringBuilder sb = new StringBuilder();
- //创建可变字符串
for (int i = 0; i < mEditTextList.getChildCount(); i++) {
View view = mEditTextList.getChildAt(i);
- //遍历所有子编辑框的视图
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
if (!TextUtils.isEmpty(edit.getText())) {
- //若文本不为空
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
- //该选项框已打钩
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");
hasChecked = true;
- //扩展字符串为已打钩并把标记置true
} else {
sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");
- //扩展字符串添加未打钩
}
}
}
mWorkingNote.setWorkingText(sb.toString());
- //利用编辑好的字符串设置运行便签的内容
} else {
mWorkingNote.setWorkingText(mNoteEditor.getText().toString());
- // 若不是该模式直接用编辑器中的内容设置运行中标签的内容
}
return hasChecked;
}
- /*
- * 函数功能:保存便签
- * 函数实现:如下注释
- */
+
private boolean saveNote() {
getWorkingText();
boolean saved = mWorkingNote.saveNote();
- //运行 getWorkingText()之后保存
if (saved) {
/**
* There are two modes from List view to edit view, open one note,
@@ -970,15 +816,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
- //如英文注释所说链接RESULT_OK是为了识别保存的2种情况,一是创建后保存,二是修改后保存
setResult(RESULT_OK);
}
return saved;
}
- /*
- * 函数功能:将便签发送至桌面
- * 函数实现:如下注释
- */
+
private void sendToDesktop() {
/**
* Before send message to home, we should make sure that current
@@ -987,16 +829,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
- //若不存在数据也就是新的标签就保存起来先
}
if (mWorkingNote.getNoteId() > 0) {
- //若是有内容
Intent sender = new Intent();
Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
- //建立发送到桌面的连接器
shortcutIntent.setAction(Intent.ACTION_VIEW);
- //链接为一个视图
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId());
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
@@ -1004,12 +842,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app));
sender.putExtra("duplicate", true);
- //将便签的相关信息都添加到要发送的文件里
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
- //设置sneder的行为是发送
showToast(R.string.info_note_enter_desktop);
sendBroadcast(sender);
- //显示到桌面
} else {
/**
* There is the condition that user has input nothing (the note is
@@ -1018,31 +853,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
*/
Log.e(TAG, "Send to desktop error");
showToast(R.string.error_note_empty_for_send_to_desktop);
- //空便签直接报错
}
}
- /*
- * 函数功能:编辑小图标的标题
- * 函数实现:如下注释
- */
+
private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, "");
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content;
- //直接设置为content中的内容并返回,有勾选和未勾选2种
}
- /*
- * 函数功能:显示提示的视图
- * 函数实现:根据下标显示对应的提示
- */
+
private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT);
}
- /*
- * 函数功能:持续显示提示的视图
- * 函数实现:根据下标和持续的时间(duration)编辑提示视图并显示
- */
+
private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show();
}
diff --git a/other/06_凌子杰_代码标注/ui/NoteEditText.java b/doc/ui/NoteEditText.java
similarity index 64%
rename from other/06_凌子杰_代码标注/ui/NoteEditText.java
rename to doc/ui/NoteEditText.java
index 6dab416..2afe2a8 100644
--- a/other/06_凌子杰_代码标注/ui/NoteEditText.java
+++ b/doc/ui/NoteEditText.java
@@ -36,7 +36,7 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
-//继承edittext,设置便签设置文本框
+
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
@@ -45,7 +45,7 @@ public class NoteEditText extends EditText {
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
- //建立一个字符和整数的hash表,用于链接电话,网站,还有邮箱
+
private static final Map sSchemaActionResMap = new HashMap();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
@@ -56,20 +56,17 @@ public class NoteEditText extends EditText {
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*/
- //在NoteEditActivity中删除或添加文本的操作,可以看做是一个文本是否被变的标记,英文注释已说明的很清楚
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
- //处理删除按键时的操作
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
- //处理进入按键时的操作
void onEditTextEnter(int index, String text);
/**
@@ -79,194 +76,142 @@ public class NoteEditText extends EditText {
}
private OnTextViewChangeListener mOnTextViewChangeListener;
- //根据context设置文本
+
public NoteEditText(Context context) {
- super(context, null);//用super引用父类变量
+ super(context, null);
mIndex = 0;
}
- //设置当前光标
+
public void setIndex(int index) {
mIndex = index;
}
- //初始化文本修改标记
+
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
- //AttributeSet 百度了一下是自定义空控件属性,用于维护便签动态变化的属性
- //初始化便签
+
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
- // 根据defstyle自动初始化
+
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
- //view里的函数,处理手机屏幕的所有事件
- /*参数event为手机屏幕触摸事件封装类的对象,其中封装了该事件的所有信息,
- 例如触摸的位置、触摸的类型以及触摸的时间等。该对象会在用户触摸手机屏幕时被创建。*/
+
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
- //重写了需要处理屏幕被按下的事件
case MotionEvent.ACTION_DOWN:
- //跟新当前坐标值
+
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
- //用布局控件layout根据x,y的新值设置新的位置
+
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
- //更新光标新的位置
Selection.setSelection(getText(), off);
break;
}
return super.onTouchEvent(event);
}
- /*
- * 函数功能:处理用户按下一个键盘按键时会触发 的事件
- * 实现过程:如下注释
- */
+
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
- //根据按键的 Unicode 编码值来处理
case KeyEvent.KEYCODE_ENTER:
- //“进入”按键
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
- //“删除”按键
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
- //继续执行父类的其他点击事件
return super.onKeyDown(keyCode, event);
}
@Override
- /*
- * 函数功能:处理用户松开一个键盘按键时会触发 的事件
- * 实现方式:如下注释
- */
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
- //根据按键的 Unicode 编码值来处理,有删除和进入2种操作
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
- //若是被修改过
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
- //若之前有被修改并且文档不为空
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
- //利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
- //其他情况报错,文档的改动监听器并没有建立
}
break;
case KeyEvent.KEYCODE_ENTER:
- //同上也是分为监听器是否建立2种情况
if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart();
- //获取当前位置
String text = getText().subSequence(selectionStart, length()).toString();
- //获取当前文本
setText(getText().subSequence(0, selectionStart));
- //根据获取的文本设置当前文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
- //当{@link KeyEvent#KEYCODE_ENTER}添加新文本
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
- //其他情况报错,文档的改动监听器并没有建立
}
break;
default:
break;
}
- //继续执行父类的其他按键弹起的事件
return super.onKeyUp(keyCode, event);
}
@Override
- /*
- * 函数功能:当焦点发生变化时,会自动调用该方法来处理焦点改变的事件
- * 实现方式:如下注释
- * 参数:focused表示触发该事件的View是否获得了焦点,当该控件获得焦点时,Focused等于true,否则等于false。
- direction表示焦点移动的方向,用数值表示
- Rect:表示在触发事件的View的坐标系中,前一个获得焦点的矩形区域,即表示焦点是从哪里来的。如果不可用则为null
- */
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
- //若监听器已经建立
if (!focused && TextUtils.isEmpty(getText())) {
- //获取到焦点并且文本不为空
mOnTextViewChangeListener.onTextChange(mIndex, false);
- //mOnTextViewChangeListener子函数,置false隐藏事件选项
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
- //mOnTextViewChangeListener子函数,置true显示事件选项
}
}
- //继续执行父类的其他焦点变化的事件
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
- /*
- * 函数功能:生成上下文菜单
- * 函数实现:如下注释
- */
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
- //有文本存在
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
- //获取文本开始和结尾位置
+
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
- //获取开始到结尾的最大值和最小值
+
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
- //设置url的信息的范围值
if (urls.length == 1) {
int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) {
- //获取计划表中所有的key值
if(urls[0].getURL().indexOf(schema) >= 0) {
- //若url可以添加则在添加后将defaultResId置为key所映射的值
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
- //defaultResId == 0则说明url并没有添加任何东西,所以置为连接其他SchemaActionResMap的值
defaultResId = R.string.note_link_other;
}
- //建立菜单
+
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
- //新建按键监听器
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
urls[0].onClick(NoteEditText.this);
- //根据相应的文本设置菜单的按键
return true;
}
});
}
}
- //继续执行父类的其他菜单创建的事件
super.onCreateContextMenu(menu);
}
}
diff --git a/other/06_凌子杰_代码标注/ui/NoteItemData.java b/doc/ui/NoteItemData.java
similarity index 88%
rename from other/06_凌子杰_代码标注/ui/NoteItemData.java
rename to doc/ui/NoteItemData.java
index 85052ab..0f5a878 100644
--- a/other/06_凌子杰_代码标注/ui/NoteItemData.java
+++ b/doc/ui/NoteItemData.java
@@ -75,9 +75,8 @@ public class NoteItemData {
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
- //初始化NoteItemData,主要利用光标cursor获取的东西
+
public NoteItemData(Context context, Cursor cursor) {
- //getxxx为转换格式
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@@ -92,12 +91,11 @@ public class NoteItemData {
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
- //初始化电话号码的信息
+
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
- //mphonenumber里有符合字符串,则用contart功能连接
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
@@ -110,32 +108,26 @@ public class NoteItemData {
}
checkPostion(cursor);
}
- //根据鼠标的位置设置标记,和位置
+
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
- //初始化“多重子文件”“单一子文件”2个标记
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
- //主要是设置上诉2标记
+
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
- //若是note格式并且不是第一个元素
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
- //获取光标位置后看上一行
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
- //若光标满足系统或note格式
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
- //若是数据行数大于但前位置+1则设置成正确
} else {
mIsOneNoteFollowingFolder = true;
- //否则单一文件夹标记为true
}
}
- if (!cursor.moveToNext()) {//若不能再往下走则报错
+ if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
@@ -221,7 +213,7 @@ public class NoteItemData {
public boolean hasAlert() {
return (mAlertDate > 0);
}
- //若数据父id为保存至文件夹模式的id且满足电话号码单元不为空,则isCallRecord为true
+
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
diff --git a/other/06_刘峻豪_代码标注/ui/NotesListActivity.java b/doc/ui/NotesListActivity.java
similarity index 100%
rename from other/06_刘峻豪_代码标注/ui/NotesListActivity.java
rename to doc/ui/NotesListActivity.java
diff --git a/other/06_刘峻豪_代码标注/ui/NotesListAdapter.java b/doc/ui/NotesListAdapter.java
similarity index 100%
rename from other/06_刘峻豪_代码标注/ui/NotesListAdapter.java
rename to doc/ui/NotesListAdapter.java
diff --git a/other/06_刘峻豪_代码标注/ui/NotesListItem.java b/doc/ui/NotesListItem.java
similarity index 100%
rename from other/06_刘峻豪_代码标注/ui/NotesListItem.java
rename to doc/ui/NotesListItem.java
diff --git a/other/06_刘峻豪_代码标注/ui/NotesPreferenceActivity.java b/doc/ui/NotesPreferenceActivity.java
similarity index 100%
rename from other/06_刘峻豪_代码标注/ui/NotesPreferenceActivity.java
rename to doc/ui/NotesPreferenceActivity.java
index 982b261..2e85044 100644
--- a/other/06_刘峻豪_代码标注/ui/NotesPreferenceActivity.java
+++ b/doc/ui/NotesPreferenceActivity.java
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@@ -543,4 +544,3 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
}
-
diff --git a/doc/widget/NoteWidgetProvider.java b/doc/widget/NoteWidgetProvider.java
new file mode 100644
index 0000000..ec6f819
--- /dev/null
+++ b/doc/widget/NoteWidgetProvider.java
@@ -0,0 +1,132 @@
+/*
+ * 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.widget;
+import android.app.PendingIntent;
+import android.appwidget.AppWidgetManager;
+import android.appwidget.AppWidgetProvider;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.Intent;
+import android.database.Cursor;
+import android.util.Log;
+import android.widget.RemoteViews;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.tool.ResourceParser;
+import net.micode.notes.ui.NoteEditActivity;
+import net.micode.notes.ui.NotesListActivity;
+
+public abstract class NoteWidgetProvider extends AppWidgetProvider {
+ public static final String [] PROJECTION = new String [] {
+ NoteColumns.ID,
+ NoteColumns.BG_COLOR_ID,
+ NoteColumns.SNIPPET
+ };
+
+ public static final int COLUMN_ID = 0;
+ public static final int COLUMN_BG_COLOR_ID = 1;
+ public static final int COLUMN_SNIPPET = 2;
+
+ private static final String TAG = "NoteWidgetProvider";
+
+ @Override
+ public void onDeleted(Context context, int[] appWidgetIds) {
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
+ for (int i = 0; i < appWidgetIds.length; i++) {
+ context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
+ values,
+ NoteColumns.WIDGET_ID + "=?",
+ new String[] { String.valueOf(appWidgetIds[i])});
+ }
+ }
+
+ private Cursor getNoteWidgetInfo(Context context, int widgetId) {
+ return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
+ PROJECTION,
+ NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
+ new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
+ null);
+ }
+
+ protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
+ update(context, appWidgetManager, appWidgetIds, false);
+ }
+
+ private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
+ boolean privacyMode) {
+ for (int i = 0; i < appWidgetIds.length; i++) {
+ if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
+ int bgId = ResourceParser.getDefaultBgId(context);
+ String snippet = "";
+ Intent intent = new Intent(context, NoteEditActivity.class);
+ intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
+ intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
+ intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
+
+ Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
+ if (c != null && c.moveToFirst()) {
+ if (c.getCount() > 1) {
+ Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
+ c.close();
+ return;
+ }
+ snippet = c.getString(COLUMN_SNIPPET);
+ bgId = c.getInt(COLUMN_BG_COLOR_ID);
+ intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
+ intent.setAction(Intent.ACTION_VIEW);
+ } else {
+ snippet = context.getResources().getString(R.string.widget_havenot_content);
+ intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
+ }
+
+ if (c != null) {
+ c.close();
+ }
+
+ RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
+ rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
+ intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
+ /**
+ * Generate the pending intent to start host for the widget
+ */
+ PendingIntent pendingIntent = null;
+ if (privacyMode) {
+ rv.setTextViewText(R.id.widget_text,
+ context.getString(R.string.widget_under_visit_mode));
+ pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
+ context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
+ } else {
+ rv.setTextViewText(R.id.widget_text, snippet);
+ pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
+ PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+
+ rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
+ appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
+ }
+ }
+ }
+
+ protected abstract int getBgResourceId(int bgId);
+
+ protected abstract int getLayoutId();
+
+ protected abstract int getWidgetType();
+}
diff --git a/doc/widget/NoteWidgetProvider_2x.java b/doc/widget/NoteWidgetProvider_2x.java
new file mode 100644
index 0000000..adcb2f7
--- /dev/null
+++ b/doc/widget/NoteWidgetProvider_2x.java
@@ -0,0 +1,47 @@
+/*
+ * 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.widget;
+
+import android.appwidget.AppWidgetManager;
+import android.content.Context;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.tool.ResourceParser;
+
+
+public class NoteWidgetProvider_2x extends NoteWidgetProvider {
+ @Override
+ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
+ super.update(context, appWidgetManager, appWidgetIds);
+ }
+
+ @Override
+ protected int getLayoutId() {
+ return R.layout.widget_2x;
+ }
+
+ @Override
+ protected int getBgResourceId(int bgId) {
+ return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
+ }
+
+ @Override
+ protected int getWidgetType() {
+ return Notes.TYPE_WIDGET_2X;
+ }
+}
diff --git a/doc/widget/NoteWidgetProvider_4x.java b/doc/widget/NoteWidgetProvider_4x.java
new file mode 100644
index 0000000..c12a02e
--- /dev/null
+++ b/doc/widget/NoteWidgetProvider_4x.java
@@ -0,0 +1,46 @@
+/*
+ * 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.widget;
+
+import android.appwidget.AppWidgetManager;
+import android.content.Context;
+
+import net.micode.notes.R;
+import net.micode.notes.data.Notes;
+import net.micode.notes.tool.ResourceParser;
+
+
+public class NoteWidgetProvider_4x extends NoteWidgetProvider {
+ @Override
+ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
+ super.update(context, appWidgetManager, appWidgetIds);
+ }
+
+ protected int getLayoutId() {
+ return R.layout.widget_4x;
+ }
+
+ @Override
+ protected int getBgResourceId(int bgId) {
+ return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
+ }
+
+ @Override
+ protected int getWidgetType() {
+ return Notes.TYPE_WIDGET_4X;
+ }
+}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..e708b1c
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..a13927f
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Thu Mar 30 20:03:20 CST 2023
+distributionBase=GRADLE_USER_HOME
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
+distributionPath=wrapper/dists
+zipStorePath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
new file mode 100644
index 0000000..4f906e0
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,185 @@
+#!/usr/bin/env sh
+
+#
+# Copyright 2015 the original author or authors.
+#
+# 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
+#
+# https://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.
+#
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=`expr $i + 1`
+ done
+ case $i in
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=`save "$@"`
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..107acd3
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,89 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/import-summary.txt b/import-summary.txt
new file mode 100644
index 0000000..f2e6428
--- /dev/null
+++ b/import-summary.txt
@@ -0,0 +1,36 @@
+ECLIPSE ANDROID PROJECT IMPORT SUMMARY
+======================================
+
+Ignored Files:
+--------------
+The following files were *not* copied into the new Gradle project; you
+should evaluate whether these are still needed in your project and if
+so manually move them:
+
+* .gitignore
+* NOTICE
+* README
+
+Moved Files:
+------------
+Android Gradle projects use a different directory structure than ADT
+Eclipse projects. Here's how the projects were restructured:
+
+* AndroidManifest.xml => app\src\main\AndroidManifest.xml
+* res\ => app\src\main\res\
+* src\ => app\src\main\java\
+
+Next Steps:
+-----------
+You can now build the project. The Gradle project needs network
+connectivity to download dependencies.
+
+Bugs:
+-----
+If for some reason your project does not build, and you determine that
+it is due to a bug or limitation of the Eclipse to Gradle importer,
+please file a bug at http://b.android.com with category
+Component-Tools.
+
+(This import summary is for your information only, and can be deleted
+after import once you are satisfied with the results.)
diff --git a/local.properties b/local.properties
new file mode 100644
index 0000000..9dcdbe6
--- /dev/null
+++ b/local.properties
@@ -0,0 +1,7 @@
+## This file must *NOT* be checked into Version Control Systems,
+# as it contains information specific to your local configuration.
+#
+# Location of the SDK. This is only used by Gradle.
+#
+#Thu Mar 30 20:03:20 CST 2023
+sdk.dir=E\:\\AndroidSDK
diff --git a/model/界面流设计/跳转顺序图和类图.doc b/model/界面流设计/跳转顺序图和类图.doc
deleted file mode 100644
index e7d3d02..0000000
Binary files a/model/界面流设计/跳转顺序图和类图.doc and /dev/null differ
diff --git a/model/详细设计/详细设计.doc b/model/详细设计/详细设计.doc
deleted file mode 100644
index 7d8b482..0000000
Binary files a/model/详细设计/详细设计.doc and /dev/null differ
diff --git a/model/需求分析/需求分析.doc b/model/需求分析/需求分析.doc
deleted file mode 100644
index 1cb97e8..0000000
Binary files a/model/需求分析/需求分析.doc and /dev/null differ
diff --git a/model/需求获取/软件需求描述文档.docx b/model/需求获取/软件需求描述文档.docx
deleted file mode 100644
index b788769..0000000
Binary files a/model/需求获取/软件需求描述文档.docx and /dev/null differ
diff --git a/other/04_江一阳_软件工程汇报PPT.pptx b/other/04_江一阳_软件工程汇报PPT.pptx
deleted file mode 100644
index abe34c6..0000000
Binary files a/other/04_江一阳_软件工程汇报PPT.pptx and /dev/null differ
diff --git a/other/05_江一阳_贡献度.xls b/other/05_江一阳_贡献度.xls
deleted file mode 100644
index 31c57cc..0000000
Binary files a/other/05_江一阳_贡献度.xls and /dev/null differ
diff --git a/other/06_何越_代码标注/gtask/exception/ActionFailureException.java b/other/06_何越_代码标注/gtask/exception/ActionFailureException.java
deleted file mode 100644
index 0da5f17..0000000
--- a/other/06_何越_代码标注/gtask/exception/ActionFailureException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.exception; // 定义了一个异常类,位于 net.micode.notes.gtask.exception 包下
-
-public class ActionFailureException extends RuntimeException { // 定义了一个继承自 RuntimeException 的异常类
-
- private static final long serialVersionUID = 4425249765923293627L; // 定义一个序列化 ID,用于版本控制
-
- public ActionFailureException() { // 无参构造函数
- super(); // 调用父类 RuntimeException 的无参构造函数
- }
-
- public ActionFailureException(String paramString) { // 带参数构造函数,传入异常信息
- super(paramString); // 调用父类 RuntimeException 的带参数构造函数,将异常信息传给父类
- }
-
- public ActionFailureException(String paramString, Throwable paramThrowable) { // 带参数构造函数,传入异常信息和原始异常
- super(paramString, paramThrowable); // 调用父类 RuntimeException 的带参数构造函数,将异常信息和原始异常都传给父类
- }
-}
diff --git a/other/06_何越_代码标注/gtask/remote/GTaskASyncTask.java b/other/06_何越_代码标注/gtask/remote/GTaskASyncTask.java
deleted file mode 100644
index f4665f9..0000000
--- a/other/06_何越_代码标注/gtask/remote/GTaskASyncTask.java
+++ /dev/null
@@ -1,117 +0,0 @@
-
-/*
- * 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.
- */
-
-public class GTaskASyncTask extends AsyncTask {
-
- private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
-
- // 定义回调接口 OnCompleteListener
- public interface OnCompleteListener {
- void onComplete();
- }
-
- private Context mContext;
-
- private NotificationManager mNotifiManager;
-
- private GTaskManager mTaskManager;
-
- private OnCompleteListener mOnCompleteListener;
-
- // 构造函数,初始化成员变量
- public GTaskASyncTask(Context context, OnCompleteListener listener) {
- mContext = context;
- mOnCompleteListener = listener;
- mNotifiManager = (NotificationManager) mContext
- .getSystemService(Context.NOTIFICATION_SERVICE);
- mTaskManager = GTaskManager.getInstance();
- }
-
- // 取消同步
- public void cancelSync() {
- mTaskManager.cancelSync();
- }
-
- // 发布进度
- public void publishProgess(String message) {
- publishProgress(new String[] {
- message
- });
- }
-
- // 显示通知
- private void showNotification(int tickerId, String content) {
- Notification notification = new Notification(R.drawable.notification, mContext
- .getString(tickerId), System.currentTimeMillis());
- notification.defaults = Notification.DEFAULT_LIGHTS;
- notification.flags = Notification.FLAG_AUTO_CANCEL;
- PendingIntent pendingIntent;
- if (tickerId != R.string.ticker_success) {
- pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
- NotesPreferenceActivity.class), 0);
-
- } else {
- pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
- NotesListActivity.class), 0);
- }
- //notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
- // pendingIntent);
- mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
- }
-
- @Override
- protected Integer doInBackground(Void... unused) {
- publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
- .getSyncAccountName(mContext)));
- // 执行同步任务,返回状态码
- return mTaskManager.sync(mContext, this);
- }
-
- @Override
- protected void onProgressUpdate(String... progress) {
- showNotification(R.string.ticker_syncing, progress[0]);
- if (mContext instanceof GTaskSyncService) {
- ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
- }
- }
-
- @Override
- protected void onPostExecute(Integer result) {
- // 根据状态码显示通知
- if (result == GTaskManager.STATE_SUCCESS) {
- showNotification(R.string.ticker_success, mContext.getString(
- R.string.success_sync_account, mTaskManager.getSyncAccount()));
- NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
- } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
- } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
- } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
- showNotification(R.string.ticker_cancel, mContext
- .getString(R.string.error_sync_cancelled));
- }
-
- if (mOnCompleteListener != null) {
- new Thread(new Runnable() {
-
- public void run() {
- mOnCompleteListener.onComplete();
- }
- }).start();
- }
- }
-}
diff --git a/other/06_何越_代码标注/gtask/remote/GTaskClient.java b/other/06_何越_代码标注/gtask/remote/GTaskClient.java
deleted file mode 100644
index 3fb1e33..0000000
--- a/other/06_何越_代码标注/gtask/remote/GTaskClient.java
+++ /dev/null
@@ -1,671 +0,0 @@
-/*
- * 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.remote;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerFuture;
-import android.app.Activity;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.gtask.data.Node;
-import net.micode.notes.gtask.data.Task;
-import net.micode.notes.gtask.data.TaskList;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.gtask.exception.NetworkFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.cookie.Cookie;
-import org.apache.http.impl.client.BasicCookieStore;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.params.HttpProtocolParams;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.Inflater;
-import java.util.zip.InflaterInputStream;
-
-
-public class GTaskClient {
- private static final String TAG = GTaskClient.class.getSimpleName();
-
- private static final String GTASK_URL = "https://mail.google.com/tasks/";
-
- private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
-
- private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
-
- private static GTaskClient mInstance = null;
-
- private DefaultHttpClient mHttpClient;
-
- private String mGetUrl;
-
- private String mPostUrl;
-
- private long mClientVersion;
-
- private boolean mLoggedin;
-
- private long mLastLoginTime;
-
- private int mActionId;
-
- private Account mAccount;
-
- private JSONArray mUpdateArray;
-
-// 定义一个GTaskClient类,用于管理Google任务API
-public class GTaskClient {
-
- // 初始化GTaskClient类的私有构造函数
- private GTaskClient() {
- mHttpClient = null;
- mGetUrl = GTASK_GET_URL;
- mPostUrl = GTASK_POST_URL;
- mClientVersion = -1;
- mLoggedin = false;
- mLastLoginTime = 0;
- mActionId = 1;
- mAccount = null;
- mUpdateArray = null;
- }
-
- // 创建一个静态的GTaskClient实例,确保线程安全
- public static synchronized GTaskClient getInstance() {
- if (mInstance == null) {
- mInstance = new GTaskClient();
- }
- return mInstance;
- }
-
- public boolean login(Activity activity) {
- // 假设cookie在5分钟后会过期,所以需要重新登录
- final long interval = 1000 * 60 * 5;
- if (mLastLoginTime + interval < System.currentTimeMillis()) {
- mLoggedin = false;
- }
-
- // 如果帐户发生变化,则需要重新登录
- if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
- mLoggedin = false;
- }
-
- if (mLoggedin) {
- Log.d(TAG, "already logged in");
- return true;
- }
-
- mLastLoginTime = System.currentTimeMillis();
- String authToken = loginGoogleAccount(activity, false);
- if (authToken == null) {
- Log.e(TAG, "login google account failed");
- return false;
- }
-
- // 如果需要,使用自定义域名进行登录
- if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
- StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
- int index = mAccount.name.indexOf('@') + 1;
- String suffix = mAccount.name.substring(index);
- url.append(suffix + "/");
- mGetUrl = url.toString() + "ig";
- mPostUrl = url.toString() + "r/ig";
-
- if (tryToLoginGtask(activity, authToken)) {
- mLoggedin = true;
- }
- }
-
- // 尝试使用Google官方URL进行登录
- if (!mLoggedin) {
- mGetUrl = GTASK_GET_URL;
- mPostUrl = GTASK_POST_URL;
- if (!tryToLoginGtask(activity, authToken)) {
- return false;
- }
- }
-
- mLoggedin = true;
- return true;
- }
-
- // 登录Google账户,获取授权令牌
- private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
- String authToken;
- AccountManager accountManager = AccountManager.get(activity);
- Account[] accounts = accountManager.getAccountsByType("com.google");
-
- if (accounts.length == 0) {
- Log.e(TAG, "there is no available google account");
- return null;
- }
-
- String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
- Account account = null;
- for (Account a : accounts) {
- if (a.name.equals(accountName)) {
- account = a;
- break;
- }
- }
- if (account != null) {
- mAccount = account;
- } else {
- Log.e(TAG, "unable to get an account with the same name in the settings");
- return null;
- }
-
- // 获取授权令牌
- AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,
- "goanna_mobile", null, activity, null, null);
- try {
- Bundle authTokenBundle = accountManagerFuture.getResult();
- authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
- if (invalidateToken) {
- // 使令牌无效,并重新获取令牌
- accountManager.invalidateAuthToken("com.google", authToken);
- loginGoogleAccount(activity, false);
- }
- } catch (Exception e) {
- Log.e(TAG, "get auth token failed");
- authToken = null;
- }
-
- return authToken;
- }
-
- // 尝试使用授权令牌进行Gtask登录
-/**
- * 尝试使用指定的身份验证令牌登录到 Gtask 服务。
- *
- * @param activity 调用此方法的 Activity
- * @param authToken Gtask 服务的身份验证令牌
- * @return 如果登录成功,则返回 true;否则返回 false。
- */
- private boolean tryToLoginGtask(Activity activity, String authToken) {
- // 如果无法成功登录 Gtask 服务,则进行以下处理。
- if (!loginGtask(authToken)) {
- // 可能是身份验证令牌过期了,现在我们需要将令牌作废并再次尝试登录。
- authToken = loginGoogleAccount(activity, true);
- // 如果登录谷歌帐号失败,则返回 false。
- if (authToken == null) {
- Log.e(TAG, "login google account failed");
- return false;
- }
-
- // 如果仍然无法成功登录 Gtask 服务,则返回 false。
- if (!loginGtask(authToken)) {
- Log.e(TAG, "login gtask failed");
- return false;
- }
- }
- // 如果登录成功,则返回 true。
- return true;
- }
-
- /**
- * 使用给定的身份验证令牌登录到 Gtask 服务。
- *
- * @param authToken Gtask 服务的身份验证令牌
- * @return 如果登录成功,则返回 true;否则返回 false。
- */
-private boolean loginGtask(String authToken) {
- // 配置 HTTP 连接参数。
- int timeoutConnection = 10000;
- int timeoutSocket = 15000;
- HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
- HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
-
- // 创建 HTTP 客户端。
- mHttpClient = new DefaultHttpClient(httpParameters);
- BasicCookieStore localBasicCookieStore = new BasicCookieStore();
- mHttpClient.setCookieStore(localBasicCookieStore);
- HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
-
- // 使用身份验证令牌登录 Gtask 服务。
- try {
- String loginUrl = mGetUrl + "?auth=" + authToken;
- HttpGet httpGet = new HttpGet(loginUrl);
- HttpResponse response = mHttpClient.execute(httpGet);
-
- // 获取 Cookie。
- List cookies = mHttpClient.getCookieStore().getCookies();
- boolean hasAuthCookie = false;
- for (Cookie cookie : cookies) {
- if (cookie.getName().contains("GTL")) {
- hasAuthCookie = true;
- }
- }
- if (!hasAuthCookie) {
- Log.w(TAG, "it seems that there is no auth cookie");
- }
-
- // 获取客户端版本。
- String resString = getResponseContent(response.getEntity());
- String jsBegin = "_setup(";
- String jsEnd = ")}";
- int begin = resString.indexOf(jsBegin);
- int end = resString.lastIndexOf(jsEnd);
- String jsString = null;
- if (begin != -1 && end != -1 && begin < end) {
- jsString = resString.substring(begin + jsBegin.length(), end);
- }
- JSONObject js = new JSONObject(jsString);
- mClientVersion = js.getLong("v");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return false;
- } catch (Exception e) {
- Log.e(TAG, "httpget gtask_url failed");
- return false;
- }
-
- return true;
-}
-
-/**
- * 获取下一个操作 ID。
- *
- * @return 下一个操作 ID。
- */
-private int getActionId() {
- return mActionId++;
-}
-
-/**
- * 创建 HTTP POST 请求。
- *
- * @return 新的 HTTP POST 请求。
- */
-private HttpPost createHttpPost() {
- HttpPost httpPost = new HttpPost(mPostUrl);
- httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- httpPost.setHeader("AT", "1");
- return httpPost;
-}
-
-
-/**
- * 从HttpEntity中获取响应内容
- * @param entity HttpEntity对象
- * @return 响应内容
- * @throws IOException
- */
-private String getResponseContent(HttpEntity entity) throws IOException {
- String contentEncoding = null;
- // 获取响应编码方式
- if (entity.getContentEncoding() != null) {
- contentEncoding = entity.getContentEncoding().getValue();
- Log.d(TAG, "encoding: " + contentEncoding);
- }
-
- InputStream input = entity.getContent();
- // 根据编码方式设置InputStream
- if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
- input = new GZIPInputStream(entity.getContent());
- } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
- Inflater inflater = new Inflater(true);
- input = new InflaterInputStream(entity.getContent(), inflater);
- }
-
- try {
- // 将InputStream转为字符流,并读取响应内容
- InputStreamReader isr = new InputStreamReader(input);
- BufferedReader br = new BufferedReader(isr);
- StringBuilder sb = new StringBuilder();
-
- while (true) {
- String buff = br.readLine();
- if (buff == null) {
- return sb.toString();
- }
- sb = sb.append(buff);
- }
- } finally {
- // 关闭InputStream
- input.close();
- }
-}
-
-/**
- * 发送HttpPost请求,并返回JSONObject格式的响应内容
- * @param js JSONObject格式的请求内容
- * @return JSONObject格式的响应内容
- * @throws NetworkFailureException
- */
-private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
- if (!mLoggedin) {
- Log.e(TAG, "please login first");
- throw new ActionFailureException("not logged in");
- }
-
- HttpPost httpPost = createHttpPost();
- try {
- // 创建请求参数并设置到HttpPost对象中
- LinkedList list = new LinkedList();
- list.add(new BasicNameValuePair("r", js.toString()));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
- httpPost.setEntity(entity);
-
- // 执行HttpPost请求
- HttpResponse response = mHttpClient.execute(httpPost);
- // 获取响应内容,并将其转为JSONObject对象
- String jsString = getResponseContent(response.getEntity());
- return new JSONObject(jsString);
-
- } catch (ClientProtocolException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("postRequest failed");
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("postRequest failed");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("unable to convert response content to jsonobject");
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("error occurs when posting request");
- }
-}
-
-public void createTask(Task task) throws NetworkFailureException {
- commitUpdate(); // 提交更新
- try {
- JSONObject jsPost = new JSONObject(); // 创建一个JSON对象
- JSONArray actionList = new JSONArray(); // 创建一个JSON数组
-
- // action_list
- // 将Task对象的创建操作添加到JSON数组中
- actionList.put(task.getCreateAction(getActionId()));
- // 将JSON数组添加到JSON对象中
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- // 将客户端版本添加到JSON对象中
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // post
- // 发送post请求并接收响应
- JSONObject jsResponse = postRequest(jsPost);
- // 获取响应中的结果数组并获取第一个结果对象
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
- GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
- // 将新任务的ID设置为响应中的新ID
- task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString()); // 输出异常日志
- e.printStackTrace(); // 打印异常堆栈信息
- throw new ActionFailureException("create task: handing jsonobject failed"); // 抛出自定义异常
- }
-}
-
-public void createTaskList(TaskList tasklist) throws NetworkFailureException {
- commitUpdate(); // 提交更新
- try {
- JSONObject jsPost = new JSONObject(); // 创建一个JSON对象
- JSONArray actionList = new JSONArray(); // 创建一个JSON数组
-
- // action_list
- // 将TaskList对象的创建操作添加到JSON数组中
- actionList.put(tasklist.getCreateAction(getActionId()));
- // 将JSON数组添加到JSON对象中
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client version
- // 将客户端版本添加到JSON对象中
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // post
- // 发送post请求并接收响应
- JSONObject jsResponse = postRequest(jsPost);
- // 获取响应中的结果数组并获取第一个结果对象
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
- GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
- // 将新任务列表的ID设置为响应中的新ID
- tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
-
- } catch (JSONException e) {
- Log.e(TAG, e.toString()); // 输出异常日志
- e.printStackTrace(); // 打印异常堆栈信息
- throw new ActionFailureException("create tasklist: handing jsonobject failed"); // 抛出自定义异常
- }
-}
-
-public void commitUpdate() throws NetworkFailureException {
- // 如果 mUpdateArray 不为空
- if (mUpdateArray != null) {
- try {
- // 新建一个 JSON 对象
- JSONObject jsPost = new JSONObject();
-
- // 将 mUpdateArray 放入 JSON 对象中的 action_list 字段
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
-
- // 将 mClientVersion 放入 JSON 对象中的 client_version 字段
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // 发送 POST 请求
- postRequest(jsPost);
-
- // 清空 mUpdateArray
- mUpdateArray = null;
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
-
- // 抛出异常
- throw new ActionFailureException("commit update: handing jsonobject failed");
- }
- }
-}
-
-public void addUpdateNode(Node node) throws NetworkFailureException {
- // 如果 node 不为空
- if (node != null) {
- // 如果 mUpdateArray 不为空且长度超过 10,提交更新
- if (mUpdateArray != null && mUpdateArray.length() > 10) {
- commitUpdate();
- }
-
- // 如果 mUpdateArray 为空,新建一个 JSON 数组
- if (mUpdateArray == null)
- mUpdateArray = new JSONArray();
-
- // 将 node 对象的更新操作添加到 mUpdateArray 中
- mUpdateArray.put(node.getUpdateAction(getActionId()));
- }
-}
-
-
-public void moveTask(Task task, TaskList preParent, TaskList curParent)
-throws NetworkFailureException {
-commitUpdate(); // 提交之前所有的更新操作
-
-try {
-JSONObject jsPost = new JSONObject(); // 创建一个 JSON 对象
-JSONArray actionList = new JSONArray(); // 创建一个 JSON 数组,用于存放操作列表
-JSONObject action = new JSONObject(); // 创建一个操作对象
-
-// action_list
-action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, // 设置操作类型
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
-action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作 ID
-action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 设置要移动的任务 ID
-
-if (preParent == curParent && task.getPriorSibling() != null) {
- // 如果任务在同一个任务列表中移动且不是第一个任务,则添加其前一个任务的 ID
- action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
-}
-
-action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 设置原任务列表的 ID
-action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 设置目标任务列表的 ID
-
-if (preParent != curParent) {
- // 如果任务在不同的任务列表中移动,则添加目标任务列表的 ID
- action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
-}
-
-actionList.put(action); // 将操作添加到操作列表中
-jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将操作列表添加到 JSON 对象中
-
-// client_version
-jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 添加客户端版本信息
-
-postRequest(jsPost); // 发送请求
-} catch (JSONException e) {
-Log.e(TAG, e.toString());
-e.printStackTrace();
-throw new ActionFailureException("move task: handing jsonobject failed");
-}
-}
-
-public void deleteNode(Node node) throws NetworkFailureException {
-commitUpdate(); // 提交之前所有的更新操作
-
-try {
-JSONObject jsPost = new JSONObject(); // 创建一个 JSON 对象
-JSONArray actionList = new JSONArray(); // 创建一个 JSON 数组,用于存放操作列表
-
-// action_list
-node.setDeleted(true); // 将节点标记为已删除
-actionList.put(node.getUpdateAction(getActionId())); // 将更新操作添加到操作列表中
-jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将操作列表添加到 JSON 对象中
-
-// client_version
-jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 添加客户端版本信息
-
-postRequest(jsPost); // 发送请求
-mUpdateArray = null; // 重置更新操作数组
-} catch (JSONException e) {
-Log.e(TAG, e.toString());
-e.printStackTrace();
-throw new ActionFailureException("delete node: handing jsonobject failed");
-}
-}
-
-
-public JSONArray getTaskLists() throws NetworkFailureException {
- // 如果用户没有登录,则抛出异常
- if (!mLoggedin) {
- Log.e(TAG, "please login first");
- throw new ActionFailureException("not logged in");
- }
-
- try {
- // 发送 HTTP GET 请求,获取任务列表
- HttpGet httpGet = new HttpGet(mGetUrl);
- HttpResponse response = null;
- response = mHttpClient.execute(httpGet);
-
- // 从响应中提取 JSON 字符串
- String resString = getResponseContent(response.getEntity());
- String jsBegin = "_setup(";
- String jsEnd = ")}";
- int begin = resString.indexOf(jsBegin);
- int end = resString.lastIndexOf(jsEnd);
- String jsString = null;
- if (begin != -1 && end != -1 && begin < end) {
- jsString = resString.substring(begin + jsBegin.length(), end);
- }
-
- // 解析 JSON 字符串,返回任务列表
- JSONObject js = new JSONObject(jsString);
- return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
- } catch (ClientProtocolException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("gettasklists: httpget failed");
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new NetworkFailureException("gettasklists: httpget failed");
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("get task lists: handing jasonobject failed");
- }
-}
-
-public JSONArray getTaskList(String listGid) throws NetworkFailureException {
- // 提交未提交的更改
- commitUpdate();
- try {
- JSONObject jsPost = new JSONObject();
- JSONArray actionList = new JSONArray();
- JSONObject action = new JSONObject();
-
- // action_list
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
- action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
- action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
- actionList.put(action);
- jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
-
- // client_version
- jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
-
- // 发送 POST 请求,获取指定任务列表的任务
- JSONObject jsResponse = postRequest(jsPost);
- return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("get task list: handing jsonobject failed");
- }
-}
-
-public Account getSyncAccount() {
- // 获取同步账户
- return mAccount;
-}
-
-public void resetUpdateArray() {
- // 重置未提交的更改
- mUpdateArray = null;
-}
-
diff --git a/other/06_何越_代码标注/gtask/remote/GTaskManager.java b/other/06_何越_代码标注/gtask/remote/GTaskManager.java
deleted file mode 100644
index c10fc10..0000000
--- a/other/06_何越_代码标注/gtask/remote/GTaskManager.java
+++ /dev/null
@@ -1,929 +0,0 @@
-/*
- * 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.remote;
-
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.ContentUris;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.util.Log;
-
- import net.micode.notes.R;
- import net.micode.notes.data.Notes;
- import net.micode.notes.data.Notes.DataColumns;
- import net.micode.notes.data.Notes.NoteColumns;
- import net.micode.notes.gtask.data.MetaData;
- import net.micode.notes.gtask.data.Node;
- import net.micode.notes.gtask.data.SqlNote;
- import net.micode.notes.gtask.data.Task;
- import net.micode.notes.gtask.data.TaskList;
- import net.micode.notes.gtask.exception.ActionFailureException;
- import net.micode.notes.gtask.exception.NetworkFailureException;
- import net.micode.notes.tool.DataUtils;
- import net.micode.notes.tool.GTaskStringUtils;
-
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
-
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Map;
-
-
- public class GTaskManager {
- private static final String TAG = GTaskManager.class.getSimpleName();
-
- public static final int STATE_SUCCESS = 0;
-
- public static final int STATE_NETWORK_ERROR = 1;
-
- public static final int STATE_INTERNAL_ERROR = 2;
-
- public static final int STATE_SYNC_IN_PROGRESS = 3;
-
- public static final int STATE_SYNC_CANCELLED = 4;
-
- private static GTaskManager mInstance = null;
-
- private Activity mActivity;
-
- private Context mContext;
-
- private ContentResolver mContentResolver;
-
- private boolean mSyncing;
-
- private boolean mCancelled;
-
- private HashMap mGTaskListHashMap;
-
- private HashMap mGTaskHashMap;
-
- private HashMap mMetaHashMap;
-
- private TaskList mMetaList;
-
- private HashSet mLocalDeleteIdMap;
-
- private HashMap mGidToNid;
-
- private HashMap mNidToGid;
-
- // 定义了一个名为 GTaskManager 的私有类
-private GTaskManager() {
- // 初始化一些变量
- mSyncing = false; // 当前不在同步状态
- mCancelled = false; // 当前没有取消
- mGTaskListHashMap = new HashMap(); // 存储多个任务列表的 HashMap
- mGTaskHashMap = new HashMap(); // 存储任务的 HashMap
- mMetaHashMap = new HashMap(); // 存储元数据的 HashMap
- mMetaList = null; // 初始化元数据列表为空
- mLocalDeleteIdMap = new HashSet(); // 存储本地删除的任务的 ID 集合
- mGidToNid = new HashMap(); // 存储 GTask ID 到 Node ID 的映射
- mNidToGid = new HashMap(); // 存储 Node ID 到 GTask ID 的映射
-}
-
-
- // 定义了一个名为 getInstance 的静态方法,返回一个 GTaskManager 对象
-public static synchronized GTaskManager getInstance() {
- // 如果当前 GTaskManager 对象为空,就创建一个新的 GTaskManager 对象
- if (mInstance == null) {
- mInstance = new GTaskManager();
- }
- // 返回 GTaskManager 对象
- return mInstance;
-}
-
- // 定义了一个名为 setActivityContext 的方法,用于设置 Activity 的上下文
-public synchronized void setActivityContext(Activity activity) {
- // 用于获取授权令牌(authtoken)的 Activity 上下文
- mActivity = activity;
-}
-
-
- // 定义了一个名为 sync 的方法,用于同步 Google 任务列表
-public int sync(Context context, GTaskASyncTask asyncTask) {
- // 如果正在同步,则返回“同步进行中”状态
- if (mSyncing) {
- Log.d(TAG, "Sync is in progress");
- return STATE_SYNC_IN_PROGRESS;
- }
- // 重置相关变量
- mContext = context;
- mContentResolver = mContext.getContentResolver();
- mSyncing = true;
- mCancelled = false;
- mGTaskListHashMap.clear();
- mGTaskHashMap.clear();
- mMetaHashMap.clear();
- mLocalDeleteIdMap.clear();
- mGidToNid.clear();
- mNidToGid.clear();
-
- try {
- // 获取 GTaskClient 的单例对象
- GTaskClient client = GTaskClient.getInstance();
- // 重置更新数组
- client.resetUpdateArray();
-
- // 登录 Google 任务列表
- if (!mCancelled) {
- if (!client.login(mActivity)) {
- throw new NetworkFailureException("login google task failed");
- }
- }
-
- // 从 Google 获取任务列表
- asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
- initGTaskList();
-
- // 进行内容同步工作
- asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
- syncContent();
- } catch (NetworkFailureException e) {
- Log.e(TAG, e.toString());
- return STATE_NETWORK_ERROR;
- } catch (ActionFailureException e) {
- Log.e(TAG, e.toString());
- return STATE_INTERNAL_ERROR;
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return STATE_INTERNAL_ERROR;
- } finally {
- // 清空相关变量
- mGTaskListHashMap.clear();
- mGTaskHashMap.clear();
- mMetaHashMap.clear();
- mLocalDeleteIdMap.clear();
- mGidToNid.clear();
- mNidToGid.clear();
- mSyncing = false;
- }
-
- // 如果已取消,则返回“同步已取消”状态;否则返回“成功”状态
- return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
-}
-
- // 初始化 GTask 列表
-
- private void initGTaskList() throws NetworkFailureException {
- // 检查是否已取消
- if (mCancelled)
- return;
- // 获取 GTask 客户端
- GTaskClient client = GTaskClient.getInstance();
- try {
- // 获取任务列表的 JSON 数据
- JSONArray jsTaskLists = client.getTaskLists();
-
- // 先初始化元列表
- mMetaList = null;
- for (int i = 0; i < jsTaskLists.length(); i++) {
- // 获取 JSON 数据中的任务列表对象
- JSONObject object = jsTaskLists.getJSONObject(i);
- String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
- // 如果任务列表名称为“MIUI_FOLDER_PREFFIX + FOLDER_META”,则表示为元列表
- if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
- // 初始化元列表
- mMetaList = new TaskList();
- mMetaList.setContentByRemoteJSON(object);
-
- // 加载元数据
- JSONArray jsMetas = client.getTaskList(gid);
- for (int j = 0; j < jsMetas.length(); j++) {
- object = (JSONObject) jsMetas.getJSONObject(j);
- MetaData metaData = new MetaData();
- metaData.setContentByRemoteJSON(object);
- // 如果元数据值得保存,将其添加到元列表中
- if (metaData.isWorthSaving()) {
- mMetaList.addChildTask(metaData);
- // 将元数据关联的 GID 和元数据存储在哈希映射表中
- if (metaData.getGid() != null) {
- mMetaHashMap.put(metaData.getRelatedGid(), metaData);
- }
- }
- }
- }
- }
-
- // 如果元列表不存在,则创建元列表
- if (mMetaList == null) {
- mMetaList = new TaskList();
- mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_META);
- GTaskClient.getInstance().createTaskList(mMetaList);
- }
-
- // 初始化任务列表
- for (int i = 0; i < jsTaskLists.length(); i++) {
- // 获取 JSON 数据中的任务列表对象
- JSONObject object = jsTaskLists.getJSONObject(i);
- String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
- // 如果任务列表名称以“MIUI_FOLDER_PREFFIX”开头且不是元列表,则为任务列表
- if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
- && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_META)) {
- // 初始化任务列表
- TaskList tasklist = new TaskList();
- tasklist.setContentByRemoteJSON(object);
- mGTaskListHashMap.put(gid, tasklist);
- mGTaskHashMap.put(gid, tasklist);
-
- // 加载任务
- JSONArray jsTasks = client.getTaskList(gid);
- for (int j = 0; j < jsTasks.length(); j++) {
- object = (JSONObject) jsTasks.getJSONObject(j);
- gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
- Task task = new Task();
- task.setContentByRemoteJSON(object);
- // 如果任务值得保存,将其添加
- if (task.isWorthSaving()) {
- task.setMetaInfo(mMetaHashMap.get(gid));// 设置任务元信息
- tasklist.addChildTask(task);// 将任务添加到任务列表的子任务中
- mGTaskHashMap.put(gid, task); // 在哈希表中添加任务的ID和任务对象
- }
- }
- }
- }
- } catch (JSONException e) {
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("initGTaskList: handing JSONObject failed");
- }
- }
- // 同步笔记内容
- private void syncContent() throws NetworkFailureException {
- int syncType;
- Cursor c = null;
- String gid;
- Node node;
-
- mLocalDeleteIdMap.clear();
- if (mCancelled) {// 如果已取消,直接返回
- return;
- }
-
- // 处理本地已删除笔记
- try {
- // 查询非系统类型且父级 ID 不是回收站的笔记
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type<>? AND parent_id=?)", new String[] {
- String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
- }, null);
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
- }
-
- mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
- }
- } else {
- Log.w(TAG, "failed to query trash folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // 先同步文件夹
- syncFolder();
-
- // 处理已存在于数据库中的笔记
- try {
- // 查询类型为笔记且父级 ID 不是回收站的笔记,按类型倒序排序
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type=? AND parent_id<>?)", new String[] {
- String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
- }, NoteColumns.TYPE + " DESC");
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
- mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- syncType = node.getSyncAction(c);// 获取同步类型
- } else {
- if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // 本地新增
- syncType = Node.SYNC_ACTION_ADD_REMOTE;
- } else {
- // 远程删除
- syncType = Node.SYNC_ACTION_DEL_LOCAL;
- }
- }
- doContentSync(syncType, node, c);
- }
- } else {
- Log.w(TAG, "failed to query existing note in database");
- }
-
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // 处理剩余项
- Iterator> iter = mGTaskHashMap.entrySet().iterator();
- while (iter.hasNext()) {// 如果还有下一个键值对
- Map.Entry entry = iter.next();// 获取下一个键值对
- node = entry.getValue();// 获取键值对中的value并将其赋值给node
- doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);// 将node添加到本地同步
- }
-
- // mCancelled 可能会被另一个线程设置,因此我们需要逐个检查
- // 清除本地删除表
- if (!mCancelled) {// 如果未被取消
- if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {// 批量删除本地删除表中的笔记
- throw new ActionFailureException("failed to batch-delete local deleted notes");
- }// 如果删除失败则抛出异常
- }
-
- // 刷新本地同步id
- if (!mCancelled) {
- GTaskClient.getInstance().commitUpdate();
- refreshLocalSyncId();
- }
-
- }
-
- private void syncFolder() throws NetworkFailureException {
- Cursor c = null;// 游标对象,用于访问数据
- String gid;// GTask任务列表的ID
- Node node;// GTask任务列表对应的本地节点
- int syncType;// 本地与远程数据同步的类型
-
- if (mCancelled) {// 如果同步已被取消,则直接返回
- return;
- }
-
- // for root folder
- try {
- // 查询根目录的数据
- c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
- Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
- if (c != null) {
- c.moveToNext();// 将游标移动到下一个记录
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);// 获取GTask任务列表ID
- node = mGTaskHashMap.get(gid);// 从GTask任务列表映射中获取对应本地节点
- if (node != null) {
- mGTaskHashMap.remove(gid);// 从映射中移除该节点
- mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);// 将GTask ID映射到本地ID
- mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);// 将本地ID映射到GTask ID
- // 仅当名称不是默认值时,才更新远程名称
- if (!node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
- doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);// 同步本地和远程数据
- } else {
- doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);// 将本地数据同步到远程
- }
- } else {
- Log.w(TAG, "failed to query root folder");// 记录警告信息
- }
- } finally {
- if (c != null) {
- c.close();// 关闭游标
- c = null;// 将游标对象设置为null
- }
- }
-
- // for call-note folder
- try {
- // 查询通话记录文件夹的数据
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
- new String[] {
- String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
- }, null);
- if (c != null) {
- if (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);// 获取GTask任务列表ID
- node = mGTaskHashMap.get(gid);// 从GTask任务列表映射中获取对应本地节点
- if (node != null) {
- mGTaskHashMap.remove(gid);// 从映射中移除该节点
- mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);// 将GTask ID映射到本地ID
- mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);// 将本地ID映射到GTask ID
- // 仅当名称不是默认值时,才更新远端
- if (!node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX
- + GTaskStringUtils.FOLDER_CALL_NOTE))
- doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
- } else {
- doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
- }
- }
- } else {
- Log.w(TAG, "failed to query call note folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // 处理本地现有文件夹
- try {
- c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
- "(type=? AND parent_id<>?)", new String[] {
- String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
- }, NoteColumns.TYPE + " DESC");
- if (c != null) {
- while (c.moveToNext()) {
- gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- node = mGTaskHashMap.get(gid);
- if (node != null) {
- mGTaskHashMap.remove(gid);
- mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
- mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- syncType = node.getSyncAction(c);
- } else {
- if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // 本地新增
- syncType = Node.SYNC_ACTION_ADD_REMOTE;
- } else {
- // 远端删除
- syncType = Node.SYNC_ACTION_DEL_LOCAL;
- }
- }
- doContentSync(syncType, node, c);
- }
- } else {
- Log.w(TAG, "failed to query existing folder");
- }
- } finally {
- if (c != null) {
- c.close();
- c = null;
- }
- }
-
- // 处理远端新增文件夹
- Iterator> iter = mGTaskListHashMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = iter.next();
- gid = entry.getKey();
- node = entry.getValue();
- if (mGTaskHashMap.containsKey(gid)) {
- mGTaskHashMap.remove(gid);
- doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
- }
- }
-
- if (!mCancelled)
- GTaskClient.getInstance().commitUpdate();
- }
-
- private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
- // 如果取消了同步,则直接返回
- if (mCancelled) {
- return;
- }
- // 元数据对象
- MetaData meta;
- // 根据同步类型执行相应的操作
- switch (syncType) {
- // 本地添加节点
- case Node.SYNC_ACTION_ADD_LOCAL:
- addLocalNode(node);
- break;
- // 远程添加节点
- case Node.SYNC_ACTION_ADD_REMOTE:
- addRemoteNode(node, c);
- break;
- // 本地删除节点
- case Node.SYNC_ACTION_DEL_LOCAL:
- // 获取需要删除的节点的元数据
- meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
- if (meta != null) {
- // 使用 GTaskClient 删除节点
- GTaskClient.getInstance().deleteNode(meta);
- }
- // 将节点 ID 添加到本地删除 ID 映射表中
- mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
- break;
- // 远程删除节点
- case Node.SYNC_ACTION_DEL_REMOTE:
- // 获取需要删除的节点的元数据
- meta = mMetaHashMap.get(node.getGid());
- if (meta != null) {
- // 使用 GTaskClient 删除节点
- GTaskClient.getInstance().deleteNode(meta);
- }
- // 使用 GTaskClient 删除节点
- GTaskClient.getInstance().deleteNode(node);
- break;
- // 本地更新节点
- case Node.SYNC_ACTION_UPDATE_LOCAL:
- updateLocalNode(node, c);
- break;
- // 远程更新节点
- case Node.SYNC_ACTION_UPDATE_REMOTE:
- updateRemoteNode(node, c);
- break;
- // 更新冲突
- case Node.SYNC_ACTION_UPDATE_CONFLICT:
- // 可以考虑合并两个修改
- // 现在先简单地使用本地更新
- updateRemoteNode(node, c);
- break;
- // 不执行任何操作
- case Node.SYNC_ACTION_NONE:
- break;
- // 同步操作失败
- case Node.SYNC_ACTION_ERROR:
- default:
- // 抛出异常
- throw new ActionFailureException("unkown sync action type");
- }
- }
-
- private void addLocalNode(Node node) throws NetworkFailureException {
- // 如果取消了操作,直接返回
- if (mCancelled) {
- return;
- }
- // 声明一个 SqlNote 对象
- SqlNote sqlNote;
- // 如果是 TaskList,判断是哪种文件夹
- if (node instanceof TaskList) {
- // 如果是默认文件夹
- if (node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
- // 新建一个根文件夹的 SqlNote 对象
- sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
- }
- // 如果是通话记录文件夹
- else if (node.getName().equals(
- GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
- // 新建一个通话记录文件夹的 SqlNote 对象
- sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
- }
- // 如果是其他类型的文件夹
- else {
- // 新建一个普通的 SqlNote 对象,并设置其内容和父文件夹 ID
- sqlNote = new SqlNote(mContext);
- sqlNote.setContent(node.getLocalJSONFromContent());
- sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
- }
- }
- // 如果是 Task
- else {
- // 新建一个普通的 SqlNote 对象
- sqlNote = new SqlNote(mContext);
- // 从 Task 中获取其内容的 JSON 对象
- JSONObject js = node.getLocalJSONFromContent();
- try {
- // 如果 JSON 对象中包含元数据头部信息
- if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
- // 获取元数据头部信息中的 Note 对象
- JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- // 如果 Note 对象中包含 ID
- if (note.has(NoteColumns.ID)) {
- // 获取 Note 的 ID
- long id = note.getLong(NoteColumns.ID);
- // 如果该 ID 在 Note 数据库中已经存在
- if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
- // 该 ID 已经被占用,需要新建一个 ID
- note.remove(NoteColumns.ID);
- }
- }
- }
- // 如果 JSON 对象中包含元数据数据部分
- if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
- // 获取元数据数据部分的 JSON 数组
- JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
- // 遍历该 JSON 数组
- for (int i = 0; i < dataArray.length(); i++) {
- // 获取数组中的 JSON 对象
- JSONObject data = dataArray.getJSONObject(i);
- // 如果该 JSON 对象中包含 ID
- if (data.has(DataColumns.ID)) {
- // 获取该数据的 ID
- long dataId = data.getLong(DataColumns.ID);
- // 如果该 ID 在数据数据库中已经存在
- if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
- // 该 ID 已经被占用,需要新建一个 ID
- data.remove(DataColumns.ID);
- }
- }
- }
-
- }
- } catch (JSONException e) {// 捕获 JSON 解析异常
- Log.w(TAG, e.toString());// 记录警告日志
- e.printStackTrace();// 打印异常堆栈信息
- }
- sqlNote.setContent(js);// 设置 SQLNote 的内容为解析出的 js
-
- Long parentId = mGidToNid.get(((Task) node).getParent().getGid());// 获取 Task 节点的父节点的 GID 对应的 NID
- // 如果获取到的 NID 为空
- if (parentId == null) {
- Log.e(TAG, "cannot find task's parent id locally");// 记录错误日志
- throw new ActionFailureException("cannot add local node");// 抛出 ActionFailureException 异常
- }
- sqlNote.setParentId(parentId.longValue());// 将 SQLNote 的父节点 ID 设置为获取到的 NID
- }
-
- // 创建本地节点
- sqlNote.setGtaskId(node.getGid());// 设置 SQLNote 的 GTask ID 为节点的 GID
- sqlNote.commit(false);// 将 SQLNote 提交到本地数据库,不需要立即同步到远程服务器
-
- // 更新 GID-NID 映射
- mGidToNid.put(node.getGid(), sqlNote.getId());// 将节点的 GID 映射为 SQLNote 的 ID
- mNidToGid.put(sqlNote.getId(), node.getGid());// 将 SQLNote 的 ID 映射为节点的 GID
-
- // 更新元数据
- updateRemoteMeta(node.getGid(), sqlNote);// 同步 SQLNote 的元数据到远程服务器
- }
-
- private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
- // 如果操作已经被取消,则不进行任何操作
- if (mCancelled) {
- return;
- }
-
- SqlNote sqlNote;
- // 将数据库查询结果保存到 SqlNote 对象中
- sqlNote = new SqlNote(mContext, c);
- // 将节点内容转换为 JSON 格式并保存到 SqlNote 对象中
- sqlNote.setContent(node.getLocalJSONFromContent());
-
- // 如果节点是任务类型,则将其父节点的 ID 设置为对应的本地 ID,
- // 否则将其父节点的 ID 设置为根文件夹的 ID
- Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
- : new Long(Notes.ID_ROOT_FOLDER);
- // 如果 parentId 为 null,则说明无法在本地找到该任务的父节点 ID,
- // 此时抛出一个异常
- if (parentId == null) {
- Log.e(TAG, "cannot find task's parent id locally");
- throw new ActionFailureException("cannot update local node");
- }
- // 将父节点 ID 设置为 sqlNote 对象的 parentId 属性
- sqlNote.setParentId(parentId.longValue());
- // 将 sqlNote 对象的属性保存到数据库中
- sqlNote.commit(true);
-
- // 更新远程节点的元信息
- updateRemoteMeta(node.getGid(), sqlNote);
- }
-
- private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- // 如果任务已经被取消,直接返回
- if (mCancelled) {
- return;
- }
- // 通过Cursor获取SqlNote对象
- SqlNote sqlNote = new SqlNote(mContext, c);
- Node n;
-
- // 如果SqlNote是任务类型,进行以下操作
- if (sqlNote.isNoteType()) {
- // 创建一个Task对象并用SqlNote的内容更新它
- Task task = new Task();
- task.setContentByLocalJSON(sqlNote.getContent());
-
- // 获取Task对象的父任务列表的gid
- String parentGid = mNidToGid.get(sqlNote.getParentId());
- // 如果无法找到父任务列表的gid,抛出ActionFailureException异常
- if (parentGid == null) {
- Log.e(TAG, "cannot find task's parent tasklist");
- throw new ActionFailureException("cannot add remote task");
- }
- // 在父任务列表中添加子任务
- mGTaskListHashMap.get(parentGid).addChildTask(task);
- // 通过GTaskClient实例创建Task任务
- GTaskClient.getInstance().createTask(task);
- n = (Node) task;
-
- // 添加元数据
- updateRemoteMeta(task.getGid(), sqlNote);
- } else {
- TaskList tasklist = null;
- // 如果SqlNote是文件夹类型,进行以下操作
- // 如果是根文件夹,设置文件夹名为默认文件夹
- String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
- if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
- folderName += GTaskStringUtils.FOLDER_DEFAULT;
- // 如果是通话记录文件夹,设置文件夹名为通话记录文件夹
- else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
- folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
- // 否则,将文件夹名设置为SqlNote对象的片段内容
- else
- folderName += sqlNote.getSnippet();
- // 遍历mGTaskListHashMap查找是否存在与SqlNote对象匹配的TaskList对象
- Iterator> iter = mGTaskListHashMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = iter.next();
- String gid = entry.getKey();
- TaskList list = entry.getValue();
- // 如果存在匹配的TaskList对象,则将tasklist设置为该对象
- if (list.getName().equals(folderName)) {
- tasklist = list;
- // 如果mGTaskHashMap包含gid,将其从中移除
- if (mGTaskHashMap.containsKey(gid)) {
- mGTaskHashMap.remove(gid);
- }
- break;
- }
- }
-
- // 如果未找到匹配的TaskList对象,新建一个TaskList对象
- if (tasklist == null) {
- tasklist = new TaskList();
- tasklist.setContentByLocalJSON(sqlNote.getContent());
- GTaskClient.getInstance().createTaskList(tasklist);
- mGTaskListHashMap.put(tasklist.getGid(), tasklist);
- }
- n = (Node) tasklist;
- }
-
- // 更新SqlNote对象的GTaskId,并将其提交到本地数据库
- sqlNote.setGtaskId(n.getGid());
- sqlNote.commit(false);
- sqlNote.resetLocalModified();
- sqlNote.commit(true);
-
- // gid-id 映射表
- mGidToNid.put(n.getGid(), sqlNote.getId());
- mNidToGid.put(sqlNote.getId(), n.getGid());
- }
-
- private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- if (mCancelled) {
- return; // 如果任务已取消,则退出此方法
- }
-
- SqlNote sqlNote = new SqlNote(mContext, c); // 创建 SqlNote 实例
-
- // 更新远程服务器的节点内容
- node.setContentByLocalJSON(sqlNote.getContent());
- GTaskClient.getInstance().addUpdateNode(node);
-
- // 更新节点的元数据
- updateRemoteMeta(node.getGid(), sqlNote);
-
- // 如果是笔记类型,则移动任务(子任务)到另一个任务列表中
- if (sqlNote.isNoteType()) {
- Task task = (Task) node;
- TaskList preParentList = task.getParent(); // 获取任务当前的父任务列表
-
- // 查找新的父任务列表的 GID
- String curParentGid = mNidToGid.get(sqlNote.getParentId());
- if (curParentGid == null) {
- Log.e(TAG, "cannot find task's parent tasklist"); // 找不到新父任务列表,记录错误并抛出异常
- throw new ActionFailureException("cannot update remote task");
- }
- TaskList curParentList = mGTaskListHashMap.get(curParentGid); // 获取新父任务列表的 TaskList 实例
-
- // 如果新旧父任务列表不同,则移动任务到新的父任务列表
- if (preParentList != curParentList) {
- preParentList.removeChildTask(task); // 从旧父任务列表中移除该任务
- curParentList.addChildTask(task); // 添加该任务到新的父任务列表中
- GTaskClient.getInstance().moveTask(task, preParentList, curParentList); // 移动任务到新父任务列表
- }
- }
-
- sqlNote.resetLocalModified(); // 重置本地修改标记
- sqlNote.commit(true); // 将 SqlNote 中的修改提交到本地 SQLite 数据库中
- }
-
- private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
- // 如果 sqlNote 不为空且为笔记类型,则执行以下代码
- if (sqlNote != null && sqlNote.isNoteType()) {
- // 获取 gid 对应的 metaData
- MetaData metaData = mMetaHashMap.get(gid);
- if (metaData != null) {
- // 设置 gid 对应的 metaData 的内容为 sqlNote 的内容
- metaData.setMeta(gid, sqlNote.getContent());
- // 将 metaData 添加到更新队列中
- GTaskClient.getInstance().addUpdateNode(metaData);
- } else {
- // 如果 metaData 为空,则创建新的 metaData,并设置其内容为 sqlNote 的内容
- metaData = new MetaData();
- metaData.setMeta(gid, sqlNote.getContent());
- // 将 metaData 添加到 mMetaList 的子任务列表中
- mMetaList.addChildTask(metaData);
- // 将 metaData 添加到 mMetaHashMap 中
- mMetaHashMap.put(gid, metaData);
- // 创建任务并将其添加到 GTaskClient 的任务列表中
- GTaskClient.getInstance().createTask(metaData);
- }
- }
- }
-
-
- // 声明一个方法,用于更新本地同步 ID,如果网络故障则抛出 NetworkFailureException 异常
- private void refreshLocalSyncId() throws NetworkFailureException {
- // 如果已取消,则直接返回
- if (mCancelled) {
- return;
- }
-
- // 清空哈希表
- mGTaskHashMap.clear();
- mGTaskListHashMap.clear();
- mMetaHashMap.clear();
- // 初始化 GTask 列表
- initGTaskList();
-
- // 声明一个游标,用于查询本地便签
- Cursor c = null;
- try {
- // 查询不属于系统类型和垃圾桶类型的所有便签
- c = mContentResolver.query(
- Notes.CONTENT_NOTE_URI,
- SqlNote.PROJECTION_NOTE,
- "(type<>? AND parent_id<>?)",
- new String[] {
- String.valueOf(Notes.TYPE_SYSTEM),
- String.valueOf(Notes.ID_TRASH_FOLER)
- },
- NoteColumns.TYPE + " DESC"
- );
-
- // 如果查询结果不为空
- if (c != null) {
- // 遍历查询结果
- while (c.moveToNext()) {
- // 获取当前便签的 GTask ID
- String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- // 根据 GTask ID 从 GTask 哈希表中获取节点信息
- Node node = mGTaskHashMap.get(gid);
- // 如果节点信息不为空
- if (node != null) {
- // 从 GTask 哈希表中移除当前 GTask ID 对应的节点
- mGTaskHashMap.remove(gid);
- // 创建一个 ContentValues 对象,用于更新本地便签的同步 ID
- ContentValues values = new ContentValues();
- values.put(NoteColumns.SYNC_ID, node.getLastModified());
- // 更新本地便签的同步 ID
- mContentResolver.update(
- ContentUris.withAppendedId(
- Notes.CONTENT_NOTE_URI,
- c.getLong(SqlNote.ID_COLUMN)
- ),
- values,
- null,
- null
- );
- } else {
- // 如果节点信息为空,打印日志并抛出 ActionFailureException 异常
- Log.e(TAG, "something is missed");
- throw new ActionFailureException(
- "some local items don't have gid after sync"
- );
- }
- }
- } else {
- // 如果查询结果为空,打印警告日志
- Log.w(TAG, "failed to query local note to refresh sync id");
- }
- } finally {
- // 关闭游标
- if (c != null) {
- c.close();
- c = null;
- }
- }
- }
-
-
- public String getSyncAccount() {
- return GTaskClient.getInstance().getSyncAccount().name;
- }
-
- public void cancelSync() {
- mCancelled = true;
- }
- }
-
\ No newline at end of file
diff --git a/other/07_何越_实践总结报告.docx b/other/07_何越_实践总结报告.docx
deleted file mode 100644
index c879760..0000000
Binary files a/other/07_何越_实践总结报告.docx and /dev/null differ
diff --git a/other/07_凌子杰_实践总结报告.docx b/other/07_凌子杰_实践总结报告.docx
deleted file mode 100644
index ec99fa4..0000000
Binary files a/other/07_凌子杰_实践总结报告.docx and /dev/null differ
diff --git a/other/07_刘峻豪_实践总结报告.docx b/other/07_刘峻豪_实践总结报告.docx
deleted file mode 100644
index 2585b39..0000000
Binary files a/other/07_刘峻豪_实践总结报告.docx and /dev/null differ
diff --git a/other/07_江一 阳_实践总结报告.docx b/other/07_江一 阳_实践总结报告.docx
deleted file mode 100644
index 699c3a9..0000000
Binary files a/other/07_江一 阳_实践总结报告.docx and /dev/null differ
diff --git a/other/07_陈七源_代码标注/model/Note.java b/other/07_陈七源_代码标注/model/Note.java
deleted file mode 100644
index 25eba68..0000000
--- a/other/07_陈七源_代码标注/model/Note.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- * 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.model;
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.OperationApplicationException;
-import android.net.Uri;
-import android.os.RemoteException;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-
-import java.util.ArrayList;
-
-
-public class Note {
- private ContentValues mNoteDiffValues;
- private NoteData mNoteData;
- private static final String TAG = "Note";
- /**
- * 获取新笔记的唯一标识符
- * @param context 上下文对象
- * @param folderId 新建笔记所属文件夹的id
- * @return 新建笔记的唯一标识符
- */
- public static synchronized long getNewNoteId(Context context, long folderId) {
- // 创建一个新的ContentValues对象,并设置相关键值对
- ContentValues values = new ContentValues();
- long createdTime = System.currentTimeMillis(); // 获取当前时间作为创建时间
- values.put(NoteColumns.CREATED_DATE, createdTime); // 存入创建时间
- values.put(NoteColumns.MODIFIED_DATE, createdTime); // 存入修改时间(初始与创建时间相同)
- values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 存入笔记类型
- values.put(NoteColumns.LOCAL_MODIFIED, 1); // 存入本地修改状态
- values.put(NoteColumns.PARENT_ID, folderId); // 存入所属文件夹id
-
- // 向数据库中插入新笔记数据,并获取包含新建笔记Uri的对象uri
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
-
- long noteId = 0;
- try {
- // 从uri中获得新建笔记的id,即路径segments的第二个元素,并将其转换为long类型返回
- noteId = Long.valueOf(uri.getPathSegments().get(1));
- } catch (NumberFormatException e) {
- // 如果获取不到这个id或者它等于-1,则会抛出相应的异常
- Log.e(TAG, "Get note id error :" + e.toString());
- noteId = 0;
- }
- if (noteId == -1) {
- throw new IllegalStateException("Wrong note id:" + noteId);
- }
- return noteId;
- }
-
- /**
- * Note类的构造函数,用于初始化对象
- * 该代码定义了一个名为"Note"的类的构造函数。这个类可能是一个笔记应用程序的一部分,用于表示一个笔记。
- */
- public Note() {
- // 创建一个ContentValues对象,用于保存笔记中改变的值,即笔记已经被修改但还没同步到数据库
- mNoteDiffValues = new ContentValues();
- // 创建一个NoteData对象,用于保存笔记的所有数据,包括标题、正文、颜色等
- mNoteData = new NoteData();
- }
-
-
- /**
- * 设置笔记的key-value值
- * @param key 键名
- * @param value 键值
- *
- * 在构造函数中,首先创建一个空的ContentValues对象mNoteDiffValues,用于保存笔记中改变的值,因为当我们修改笔记后并不会立即同步到数据库,而是需要等待一段时间或者手动进行同步。接着创建一个NoteData对象mNoteData,用于保存笔记的所有数据,包括标题、正文、颜色等。
- *
- *
- */
- public void setNoteValue(String key, String value) {
- // 向ContentValues对象中添加键值对
- mNoteDiffValues.put(key, value);
- // 将本地修改状态设置为1,表示笔记已经被修改但还没同步到数据库
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 将修改时间设置为当前时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
-
- /**
- * 设置笔记文本数据
- *
- * @param key 一个字符串类型的键,用于标识要设置的文本数据类型。例如:"title"、"content"等。
- * @param value 一个字符串类型的值,表示要设置的文本数据内容。例如:标题或正文内容等。
- *
- * 在构造函数中,首先创建一个空的ContentValues对象mNoteDiffValues,用于保存笔记中改变的值。因为当我们修改笔记后并不会立即同步到数据库,而是需要等待一段时间或者手动进行同步。接着创建一个NoteData对象mNoteData,用于保存笔记的所有数据,包括标题、正文、颜色等。
- */
- public void setTextData(String key, String value) {
- // 调用mNoteData对象的setTextData方法,将指定键(key)和值(value)添加到笔记的文本数据中
- mNoteData.setTextData(key, value);
- }
-
- /**
- * 设置笔记文本数据id
- *
- * @param id 一个长整型的值,表示要设置的笔记文本数据的id。
- *
- * 该函数用于将指定的长整型数值作为笔记文本数据的id进行设置。
- * mNoteData是在类构造函数中创建的NoteData对象,通过调用它的setTextDataId方法,可以设置笔记的文本数据id。
- */
- public void setTextDataId(long id) {
- // 调用mNoteData对象的setTextDataId方法,将指定的长整型数值作为笔记文本数据的id进行设置
- mNoteData.setTextDataId(id);
- }
-
-
-
- /**
- * 获取笔记文本数据id
- *
- * @return 一个长整型的值,表示当前笔记文本数据的id。
- *
- * 该函数用于从当前Note对象中获取保存的笔记文本数据的id。
- * mNoteData是在类构造函数中创建的NoteData对象,其中mTextDataId是NoteData类成员变量,用于保存笔记文本数据的id。
- */
- public long getTextDataId() {
- // 返回mNoteData对象中保存的笔记文本数据的id
- return mNoteData.mTextDataId;
- }
-
-
- /**
- * 设置笔记的通话记录id
- *
- * @param id 一个长整型的值,表示要设置的笔记通话记录的id。
- *
- * 该函数用于将指定的长整型数值作为笔记的通话记录id进行设置。
- * mNoteData是在类构造函数中创建的NoteData对象,通过调用它的setCallDataId方法,可以设置笔记的通话记录id。
- */
- public void setCallDataId(long id) {
- // 调用mNoteData对象的setCallDataId方法,将指定的长整型数值作为笔记的通话记录id进行设置
- mNoteData.setCallDataId(id);
- }
-
-
- /**
- * 设置笔记通话记录数据
- *
- * @param key 一个字符串类型的键,用于标识要设置的通话记录数据类型。例如:"name"、"number"等。
- * @param value 一个字符串类型的值,表示要设置的通话记录数据内容。例如:联系人姓名或电话号码等。
- *
- * 该函数用于向当前Note对象中添加指定的通话记录数据。
- * mNoteData是在类构造函数中创建的NoteData对象,通过调用它的setCallData方法,可以将指定的键/值对添加到笔记的通话记录数据中。
- */
- public void setCallData(String key, String value) {
- // 调用mNoteData对象的setCallData方法,将指定键(key)和值(value)添加到笔记的通话记录数据中
- mNoteData.setCallData(key, value);
- }
-
-
- /**
- * 检查笔记是否已经被本地修改
- *
- * @return 一个布尔值,表示当前笔记是否已经被本地修改。
- *
- * 该函数用于检查当前Note对象是否已经被本地修改。它会检查mNoteDiffValues和mNoteData对象,
- * 如果它们中的任意一个在本地被修改过,则返回true;否则返回false。
- */
- public boolean isLocalModified() {
- // 判断mNoteDiffValues对象是否包含数据,或者mNoteData对象中是否有数据被本地修改。
- return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
- }
-
- /**
- * 同步笔记数据到本地数据库
- *
- * @param context 一个Context对象,用于访问应用程序的内容提供器。
- * @param noteId 一个长整型的值,表示要同步的笔记ID。
- *
- * @return 一个布尔值,表示笔记是否成功同步到本地数据库。
- *
- * 该函数用于将当前Note对象保存到本地数据库中。如果当前Note对象没有被本地修改,则直接返回true;
- * 否则,使用ContentResolver对象将mNoteDiffValues中保存的数值更新到NoteColumns.LOCAL_MODIFIED和NoteColumns.MODIFIED_DATE字段上。
- * 如果更新失败,则在日志中记录错误信息,并返回false;否则,清空mNoteDiffValues中的数据,并将mNoteData中的数据保存到本地数据库中。
- * 如果保存失败,则返回false;否则,返回true。
- */
- public boolean syncNote(Context context, long noteId) {
- // 检查noteId参数是否合法,如果小于等于0,则抛出IllegalArgumentException异常
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- // 如果当前Note对象没有被本地修改,则直接返回true
- if (!isLocalModified()) {
- return true;
- }
-
- // 使用ContentResolver对象将mNoteDiffValues中保存的数值更新到NoteColumns.LOCAL_MODIFIED和NoteColumns.MODIFIED_DATE字段上
- if (context.getContentResolver().update(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
- null) == 0) {
- // 如果更新失败,则在日志中记录错误信息
- Log.e(TAG, "Update note error, should not happen");
- // Do not return, fall through
- }
-
- // 清空mNoteDiffValues中的数据
- mNoteDiffValues.clear();
-
- // 将mNoteData中的数据保存到本地数据库中
- if (mNoteData.isLocalModified()
- && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
- // 如果保存失败,则返回false
- return false;
- }
-
- // 如果保存成功,则返回true
- return true;
- }
-
-
- private class NoteData {
- private long mTextDataId;
-
- private ContentValues mTextDataValues;
-
- private long mCallDataId;
-
- private ContentValues mCallDataValues;
-
- private static final String TAG = "NoteData";
-
- /**
- * 构造函数
- *
- * 该函数用于创建一个新的NoteData对象,并初始化mTextDataValues、mCallDataValues、mTextDataId和mCallDataId成员变量。
- * mTextDataValues和mCallDataValues对象分别用于保存笔记的文本数据和通话记录数据。
- * mTextDataId和mCallDataId分别表示当前笔记的文本数据ID和通话记录数据ID,初始值为0。
- */
- public NoteData() {
- // 创建一个新的ContentValues对象mTextDataValues,用于保存笔记的文本数据
- mTextDataValues = new ContentValues();
- // 创建一个新的ContentValues对象mCallDataValues,用于保存笔记的通话记录数据
- mCallDataValues = new ContentValues();
- // 将mTextDataId和mCallDataId的初始值设置为0
- mTextDataId = 0;
- mCallDataId = 0;
- }
-
-
- /**
- * 检查笔记数据是否已经被本地修改
- *
- * @return 一个布尔值,表示当前笔记数据是否已经被本地修改。
- *
- * 该函数用于检查当前NoteData对象是否已经被本地修改。它会检查mTextDataValues和mCallDataValues对象,
- * 如果它们中的任意一个在本地被修改过,则返回true;否则返回false。
- */
- boolean isLocalModified() {
- // 判断mTextDataValues和mCallDataValues对象是否包含数据,如果有数据被本地修改过,则返回true
- return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
- }
-
- /**
- * 设置笔记的文本数据id
- *
- * @param id 一个长整型的值,表示要设置的笔记文本数据的id。
- *
- * 该函数用于将指定的长整型数值作为笔记的文本数据id进行设置。如果指定的id小于等于0,则抛出IllegalArgumentException异常。
- * mTextDataId是NoteData类成员变量,用于保存笔记文本数据的ID。
- */
- void setTextDataId(long id) {
- // 如果指定的id小于等于0,则抛出IllegalArgumentException异常
- if(id <= 0) {
- throw new IllegalArgumentException("Text data id should larger than 0");
- }
- // 将指定的长整型数值作为笔记的文本数据id进行设置
- mTextDataId = id;
- }
-
-
- /**
- * 设置笔记的通话记录数据id
- *
- * @param id 一个长整型的值,表示要设置的笔记通话记录数据的id。
- *
- * 该函数用于将指定的长整型数值作为笔记的通话记录数据id进行设置。如果指定的id小于等于0,
- * 则抛出IllegalArgumentException异常。
- * mCallDataId是NoteData类成员变量,用于保存笔记的通话记录数据ID。
- */
- void setCallDataId(long id) {
- // 如果指定的id小于等于0,则抛出IllegalArgumentException异常
- if (id <= 0) {
- throw new IllegalArgumentException("Call data id should larger than 0");
- }
- // 将指定的长整型数值作为笔记的通话记录数据id进行设置
- mCallDataId = id;
- }
-
-
- /**
- * 设置笔记的通话记录数据
- *
- * @param key 一个字符串,表示要设置的通话记录数据的键。
- * @param value 一个字符串,表示要设置的通话记录数据的值。
- *
- * 该函数用于将指定的字符串作为笔记的通话记录数据进行设置。它会将键值对保存到mCallDataValues对象中,并将NoteColumns.LOCAL_MODIFIED和NoteColumns.MODIFIED_DATE字段的值更新为1和当前时间戳,
- * 表示笔记已被本地修改过。
- */
- void setCallData(String key, String value) {
- // 将键值对保存到mCallDataValues对象中
- mCallDataValues.put(key, value);
- // 将NoteColumns.LOCAL_MODIFIED字段的值设置为1,表示笔记已被本地修改过
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 将NoteColumns.MODIFIED_DATE字段的值更新为当前时间戳,表示笔记最近一次被修改的时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
-
- /**
- * 设置笔记的文本数据
- *
- * @param key 一个字符串,表示要设置的文本数据的键。
- * @param value 一个字符串,表示要设置的文本数据的值。
- *
- * 该函数用于将指定的字符串作为笔记的文本数据进行设置。它会将键值对保存到mTextDataValues对象中,并将NoteColumns.LOCAL_MODIFIED和NoteColumns.MODIFIED_DATE字段的值更新为1和当前时间戳,
- * 表示笔记已被本地修改过。
- */
- void setTextData(String key, String value) {
- // 将键值对保存到mTextDataValues对象中
- mTextDataValues.put(key, value);
- // 将NoteColumns.LOCAL_MODIFIED字段的值设置为1,表示笔记已被本地修改过
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 将NoteColumns.MODIFIED_DATE字段的值更新为当前时间戳,表示笔记最近一次被修改的时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
-
- /**
- * 将笔记数据插入ContentResolver中
- *
- * @param context Context对象,表示当前应用程序的上下文环境。
- * @param noteId 一个长整型数值,表示要插入的笔记的id。
- *
- * @return 返回插入成功的Uri对象,如果插入失败则返回null。
- *
- * 该函数用于将当前NoteData对象保存到ContentResolver中。它会将mTextDataValues和mCallDataValues对象中的数据保存到ContentResolver中,并更新NoteColumns.LOCAL_MODIFIED和NoteColumns.MODIFIED_DATE字段的值为0和当前时间戳,
- * 表示笔记已被同步到云端。
- */
- Uri pushIntoContentResolver(Context context, long noteId) {
- /**
- * 检查noteId是否合法
- */
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- // 初始化operationList列表和builder对象
- ArrayList operationList = new ArrayList();
- ContentProviderOperation.Builder builder = null;
-
- // 如果mTextDataValues对象不为空,则将其中的数据保存到ContentResolver中
- if(mTextDataValues.size() > 0) {
- // 为mTextDataValues对象添加笔记id
- mTextDataValues.put(DataColumns.NOTE_ID, noteId);
- if (mTextDataId == 0) {
- // 如果mTextDataId为0,则表明当前笔记没有文本数据,需要进行插入操作
- mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
- // 通过ContentResolver插入数据,并获取插入的Uri对象
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mTextDataValues);
- try {
- // 解析Uri中的id值,并将其设置为mTextDataId
- setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Insert new text data fail with noteId" + noteId);
- // 插入失败,清空mTextDataValues,并返回null
- mTextDataValues.clear();
- return null;
- }
- } else {
- // 如果mTextDataId不为0,则表明当前笔记已经有文本数据,需要进行更新操作
- builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mTextDataId));
- builder.withValues(mTextDataValues);
- operationList.add(builder.build());
- }
- // 清空mTextDataValues对象
- mTextDataValues.clear();
- }
-
- // 如果mCallDataValues对象不为空,则将其中的数据保存到ContentResolver中
- if(mCallDataValues.size() > 0) {
- // 为mCallDataValues对象添加笔记id
- mCallDataValues.put(DataColumns.NOTE_ID, noteId);
- if (mCallDataId == 0) {
- // 如果mCallDataId为0,则表明当前笔记没有通话记录数据,需要进行插入操作
- mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
- // 通过ContentResolver插入数据,并获取插入的Uri对象
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mCallDataValues);
- try {
- // 解析Uri中的id值,并将其设置为mCallDataId
- setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- Log.e(TAG, "Insert new call data fail with noteId" + noteId);
- // 插入失败,清空mCallDataValues,并返回null
- mCallDataValues.clear();
- return null;
- }
- } else {
- // 如果mCallDataId不为0,则表明当前笔记已经有通话记录数据,需要进行更新操作
- builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mCallDataId));
- builder.withValues(mCallDataValues);
- operationList.add(builder.build());
- }
- // 清空mCallDataValues对象
- mCallDataValues.clear();
- }
- if (operationList.size() > 0) { // 如果操作列表中有操作
- try {
- // 调用 ContentResolver 的 applyBatch 方法执行操作
- ContentProviderResult[] results = context.getContentResolver().applyBatch(
- Notes.AUTHORITY, operationList);
- // 判断操作是否成功,并返回对应的 Uri
- return (results == null || results.length == 0 || results[0] == null) ? null
- : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- } catch (RemoteException e) { // 捕获 RemoteException 异常
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录异常信息到日志
- return null; // 返回 null
- } catch (OperationApplicationException e) { // 捕获 OperationApplicationException 异常
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 记录异常信息到日志
- return null; // 返回 null
- }
- }
- return null; // 如果操作列表为空,则返回 null
- }
- }
-}
diff --git a/other/07_陈七源_代码标注/model/WorkingNote.java b/other/07_陈七源_代码标注/model/WorkingNote.java
deleted file mode 100644
index 683df72..0000000
--- a/other/07_陈七源_代码标注/model/WorkingNote.java
+++ /dev/null
@@ -1,629 +0,0 @@
-/*
- * 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.model;
-
-import android.appwidget.AppWidgetManager;
-import android.content.ContentUris;
-import android.content.Context;
-import android.database.Cursor;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-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.Notes.TextNote;
-import net.micode.notes.tool.ResourceParser.NoteBgResources;
-
-
-public class WorkingNote {
- // Note for the working note
- private Note mNote;
- // Note Id
- private long mNoteId;
- // Note content
- private String mContent;
- // Note mode
- private int mMode;
-
- private long mAlertDate;
-
- private long mModifiedDate;
-
- private int mBgColorId;
-
- private int mWidgetId;
-
- private int mWidgetType;
-
- private long mFolderId;
-
- private Context mContext;
-
- private static final String TAG = "WorkingNote";
-
- private boolean mIsDeleted;
-
- private NoteSettingChangedListener mNoteSettingStatusListener;
-
- public static final String[] DATA_PROJECTION = new String[] {
- DataColumns.ID, // 表示数据行的 ID
- DataColumns.CONTENT, // 表示数据行的内容
- DataColumns.MIME_TYPE, // 表示数据行的 MIME 类型
- DataColumns.DATA1, // 表示数据行的附加数据
- DataColumns.DATA2, // 表示数据行的附加数据
- DataColumns.DATA3, // 表示数据行的附加数据
- DataColumns.DATA4, // 表示数据行的附加数据
- };
- public static final String[] NOTE_PROJECTION = new String[] {
- NoteColumns.PARENT_ID, // 表示笔记的父笔记 ID
- NoteColumns.ALERTED_DATE, // 表示笔记的提醒时间
- NoteColumns.BG_COLOR_ID, // 表示笔记的背景颜色 ID
- NoteColumns.WIDGET_ID, // 表示笔记的小部件 ID
- NoteColumns.WIDGET_TYPE, // 表示笔记的小部件类型
- NoteColumns.MODIFIED_DATE // 表示笔记的修改时间
- };
-
- private static final int DATA_ID_COLUMN = 0;
-
- private static final int DATA_CONTENT_COLUMN = 1;
-
- private static final int DATA_MIME_TYPE_COLUMN = 2;
-
- private static final int DATA_MODE_COLUMN = 3;
-
- private static final int NOTE_PARENT_ID_COLUMN = 0;
-
- private static final int NOTE_ALERTED_DATE_COLUMN = 1;
-
- private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
-
- private static final int NOTE_WIDGET_ID_COLUMN = 3;
-
- private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
-
- private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
-
- // New note construct
- /**
- * 构造方法,创建一个新的 WorkingNote 对象。
- * @param context 上下文对象
- * @param folderId 笔记所属文件夹的 ID
- */
- private WorkingNote(Context context, long folderId) {
- // 初始化成员变量
- mContext = context; // 上下文对象
- mAlertDate = 0; // 提醒时间
- mModifiedDate = System.currentTimeMillis(); // 修改时间,初始化为当前时间戳
- mFolderId = folderId; // 笔记所属文件夹的 ID
- mNote = new Note(); // Note 对象
- mNoteId = 0; // 笔记 ID,初始值为 0
- mIsDeleted = false; // 是否已删除,初始值为 false
- mMode = 0; // 模式,初始值为 0
- mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 小部件类型,初始值为无效类型
- }
-
-
- // Existing note construct
- /**
- * 构造方法,创建一个新的 WorkingNote 对象。
- * @param context 上下文对象
- * @param noteId 笔记的ID
- * @param folderId 笔记所属文件夹的 ID
- */
- private WorkingNote(Context context, long noteId, long folderId) {
- // 初始化成员变量
- mContext = context; // 上下文对象
- mNoteId = noteId; // 笔记 ID
- mFolderId = folderId; // 笔记所属文件夹的 ID
- mIsDeleted = false; // 是否已删除,初始值为 false
- mNote = new Note(); // Note 对象
- loadNote(); // 加载笔记数据
- }
-
-
- /**
- * 从内容提供程序中使用当前笔记 ID 加载笔记的详细信息。
- * 查询 CONTENT_NOTE_URI,检索与指定笔记 ID 相对应的记录。
- * 如果游标不为空并且可以将其移动到第一个结果,则结果将填充 mFolderId、mBgColorId、
- * mWidgetId、mWidgetType、mAlertDate 和 mModifiedDate 变量。
- * 然后关闭游标并调用 loadNoteData() 方法以加载笔记剩余部分的数据。
- * 如果没有检索到任何记录,则在打印错误日志后抛出 IllegalArgumentException 异常。
- */
- private void loadNote() {
- Cursor cursor = mContext.getContentResolver().query(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId),
- NOTE_PROJECTION,
- null,
- null,
- null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- // 结果将填充以下变量:mFolderId、mBgColorId、mWidgetId、mWidgetType、mAlertDate 和 mModifiedDate
- mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
- mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
- mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
- mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
- mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
- mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
- }
- cursor.close();
- } else {
- // 没有检索到任何记录,则在打印错误日志后抛出 IllegalArgumentException 异常
- Log.e(TAG, "No note with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
- }
- // 加载笔记剩余部分的数据
- loadNoteData();
- }
-
-
- /**
- * 加载笔记数据。
- *
- * 该方法用于从Content Provider中加载当前Note对象的数据。它会查询Notes.CONTENT_DATA_URI,条件为
- * DataColumns.NOTE_ID等于mNoteId,如果存在符合条件的数据,则将其加载到Note对象中。
- * 如果在查询时出现错误(例如Content Provider不存在或无法工作、指定的笔记ID无效等),则会抛出IllegalArgumentException异常。
- */
- private void loadNoteData() {
- Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
- DataColumns.NOTE_ID + "=?", new String[] { String.valueOf(mNoteId) }, null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- // 遍历所有数据并将它们加载到Note对象中。
- do {
- String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
- if (DataConstants.NOTE.equals(type)) {
- mContent = cursor.getString(DATA_CONTENT_COLUMN);
- mMode = cursor.getInt(DATA_MODE_COLUMN);
- mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
- } else if (DataConstants.CALL_NOTE.equals(type)) {
- mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
- } else {
- Log.d(TAG, "Wrong note type with type:" + type);
- }
- } while (cursor.moveToNext());
- }
- cursor.close();
- } else {
- // 如果未找到任何数据,则抛出异常。
- Log.e(TAG, "No data with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
- }
- }
-
-
- /**
- * 创建一个空的笔记对象。
- *
- * 该方法用于创建一个空白的WorkingNote对象,并设置其初始值。它接受context、folderId、widgetId、
- * widgetType和defaultBgColorId等参数作为输入,并返回一个新的WorkingNote对象。
- *
- * @param context 上下文环境
- * @param folderId 笔记所在文件夹的ID
- * @param widgetId 笔记所绑定的Widget的ID(如果有)
- * @param widgetType 笔记所绑定的Widget的类型(例如便签、待办事项等)
- * @param defaultBgColorId 笔记默认的背景颜色ID
- * @return 返回一个新的WorkingNote对象
- */
- public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
- int widgetType, int defaultBgColorId) {
- // 创建一个空白的WorkingNote对象
- WorkingNote note = new WorkingNote(context, folderId);
- // 设置笔记的默认背景颜色
- note.setBgColorId(defaultBgColorId);
- // 设置笔记所绑定的Widget的ID
- note.setWidgetId(widgetId);
- // 设置笔记所绑定的Widget的类型
- note.setWidgetType(widgetType);
- // 返回一个新的WorkingNote对象
- return note;
- }
-
-
- /**
- * 从数据库中加载一个WorkingNote对象。
- *
- * 该方法用于从数据库中加载一个指定ID的WorkingNote对象。它接受context和id等参数作为输入,并返回
- * 一个新的WorkingNote对象。
- *
- * @param context 上下文环境
- * @param id 待加载的WorkingNote对象的ID
- * @return 返回一个新的WorkingNote对象
- */
- public static WorkingNote load(Context context, long id) {
- // 创建一个新的WorkingNote对象,并将id和0作为参数传入构造函数中
- return new WorkingNote(context, id, 0);
- }
-
-
- /**
- * 保存笔记对象。
- *
- * 该方法用于将当前WorkingNote对象(如果有必要)保存到数据库中。如果该笔记尚未存在于数据库中,
- * 则会先创建一个新的笔记记录。它还会更新绑定在该笔记上的Widget内容(如果该笔记绑定了Widget)。
- *
- * @return 如果笔记成功保存,则返回true;否则返回false
- */
- public synchronized boolean saveNote() {
- // 检查该笔记是否值得被保存
- if (isWorthSaving()) {
- // 如果该笔记尚未存在于数据库中,则需要先创建一个新的笔记记录。
- if (!existInDatabase()) {
- // 获取一个新的笔记ID
- if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
- Log.e(TAG, "Create new note fail with id:" + mNoteId);
- return false;
- }
- }
-
- // 将当前WorkingNote对象同步到Note对象中
- mNote.syncNote(mContext, mNoteId);
-
- /**
- * 如果该笔记绑定了Widget,则需要更新Widget的内容。
- */
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
- && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
-
- return true;
- } else {
- return false;
- }
- }
-
-
- /**
- * 检查当前WorkingNote对象是否存在于数据库中。
- *
- * 该方法用于检查当前WorkingNote对象是否已经存在于数据库中。如果该笔记已经保存过,则existInDatabase()
- * 方法会返回true;否则返回false。
- *
- * @return 如果笔记已经存在于数据库中,则返回true;否则返回false
- */
- public boolean existInDatabase() {
- return mNoteId > 0;
- }
-
- /**
- * 判断笔记是否值得被保存。
- *
- * 该方法用于判断当前WorkingNote对象是否值得被保存到数据库中。它会根据笔记内容、是否被删除以及
- * 是否已经保存到数据库等因素做出判断。如果该笔记不需要被保存,则isWorthSaving()方法会返回
- * false;否则返回true。
- *
- * @return 如果笔记值得被保存到数据库中,则返回true;否则返回false
- */
- private boolean isWorthSaving() {
- if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
- || (existInDatabase() && !mNote.isLocalModified())) {
- // 如果该笔记已经被标记为“已删除”,或者它既没有保存到数据库中,也没有任何数据,或者它已经存在于
- // 数据库中但没有被修改过,则认为该笔记不需要被保存。
- return false;
- } else {
- return true;
- }
- }
-
-
- /**
- * 设置笔记设置状态更改监听器。
- *
- * 该方法用于设置一个NoteSettingChangedListener对象,以便能够在笔记设置状态发生更改时接收通知。
- *
- * @param l 笔记设置状态更改监听器
- */
- public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
- mNoteSettingStatusListener = l;
- }
-
-
- /**
- * 设置笔记提醒日期。
- *
- * 该方法用于为当前WorkingNote对象设置一个提醒日期。它接受date和set两个参数作为输入,分别表示
- * 待设置的提醒日期和是否需要进行设置。如果待设置的提醒日期与当前笔记的提醒日期不同,则会将其更新到
- * Note对象中,并通知设置状态更改监听器。
- *
- * @param date 待设置的提醒日期
- * @param set 是否需要进行设置
- */
- public void setAlertDate(long date, boolean set) {
- if (date != mAlertDate) {
- // 如果待设置的提醒日期与当前笔记的提醒日期不同,则需要更新Note对象中的数据。
- mAlertDate = date;
- mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
- }
- // 通知设置状态更改监听器。
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onClockAlertChanged(date, set);
- }
- }
-
-
- /**
- * 标记笔记是否被删除。
- *
- * 该方法用于标记当前WorkingNote对象是否已经被删除。它接受一个mark参数作为输入,如果mark为true,
- * 则表示该笔记已经被删除,否则表示该笔记未被删除。在标记笔记删除状态的同时,该方法还会检查
- * 是否存在与该笔记绑定的Widget,如果有,则需要更新Widget的内容。
- *
- * @param mark 是否将当前WorkingNote对象标记为“已删除”
- */
- public void markDeleted(boolean mark) {
- // 标记当前WorkingNote对象是否已经被删除。
- mIsDeleted = mark;
- // 检查是否存在与该笔记绑定的Widget,如果有,则需要更新Widget的内容。
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
- && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
- }
-
-
- /**
- * 设置笔记的背景颜色ID。
- *
- * 该方法用于为当前WorkingNote对象设置一个新的背景颜色ID。它接受一个id参数作为输入,表示待设置
- * 的背景颜色ID。如果待设置的背景颜色ID与当前笔记的背景颜色ID不同,则会将其更新到Note对象中,
- * 并通知设置状态更改监听器。
- *
- * @param id 待设置的背景颜色ID
- */
- public void setBgColorId(int id) {
- if (id != mBgColorId) {
- // 如果待设置的背景颜色ID与当前笔记的背景颜色ID不同,则需要更新Note对象中的数据。
- mBgColorId = id;
- mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
- // 通知设置状态更改监听器。
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onBackgroundColorChanged();
- }
- }
- }
-
- /**
- * 设置笔记的清单模式。
- *
- * 该方法用于设置当前WorkingNote对象的清单模式。它接受一个mode参数作为输入,表示待设置的清单模式。
- * 如果当前笔记的清单模式与待设置的清单模式不同,则会将其更新到Note对象中,并通知设置状态更改监听器。
- *
- * @param mode 待设置的清单模式
- */
- public void setCheckListMode(int mode) {
- if (mMode != mode) {
- // 如果当前笔记的清单模式与待设置的清单模式不同,则需要更新Note对象中的数据。
- mMode = mode;
- mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
- // 通知设置状态更改监听器。
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
- }
- }
- }
-
- /**
- * 设置笔记绑定的Widget类型。
- *
- * 该方法用于设置当前WorkingNote对象绑定的Widget类型。它接受一个type参数作为输入,表示待设置的
- * Widget类型。如果当前笔记绑定的Widget类型与待设置的Widget类型不同,则会将其更新到Note对象中。
- *
- * @param type 待设置的Widget类型
- */
- public void setWidgetType(int type) {
- if (type != mWidgetType) {
- // 如果当前笔记绑定的Widget类型与待设置的Widget类型不同,则需要更新Note对象中的数据。
- mWidgetType = type;
- mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
- }
- }
-
- /**
- * 设置笔记绑定的Widget ID。
- *
- * 该方法用于设置当前WorkingNote对象绑定的Widget ID。它接受一个id参数作为输入,表示待设置的
- * Widget ID。如果当前笔记绑定的Widget ID与待设置的Widget ID不同,则会将其更新到Note对象中。
- *
- * @param id 待设置的Widget ID
- */
- public void setWidgetId(int id) {
- if (id != mWidgetId) {
- // 如果当前笔记绑定的Widget ID与待设置的Widget ID不同,则需要更新Note对象中的数据。
- mWidgetId = id;
- mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
- }
- }
-
-
- /**
- * 设置笔记的文本内容。
- *
- * 该方法用于设置当前WorkingNote对象的文本内容。它接受一个text参数作为输入,表示待设置的文本内容。
- * 如果当前笔记的文本内容与待设置的文本内容不同,则会将其更新到Note对象中。
- *
- * @param text 待设置的文本内容
- */
- public void setWorkingText(String text) {
- if (!TextUtils.equals(mContent, text)) {
- // 如果当前笔记的文本内容与待设置的文本内容不同,则需要更新Note对象中的数据。
- mContent = text;
- mNote.setTextData(DataColumns.CONTENT, mContent);
- }
- }
-
- /**
- * 将笔记转换为通话记录。
- *
- * 该方法用于将当前WorkingNote对象转换为通话记录。它接受一个phoneNumber和callDate两个参数作为输入,
- * 分别表示通话记录的电话号码和通话日期。该方法会将笔记的类型设置为通话记录,并将相应的数据保存到Note对象中。
- *
- * @param phoneNumber 通话记录的电话号码
- * @param callDate 通话记录的通话日期
- */
- public void convertToCallNote(String phoneNumber, long callDate) {
- // 将笔记的类型设置为通话记录,并将相应的数据保存到Note对象中。
- mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
- mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
- mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
- }
-
-
- /**
- * 检查笔记是否设置了提醒。
- *
- * 该方法用于检查当前WorkingNote对象是否设置了提醒。如果已经设置了提醒,则返回true;否则返回false。
- *
- * @return 如果笔记设置了提醒,则返回true;否则返回false
- */
- public boolean hasClockAlert() {
- return (mAlertDate > 0 ? true : false);
- }
-
- /**
- * 获取笔记的文本内容。
- *
- * 该方法用于获取当前WorkingNote对象的文本内容。
- *
- * @return 当前WorkingNote对象的文本内容
- */
- public String getContent() {
- return mContent;
- }
-
- /**
- * 获取笔记的提醒日期。
- *
- * 该方法用于获取当前WorkingNote对象的提醒日期。
- *
- * @return 当前WorkingNote对象的提醒日期
- */
- public long getAlertDate() {
- return mAlertDate;
- }
-
- /**
- * 获取笔记的修改日期。
- *
- * 该方法用于获取当前WorkingNote对象的修改日期。
- *
- * @return 当前WorkingNote对象的修改日期
- */
- public long getModifiedDate() {
- return mModifiedDate;
- }
-
- /**
- * 获取笔记的背景颜色资源ID。
- *
- * 该方法用于获取当前WorkingNote对象的背景颜色资源ID。它会根据当前笔记的背景颜色ID返回相应的颜色资源ID。
- *
- * @return 当前WorkingNote对象的背景颜色资源ID
- */
- public int getBgColorResId() {
- return NoteBgResources.getNoteBgResource(mBgColorId);
- }
-
-
- /**
- * 获取笔记的背景颜色ID。
- *
- * 该方法用于获取当前WorkingNote对象的背景颜色ID。
- *
- * @return 当前WorkingNote对象的背景颜色ID
- */
- public int getBgColorId() {
- return mBgColorId;
- }
-
- /**
- * 获取笔记标题的背景颜色资源ID。
- *
- * 该方法用于获取当前WorkingNote对象的标题栏背景颜色资源ID。它会根据当前笔记的背景颜色ID返回相应的颜色资源ID。
- *
- * @return 当前WorkingNote对象的标题栏背景颜色资源ID
- */
- public int getTitleBgResId() {
- return NoteBgResources.getNoteTitleBgResource(mBgColorId);
- }
-
- /**
- * 获取笔记的清单模式。
- *
- * 该方法用于获取当前WorkingNote对象的清单模式。
- *
- * @return 当前WorkingNote对象的清单模式
- */
- public int getCheckListMode() {
- return mMode;
- }
-
- /**
- * 获取笔记的ID。
- *
- * 该方法用于获取当前WorkingNote对象对应的Note对象的ID。
- *
- * @return 当前WorkingNote对象对应的Note对象的ID
- */
- public long getNoteId() {
- return mNoteId;
- }
-
-
- public long getFolderId() {
- return mFolderId;
- }
-
- public int getWidgetId() {
- return mWidgetId;
- }
-
- public int getWidgetType() {
- return mWidgetType;
- }
-
- public interface NoteSettingChangedListener {
- /**
- * Called when the background color of current note has just changed
- */
- void onBackgroundColorChanged();
-
- /**
- * Called when user set clock
- */
- void onClockAlertChanged(long date, boolean set);
-
- /**
- * Call when user create note from widget
- */
- void onWidgetChanged();
-
- /**
- * Call when switch between check list mode and normal mode
- * @param oldMode is previous mode before change
- * @param newMode is new mode
- */
- void onCheckListModeChanged(int oldMode, int newMode);
- }
-}
diff --git a/other/07_陈七源_代码标注/tool/BackupUtils.java b/other/07_陈七源_代码标注/tool/BackupUtils.java
deleted file mode 100644
index 9243427..0000000
--- a/other/07_陈七源_代码标注/tool/BackupUtils.java
+++ /dev/null
@@ -1,442 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.os.Environment;
-import android.text.TextUtils;
-import android.text.format.DateFormat;
-import android.util.Log;
-
-import net.micode.notes.R;
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-
-
-public class BackupUtils {
- private static final String TAG = "BackupUtils";
- // Singleton stuff
- private static BackupUtils sInstance;
-
- /**
- * 返回 BackupUtils 类的单例实例,并确保线程安全。
- * @param context 应用程序的上下文。
- * @return BackupUtils 类的实例。
- */
- public static synchronized BackupUtils getInstance(Context context) {
- // 如果实例不存在,创建一个新的实例
- if (sInstance == null) {
- sInstance = new BackupUtils(context);
- }
- // 返回现有实例或新创建的实例
- return sInstance;
- }
-
-
- /**
- * Following states are signs to represents backup or restore
- * status
- */
- // Currently, the sdcard is not mounted
- // SD卡未挂载的状态
- public static final int STATE_SD_CARD_UNMOUONTED = 0;
- // 备份文件不存在的状态
- public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
- // 数据格式不正确,可能被其他程序更改的状态
- public static final int STATE_DATA_DESTROIED = 2;
- // 恢复或备份失败的状态,由运行时异常引起
- public static final int STATE_SYSTEM_ERROR = 3;
- // 备份或恢复成功的状态
- public static final int STATE_SUCCESS = 4;
-
- private TextExport mTextExport; // 用于导出文本数据的 TextExport 实例
-
- // 构造函数,用于创建 BackupUtils 类的实例
- private BackupUtils(Context context) {
- mTextExport = new TextExport(context); // 创建 TextExport 实例并保存到成员变量中
- }
-
- /**
- * 检查外部存储是否可用。
- * @return 如果外部存储可用,则返回 true;否则返回 false。
- */
- private static boolean externalStorageAvailable() {
- return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
- }
-
- /**
- * 将数据导出到文本文件中。
- * @return 导出操作的结果状态。
- */
- public int exportToText() {
- return mTextExport.exportToText();
- }
-
- /**
- * 获取导出的文本文件名。
- * @return 导出的文本文件名。
- */
- public String getExportedTextFileName() {
- return mTextExport.mFileName;
- }
-
- /**
- * 获取导出的文本文件所在的目录。
- * @return 导出的文本文件所在的目录。
- */
- public String getExportedTextFileDir() {
- return mTextExport.mFileDirectory;
- }
-
- private static class TextExport {
- private static final String[] NOTE_PROJECTION = {
- NoteColumns.ID, // 笔记的标识符
- NoteColumns.MODIFIED_DATE, // 笔记最近修改的日期
- NoteColumns.SNIPPET, // 笔记内容的片段,用于快速预览笔记
- NoteColumns.TYPE // 笔记的类型
- };
-
- private static final int NOTE_COLUMN_ID = 0; // 列 ID
- private static final int NOTE_COLUMN_MODIFIED_DATE = 1; // 列 MODIFIED_DATE
- private static final int NOTE_COLUMN_SNIPPET = 2; // 列 SNIPPET
-
- private static final String[] DATA_PROJECTION = {
- DataColumns.CONTENT, // 数据的主体内容
- DataColumns.MIME_TYPE, // 数据的 MIME 类型
- DataColumns.DATA1, // 此列可能包含电话号码、电子邮件地址等。
- DataColumns.DATA2, // 此列可能包含电话类型(家庭、工作等)、电子邮件类型等。
- DataColumns.DATA3, // 通常情况下,此列的使用与 DATA2 相同。
- DataColumns.DATA4 // 保留供将来使用。
- };
-
- private static final int DATA_COLUMN_CONTENT = 0; // 列 CONTENT
- private static final int DATA_COLUMN_MIME_TYPE = 1; // 列 MIME_TYPE
- private static final int DATA_COLUMN_CALL_DATE = 2; // 列 CALL_DATE
-
-
- private static final int DATA_COLUMN_PHONE_NUMBER = 4; // 列 PHONE_NUMBER
-
- private final String[] TEXT_FORMAT; // 存储导出文本的格式
- private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名对应的格式
- private static final int FORMAT_NOTE_DATE = 1; // 笔记日期对应的格式
- private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容对应的格式
-
- private Context mContext; // 应用程序上下文
- private String mFileName; // 导出文件的名称
- private String mFileDirectory; // 导出文件所在的目录
-
-
- /**
- * 构造函数,用于创建 TextExport 类的实例。
- *
- * @param context 应用程序上下文。
- */
- public TextExport(Context context) {
- TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); // 从资源中获取导出文本的格式
- mContext = context; // 保存应用程序上下文
- mFileName = ""; // 导出文件名称为空
- mFileDirectory = ""; // 导出文件所在目录为空
- }
-
- /**
- * 获取指定索引处的导出文本格式。
- *
- * @param id 索引值。
- * @return 指定索引处的导出文本格式。
- */
- private String getFormat(int id) {
- return TEXT_FORMAT[id]; // 返回指定索引处的导出文本格式
- }
-
- /**
- * Export the folder identified by folder id to text
- */
- /**
- * 导出指定笔记本中的所有笔记到文本文件。
- *
- * @param folderId 笔记本的标识符。
- * @param ps PrintStream 对象,用于写入导出的文本数据。
- */
- private void exportFolderToText(String folderId, PrintStream ps) {
- // 查询属于该笔记本的笔记
- Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
- NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[]{folderId}, null);
-
- if (notesCursor != null) {
- if (notesCursor.moveToFirst()) {
- do {
- // 打印笔记的最近修改日期
- ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
- mContext.getString(R.string.format_datetime_mdhm),
- notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
- // 查询属于该笔记的数据
- String noteId = notesCursor.getString(NOTE_COLUMN_ID);
- exportNoteToText(noteId, ps); // 将笔记导出到文本文件
- } while (notesCursor.moveToNext());
- }
- notesCursor.close();
- }
- }
-
- /**
- * 将指定 ID 的笔记导出到打印流中。
- *
- * @param noteId 要导出的笔记 ID。
- * @param ps 要写入笔记的打印流对象。
- */
- private void exportNoteToText(String noteId, PrintStream ps) {
- // 查询与该笔记关联的数据项
- Cursor dataCursor = mContext.getContentResolver().query(
- Notes.CONTENT_DATA_URI, // 查询的 URI
- DATA_PROJECTION, // 要查询的列名
- DataColumns.NOTE_ID + "=?", // WHERE 子句
- new String[]{noteId}, // WHERE 子句中占位符的值
- null // 排序方式
- );
-
- if (dataCursor != null) {
- if (dataCursor.moveToFirst()) {
- do {
- // 获取当前数据项的 MIME 类型
- String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
- if (DataConstants.CALL_NOTE.equals(mimeType)) {
- // 处理通话记录类型的笔记
- String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); // 电话号码
- long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); // 通话日期
- String location = dataCursor.getString(DATA_COLUMN_CONTENT); // 通话位置
-
- if (!TextUtils.isEmpty(phoneNumber)) {
- // 如果电话号码不为空,就将其写入打印流中
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
- }
-
- // 将通话日期格式化为字符串,并写入打印流中
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
- DateFormat.format(mContext.getString(R.string.format_datetime_mdhm), callDate)));
-
- if (!TextUtils.isEmpty(location)) {
- // 如果通话位置不为空,就将其写入打印流中
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
- }
- } else if (DataConstants.NOTE.equals(mimeType)) {
- // 处理普通笔记类型
- String content = dataCursor.getString(DATA_COLUMN_CONTENT); // 笔记内容
-
- if (!TextUtils.isEmpty(content)) {
- // 如果笔记内容不为空,就将其写入打印流中
- ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
- }
- }
- } while (dataCursor.moveToNext());
- }
-
- // 关闭游标
- dataCursor.close();
- }
-
- // 在每个笔记之间输出一个分隔符
- try {
- ps.write(new byte[]{Character.LINE_SEPARATOR, Character.LETTER_NUMBER});
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- }
- }
-
- /**
- * 将笔记导出为纯文本文件。
- *
- * @return 导出的状态码。
- */
- public int exportToText() {
- // 检查外部存储是否可用
- if (!externalStorageAvailable()) {
- Log.d(TAG, "Media was not mounted");
- return STATE_SD_CARD_UNMOUONTED;
- }
-
- // 获取打印流对象,准备写入数据
- PrintStream ps = getExportToTextPrintStream();
- if (ps == null) {
- Log.e(TAG, "get print stream error");
- return STATE_SYSTEM_ERROR;
- }
-
- // 先导出所有的文件夹及其笔记
- Cursor folderCursor = mContext.getContentResolver().query(
- Notes.CONTENT_NOTE_URI, // 查询的 URI
- NOTE_PROJECTION, // 要查询的列名
- "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
- + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
- + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, // WHERE 子句
- null, // WHERE 子句中占位符的值
- null // 排序方式
- );
-
- if (folderCursor != null) {
- if (folderCursor.moveToFirst()) {
- do {
- // 打印文件夹名称
- String folderName = "";
- if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
- folderName = mContext.getString(R.string.call_record_folder_name);
- } else {
- folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
- }
- if (!TextUtils.isEmpty(folderName)) {
- ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
- }
- String folderId = folderCursor.getString(NOTE_COLUMN_ID);
- // 导出当前文件夹下的所有笔记
- exportFolderToText(folderId, ps);
- } while (folderCursor.moveToNext());
- }
-
- // 关闭游标
- folderCursor.close();
- }
-
- // 导出根目录下的笔记
- Cursor noteCursor = mContext.getContentResolver().query(
- Notes.CONTENT_NOTE_URI, // 查询的 URI
- NOTE_PROJECTION, // 要查询的列名
- NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0", // WHERE 子句
- null, // WHERE 子句中占位符的值
- null // 排序方式
- );
-
- if (noteCursor != null) {
- if (noteCursor.moveToFirst()) {
- do {
- // 打印笔记的最后修改时间
- ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
- mContext.getString(R.string.format_datetime_mdhm),
- noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
- // 导出当前笔记的内容
- String noteId = noteCursor.getString(NOTE_COLUMN_ID);
- exportNoteToText(noteId, ps);
- } while (noteCursor.moveToNext());
- }
-
- // 关闭游标
- noteCursor.close();
- }
-
- // 关闭打印流
- ps.close();
- return STATE_SUCCESS;
- }
- /**
- * Get a print stream pointed to the file {@generateExportedTextFile}
- */
- /**
- * 生成用于将数据输出到文本文件中的PrintStream对象。
- *
- * @return 用于将数据输出到文本文件中的PrintStream对象。
- */
- private PrintStream getExportToTextPrintStream() {
- // 生成指定路径和名称的文本文件,保存在SD卡上。
- File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
- R.string.file_name_txt_format);
- if (file == null) {
- // 如果创建文件失败,则记录错误日志并返回null。
- Log.e(TAG, "create file to exported failed");
- return null;
- }
- // 将文件名保存在成员变量中。
- mFileName = file.getName();
- // 将文件目录路径保存在成员变量中。
- mFileDirectory = mContext.getString(R.string.file_path);
- PrintStream ps = null;
- try {
- // 创建一个新的FileOutputStream对象,并将其包装在PrintStream对象中。
- FileOutputStream fos = new FileOutputStream(file);
- ps = new PrintStream(fos);
- } catch (FileNotFoundException e) {
- // 如果找不到文件,则打印堆栈跟踪并返回null。
- e.printStackTrace();
- return null;
- } catch (NullPointerException e) {
- // 如果发生空指针异常,则打印堆栈跟踪并返回null。
- e.printStackTrace();
- return null;
- }
- // 返回用于将数据输出到文本文件中的PrintStream对象。
- return ps;
- }
- }
-
- /**
- * Generate the text file to store imported data
- */
- /**
- * 在SD卡上创建目录和指定格式的文件。
- *
- * @param context 上下文对象。
- * @param filePathResId 文件路径的字符串资源ID。
- * @param fileNameFormatResId 文件名格式的字符串资源ID。
- * @return 生成的文件对象,如果创建失败则返回null。
- */
- private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
- // 创建一个StringBuilder对象,用于拼接文件路径和名称。
- StringBuilder sb = new StringBuilder();
- // 将外部存储器目录添加到StringBuilder中。
- sb.append(Environment.getExternalStorageDirectory());
- // 将文件路径的字符串资源ID添加到StringBuilder中。
- sb.append(context.getString(filePathResId));
- // 创建一个包含文件路径的File对象。
- File filedir = new File(sb.toString());
- // 将文件名格式化并将其添加到StringBuilder末尾。
- sb.append(context.getString(fileNameFormatResId,
- DateFormat.format(context.getString(R.string.format_date_ymd), System.currentTimeMillis())));
- // 创建一个包含完整文件路径的File对象。
- File file = new File(sb.toString());
-
- try {
- // 如果文件夹不存在,则创建它。
- if (!filedir.exists()) {
- filedir.mkdir();
- }
- // 如果文件不存在,则创建它。
- if (!file.exists()) {
- file.createNewFile();
- }
- // 返回创建的文件对象。
- return file;
- } catch (SecurityException e) {
- // 捕获安全异常,并打印错误日志。
- e.printStackTrace();
- } catch (IOException e) {
- // 捕获I/O异常,并打印错误日志。
- e.printStackTrace();
- }
-
- // 如果创建文件失败,则返回null。
- return null;
- }
-
-}
-
-
diff --git a/other/07_陈七源_代码标注/tool/ResourceParser.java b/other/07_陈七源_代码标注/tool/ResourceParser.java
deleted file mode 100644
index bc160a2..0000000
--- a/other/07_陈七源_代码标注/tool/ResourceParser.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.tool;
-
-import android.content.Context;
-import android.preference.PreferenceManager;
-
-import net.micode.notes.R;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-public class ResourceParser {
-
- public static final int YELLOW = 0;
- public static final int BLUE = 1;
- public static final int WHITE = 2;
- public static final int GREEN = 3;
- public static final int RED = 4;
-
- public static final int BG_DEFAULT_COLOR = YELLOW;
-
- public static final int TEXT_SMALL = 0;
- public static final int TEXT_MEDIUM = 1;
- public static final int TEXT_LARGE = 2;
- public static final int TEXT_SUPER = 3;
-
- public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
-
- public static class NoteBgResources {
- // 存储五种不同颜色的背景图片资源id
- private final static int [] BG_EDIT_RESOURCES = new int [] {
- R.drawable.edit_yellow, // 黄色背景图片
- R.drawable.edit_blue, // 蓝色背景图片
- R.drawable.edit_white, // 白色背景图片
- R.drawable.edit_green, // 绿色背景图片
- R.drawable.edit_red // 红色背景图片
- };
-
- // 存储五种不同颜色的标题栏背景图片资源id
- private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
- R.drawable.edit_title_yellow, // 黄色标题栏背景图片
- R.drawable.edit_title_blue, // 蓝色标题栏背景图片
- R.drawable.edit_title_white, // 白色标题栏背景图片
- R.drawable.edit_title_green, // 绿色标题栏背景图片
- R.drawable.edit_title_red // 红色标题栏背景图片
- };
-
- /**
- * 获取给定 id 对应的笔记项背景资源 ID
- *
- * @param id 笔记项背景色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 笔记项背景资源的 ID
- */
- public static int getNoteBgResource(int id) {
- return BG_EDIT_RESOURCES[id];
- }
-
- /**
- * 获取给定 id 对应的标题栏背景资源 ID
- *
- * @param id 标题栏背景色的 ID,从 0 到 2 分别表示橙色、蓝色和绿色三种颜色
- * @return 标题栏背景资源的 ID
- */
- public static int getNoteTitleBgResource(int id) {
- return BG_EDIT_TITLE_RESOURCES[id];
- }
-
- }
-
- /**
- * 获取笔记项的默认背景 ID
- *
- * @param context 上下文对象
- * @return 笔记项的默认背景资源 ID
- */
- public static int getDefaultBgId(Context context) {
- // 检查应用程序的共享首选项中是否启用了自定义笔记项背景颜色
- if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
- NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
- // 如果已经启用,则生成一个随机数并返回对应的笔记项背景资源 ID
- return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
- } else {
- // 如果未启用,则返回默认背景颜色(即 BG_DEFAULT_COLOR)所对应的资源 ID。
- return BG_DEFAULT_COLOR;
- }
- }
-
-
- public static class NoteItemBgResources {
- /**
- * 笔记项在列表中作为第一个条目时的背景资源 ID
- */
- private final static int [] BG_FIRST_RESOURCES = new int [] {
- R.drawable.list_yellow_up,
- R.drawable.list_blue_up,
- R.drawable.list_white_up,
- R.drawable.list_green_up,
- R.drawable.list_red_up
- };
-
- /**
- * 笔记项在列表中作为中间条目时的背景资源 ID
- */
- private final static int [] BG_NORMAL_RESOURCES = new int [] {
- R.drawable.list_yellow_middle,
- R.drawable.list_blue_middle,
- R.drawable.list_white_middle,
- R.drawable.list_green_middle,
- R.drawable.list_red_middle
- };
-
- /**
- * 笔记项在列表中作为最后一个条目时的背景资源 ID
- */
- private final static int [] BG_LAST_RESOURCES = new int [] {
- R.drawable.list_yellow_down,
- R.drawable.list_blue_down,
- R.drawable.list_white_down,
- R.drawable.list_green_down,
- R.drawable.list_red_down,
- };
-
-
- /**
- * 笔记项在列表中作为唯一条目时的背景资源 ID
- */
- private final static int [] BG_SINGLE_RESOURCES = new int [] {
- R.drawable.list_yellow_single,
- R.drawable.list_blue_single,
- R.drawable.list_white_single,
- R.drawable.list_green_single,
- R.drawable.list_red_single
- };
-
- /**
- * 获取给定 id 对应的笔记项在列表中作为第一个条目时的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 笔记项在列表中作为第一个条目时的背景资源 ID
- */
- public static int getNoteBgFirstRes(int id) {
- return BG_FIRST_RESOURCES[id];
- }
-
- /**
- * 获取给定 id 对应的笔记项在列表中作为最后一个条目时的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 笔记项在列表中作为最后一个条目时的背景资源 ID
- */
- public static int getNoteBgLastRes(int id) {
- return BG_LAST_RESOURCES[id];
- }
-
- /**
- * 获取给定 id 对应的笔记项在列表中作为唯一条目时的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 笔记项在列表中作为唯一条目时的背景资源 ID
- */
- public static int getNoteBgSingleRes(int id) {
- return BG_SINGLE_RESOURCES[id];
- }
-
-
- /**
- * 获取给定 id 对应的笔记项在列表中作为中间条目时的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 笔记项在列表中作为中间条目时的背景资源 ID
- */
- public static int getNoteBgNormalRes(int id) {
- return BG_NORMAL_RESOURCES[id];
- }
-
- /**
- * 返回文件夹列表中文件夹的背景资源 ID,该资源是一个 drawable(R.drawable.list_folder)
- *
- * @return 文件夹列表中文件夹的背景资源 ID
- */
- public static int getFolderBgRes() {
- return R.drawable.list_folder;
- }
-
- }
-
- public static class WidgetBgResources {
- /**
- * 小部件在 2x2 模式下的背景资源 ID 数组
- */
- private final static int [] BG_2X_RESOURCES = new int [] {
- R.drawable.widget_2x_yellow,
- R.drawable.widget_2x_blue,
- R.drawable.widget_2x_white,
- R.drawable.widget_2x_green,
- R.drawable.widget_2x_red,
- };
-
- /**
- * 获取给定 id 对应的小部件在 2x2 模式下的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 给定 id 对应的小部件在 2x2 模式下的背景资源 ID
- */
- public static int getWidget2xBgResource(int id) {
- return BG_2X_RESOURCES[id];
- }
-
- /**
- * 小部件在 4x4 模式下的背景资源 ID 数组
- */
- private final static int [] BG_4X_RESOURCES = new int [] {
- R.drawable.widget_4x_yellow,
- R.drawable.widget_4x_blue,
- R.drawable.widget_4x_white,
- R.drawable.widget_4x_green,
- R.drawable.widget_4x_red
- };
-
- /**
- * 获取给定 id 对应的小部件在 4x4 模式下的背景资源 ID
- *
- * @param id 背景颜色的 ID,从 0 到 4 分别表示黄、蓝、白、绿、红五种颜色
- * @return 给定 id 对应的小部件在 4x4 模式下的背景资源 ID
- */
- public static int getWidget4xBgResource(int id) {
- return BG_4X_RESOURCES[id];
- }
-
- }
-
- public static class TextAppearanceResources {
- /**
- * 文字外观资源 ID 数组
- */
- private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
- R.style.TextAppearanceNormal,
- R.style.TextAppearanceMedium,
- R.style.TextAppearanceLarge,
- R.style.TextAppearanceSuper
- };
-
- /**
- * 获取给定 id 对应的文字外观资源 ID
- *
- * @param id 文字外观的 ID,从 0 到 3 分别表示 Normal、Medium、Large、Super 四种大小
- * @return 给定 id 对应的文字外观资源 ID
- */
- public static int getTexAppearanceResource(int id) {
- /**
- * HACKME: 修复在共享偏好中存储资源 ID 的 bug。
- * 在某些情况下,id 可能大于资源数组的长度,在这种情况下,
- * 返回 {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
- */
- if (id >= TEXTAPPEARANCE_RESOURCES.length) {
- return BG_DEFAULT_FONT_SIZE;
- }
- return TEXTAPPEARANCE_RESOURCES[id];
- }
-
- /**
- * 获取文字外观资源 ID 数组的长度
- *
- * @return 文字外观资源 ID 数组的长度
- */
- public static int getResourcesSize() {
- return TEXTAPPEARANCE_RESOURCES.length;
- }
-
- }
-}
diff --git a/other/07_陈七源_实践总结报告.docx b/other/07_陈七源_实践总结报告.docx
deleted file mode 100644
index 9d881b3..0000000
Binary files a/other/07_陈七源_实践总结报告.docx and /dev/null differ
diff --git a/other/08_演示录屏.mp4 b/other/08_演示录屏.mp4
deleted file mode 100644
index 655fa2c..0000000
Binary files a/other/08_演示录屏.mp4 and /dev/null differ
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/src/src.zip b/src/src.zip
deleted file mode 100644
index 21a12ad..0000000
Binary files a/src/src.zip and /dev/null differ
diff --git a/测试.txt b/测试.txt
new file mode 100644
index 0000000..4d280d3
--- /dev/null
+++ b/测试.txt
@@ -0,0 +1 @@
+测试1
\ No newline at end of file