Compare commits

..

6 Commits

Binary file not shown.

Binary file not shown.

@ -26,12 +26,9 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
public class Contact { public class Contact {
// 联系人缓存,用于存储已查询过的联系人信息
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact"; private static final String TAG = "Contact";
// 查询联系人的条件语句使用PHONE_NUMBERS_EQUAL函数进行号码匹配
// 并且限定数据类型为电话号码同时要求所属的RAW_CONTACT_ID在phone_lookup表中min_match字段为'+'的记录中
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
@ -39,23 +36,17 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
// 获取联系人信息的方法
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 如果联系人缓存为空则创建一个新的HashMap对象
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 如果联系人缓存中已存在该号码对应的联系人信息,则直接返回缓存中的信息
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 使用PhoneNumberUtils工具类将给定的号码转换为标准化的号码
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人信息
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME },
@ -63,11 +54,9 @@ public class Contact {
new String[] { phoneNumber }, new String[] { phoneNumber },
null); null);
// 如果查询结果不为空且有数据,则处理结果并返回联系人姓名
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
String name = cursor.getString(0); String name = cursor.getString(0);
// 将查询到的联系人信息存入缓存中
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {

@ -17,246 +17,234 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
public class Notes { public class Notes {
// 常量ContentProvider的authority
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes";
// 常量日志输出时的tag
public static final String TAG = "Notes"; public static final String TAG = "Notes";
// 常量:笔记类型
public static final int TYPE_NOTE = 0; public static final int TYPE_NOTE = 0;
// 常量:文件夹类型
public static final int TYPE_FOLDER = 1; public static final int TYPE_FOLDER = 1;
// 常量:系统类型
public static final int TYPE_SYSTEM = 2; public static final int TYPE_SYSTEM = 2;
/** /**
* * Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER} * {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER} * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_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_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3;
// 常量intent传递的提醒日期extra的key
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
// 常量intent传递的背景颜色id extra的key
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
// 常量intent传递的widget id extra的key
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
// 常量intent传递的widget type extra的key
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
// 常量intent传递的文件夹id extra的key
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
// 常量intent传递的通话日期extra的key
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
// 常量无效的widget类型
public static final int TYPE_WIDGET_INVALIDE = -1; public static final int TYPE_WIDGET_INVALIDE = -1;
// 常量2x2的widget类型
public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_2X = 0;
// 常量4x4的widget类型
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants { public static class DataConstants {
// 常量笔记的MIME type
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
// 常量通话记录的MIME type
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
} }
/** /**
* Uri * Uri to query all notes and folders
*/ */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/** /**
* Uri * Uri to query data
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns { public interface NoteColumns {
/** /**
* ID * The unique ID for a row
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* ID * The parent's id for note or folder
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
/** /**
* * Created data for note or folder
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* * Latest modified date
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* * Alert date
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";
/** /**
* * Folder's name or text content of note
* <P> TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
/** /**
* widget id * Note's widget id
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
/** /**
* widget * Note's widget type
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
/** /**
* id * Note's background color's id
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";
/** /**
* * For text note, it doesn't has attachment, for multi-media
* <P> INTEGER </P> * note, it has at least one attachment
* <P> Type: INTEGER </P>
*/ */
public static final String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment";
/** /**
* * Folder's count of notes
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";
/** /**
* * The file type: folder or note
* <P> INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";
/** /**
* ID * The last sync id
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
/** /**
* * Sign to indicate local modified or not
* <P> INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
/** /**
* ID * Original parent id before moving into temporary folder
* <P> INTEGER </P> * <P> Type : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/** /**
* Gtask ID * The gtask id
* <P> TEXT </P> * <P> Type : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
/** /**
* * The version code
* <P> INTEGER (long) </P> * <P> Type : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
public interface DataColumns { public interface DataColumns {
/** /**
* ID * The unique ID for a row
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* MIME * The MIME type of the item represented by this row.
* <P> TEXT </P> * <P> Type: Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";
/** /**
* ID * The reference id to note that this data belongs to
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";
/** /**
* * Created data for note or folder
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* * Latest modified date
* <P> INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* * Data's content
* <P> TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String CONTENT = "content"; public static final String CONTENT = "content";
/** /**
* {@link #MIMETYPE} * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> INTEGER </P> * integer data type
* <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static final String DATA1 = "data1";
/** /**
* {@link #MIMETYPE} * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> INTEGER </P> * integer data type
* <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static final String DATA2 = "data2";
/** /**
* {@link #MIMETYPE}TEXT * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> TEXT </P> * TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static final String DATA3 = "data3";
/** /**
* {@link #MIMETYPE}TEXT * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> TEXT </P> * TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA4 = "data4";
/** /**
* {@link #MIMETYPE}TEXT * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> TEXT </P> * TEXT data type
* <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* * Mode to indicate the text in check list mode or not
* <P> : Integer 1:check list mode 0: normal mode </P> * <P> Type: Integer 1:check list mode 0: normal mode </P>
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1;
@ -287,6 +275,5 @@ public class Notes {
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/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"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}//电话内容的数据结构
} }
}

@ -16,23 +16,23 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentValues;//就是用于保存一些数据string boolean byte double float int long short ...)信息,这些信息可以被数据库操作时使用。 import android.content.ContentValues;
import android.content.Context;//加载和访问资源。android中主要是这两个功能但是这里具体不清楚 import android.content.Context;
import android.database.sqlite.SQLiteDatabase;//主要提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query()。配合content.values import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;//用来管理数据的创建和版本更新 import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
//数据库操作用SQLOpenhelper,对一些note和文件进行数据库的操作比如删除文件后将文件里的note也相应删除
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
public interface TABLE { //接口分成note和data在后面的程序里分别使用过 public interface TABLE {
public static final String NOTE = "note"; public static final String NOTE = "note";
public static final String DATA = "data"; public static final String DATA = "data";
@ -61,7 +61,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";//数据库中需要存储的项目的名称,就相当于创建一个表格的表头的内容。 ")";
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
@ -76,11 +76,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";//和上面的功能一样,主要是存储的项目不同 ")";
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";//存储便签编号的一个数据表格 TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/** /**
* Increase folder's note count when move note to the folder * Increase folder's note count when move note to the folder
@ -92,7 +92,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";//在文件夹中移入一个Note之后需要更改的数据的表格。 " END";
/** /**
* Decrease folder's note count when move note from folder * Decrease folder's note count when move note from folder
@ -105,7 +105,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";//在文件夹中移出一个Note之后需要更改的数据的表格。 " END";
/** /**
* Increase folder's note count when insert new note to the folder * Increase folder's note count when insert new note to the folder
@ -117,7 +117,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";//在文件夹中插入一个Note之后需要更改的数据的表格。 " END";
/** /**
* Decrease folder's note count when delete note from the folder * Decrease folder's note count when delete note from the folder
@ -130,7 +130,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";//在文件夹中删除一个Note之后需要更改的数据的表格。 " END";
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} * Update note's content when insert data with type {@link DataConstants#NOTE}
@ -143,7 +143,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//在文件夹中对一个Note导入新的数据之后需要更改的数据的表格。 " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed * Update note's content when data with {@link DataConstants#NOTE} type has changed
@ -156,7 +156,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被修改后需要更改的数据的表格。 " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted * Update note's content when data with {@link DataConstants#NOTE} type has deleted
@ -169,7 +169,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" + " SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被删除后需要更改的数据的表格。 " END";
/** /**
* Delete datas belong to note which has been deleted * Delete datas belong to note which has been deleted
@ -180,7 +180,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" BEGIN" + " BEGIN" +
" DELETE FROM " + TABLE.DATA + " DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的便签的数据后需要更改的数据的表格。 " END";
/** /**
* Delete notes belong to folder which has been deleted * Delete notes belong to folder which has been deleted
@ -191,7 +191,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" BEGIN" + " BEGIN" +
" DELETE FROM " + TABLE.NOTE + " DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的文件夹的便签后需要更改的数据的表格。 " END";
/** /**
* Move notes belong to folder which has been moved to trash folder * Move notes belong to folder which has been moved to trash folder
@ -204,18 +204,18 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//还原垃圾桶中便签后需要更改的数据的表格。 " END";
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
}//构造函数,传入数据库的名称和版本 }
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
createSystemFolder(db); createSystemFolder(db);
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
}//创建表格(用来存储标签属性) }
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
@ -233,8 +233,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}//execSQL是数据库操作的API主要是更改行为的SQL语句。 }
//在这里主要是用来重新创建上述定义的表格用的,先删除原来有的数据库的触发器再重新创建新的数据库
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -269,14 +268,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
}//创建几个系统文件夹 }
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
}//创建表格(用来存储标签内容) }
private void reCreateDataTableTriggers(SQLiteDatabase db) { 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_insert");
@ -286,22 +285,20 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); 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_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}//同上面的execSQL }
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
} }
return mInstance; return mInstance;
}//解决同一时刻只能有一个线程执行. }
//在写程序库代码时,有时有一个类需要被所有的其它类使用,
//但又要求这个类只能被实例化一次,是个服务类,定义一次,其它类使用同一个这个类的实例
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
}//实现两个表格(上面创建的两个表格) }
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@ -334,14 +331,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + "fails");
} }
}//数据库版本的更新(数据库内容的更改) }
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
}//更新到V2版本 }
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // drop unused triggers
@ -356,10 +353,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
}//更新到V3版本 }
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");
}//更新到V4版本,但是不知道V2、V3、V4是什么意思 }
} }

@ -16,6 +16,7 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.app.SearchManager; import android.app.SearchManager;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentUris; import android.content.ContentUris;
@ -32,15 +33,9 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
//ContentProvider提供的方法
//query查询
//insert插入
//update更新
//delete删除
//getType得到数据类型
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// UriMatcher用于匹配Uri
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
@ -56,9 +51,7 @@ public class NotesProvider extends ContentProvider {
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6;
static { static {
// 创建UriMatcher时调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 把需要匹配Uri路径全部给注册上
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -72,7 +65,6 @@ public class NotesProvider extends ContentProvider {
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * 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. * we will trim '\n' and white space in order to show more information.
*/ */
// 声明 NOTES_SEARCH_PROJECTION
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + 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_1 + ","
@ -80,7 +72,7 @@ public class NotesProvider extends ContentProvider {
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 声明NOTES_SNIPPET_SEARCH_QUERY
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
@ -88,24 +80,18 @@ public class NotesProvider extends ContentProvider {
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
// Context只有在onCreate()中才被初始化
// 对mHelper进行实例化
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
@Override @Override
// 查询uri在数据库中对应的位置
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 匹配查找uri
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 对于不同的匹配值,在数据库中查找相应的条目
case URI_NOTE: case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
@ -127,7 +113,6 @@ public class NotesProvider extends ContentProvider {
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
// 不合法的参数异常
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
@ -135,8 +120,6 @@ public class NotesProvider extends ContentProvider {
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
// getPathSegments()方法得到一个String的List
// 在uri.getPathSegments().get(1)为第2个元素
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
@ -156,7 +139,6 @@ public class NotesProvider extends ContentProvider {
} }
break; break;
default: default:
// 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) { if (c != null) {
@ -166,17 +148,13 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 插入一个uri
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 新增一个条目
case URI_NOTE: case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
// 如果存在查找NOTE_ID
case URI_DATA: case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
@ -189,7 +167,6 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri // Notify the note uri
// notifyChange获得一个ContextResolver对象并且更新里面的内容
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
@ -201,17 +178,13 @@ public class NotesProvider extends ContentProvider {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
// 返回插入的uri的路径
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
@Override @Override
// 删除一个uri
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
//Uri代表要操作的数据Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示。
int count = 0; int count = 0;
String id = null; String id = null;
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
@ -255,7 +228,6 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 更新一个uri
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
@ -295,12 +267,10 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
// 将字符串解析成规定格式
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
//增加一个noteVersion
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -323,7 +293,6 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString); sql.append(selectString);
} }
// execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }

@ -26,54 +26,29 @@
public class MetaData extends Task { public class MetaData extends Task {
/*
* TAG
* getSimpleName ()
*/
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
private String mRelatedGid = null; private String mRelatedGid = null;
/*
* public void setMeta(String gid, JSONObject metaInfo) {
* JSONObjectput ()TasksetNotes ()setName ()
*
*/
public void setMeta(String gid, JSONObject metaInfo)
{
//对函数块进行注释
try { try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
/*
* metaInfojsonobject
*/
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
/*
*
*/
} }
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/*
* Gid
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/*
*
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/*
* 使json
* TasksetContentByRemoteJSON ()
*
*/
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
@ -87,28 +62,21 @@
} }
} }
} }
/*
* 使json
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called // this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
/*
* json
*/
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
/*
*
*/
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");
} }
} }

@ -20,37 +20,32 @@
import org.json.JSONObject; import org.json.JSONObject;
/*
*
* abstract
*/
public abstract class Node { public abstract class Node {
//定义了各种用于表征同步状态的常量 public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_NONE = 0;// 本地和云端都无可更新内容(即本地和云端内容一致)
public static final int SYNC_ACTION_ADD_REMOTE = 1;// 需要在远程云端增加内容 public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2;// 需要在本地增加内容 public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;// 需要在远程云端删除内容 public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;// 需要在本地删除内容 public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;// 需要将本地内容更新到远程云端 public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 需要将远程云端内容更新到本地 public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 同步出现冲突 public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;// 同步出现错误 public static final int SYNC_ACTION_ERROR = 8;
private String mGid; private String mGid;
private String mName; private String mName;
private long mLastModified;//记录最后一次修改时间 private long mLastModified;
private boolean mDeleted;//表征是否被删除 private boolean mDeleted;
public Node() { public Node() {
mGid = null; mGid = null;

@ -35,36 +35,16 @@
import org.json.JSONObject; import org.json.JSONObject;
/*
* Description便sqlnotedatanote
* SqlData
*/
public class SqlData { public class SqlData {
/*
* TAG
* getSimpleName ()
*/
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
private static final int INVALID_ID = -99999;//为mDataId置初始值-99999 private static final int INVALID_ID = -99999;
/**
* NotesDataColumn
*/
// 集合了interface DataColumns中所有SF常量
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
/**
* sql5
*/
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
@ -76,7 +56,7 @@
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
//判断是否直接用Content生成是为true否则为false
private boolean mIsCreate; private boolean mIsCreate;
private long mDataId; private long mDataId;
@ -91,15 +71,10 @@
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
mDataId = INVALID_ID;//mDataId置初始值-99999 mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE; mDataMimeType = DataConstants.NOTE;
mDataContent = ""; mDataContent = "";
mDataContentData1 = 0; mDataContentData1 = 0;
@ -107,12 +82,6 @@
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -120,10 +89,6 @@
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/*
*
*
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -132,12 +97,7 @@
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/*
*
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
//如果传入的JSONObject对象中有DataColumns.ID这一项则设置否则设为INVALID_ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId);
@ -170,16 +130,11 @@
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/*
*
*/
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
return null; return null;
} }
//创建JSONObject对象。并将相关数据放入其中并返回。
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId); js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType); js.put(DataColumns.MIME_TYPE, mDataMimeType);
@ -189,9 +144,6 @@
return js; return js;
} }
/*
* commit
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
@ -231,9 +183,6 @@
mIsCreate = false; mIsCreate = false;
} }
/*
* id
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }

@ -38,21 +38,11 @@
import java.util.ArrayList; import java.util.ArrayList;
/*
* Description便sqldatanotedata
* SqlDataSqlNote
*/
public class SqlNote { public class SqlNote {
/*
* TAG
* getSimpleName ()
*/
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
// 集合了interface NoteColumns中所有SF常量17个
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -62,7 +52,6 @@
NoteColumns.VERSION NoteColumns.VERSION
}; };
//以下设置17个列的编号
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
@ -97,7 +86,6 @@
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
//一下定义了17个内部的变量其中12个可以由content中获得5个需要初始化为0或者new
private Context mContext; private Context mContext;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
@ -134,11 +122,6 @@
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
/*
*
* mIsCreate
*/
//构造函数只有context对所有的变量进行初始化
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -146,9 +129,9 @@
mId = INVALID_ID; mId = INVALID_ID;
mAlertDate = 0; mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();//调用系统函数获得创建时间 mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0; mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();//最后一次修改时间初始化为创建时间 mModifiedDate = System.currentTimeMillis();
mParentId = 0; mParentId = 0;
mSnippet = ""; mSnippet = "";
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE;
@ -160,29 +143,17 @@
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/*
*
* mIsCreate
*/
//构造函数有context和一个数据库的cursor多数变量通过cursor指向的一条记录直接进行初始化
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
loadFromCursor(c); loadFromCursor(c);
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
//
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/*
*
* mIsCreate
*/
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -195,20 +166,16 @@
} }
/*
* id
*/
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(id) String.valueOf(id)
}, null);//通过id获得对应的ContentResolver中的cursor }, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();
loadFromCursor(c);//然后加载数据进行初始化,这样函数 loadFromCursor(c);
//SqlNote(Context context, long id)与SqlNote(Context context, long id)的实现方式基本相同
} else { } else {
Log.w(TAG, "loadFromCursor: cursor = null"); Log.w(TAG, "loadFromCursor: cursor = null");
} }
@ -218,11 +185,7 @@
} }
} }
/*
*
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
//直接从一条记录中的获得以下变量的初始值
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
@ -237,9 +200,6 @@
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/*
* content
*/
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
@ -266,9 +226,6 @@
} }
} }
/*
* content
*/
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -310,6 +267,7 @@
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
} }
mBgColorId = bgColorId; mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) { if (mIsCreate || mCreatedDate != createDate) {
@ -401,9 +359,6 @@
return true; return true;
} }
/*
* contentnote
*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -414,7 +369,7 @@
} }
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
if (mType == Notes.TYPE_NOTE) {//类型为note时 if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
@ -437,7 +392,7 @@
} }
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为文件夹或者 } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet);
@ -452,66 +407,39 @@
return null; return null;
} }
/*
* idid
*/
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
/*
* idGtaskid
*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/*
* idid
*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/*
*
*/
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
/*
* id
*/
public long getId() { public long getId() {
return mId; return mId;
} }
/*
* idid
*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/*
* 便
*/
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
/*
* 便
*/
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
/*
* commit
*/
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
@ -530,7 +458,7 @@
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {//直接使用sqldata中的实现 for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1); sqlData.commit(mId, false, -1);
} }
} }
@ -542,7 +470,7 @@
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) {
mVersion ++; mVersion ++;
int result = 0; int result = 0;
if (!validateVersion) {//构造字符串 if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
@ -575,4 +503,3 @@
mIsCreate = false; mIsCreate = false;
} }
} }

@ -32,26 +32,25 @@
import org.json.JSONObject; import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;//是否完成 private boolean mCompleted;
private String mNotes; private String mNotes;
private JSONObject mMetaInfo;//将在实例中存储数据的类型 private JSONObject mMetaInfo;
private Task mPriorSibling;//对应的优先兄弟Task的指针待完善 private Task mPriorSibling;
private TaskList mParent;//所在的任务列表的指针 private TaskList mParent;
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
mNotes = null; mNotes = null;
mPriorSibling = null;//TaskList中当前Task前面的Task的指针 mPriorSibling = null;
mParent = null;//当前Task所在的TaskList mParent = null;
mMetaInfo = null; mMetaInfo = null;
} }
@ -81,18 +80,14 @@
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id // parent_id
if (mParent!= null) {
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
}
// dest_parent_type // dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id // list_id
if (mParent!= null) {
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
}
// prior_sibling_id // prior_sibling_id
if (mPriorSibling != null) { if (mPriorSibling != null) {
@ -180,7 +175,7 @@
} }
} }
public void setContentByLocalJSON(JSONObject js) { //<2F><>metadata<74><61><EFBFBD><EFBFBD>ʵʩ public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");

@ -30,13 +30,12 @@
import java.util.ArrayList; import java.util.ArrayList;
public class TaskList extends Node { public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();//tag标记 private static final String TAG = TaskList.class.getSimpleName();
private int mIndex;//当前TaskList的指针 private int mIndex;
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList private ArrayList<Task> mChildren;
public TaskList() { public TaskList() {
super(); super();
@ -44,10 +43,6 @@
mIndex = 1; mIndex = 1;
} }
/* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getCreateAction(int)
* JSONObject
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -63,7 +58,7 @@
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta // entity_delta
JSONObject entity = new JSONObject();//entity实体 JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
@ -79,10 +74,6 @@
return js; return js;
} }
/* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getUpdateAction(int)
* JSONObject
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -225,19 +216,10 @@
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
* @return
* TaskListmChildren
*/
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
/**
* @param task
* @return
*
*/
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
@ -247,19 +229,11 @@
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
//注意每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改
//,接下来几个函数都有相关操作
} }
} }
return ret; return ret;
} }
/**
* @param task
* @param index
* @return
*
*/
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
@ -286,11 +260,6 @@
return true; return true;
} }
/**
* @param task
* @return
* TaskListTask
*/
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task);
@ -312,12 +281,6 @@
return ret; return ret;
} }
/**
* @param task
* @param index
* @return
* TaskListTaskindex
*/
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
@ -334,14 +297,8 @@
if (pos == index) if (pos == index)
return true; return true;
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
//利用已实现好的功能完成当下功能;
} }
/**
* @param gid
* @return
* gidTask
*/
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
@ -352,20 +309,10 @@
return null; return null;
} }
/**
* @param task
* @return
* Taskindex
*/
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
/**
* @param index
* @return
* indexTask
*/
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
@ -374,13 +321,8 @@
return mChildren.get(index); return mChildren.get(index);
} }
/**
* @param gid
* @return
* gidTask
*/
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {//一种常见的ArrayList的遍历方法四种见精读笔记 for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
return task; return task;
} }

@ -14,28 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
/*
* Description便
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/*
* serialVersionUIDjava
* serialVersionUID
*/
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
/*
* JAVA使superthis.
* new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
@ -44,4 +31,3 @@
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

@ -14,29 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
/*
* Description便
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
/*
* serialVersionUIDjava
* serialVersionUID
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
/*
* JAVA使superthis.
* new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
@ -45,4 +31,3 @@
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

@ -29,16 +29,8 @@
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/*GTask
*
* private void showNotification(int tickerId, String content)
* protected Integer doInBackground(Void... unused) 线
* protected void onProgressUpdate(String... progress) 使 线
* protected void onPostExecute(Integer result) Handler UI使doInBackground UI
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
public interface OnCompleteListener { public interface OnCompleteListener {
@ -65,7 +57,7 @@
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
public void publishProgess(String message) { // 发布进度单位系统将会调用onProgressUpdate()方法更新这些值 public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
@ -74,43 +66,43 @@
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS; // 调用系统自带灯光 notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL; // 点击清除按钮或点击通知后会自动消失 notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent; //一个描述了想要启动一个Activity、Broadcast或是Service的意图 PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); //如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象 NotesPreferenceActivity.class), 0);
} else { } else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); //如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象 NotesListActivity.class), 0);
} }
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息 mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); //利用getString,将把 NotesPreferenceActivity.getSyncAccountName(mContext))的字符串内容传进sync_progress_login中 .getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); //进行后台同步具体操作 return mTaskManager.sync(mContext, this);
} }
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) { //instanceof 判断mContext是否是GTaskSyncService的实例 if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
@Override @Override
protected void onPostExecute(Integer result) { //用于在执行完后台任务后更新UI,显示结果 protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); //设置最新同步的时间 NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
@ -118,11 +110,11 @@
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} //几种不同情况下的结果显示 }
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { //这里好像是方法内的一个线程,但是并不太懂什么意思 new Thread(new Runnable() {
public void run() { //完成后的操作使用onComplete()将所有值都重新初始化,相当于完成一次操作 public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }
}).start(); }).start();

@ -61,15 +61,10 @@
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/*
* GTASKGTASK
* 使accountManager JSONObject HttpParams authToken Gid
*/
public class GTaskClient { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
private static final String GTASK_URL = "https://mail.google.com/tasks/"; //这个是指定的URL 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_GET_URL = "https://mail.google.com/tasks/ig";
@ -107,10 +102,6 @@
mUpdateArray = null; mUpdateArray = null;
} }
/*
* 使 getInstance()
* mInstance
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -118,50 +109,42 @@
return mInstance; return mInstance;
} }
/*Activity
*
* 使URL使URL
* truefalse
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // we suppose that the cookie would expire after 5 minutes
// then we need to re-login // then we need to re-login
//判断距离最后一次登录操作是否超过5分钟
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// need to re-login after account switch 重新登录操作 // need to re-login after account switch
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
//如果没超过时间,则不需要重新登录
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in");
return true; return true;
} }
mLastLoginTime = System.currentTimeMillis();//更新最后登录时间,改为系统当前的时间 mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false);//判断是否登录到谷歌账户 String authToken = loginGoogleAccount(activity, false);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
// login with custom domain if necessary // login with custom domain if necessary
//尝试使用用户自己的域名登录 if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //将用户账号名改为统一格式(小写)后判断是否为一个谷歌账号地址
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; //设置用户对应的getUrl mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig"; //设置用户对应的postUrl mPostUrl = url.toString() + "r/ig";
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true; mLoggedin = true;
@ -169,7 +152,6 @@
} }
// try to login with google official url // try to login with google official url
//如果用户账户无法登录则使用谷歌官方的URI进行登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -182,15 +164,10 @@
return true; return true;
} }
/*
* 使
* 使AccountManager
*
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; //令牌,是登录操作保证安全性的一个方法 String authToken;
AccountManager accountManager = AccountManager.get(activity);//AccountManager这个类给用户提供了集中注册账号的接口 AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
@ -199,7 +176,6 @@
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
//遍历获得的accounts信息寻找已经记录过的账户信息
for (Account a : accounts) { for (Account a : accounts) {
if (a.name.equals(accountName)) { if (a.name.equals(accountName)) {
account = a; account = a;
@ -214,13 +190,11 @@
} }
// get the token now // get the token now
//获取选中账号的令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
//如果是invalidateToken那么需要调用invalidateAuthToken(String, String)方法废除这个无效token
if (invalidateToken) { if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false);
@ -233,12 +207,10 @@
return authToken; return authToken;
} }
//尝试登陆Gtask这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of authTokedate, now let's invalidate the // maybe the auth token is out of date, now let's invalidate the
// token and try again // token and try again
//删除过一个无效的authToken申请一个新的后再次尝试登陆
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
@ -253,27 +225,25 @@
return true; return true;
} }
//实现登录GTask的具体操作
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; //socket是一种通信连接实现数据的交换的端口 int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams(); //实例化一个新的HTTP参数类 HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); //设置本地cookie BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // login gtask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; //设置登录的url String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); //通过登录的uri实例化网页上资源的查找 HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the cookie now // get the cookie now
//获取CookieStore里存放的cookie,看如果存有“GTL(不知道什么意思)”则说明有验证成功的有效的cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -286,7 +256,6 @@
} }
// get the client version // get the client version
//获取client的内容具体操作是在返回的Content中截取从_setup(开始到)}</script>中间的字符串内容也就是gtask_url的内容
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -315,10 +284,6 @@
return mActionId++; return mActionId++;
} }
/*
* 使HttpPost
* httpPost
*/
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -326,28 +291,24 @@
return httpPost; return httpPost;
} }
/*URL
* 使getContentEncoding()
*
*/
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) {//通过URL得到HttpEntity对象如果不为空则使用getContent方法创建一个流将数据从网络都过来 if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//GZIP是使用DEFLATE进行压缩数据的另一个压缩库 if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//DEFLATE是一个无专利的压缩算法它可以实现无损数据压缩 } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater); input = new InflaterInputStream(entity.getContent(), inflater);
} }
try { try {
InputStreamReader isr = new InputStreamReader(input); InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);//是一个包装类,它可以包装字符流,将字符流放入缓存里,先把字符读到缓存里,到缓存满了时候,再读入内存,是为了提供读的效率而设计的 BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
while (true) { while (true) {
@ -362,28 +323,20 @@
} }
} }
/*JSON
* jsonjs
* UrlEncodedFormEntity entityhttpPost.setEntity(entity)jshttpPost
* 使getResponseContent
* json
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {//未登录 if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
//实例化一个httpPost的对象用来向服务器传输数据在这里就是发送请求而请求的内容在js里
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
try { try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); //UrlEncodedFormEntity()的形式比较单一,是普通的键值对 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
// execute the post // execute the post
//执行这个请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); return new JSONObject(jsString);
@ -407,12 +360,6 @@
} }
} }
/*
* .gtask.data.TaskTask
* jsonTask,jsPost
* postRequest
* 使task.setGidtasknew_ID
*/
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -439,9 +386,6 @@
} }
} }
/*
* createTasktasklistgid
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -468,11 +412,6 @@
} }
} }
/*
*
* 使JSONObject使jsPost.putPutUpdateArrayClientVersion
* 使postRequestjspost,
*/
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
@ -494,10 +433,6 @@
} }
} }
/*
*
* commitUpdate()
*/
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // too many update items may result in an error
@ -512,12 +447,6 @@
} }
} }
/*
* task,tasktask
* getGidtaskgid
* JSONObject.put(String name, Object value)task
* postRequest
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -534,17 +463,15 @@
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // put prioring_sibing_id only if moving within the tasklist and
// it is not the first one // it is not the first one
//设置优先级ID只有当移动是发生在文件中
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); //设置移动前所属列表 action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); //设置当前所属列表 action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action);
//最后将ACTION_LIST加入到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
@ -559,11 +486,6 @@
} }
} }
/*
*
* JSON
* 使postRequest
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -572,7 +494,7 @@
// action_list // action_list
node.setDeleted(true); node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId())); //这里会获取到删除操作的ID加入到actionLiast中 actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
@ -587,11 +509,6 @@
} }
} }
/*
*
* GetURI使getResponseContent
* "_setup(")}</script>GTASK_JSON_LISTS
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -604,7 +521,6 @@
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the task list // get the task list
//筛选工作把筛选出的字符串放入jsString
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -615,7 +531,6 @@
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end);
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString);
//获取GTASK_JSON_LISTS
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -632,9 +547,6 @@
} }
} }
/*
* TASKListgid,
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -646,7 +558,7 @@
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); //这里设置为传入的listGid action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
@ -667,7 +579,6 @@
return mAccount; return mAccount;
} }
//重置更新的内容
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
@ -47,75 +48,72 @@
import java.util.Map; import java.util.Map;
public class GTaskManager { public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0; public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1; public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2; public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3; public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
private Activity mActivity; private Activity mActivity;
private Context mContext; private Context mContext;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
private boolean mSyncing; private boolean mSyncing;
private boolean mCancelled; private boolean mCancelled;
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList; private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
private GTaskManager() { //对象初始化函数 private GTaskManager() {
mSyncing = false; //正在同步,flase代表未执行 mSyncing = false;
mCancelled = false; //全局标识flase代表可以执行 mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>(); //<>代表Java的泛型,就是创建一个用类型作为参数的类。 mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>(); mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>(); mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null; mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>(); mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>(); //GoogleID to NodeID?? mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>(); //NodeID to GoogleID???通过hashmap散列表建立映射 mNidToGid = new HashMap<Long, String>();
} }
/** public static synchronized GTaskManager getInstance() {
* synchronized线
*
* @author TTS
* @return GtaskManger
*/
public static synchronized GTaskManager getInstance() { //可能运行在多线程环境下,使用语言级同步--synchronized
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
} }
return mInstance; return mInstance;
} }
/**
* synchronized线
* @author TTS
* @param activity
*/
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
/** public int sync(Context context, GTaskASyncTask asyncTask) {
*
*
* @author TTS
* @param context-----
* @param asyncTask-------
* @return int
*/
public int sync(Context context, GTaskASyncTask asyncTask) { //核心函数
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); //创建日志文件调试信息debug Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
mContext = context; mContext = context;
@ -130,8 +128,8 @@
mNidToGid.clear(); mNidToGid.clear();
try { try {
GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例,client--客户机 GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); //JSONArray类型reset即置为NULL client.resetUpdateArray();
// login google task // login google task
if (!mCancelled) { if (!mCancelled) {
@ -142,15 +140,15 @@
// get the task list from google // get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList initGTaskList();
// do content sync work // do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent(); syncContent();
} catch (NetworkFailureException e) { //分为两种异常,此类异常为网络异常 } catch (NetworkFailureException e) {
Log.e(TAG, e.toString()); //创建日志文件调试信息error Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR; return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { //此类异常为操作异常 } catch (ActionFailureException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} catch (Exception e) { } catch (Exception e) {
@ -170,41 +168,32 @@
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
/**
*GtaskListGoogleJSONtasklistTaskList
*mMetaListmGTaskListHashMapmGTaskHashMap
*@author TTS
*@exception NetworkFailureException
*@return void
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例client应指远端客户机 GTaskClient client = GTaskClient.getInstance();
try { try {
//Json对象是Name Value对(即子元素)的无序集合相当于一个Map对象。JsonObject类是bantouyan-json库对Json对象的抽象提供操纵Json对象的各种方法。 JSONArray jsTaskLists = client.getTaskLists();
//其格式为{"key1":value1,"key2",value2....};key 必须是字符串。
//因为ajax请求不刷新页面但配合js可以实现局部刷新因此json常常被用来作为异步请求的返回对象使用。
JSONArray jsTaskLists = client.getTaskLists(); //原注释为get task list------lists
// init meta list first // init meta list first
mMetaList = null; //TaskList类型 mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); //JSONObject与JSONArray一个为对象一个为数组。此处取出单个JASONObject JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { if (name
mMetaList = new TaskList(); //MetaList意为元表,Tasklist类型此处为初始化 .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList.setContentByRemoteJSON(object); //将JSON中部分数据复制到自己定义的对象中相对应的数据name->mname... mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data // load meta data
JSONArray jsMetas = client.getTaskList(gid); //原注释为get action_list------list JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData(); //继承自Node MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object); metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) { //if not worth to savemetadata将不加入mMetaList if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData); mMetaList.addChildTask(metaData);
if (metaData.getGid() != null) { if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData); mMetaHashMap.put(metaData.getRelatedGid(), metaData);
@ -225,16 +214,16 @@
// init task list // init task list
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); //通过getString函数传入本地某个标志数据的名称获取其在远端的名称。 String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) { + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList(); //继承自Node TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object); tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); //为什么加两遍??? mGTaskHashMap.put(gid, tasklist);
// load tasks // load tasks
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
@ -258,18 +247,13 @@
} }
} }
/** private void syncContent() throws NetworkFailureException {
*
* @throws NetworkFailureException
* @return
*/
private void syncContent() throws NetworkFailureException { //本地内容同步操作
int syncType; int syncType;
Cursor c = null; //数据库指针 Cursor c = null;
String gid; //GoogleID?? String gid;
Node node; //Node包含Sync_Action的不同类型 Node node;
mLocalDeleteIdMap.clear(); //HashSet<Long>类型 mLocalDeleteIdMap.clear();
if (mCancelled) { if (mCancelled) {
return; return;
@ -317,8 +301,8 @@
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); //通过hashmap建立联系 mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); //通过hashmap建立联系 mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
@ -343,14 +327,14 @@
} }
// go through remaining items // go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); //Iterator迭代器 Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
node = entry.getValue(); node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
} }
// mCancelled can be set by another thread, so we neet to check one by //thread----线程 // mCancelled can be set by another thread, so we neet to check one by
// one // one
// clear local delete table // clear local delete table
if (!mCancelled) { if (!mCancelled) {
@ -367,11 +351,6 @@
} }
/**
*
* @author TTS
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -497,14 +476,6 @@
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
/**
* syncTypeaddLocalNodeaddRemoteNodedeleteNodeupdateLocalNodeupdateRemoteNode
* @author TTS
* @param syncType
* @param node
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -551,12 +522,6 @@
} }
} }
/**
* Node
* @author TTS
* @param node
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -631,15 +596,6 @@
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
/**
* updatenode
* @author TTS
* @param node
* ----
* @param c
* ----Cursor
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -663,22 +619,12 @@
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
/**
* Node
* updateRemoteMeta
* @author TTS
* @param node
* ----
* @param c
* --Cursor
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote = new SqlNote(mContext, c); //从本地mContext中获取内容 SqlNote sqlNote = new SqlNote(mContext, c);
Node n; Node n;
// update remotely // update remotely
@ -688,12 +634,11 @@
String parentGid = mNidToGid.get(sqlNote.getParentId()); String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) { if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist"); //调试信息 Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task"); throw new ActionFailureException("cannot add remote task");
} }
mGTaskListHashMap.get(parentGid).addChildTask(task); //在本地生成的GTaskList中增加子结点 mGTaskListHashMap.get(parentGid).addChildTask(task);
//登录远程服务器创建Task
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
@ -711,7 +656,6 @@
else else
folderName += sqlNote.getSnippet(); folderName += sqlNote.getSnippet();
//iterator迭代器通过统一的接口迭代所有的map元素
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -743,20 +687,11 @@
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
// gid-id mapping //创建id间的映射 // gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
/**
* Nodemeta(updateRemoteMeta)
* @author TTS
* @param node
* ----
* @param c
* --Cursor
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -766,7 +701,7 @@
// update remotely // update remotely
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); //GTaskClient用途为从本地登陆远端服务器 GTaskClient.getInstance().addUpdateNode(node);
// update meta // update meta
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
@ -775,19 +710,15 @@
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = (Task) node; Task task = (Task) node;
TaskList preParentList = task.getParent(); TaskList preParentList = task.getParent();
//preParentList为通过node获取的父节点列表
String curParentGid = mNidToGid.get(sqlNote.getParentId()); String curParentGid = mNidToGid.get(sqlNote.getParentId());
//curParentGid为通过光标在数据库中找到sqlNote的mParentId再通过mNidToGid由long类型转为String类型的Gid
if (curParentGid == null) { if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist"); Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task"); throw new ActionFailureException("cannot update remote task");
} }
TaskList curParentList = mGTaskListHashMap.get(curParentGid); TaskList curParentList = mGTaskListHashMap.get(curParentGid);
//通过HashMap找到对应Gid的TaskList
if (preParentList != curParentList) { //????????????? if (preParentList != curParentList) {
preParentList.removeChildTask(task); preParentList.removeChildTask(task);
curParentList.addChildTask(task); curParentList.addChildTask(task);
GTaskClient.getInstance().moveTask(task, preParentList, curParentList); GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
@ -796,19 +727,9 @@
// clear local modified flag // clear local modified flag
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
//commit到本地数据库
sqlNote.commit(true); sqlNote.commit(true);
} }
/**
* meta meta----------
* @author TTS
* @param gid
* ---GoogleIDString
* @param sqlNote
* ---使SqlNote
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -825,18 +746,12 @@
} }
} }
/**
* syncID
* @author TTS
* @return void
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list //获取最近的(最晚的)gtask list // get the latest gtask list
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -847,16 +762,16 @@
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] { "(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC"); //query语句五个参数NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。new String[] {String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)}------为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE--------应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri }, NoteColumns.TYPE + " DESC");
if (c != null) { if (c != null) {
while (c.moveToNext()) { while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN); String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid); Node node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues(); //在ContentValues中创建键值对。准备通过contentResolver写入数据 ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified()); values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, //进行批量更改选择参数为NULL应该可以用insert替换参数分别为表名和需要更新的value对象。 mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null); c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else { } else {
Log.e(TAG, "something is missed"); Log.e(TAG, "something is missed");
@ -875,19 +790,10 @@
} }
} }
/**
* ,mAccount.name
* @author TTS
* @return String
*/
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
/**
* mCancelledtrue
* @author TTS
*/
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
@ -22,23 +23,6 @@
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
/*
* Service
*
* private void startSync()
* private void cancelSync()
* public void onCreate()
* public int onStartCommand(Intent intent, int flags, int startId) serviceserviceservice
* public void onLowMemory() serviceservice
* public IBinder onBind()
* public void sendBroadcast(String msg)
* public static void startSync(Activity activity)
* public static void cancelSync(Context context)
* public static boolean isSyncing()
* public static String getProgressString()
*/
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
@ -58,7 +42,6 @@
private static String mSyncProgress = ""; private static String mSyncProgress = "";
//开始一个同步的工作
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -69,11 +52,10 @@
} }
}); });
sendBroadcast(""); sendBroadcast("");
mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行 mSyncTask.execute();
} }
} }
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
@ -81,7 +63,7 @@
} }
@Override @Override
public void onCreate() { //初始化一个service public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
@ -90,7 +72,6 @@
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
//两种情况,开始同步或者取消同步
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync();
break; break;
@ -100,7 +81,7 @@
default: default:
break; break;
} }
return START_STICKY; //等待新的intent来是这个service继续运行 return START_STICKY;
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
@ -112,26 +93,26 @@
} }
} }
public IBinder onBind(Intent intent) { //不知道干吗用的 public IBinder onBind(Intent intent) {
return null; return null;
} }
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值 intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent); //发送这个通知 sendBroadcast(intent);
} }
public static void startSync(Activity activity) {//执行一个serviceservice的内容里的同步动作就是开始同步 public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent); activity.startService(intent);
} }
public static void cancelSync(Context context) {//执行一个serviceservice的内容里的同步动作就是取消同步 public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);

@ -1,21 +1,43 @@
/*
* 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; 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;
import android.content.ContentProviderOperation;//批量的更新、插入、删除数据。
import android.content.ContentProviderResult;//操作的结果
import android.content.ContentUris;//用于添加和获取Uri后面的ID
import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制
import android.content.Context;//需要用该类来弄清楚调用者的实例
import android.content.OperationApplicationException;//操作应用程序容错
import android.net.Uri;//表示待操作的数据
import android.os.RemoteException;//远程容错
import android.util.Log;//输出日志,比如说出错、警告等
public class Note { public class Note {
// private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
ContentValues mNoteDiffValues;//
private NoteData mNoteData; private NoteData mNoteData;
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * Create a new note id for adding a new note to databases
*/ */
@ -27,17 +49,16 @@ public class Note {
values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格 values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
//ContentResolver()主要是实现外部应用对ContentProvider中的数据
//进行添加、删除、修改和查询操作
long noteId = 0; long noteId = 0;
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0; noteId = 0;
}//try-catch异常处理 }
if (noteId == -1) { if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId); throw new IllegalStateException("Wrong note id:" + noteId);
} }
@ -47,37 +68,37 @@ public class Note {
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
}//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容 }
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}//设置数据库表格的标签属性数据 }
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
}//设置数据库表格的标签文本内容的数据 }
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
}//设置文本数据的ID }
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
}//得到文本数据的ID }
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
}//设置电话号码数据的ID }
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
}//得到电话号码数据的ID }
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}//判断是否是本地修改 }
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
@ -107,16 +128,16 @@ public class Note {
} }
return true; return true;
}//判断数据是否同步 }
private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据 private class NoteData {
private long mTextDataId; private long mTextDataId;
private ContentValues mTextDataValues;//文本数据 private ContentValues mTextDataValues;
private long mCallDataId; private long mCallDataId;
private ContentValues mCallDataValues;//电话号码数据 private ContentValues mCallDataValues;
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
@ -126,7 +147,7 @@ public class Note {
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
//下面是上述几个函数的具体实现
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
@ -156,17 +177,17 @@ public class Note {
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//下面函数的作用是将新的数据通过Uri的操作存储到数据库
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
}//判断数据是否合法 }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;//数据库的操作列表 ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
@ -188,7 +209,7 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mTextDataValues.clear(); mTextDataValues.clear();
}//把文本数据存入DataColumns }
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
@ -210,7 +231,7 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mCallDataValues.clear(); mCallDataValues.clear();
}//把电话号码数据存入DataColumns }
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
@ -225,7 +246,7 @@ public class Note {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} }
}//存储过程中的异常处理 }
return null; return null;
} }
} }

@ -1,5 +1,37 @@
/*
* 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; 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 { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -11,11 +43,17 @@ public class WorkingNote {
private int mMode; private int mMode;
private long mAlertDate; private long mAlertDate;
private long mModifiedDate; private long mModifiedDate;
private int mBgColorId; private int mBgColorId;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private long mFolderId; private long mFolderId;
private Context mContext; private Context mContext;
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
@ -24,7 +62,6 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 声明 DATA_PROJECTION字符串数组
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -35,7 +72,6 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 声明 NOTE_PROJECTION字符串数组
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -46,18 +82,27 @@ public class WorkingNote {
}; };
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; 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_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // New note construct
public WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis();
@ -69,7 +114,6 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// WorkingNote的构造函数
// Existing note construct // Existing note construct
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
@ -80,14 +124,11 @@ public class WorkingNote {
loadNote(); loadNote();
} }
// 加载Note
// 通过数据库调用query函数找到第一个条目
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
// 若存在,储存相应信息
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -98,7 +139,6 @@ public class WorkingNote {
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
} }
cursor.close(); cursor.close();
// 若不存在,报错
} else { } else {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
@ -106,7 +146,6 @@ public class WorkingNote {
loadNoteData(); loadNoteData();
} }
// 加载NoteData
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
@ -114,8 +153,7 @@ public class WorkingNote {
}, null); }, null);
if (cursor != null) { if (cursor != null) {
// 查到信息不为空 if (cursor.moveToFirst()) {
if (cursor.moveToFirst()) { // 查看第一项是否存在
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
@ -127,7 +165,7 @@ public class WorkingNote {
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
} }
} while (cursor.moveToNext());//查阅所有项,直到为空 } while (cursor.moveToNext());
} }
cursor.close(); cursor.close();
} else { } else {
@ -136,12 +174,9 @@ public class WorkingNote {
} }
} }
// 创建空的Note
// 传参context文件夹idwidget背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
// 设定相关属性
note.setBgColorId(defaultBgColorId); note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId); note.setWidgetId(widgetId);
note.setWidgetType(widgetType); note.setWidgetType(widgetType);
@ -152,10 +187,9 @@ public class WorkingNote {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
// 保存Note
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { //是否值得保存 if (isWorthSaving()) {
if (!existInDatabase()) { // 是否存在数据库中 if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
@ -178,14 +212,11 @@ public class WorkingNote {
} }
} }
// 是否在数据库中存在
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
// 是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
// 被删除,或(不在数据库中 内容为空),或 本地已保存过
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -194,14 +225,10 @@ public class WorkingNote {
} }
} }
// 设置mNoteSettingStatusListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
// 设置AlertDate
// 若 mAlertDate与data不同则更改mAlertDate并设定NoteValue
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -212,20 +239,16 @@ public class WorkingNote {
} }
} }
// 设定删除标记
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
// 设定标记
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
// 调用mNoteSettingStatusListener的 onWidgetChanged方法
} }
} }
// 设定背景颜色
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { //设定条件 id != mBgColorId if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
@ -234,10 +257,8 @@ public class WorkingNote {
} }
} }
// 设定检查列表模式
// 参数mode
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { //设定条件 mMode != mode if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -246,108 +267,81 @@ public class WorkingNote {
} }
} }
// 设定WidgetType
// 参数type
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) {//设定条件 type != mWidgetType if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
// 调用Note的setNoteValue方法更改WidgetType
} }
} }
// 设定WidgetId
// 参数id
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) {//设定条件 id != mWidgetId if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
// 调用Note的setNoteValue方法更改WidgetId
} }
} }
// 设定WorkingTex
// 参数更改的text
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {//设定条件 mContent, text内容不同 if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
// 调用Note的setTextData方法更改WorkingText
} }
} }
// 转变mNote的CallData及CallNote信息
// 参数String phoneNumber, long callDate
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
// 判断是否有时钟题型
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
// 获取Content
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
// 获取AlertDate
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取ModifiedDate
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取背景颜色来源id
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
// 获取背景颜色id
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取标题背景颜色id
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
// 获取CheckListMode
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
// 获取便签id
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
// 获取文件夹id
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
// 获取WidgetId
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取WidgetType
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 创建接口 NoteSettingChangedListener,便签更新监视
// 为NoteEditActivity提供接口
// 提供函数有
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -35,27 +35,12 @@
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
/*
便
便便
使Android(ContentProvider)便
便
*/
//单例对象是一种确保在应用程序中只有一个实例被创建的设计模式
//提供一种全局的访问方式
//这个类描述备份工具的属性和行为
public class BackupUtils { public class BackupUtils {
// 声明一个常量 TAG用于在日志中标识这个类
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// Singleton stuff // Singleton stuff
// 声明一个私有的静态变量 sInstance保存单例对象
private static BackupUtils sInstance; private static BackupUtils sInstance;
/*
*/
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) {
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
@ -68,26 +53,22 @@
* status * status
*/ */
// Currently, the sdcard is not mounted // Currently, the sdcard is not mounted
//SD卡没有挂载的状态码
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
//备份文件不存在的状态码
// The backup file not exist // The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
//数据格式不正确,可能被其他程序修改的状态码
// The data is not well formated, may be changed by other programs // The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
//运行异常导致恢复或者备份失败的状态码
// Some run-time exception which causes restore or backup fails // Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
//运行异常导致恢复或者备份成功的状态码
// Backup or restore success // Backup or restore success
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
//这个用于导出备份数据到文本文件
private TextExport mTextExport; private TextExport mTextExport;
//获取
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
@ -361,4 +342,3 @@
} }

@ -35,25 +35,6 @@
import java.util.HashSet; import java.util.HashSet;
/*
DataUtils
使便
使ContentResolverContentProvider
使
+
便
*/
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
@ -312,4 +293,3 @@
return snippet; return snippet;
} }
} }

@ -14,24 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
/*
便
ContentResolverAndroid
ContentProvider
使ContentResolverContentProvider(Android)
使便
使
*/
package net.micode.notes.tool; package net.micode.notes.tool;
public class GTaskStringUtils { public class GTaskStringUtils {

@ -14,17 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
/**
使
便使使
使
*/
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;

@ -225,4 +225,3 @@
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }
} }

@ -1,3 +1,19 @@
/*
* 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; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
@ -61,13 +77,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
//主界面,一进入就是这个界面
/** public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
* @author k
*
*/
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { //没有用特定的标签加注释。。。感觉没有什么用
// 定义一些常量和枚举类型
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
@ -78,41 +89,41 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; //单行超过80个字符 private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
}; };
private ListEditState mState; // 当前列表的编辑状态 private ListEditState mState;
private BackgroundQueryHandler mBackgroundQueryHandler; // 异步查询处理器 private BackgroundQueryHandler mBackgroundQueryHandler;
private NotesListAdapter mNotesListAdapter; // 笔记列表的适配器 private NotesListAdapter mNotesListAdapter;
private ListView mNotesListView; // 笔记列表视图 private ListView mNotesListView;
private Button mAddNewNote; // 添加新笔记的按钮 private Button mAddNewNote;
private boolean mDispatch; // 是否分发事件 private boolean mDispatch;
private int mOriginY; // 原始Y坐标 private int mOriginY;
private int mDispatchY; // 分发Y坐标 private int mDispatchY;
private TextView mTitleBar; // 标题栏 private TextView mTitleBar;
private long mCurrentFolderId; // 当前文件夹的ID private long mCurrentFolderId;
private ContentResolver mContentResolver; // 内容解析器 private ContentResolver mContentResolver;
private ModeCallback mModeCallBack; // 模式回调 private ModeCallback mModeCallBack;
private static final String TAG = "NotesListActivity"; private static final String TAG = "NotesListActivity";
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
private NoteItemData mFocusNoteDataItem; // 当前焦点笔记的数据项 private NoteItemData mFocusNoteDataItem;
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
@ -125,49 +136,38 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@Override @Override
// 创建类 protected void onCreate(Bundle savedInstanceState) {
protected void onCreate(final Bundle savedInstanceState) { //需要是final类型 根据程序上下文环境Java关键字final有“这是无法改变的”或者“终态的”含义它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变设计或效率。 super.onCreate(savedInstanceState);
// final类不能被继承没有子类final类中的方法默认是final的。
//final方法不能被子类的方法覆盖但可以被继承。
//final成员变量表示常量只能被赋值一次赋值后值不再改变。
//final不能用于修饰构造方法。
super.onCreate(savedInstanceState); // 调用父类的onCreate函数
setContentView(R.layout.note_list); setContentView(R.layout.note_list);
initResources(); initResources();
/** /**
* Insert an introduction when user firstly use this application * Insert an introduction when user firstly use this application
*/ */
setAppInfoFromRawRes();// 初始化应用信息 setAppInfoFromRawRes();
} }
@Override @Override
// 返回一些子模块完成的数据交给主Activity处理
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 结果值 和 要求值 符合要求
if (resultCode == RESULT_OK if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null); mNotesListAdapter.changeCursor(null);
} else { } else {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
// 调用 Activity 的onActivityResult
} }
} }
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {
// Android平台给我们提供了一个SharedPreferences类它是一个轻量级的存储类特别适合用于保存软件配置参数。
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {// 判断是否已添加介绍 if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream in = null; InputStream in = null;
try { try {
// 把资源文件放到应用程序的/raw/raw下那么就可以在应用中使用getResources获取资源后,
// 以openRawResource方法不带后缀的资源文件名打开这个文件。
in = getResources().openRawResource(R.raw.introduction); in = getResources().openRawResource(R.raw.introduction);
if (in != null) {// 读取原始资源文件中的介绍内容 if (in != null) {
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024]; // 自行定义的数值,使用者不知道有什么意义 char [] buf = new char[1024];
int len = 0; int len = 0;
while ((len = br.read(buf)) > 0) { while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len); sb.append(buf, 0, len);
@ -190,13 +190,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
// 创建空的WorkingNote
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED); // 创建一个新的工作笔记 ResourceParser.RED);
note.setWorkingText(sb.toString()); // 设置工作笔记的内容为读取到的介绍内容 note.setWorkingText(sb.toString());
if (note.saveNote()) { // 保存工作笔记 if (note.saveNote()) {
// 更新保存note的信息
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "Save introduction note error");
@ -211,23 +209,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
// 初始化资源
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); // 获取应用程序的数据,得到类似数据表的东西 mContentResolver = this.getContentResolver();
// 初始化BackgroundQueryHandler
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mNotesListView = (ListView) findViewById(R.id.notes_list);
// findViewById 是安卓编程的定位函数,主要是引用.R文件里的引用名
mNotesListView = (ListView) findViewById(R.id.notes_list); // 绑定XML中的ListView作为Item的容器
// 将尾部视图添加到列表视图
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false); null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this); mNotesListView.setOnItemLongClickListener(this);
mNotesListAdapter = new NotesListAdapter(this); mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter); mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note);// 在activity中要获取该按钮 mAddNewNote = (Button) findViewById(R.id.btn_new_note);
mAddNewNote.setOnClickListener(this); mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false; mDispatch = false;
@ -238,12 +231,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
// 继承自ListView.MultiChoiceModeListener 和 OnMenuItemClickListener
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu; private DropdownMenu mDropDownMenu;
private ActionMode mActionMode; private ActionMode mActionMode;
private MenuItem mMoveMenu; private MenuItem mMoveMenu;
// 创建ActionMode时触发
public boolean onCreateActionMode(ActionMode mode, Menu menu) { public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu); getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this); menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
@ -259,7 +251,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mNotesListAdapter.setChoiceMode(true); mNotesListAdapter.setChoiceMode(true);
mNotesListView.setLongClickable(false); mNotesListView.setLongClickable(false);
mAddNewNote.setVisibility(View.GONE); mAddNewNote.setVisibility(View.GONE);
// 初始化下拉菜单
View customView = LayoutInflater.from(NotesListActivity.this).inflate( View customView = LayoutInflater.from(NotesListActivity.this).inflate(
R.layout.note_list_dropdown_menu, null); R.layout.note_list_dropdown_menu, null);
mode.setCustomView(customView); mode.setCustomView(customView);
@ -267,9 +259,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(final MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu();// 更新菜单 updateMenu();
return true; return true;
} }
@ -277,12 +269,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
// 更新菜单
private void updateMenu() { private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu // Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount); String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format); // 更改标题 mDropDownMenu.setTitle(format);
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) { if (item != null) {
if (mNotesListAdapter.isAllSelected()) { if (mNotesListAdapter.isAllSelected()) {
@ -304,7 +295,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
// 销毁ActionMode时触发
public void onDestroyActionMode(ActionMode mode) { public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false); mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true); mNotesListView.setLongClickable(true);
@ -314,13 +305,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public void finishActionMode() { public void finishActionMode() {
mActionMode.finish(); mActionMode.finish();
} }
// 当选择的项发生变化时触发
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) { boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked); mNotesListAdapter.setCheckedItem(position, checked);
updateMenu(); updateMenu();
} }
// 菜单项点击事件处理
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
if (mNotesListAdapter.getSelectedCount() == 0) { if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
@ -330,7 +321,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.delete: case R.id.delete:
// 弹出删除对话框
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
@ -347,7 +337,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show(); builder.show();
break; break;
case R.id.move: case R.id.move:
startQueryDestinationFolders();// 查询目标文件夹 startQueryDestinationFolders();
break; break;
default: default:
return false; return false;
@ -376,7 +366,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** /**
* HACKME:When click the transparent part of "New Note" button, dispatch * HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of * the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94nit:pixel<EFBFBD> * "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* and the line top of the button. The coordinate based on left of the "New * and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part. * Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should * Notice that, if the background of the button changes, the formula should
@ -419,16 +409,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}; };
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {
// 构建查询语句的selection根据当前文件夹id选择不同的查询条件
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION; : NORMAL_SELECTION;
// 调用异步查询处理器进行数据库查询
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId) String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
// 异步查询处理器类
private final class BackgroundQueryHandler extends AsyncQueryHandler { private final class BackgroundQueryHandler extends AsyncQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) { public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver); super(contentResolver);
@ -438,12 +426,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
protected void onQueryComplete(int token, Object cookie, Cursor cursor) { protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) { switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN: case FOLDER_NOTE_LIST_QUERY_TOKEN:
// 查询完成后更新列表适配器的Cursor数据源
mNotesListAdapter.changeCursor(cursor); mNotesListAdapter.changeCursor(cursor);
break; break;
case FOLDER_LIST_QUERY_TOKEN: case FOLDER_LIST_QUERY_TOKEN:
if (cursor != null && cursor.getCount() > 0) { if (cursor != null && cursor.getCount() > 0) {
// 如果查询到了文件夹列表,则显示文件夹选择菜单
showFolderListMenu(cursor); showFolderListMenu(cursor);
} else { } else {
Log.e(TAG, "Query folder failed"); Log.e(TAG, "Query folder failed");
@ -454,7 +440,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
} }
// 显示文件夹选择菜单
private void showFolderListMenu(Cursor cursor) { private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
@ -462,7 +448,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setAdapter(adapter, new DialogInterface.OnClickListener() { builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 点击菜单项后进行相应操作,这里是批量移动笔记到选中的文件夹
DataUtils.batchMoveToFolder(mContentResolver, DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText( Toast.makeText(
@ -476,21 +461,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
builder.show(); builder.show();
} }
// 创建新的笔记
private void createNewNote() { private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
} }
// 批量删除操作
private void batchDelete() { private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
// 获取选中笔记对应的小部件信息
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) { if (!isSyncMode()) {
// 如果不是同步模式,则直接删除选中的笔记
// if not synced, delete notes directly // if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) { .getSelectedItemIds())) {
@ -549,7 +532,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
} }
// 打开笔记详情界面
private void openNode(NoteItemData data) { private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
@ -558,7 +541,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private void openFolder(NoteItemData data) { private void openFolder(NoteItemData data) {
// 更新当前文件夹id并进行异步查询笔记列表
mCurrentFolderId = data.getId(); mCurrentFolderId = data.getId();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
@ -578,88 +560,85 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public void onClick(View v) { public void onClick(View v) {
switch (v.getId()) { switch (v.getId()) {
case R.id.btn_new_note: case R.id.btn_new_note:
// 点击新建笔记按钮,触发创建新的笔记操作
createNewNote(); createNewNote();
break; break;
default: default:
break; break;
} }
} }
// 显示输入法软键盘
private void showSoftInput() { private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) { if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
} }
} }
// 隐藏输入法软键盘
private void hideSoftInput(View view) { private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
} }
//显示创建或修改文件夹的对话框
private void showCreateOrModifyFolderDialog(final boolean create) { private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);// 创建对话框构建器 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);//加载布局文件 View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);// 获取输入框 final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
showSoftInput();// 显示软键盘 showSoftInput();
if (!create) { // 如果是修改文件夹 if (!create) {
if (mFocusNoteDataItem != null) { // 如果有选中的文件夹 if (mFocusNoteDataItem != null) {
etName.setText(mFocusNoteDataItem.getSnippet()); // 设置输入框文字为文件夹名称 etName.setText(mFocusNoteDataItem.getSnippet());
builder.setTitle(getString(R.string.menu_folder_change_name)); // 设置对话框标题为"更改文件夹名称" builder.setTitle(getString(R.string.menu_folder_change_name));
} else { } else {
Log.e(TAG, "The long click data item is null"); // 输出错误日志 Log.e(TAG, "The long click data item is null");
return; return;
} }
} else { // 如果是创建文件夹 } else {
etName.setText(""); // 清空输入框 etName.setText("");
builder.setTitle(this.getString(R.string.menu_create_folder)); // 设置对话框标题为"创建文件夹" builder.setTitle(this.getString(R.string.menu_create_folder));
} }
builder.setPositiveButton(android.R.string.ok, null); // 设置确定按钮,暂不处理点击事件 builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName); // 隐藏软键盘 hideSoftInput(etName);
} }
}); // 设置取消按钮,点击时隐藏软键盘 });
final Dialog dialog = builder.setView(view).show(); // 创建对话框并显示 final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1); // 获取确定按钮 final Button positive = (Button)dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(new OnClickListener() { positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
hideSoftInput(etName); // 隐藏软键盘 hideSoftInput(etName);
String name = etName.getText().toString(); // 获取输入的文件夹名称 String name = etName.getText().toString();
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { // 检查文件夹名称是否可见
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
Toast.LENGTH_LONG).show(); // 显示提示信息,文件夹已存在 Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length()); // 选中输入框中的文字 etName.setSelection(0, etName.length());
return; return;
} }
if (!create) {
if (!create) { // 如果是修改文件夹 if (!TextUtils.isEmpty(name)) {
if (!TextUtils.isEmpty(name)) { // 如果文件夹名称不为空
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); // 更新文件夹名称 values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型为文件夹 values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地修改 values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] { + "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId()) String.valueOf(mFocusNoteDataItem.getId())
}); // 更新数据库中的文件夹信息 });
} }
} else if (!TextUtils.isEmpty(name)) { // 如果是创建文件夹且文件夹名称不为空 } else if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); // 设置文件夹名称 values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 设置类型为文件夹 values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); // 插入数据库中 mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
} }
dialog.dismiss();
dialog.dismiss(); // 关闭对话框
} }
}); });
if (TextUtils.isEmpty(etName.getText())) { // 如果输入框内容为空
positive.setEnabled(false); // 禁用确定按钮 if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
} }
/** /**
* When the name edit text is null, disable the positive button * When the name edit text is null, disable the positive button
@ -685,12 +664,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
} }
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*
*/
@Override @Override
public void onBackPressed() { switch (mState) { public void onBackPressed() {
switch (mState) {
case SUB_FOLDER: case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST;
@ -712,11 +688,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
* @param appWidgetId
* @param appWidgetType
* widgetintent
*/
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) { if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -736,9 +707,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
/**
*
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
@ -758,10 +726,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
super.onContextMenuClosed(menu); super.onContextMenuClosed(menu);
} }
/* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
* menu
*/
@Override @Override
public boolean onContextItemSelected(MenuItem item) { public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) { if (mFocusNoteDataItem == null) {
@ -770,10 +734,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
switch (item.getItemId()) { switch (item.getItemId()) {
case MENU_FOLDER_VIEW: case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem);//打开对应文件 openFolder(mFocusNoteDataItem);
break; break;
case MENU_FOLDER_DELETE: case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this);//设置确认是否删除的对话框 AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder));
@ -784,7 +748,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show();//显示对话框 builder.show();
break; break;
case MENU_FOLDER_CHANGE_NAME: case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false); showCreateOrModifyFolderDialog(false);
@ -799,55 +763,54 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear(); menu.clear();
if (mState == ListEditState.NOTE_LIST) { // 如果当前状态是便签列表 if (mState == ListEditState.NOTE_LIST) {
getMenuInflater().inflate(R.menu.note_list, menu); // 加载便签列表的菜单布局 getMenuInflater().inflate(R.menu.note_list, menu);
// 设置同步或取消同步选项的标题 // set sync or sync_cancel
menu.findItem(R.id.menu_sync).setTitle( menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
} else if (mState == ListEditState.SUB_FOLDER) { // 如果当前状态是子文件夹 } else if (mState == ListEditState.SUB_FOLDER) {
getMenuInflater().inflate(R.menu.sub_folder, menu); // 加载子文件夹的菜单布局 getMenuInflater().inflate(R.menu.sub_folder, menu);
} else if (mState == ListEditState.CALL_RECORD_FOLDER) { // 如果当前状态是通话记录文件夹 } else if (mState == ListEditState.CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_record_folder, menu); // 加载通话记录文件夹的菜单布局 getMenuInflater().inflate(R.menu.call_record_folder, menu);
} else { } else {
Log.e(TAG, "Wrong state:" + mState); // 如果状态不匹配,则输出错误日志 Log.e(TAG, "Wrong state:" + mState);
} }
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_folder: { // 如果选择了新建文件夹选项 case R.id.menu_new_folder: {
showCreateOrModifyFolderDialog(true); // 显示创建或修改文件夹对话框 showCreateOrModifyFolderDialog(true);
break; break;
} }
case R.id.menu_export_text: { // 如果选择了导出文本选项 case R.id.menu_export_text: {
exportNoteToText(); // 导出便签到文本 exportNoteToText();
break; break;
} }
case R.id.menu_sync: { // 如果选择了同步选项 case R.id.menu_sync: {
if (isSyncMode()) { // 如果处于同步模式 if (isSyncMode()) {
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
GTaskSyncService.startSync(this); // 启动同步服务 GTaskSyncService.startSync(this);
} else { } else {
GTaskSyncService.cancelSync(this); // 取消同步服务 GTaskSyncService.cancelSync(this);
} }
} else { } else {
startPreferenceActivity(); // 跳转到设置界面 startPreferenceActivity();
} }
break; break;
} }
case R.id.menu_setting: { // 如果选择了设置选项 case R.id.menu_setting: {
startPreferenceActivity(); // 跳转到设置界面 startPreferenceActivity();
break; break;
} }
case R.id.menu_new_note: { // 如果选择了新建便签选项 case R.id.menu_new_note: {
createNewNote(); // 创建新的便签 createNewNote();
break; break;
} }
case R.id.menu_search: case R.id.menu_search:
onSearchRequested(); // 执行搜索操作 onSearchRequested();
break; break;
default: default:
break; break;
@ -855,53 +818,46 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/* (non-Javadoc)
* @see android.app.Activity#onSearchRequested()
* startSearch
*/
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false); startSearch(null, false, null /* appData */, false);
return true; return true;
} }
/**
* 便
*/
private void exportNoteToText() { private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() { new AsyncTask<Void, Void, Integer>() {
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
return backup.exportToText(); // 调用备份工具类的导出便签到文本方法 return backup.exportToText();
} }
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { // 如果SD卡未挂载 if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); // 设置对话框标题为导出失败 .getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted)); // 设置对话框内容为SD卡未挂载 .getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) { // 如果导出成功 } else if (result == BackupUtils.STATE_SUCCESS) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.success_sdcard_export)); // 设置对话框标题为导出成功 .getString(R.string.success_sdcard_export));
builder.setMessage(NotesListActivity.this.getString( builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir())); // 设置对话框内容为导出文件的位置 .getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) { // 如果系统错误 } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); // 设置对话框标题为导出失败 .getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export)); // 设置对话框内容为导出错误 .getString(R.string.error_sdcard_export));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} }
@ -910,37 +866,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
/**
* @return
*
*/
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
/**
* PreferenceActivity
*/
private void startPreferenceActivity() { private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
/**
* @author k
* 便
*/
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData(); // 获取点击项的数据 NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) { // 如果处于选择模式 if (mNotesListAdapter.isInChoiceMode()) {
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
position = position - mNotesListView.getHeaderViewsCount(); position = position - mNotesListView.getHeaderViewsCount();
mModeCallBack.onItemCheckedStateChanged(null, position, id, mModeCallBack.onItemCheckedStateChanged(null, position, id,
!mNotesListAdapter.isSelectedItem(position)); // 更新选择状态 !mNotesListAdapter.isSelectedItem(position));
} }
return; return;
} }
@ -949,9 +894,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
case NOTE_LIST: case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) { || item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item); // 打开文件夹 openFolder(item);
} else if (item.getType() == Notes.TYPE_NOTE) { } else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); // 打开便签 openNode(item);
} else { } else {
Log.e(TAG, "Wrong note type in NOTE_LIST"); Log.e(TAG, "Wrong note type in NOTE_LIST");
} }
@ -959,7 +904,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
case SUB_FOLDER: case SUB_FOLDER:
case CALL_RECORD_FOLDER: case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); // 打开便签 openNode(item);
} else { } else {
Log.e(TAG, "Wrong note type in SUB_FOLDER"); Log.e(TAG, "Wrong note type in SUB_FOLDER");
} }
@ -972,9 +917,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
/**
*
*/
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection:
@ -993,24 +935,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
NoteColumns.MODIFIED_DATE + " DESC"); NoteColumns.MODIFIED_DATE + " DESC");
} }
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemLongClickListener#onItemLongClick(android.widget.AdapterView, android.view.View, int, long)
*
* 便ActionModeContextMenu
* ActionMOdeContextMenu
*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();// 获取当前长按项的数据 mFocusNoteDataItem = ((NotesListItem) view).getItemData();
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
if (mNotesListView.startActionMode(mModeCallBack) != null) { if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true);// 更改选择状态 mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
} else { } else {
Log.e(TAG, "startActionMode fails"); Log.e(TAG, "startActionMode fails");
} }
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);// 设置创建上下文菜单监听器 mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
} }
} }
return false; return false;

@ -1,3 +1,19 @@
/*
* 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; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -7,7 +23,6 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import java.util.Collection; import java.util.Collection;
@ -16,94 +31,55 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
/*
* 便CursorAdaptercursorListView
* NotesListAdapter便
*/
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; //便签数 private int mNotesCount;
private boolean mChoiceMode; //选择模式标记 private boolean mChoiceMode;
/*
* widget
*/
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
/*
* 便
*
*/
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); //父类对象置空 super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); //新建选项下标的hash表 mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context; mContext = context;
mNotesCount = 0; mNotesCount = 0;
} }
@Override @Override
/*
*
* 使NotesListItem
*/
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
/*
*
*
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
//若view是NotesListItem的一个实例
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
//则新建一个项目选项并且用bind跟将view和鼠标内容便签数据捆绑在一起
} }
} }
/*
*
*
*/
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
//根据定位和是否勾选设置下标
notifyDataSetChanged(); notifyDataSetChanged();
//在修改后刷新activity
} }
/*
*
*/
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
/*
*
* mode
*/
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
/*
*
*
*/
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
//获取光标位置
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
@ -111,47 +87,30 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
//遍历所有光标可用的位置在判断为便签类型之后勾选单项框
} }
/*
*
*
*/
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
//建立hash表
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
//遍历所有的关键
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
//若光标位置可用
Long id = getItemId(position); Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {
//原文件不需要添加
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); itemSet.add(id);
} }
//则将id该下标假如选项集合中
} }
} }
return itemSet; return itemSet;
} }
/*
* Widget
*
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position); Cursor c = (Cursor) getItem(position);
//以上4句和getSelectedItemIds一样不再重复
if (c != null) { if (c != null) {
//光标位置可用的话就建立新的Widget属性并编辑下标和类型最后添加到选项集中
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c); NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); widget.widgetId = item.getWidgetId();
@ -169,42 +128,26 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/*
*
*
*/
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
//首先获取选项下标的值
if (null == values) { if (null == values) {
return 0; return 0;
} }
Iterator<Boolean> iter = values.iterator(); Iterator<Boolean> iter = values.iterator();
//初始化叠加器
int count = 0; int count = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
if (true == iter.next()) { if (true == iter.next()) {
//若value值为真计数+1
count++; count++;
} }
} }
return count; return count;
} }
/*
*
*
*/
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
//获取选项数看是否等于便签的个数
} }
/*
*
*
*/
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -213,45 +156,29 @@ public class NotesListAdapter extends CursorAdapter {
} }
@Override @Override
/*
* activity便
*
*/
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
//执行基类函数
calcNotesCount(); calcNotesCount();
} }
@Override @Override
/*
* activity便
*/
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
//执行基类函数
calcNotesCount(); calcNotesCount();
} }
/*
* 便
*
*/
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
//获取总数同时遍历
Cursor c = (Cursor) getItem(i); Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; mNotesCount++;
//若该位置不为空并且文本类型为便签就+1
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "Invalid cursor");
return; return;
} }
//否则报错
} }
} }
} }

@ -1,3 +1,19 @@
/*
* 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; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -14,43 +30,37 @@ import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
//创建便签列表项目选项
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert;//闹钟图片 private ImageView mAlert;
private TextView mTitle; //标题 private TextView mTitle;
private TextView mTime; //时间 private TextView mTime;
private TextView mCallName; // private TextView mCallName;
private NoteItemData mItemData; //标签数据 private NoteItemData mItemData;
private CheckBox mCheckBox; //打钩框 private CheckBox mCheckBox;
/*初始化基本信息*/
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); //super()它的主要作用是调整调用父类构造函数的顺序 super(context);
inflate(context, R.layout.note_item, this);//Inflate可用于将一个xml中定义的布局控件找出来,这里的xml是r。layout inflate(context, R.layout.note_item, this);
//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定;
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title); mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time); mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name); mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
///根据data的属性对各个控件的属性的控制主要是可见性Visibility内容setText格式setTextAppearance
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); ///设置可见行为可见 mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); ///格子打钩 mCheckBox.setChecked(checked);
} else { } else {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE);
} }
mItemData = data; mItemData = data;
///设置控件属性一共三种情况由data的id和父id是否与保存到文件夹的id一致来决定
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
//设置该textview的style
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
//settext为设置内容
mTitle.setText(context.getString(R.string.call_record_folder_name) mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); mAlert.setImageResource(R.drawable.call_record);
@ -59,9 +69,8 @@ public class NotesListItem extends LinearLayout {
mCallName.setText(data.getCallName()); mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
///关于闹钟的设置
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);//图片来源的设置 mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
@ -69,7 +78,7 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
///设置title格式
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
@ -78,38 +87,35 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);///设置图片来源 mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} }
} }
///设置内容获取相关时间从data里编辑的日期中获取
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data); setBackground(data);
} }
//根据data的文件属性来设置背景
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
//单个数据并且只有一个子文件夹
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {//是最后一个数据 } else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {//是一个数据并有多个子文件夹 } else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else { } else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { } else {
//若不是note直接调用文件夹的背景来源
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -1,3 +1,19 @@
/*
* 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; package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
@ -31,92 +47,66 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
/*
*NotesPreferenceActivity便
* PreferenceActivityActivity
*/
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
//优先名
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
//同步账号
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
//同步时间
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
//同步密码
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
//本地密码
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
//账户分组
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
//同步任务接收器
private Account[] mOriAccounts; private Account[] mOriAccounts;
//账户
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
//账户的hash标记
@Override @Override
/*
*activity
*Bundle icicle activity
*
*/
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
//先执行父类的创建函数
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
//给左上角图标的左边加上一个返回的图标
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
//添加xml来源并显示 xml
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
//根据同步账户关键码来初始化分组
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
//初始化同步组件
mOriAccounts = null; mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
//获取listvivewListView的作用:用于列出所有选择
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
//在listview组件上方添加其他组件
} }
@Override @Override
/*
* activity
*
*/
protected void onResume() { protected void onResume() {
//先执行父类 的交互实现
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // need to set sync account automatically if user has added a new
// account // account
if (mHasAddedAccount) { if (mHasAddedAccount) {
//若用户新加了账户则自动设置同步账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
//获取google同步账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
//若原账户不为空且当前账户有增加
for (Account accountNew : accounts) { for (Account accountNew : accounts) {
boolean found = false; boolean found = false;
for (Account accountOld : mOriAccounts) { for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) { if (TextUtils.equals(accountOld.name, accountNew.name)) {
//更新账户
found = true; found = true;
break; break;
} }
} }
if (!found) { if (!found) {
setSyncAccount(accountNew.name); setSyncAccount(accountNew.name);
//若是没有找到旧的账户,那么同步账号中就只添加新账户
break; break;
} }
} }
@ -124,52 +114,35 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
refreshUI(); refreshUI();
//刷新标签界面
} }
@Override @Override
/*
* activity
*
*/
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
//注销接收器
} }
super.onDestroy(); super.onDestroy();
//执行父类的销毁动作
} }
/*
*
*
*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
//销毁所有的分组
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
//建立首选项
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setSummary(getString(R.string.preferences_account_summary));
//设置首选项的大标题和小标题
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
//建立监听器
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // the first time to set account
//若是第一次建立账户显示选择账户提示对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // if the account has already been set, we need to promp
// user about the risk // user about the risk
//若是已经建立则显示修改对话框并进行修改操作
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
//若在没有同步的情况下则在toast中显示不能修改
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
@ -178,29 +151,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
//根据新建首选项编辑新的账户分组
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
/*
*
*
*/
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取同步按钮控件和最终同步时间的的窗口
// set button state // set button state
//设置按钮的状态
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
//若是在同步状态下
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
} }
}); });
//设置按钮显示的文本为“取消同步”以及监听器
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
@ -208,67 +173,50 @@ public class NotesPreferenceActivity extends PreferenceActivity {
GTaskSyncService.startSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
//设置按键可用还是不可用
// set last sync time // set last sync time
// 设置最终同步时间
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
//若是在同步的情况下
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
// 根据当前同步服务器设置时间显示框的文本以及可见性
} else { } else {
//若是非同步情况
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
//则根据最后同步时间的信息来编辑时间显示框的文本内容和可见性
} else { } else {
//若时间为空直接设置为不可见状态
lastSyncTimeView.setVisibility(View.GONE); lastSyncTimeView.setVisibility(View.GONE);
} }
} }
} }
/*
*
*
*/
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
/*
*
*
*/
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
//设置标题以及子标题的内容
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); dialogBuilder.setPositiveButton(null, null);
//设置对话框的自定义标题建立一个YES的按钮
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);
//获取同步账户信息
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) {
//若账户不为空
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
int checkedItem = -1; int checkedItem = -1;
@ -276,119 +224,83 @@ public class NotesPreferenceActivity extends PreferenceActivity {
for (Account account : accounts) { for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) { if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index; checkedItem = index;
//在账户列表中查询到所需账户
} }
items[index++] = account.name; items[index++] = account.name;
} }
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
//在对话框建立一个单选的复选框
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); setSyncAccount(itemMapping[which].toString());
dialog.dismiss(); dialog.dismiss();
//取消对话框
refreshUI(); refreshUI();
} }
//设置点击后执行的事件,包括检录新同步账户和刷新标签界面
}); });
//建立对话框网络版的监听器
} }
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
//给新加账户对话框设置自定义样式
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
//显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; mHasAddedAccount = true;
//将新加账户的hash置true
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
//建立网络建立组件
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls" "gmail-ls"
}); });
startActivityForResult(intent, -1); startActivityForResult(intent, -1);
//跳回上一个选项
dialog.dismiss(); dialog.dismiss();
} }
}); });
//建立新加账户对话框的监听器
} }
/*
*
*
*/
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this))); getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
//根据同步修改的账户信息设置标题以及子标题的内容
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
//设置对话框的自定义标题
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
}; };
//定义一些标记字符串
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
//设置对话框要显示的一个list用于显示几个命令时,即changeremovecancel
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
//按键功能由which来决定
if (which == 0) { if (which == 0) {
//进入账户选择对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
//删除账户并且跟新便签界面
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
} }
}); });
dialogBuilder.show(); dialogBuilder.show();
//显示对话框
} }
/*
*
*
*/
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
/*
*
*
*/
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
//假如该账号不在同步账号列表中
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
//编辑共享的首选项
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
//将该账号加入到首选项中
editor.commit(); editor.commit();
//提交修改的数据
// clean up last sync time
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
//将最后同步时间清零
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
@ -399,33 +311,23 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
//重置当地同步任务的信息
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
//将toast的文本信息置为“设置账户成功”并显示出来
} }
} }
/*
*
*
*/
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
//假如当前首选项中有账户就删除
} }
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
//删除当前首选项中有账户时间
} }
editor.commit(); editor.commit();
//提交更新后的数据
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
@ -436,79 +338,51 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
//重置当地同步任务的信息
} }
/*
*
*
*/
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
/*
*
*
*/
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
// 从共享首选项中找到相关账户并获取其编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); editor.commit();
//编辑最终同步时间并提交更新
} }
/*
*
*
*/
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
/*
*
* BroadcastReceiver
*/
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
//获取随广播而来的Intent中的同步服务的数据
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
//通过获取的数据在设置系统的状态
} }
} }
} }
/*
*
*
* :MenuItem
*/
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
//根据选项的id选择这里只有一个主页
case android.R.id.home: case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
return true; return true;
//在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
default: default:
return false; return false;
} }
} }
} }

@ -15,160 +15,38 @@
*/ */
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context; 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.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser; 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; // NoteWidgetProvider_2x 类是 NoteWidgetProvider 的子类,用于特定类型的小部件
public static final int COLUMN_BG_COLOR_ID = 1; public class NoteWidgetProvider_2x extends NoteWidgetProvider {
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider";
@Override @Override
// 当小部件从主屏幕中被删除时调用的方法 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
public void onDeleted(Context context, int[] appWidgetIds) { // 调用父类的 update 方法以执行小部件更新操作
// 创建 ContentValues 对象,用于存储更新数据库的数值 super.update(context, appWidgetManager, appWidgetIds);
ContentValues values = new ContentValues();
// 将 NoteColumns.WIDGET_ID 的值设置为无效的小部件 IDAppWidgetManager.INVALID_APPWIDGET_ID
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历传入的小部件 ID 数组
for (int i = 0; i < appWidgetIds.length; i++) {
// 使用 ContentResolver 更新 Notes 数据库中的相应小部件 ID 的记录
context.getContentResolver().update(
Notes.CONTENT_NOTE_URI, // 更新的数据表的 URI
values, // 更新的数值
NoteColumns.WIDGET_ID + "=?", // 更新的条件,匹配小部件 ID
new String[] { String.valueOf(appWidgetIds[i]) } // 匹配条件的参数,传入当前小部件 ID
);
}
}
// 获取与小部件相关的笔记信息的方法
// 参数 context上下文对象用于访问内容提供程序
// 参数 widgetId要获取信息的小部件的唯一标识符
// 返回值:包含笔记信息的游标对象
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
// 使用内容解析器查询 Notes 数据库中的记录
// 查询的条件是NoteColumns.WIDGET_ID 等于给定 widgetId同时 NoteColumns.PARENT_ID 不等于垃圾箱的 IDNotes.ID_TRASH_FOLER
// 查询的列是由 PROJECTION 常量指定的列数组
return context.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 查询的数据表的 URI
PROJECTION, // 查询的列数组
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询的条件
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, // 查询条件的参数
null // 不排序
);
}
// update 方法的重载,用于执行小部件更新操作
// 参数 context上下文对象用于访问资源和小部件管理器
// 参数 appWidgetManager小部件管理器用于更新小部件
// 参数 appWidgetIds包含要更新的小部件 ID 的数组
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用 update 方法的重载版本,传入默认参数 false
update(context, appWidgetManager, appWidgetIds, false);
}
// update 方法,用于更新小部件
// 参数 context上下文对象用于访问资源和小部件管理器
// 参数 appWidgetManager小部件管理器用于更新小部件
// 参数 appWidgetIds包含要更新的小部件 ID 的数组
// 参数 privacyMode一个布尔值表示小部件是否处于隐私模式
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) {
// 获取默认背景 ID
int bgId = ResourceParser.getDefaultBgId(context);
// 初始化一个空字符串用于存储文本片段
String snippet = "";
// 创建一个意图,用于打开 NoteEditActivity
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 the same widget id:" + appWidgetIds[i]);
c.close();
return;
}
// 从查询结果中获取文本片段和背景颜色 ID
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
// 设置 intent 中的额外数据,包括笔记的唯一标识符和操作类型
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) { // 获取小部件的布局资源 ID
c.close(); @Override
protected int getLayoutId() {
return R.layout.widget_2x;
} }
// 创建远程视图对象,用于配置小部件的外观 // 获取与小部件类型相关的背景资源 ID
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); @Override
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); protected int getBgResourceId(int bgId) {
// 设置 intent 中的额外数据,包括背景 ID return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
// 生成用于启动小部件的挂起意图
PendingIntent pendingIntent = null;
if (privacyMode) {
// 如果小部件处于隐私模式,设置文本为特定文本并创建 NotesListActivity 的意图
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);
} }
// 设置小部件的点击行为 // 获取小部件的类型,此处返回 Notes.TYPE_WIDGET_2X
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); @Override
// 更新小部件 protected int getWidgetType() {
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); return Notes.TYPE_WIDGET_2X;
}
}
} }
protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId();
protected abstract int getWidgetType();
} }
Loading…
Cancel
Save