Compare commits

..

14 Commits
main ... ljy

@ -0,0 +1 @@
<mxfile host="Electron" modified="2024-01-22T11:38:25.561Z" agent="5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/16.5.1 Chrome/96.0.4664.110 Electron/16.0.7 Safari/537.36" etag="akW9Ob0vbGW2gA5Q_Zq0" version="16.5.1" type="device"><diagram name="Page-1" id="13e1069c-82ec-6db2-03f1-153e76fe0fe0">7R1bb6O4+tfw2AqDweYxNOletCONdqQ9Z/eNJDRhh4SI0ml7fv2xzSVgm0AIJoHMaqQFYz4Tf/ebq5lPu49fYu+w/RKt/VAz9PWHZs41wwC6icn/6MhnOmJDJx3YxME6m3Qc+Bb8z8/fzEbfgrX/WpmYRFGYBIfq4Cra7/1VUhnz4jh6r057icLqqgdv4wsD31ZeKI7+J1gn22wU6Prxwa9+sNlmS2Mre7D0Vt83cfS2z9bbR3s/fbLzcjDZ1Nett47eS0PmQjOf4ihK0qvdx5Mf0m3Ndyx977nmafHJsb9P2ryAlt7SAyu4XBnoBS71ByOF8MML37Jt0BZYcxea62gLpDmWhp+yT08+850iv+JAL9924R/Bix8G5Pea7sGPg52f+DF5EmbDX49j7vs2SPxvB29FX30nNETGtskuJHeAXBK0Jh55JS7uw9A7vAZLtqpORmJ/9Ra/Bj/8P/3XlHroaPSW0JWeCqpgUyk2/HUGqth1ncHdBavsOvSWfugW6HuKwoguzxBIXkvi6HtBCxTQC/nGZ28XhJTE//Ljtbf3suGMngFBqeuFwWZPblYEK+yni2jKMPfDjxP/ozSUoe0XPyLbFn+SKdlTA2YklHEXzm7fS6SaU+q2RKUA5bTnZfyxKWAfCYVcZLTSkm5ypi0TDk8mJeQeomCfsPUtV7PmHLVEcbKNNtHeC8v0csShfps4rGWm1kiFVjNOJSi1YQ8oXf72xfzL/j2J/zGTf5P47dfg6/MDQFJ5MHvWXKQtbM0FGhYR7e/XMyqA6XaF3usrxU2ZtauYTF/314I0bt7ZxIs3ft0cYMr3OvZDLyFSo6owJDuXvfqV0uoRR1aV7wDPTq/RW7zys5fKopeDA5oApT9OAMTwWPyc7qg1JaL+SojsH0d2ZWsdiLvhyNCtR+s0KNVYMjsxIMHBH1QOMi1JlKN31Jol9AkyjUqqgFhAs+zBLliv6YtuxdLKgB2tGEHAVZF+gvwuwPxFcg21UFejJf4qxQIrt7vPp3742ARLMfkjIOJpEuSP9AtxfxH5W879kL9pGb2RvwBLMfnbEjE1CfJPCfBa5I/h3ZA/0u2u1O88NoBSTPzYkhA/1NxnzZlrC0ubzTUHj5H4U/IbgPgFkpMZk0ibLbQZYNEdXcM23VrH0Wbi1v4M8wwf5oH6bYV5JBTEk8ndhXnMs5F6c2Gem7AH1cRr7CoDwVz5nx2vwbxCFEApVohGK2swVZFUoNsaBvTpCFUkuNQ+lOPwgXsjenl59dXEbW7CxFQUAUUVNnDsjtE1gG0+usaDUh1dk5mY0+QocyijU7o6bGXL0xGX/iMjeEZ3/IRtwe/dMkqSaEcelNhqGUar743GQkvTgCL5W/YpfriM3hfHAZcNkAf5V/XLsHn8IcN/zxESoLdjYLKr3mdpWmbd1a5TZDT4heoEAqeqgW5gjvLST6gTJ02/q0aaHCGp1wvQnq5eIAjgA2bA7KgbHoDeBKoGm+dS6YMB5Qud/2lSOu2NcuSpWCpCIfPZXc1ZSERoqs9mNtNepkaYhHr6bNrCoeJ3NsoIYspI/VuINkcNnMulTjLYxpQlg/1ocEwDgdFZNMBmaL1JB7N2rU4fqFRG2PJscbOMIBdYcxATFoDG/ohoIBeudZQRC2IUP9Hqr3TyTGePyDQoA0hGsIbnVOg4rH6MxhnJ4GyMsiZlzQnJGtS7rCEbGH/+l94QEyC7/ZvdIjO/n3+UJ88/y3elCOCNyS6+TMdCHdPpwBEg4cdh/V0kkw82FQsuZBfE5dVl7IzohZvaEDp1glMGJ+xM5hBf2TWYF7dg8sFmwkQXKer2OR31zOmfhUYYjLUnHHgCmOMgG3TkxQfiHPK+igBMNTPKYiJERz8x/ZvXWh/1b6pSGccRBnTSC8R4EDEWxowZZ0zX21RB41ShLyhTj5EZrxqywreTEyFrMrqumQPUuEI8t6GuhTSCwyxAUsxpjixxUnBayiGLTIFRvrKpKUy1ncMuIJuDmA9NWI4Y02ko+JkqOTIHk/mj9KHxUFU4AslKlFQalaAIYfYDDcCn0swUtvZnIcLwhQhWx34TC6uoQ8Bt6Ocn2VyfbMBt1a+00Ol3V76Cz8XpzZWv3ISllm3jyZYkNXEkPm3mcPvcOkDRBEixmSbrIZRYBSycSKwCaosRk82S5Oep5eAwCw7RBD7tXU19JXcaFaSKqmM4h3iwmIUhUedXYmDVzOkYnYtl+PIzAVRPKQ9gyj9ZaebCkMhwCfMimoNw7FwIiAUiI2Be41JCu6wS5yY639TwmiU07BiQA9Ke3Zog9cVtsGYhtcUEsr46kd2ETN8I2Q1etdPOnrBqs7j0pdU1Gg9wEyTVfXYy7eOwVJfDrEpXmznt8uYsSk8MS2q4zjScptXSSGH6aCYrc7RDgjp3GZOrDb2SMyNhQJpSL30YeRfbY+RKWw1J5gXeRd6NoyOFebfeC/tKKXVQTakbRBgPlFMfxCi2UMcmRYBtDhB6tIcVHUhWlicyb5FkILdzej2JBAK6NPN0WYbOmLBurVqFNu7MIbzbKIBS3cYrbzrlozqithUYRJKXs+h4miUnjIbnJS2ZVrMwHqR1a6Ns2sA9BwyVlqPU5KXvO9p+fp6NdzztIcPrIg5l6u0uGnckWOQUg4jDfvt0IKcETAO1UgLnhiAsrk8nX6dOp0DOfDMg4mjsVJsOT+DCrxq2S0fM0cj1lSSNoMgXvCHO6c4Jl9YecaRv5U06Zx9jwhUxCYD6s35E2XlGkM1hF5QUFNLE0aOs+JPjk7M9UxfI6+HPpy4eEHh0Sv/l6wxBbLKSKkhNXxq/LXKmJ1KlDpVH1JZmDWP4tiTRcLSVR5L0R2Dmpy/mwqMXtW44nALUO1IfhA2AekpRmFwLRL5Og74fIG8skrxy/1+NRDI5E8wwO9KEqTcA6okmIJSvozRrVdO9Uu0va6NPJ9EB23NsIJd7iCsCGqwKRGYujZSdLSHqZlrtfDeJtnBOA+pLyHOGcr7Oud+lVADkTb4N/a33IgGAGuq9Xl8qkLREjVQEGIIIsCzO9Wxv5zWCUmTp5euoZWpJmHgSh9ym1Nw/e3K4V2hftzjtcSTsKGpkmxdr7TVyA6CemNHiTPl8nVoxgc6cb56cr6jOUxamEDV4izip5IQK4aSbEQoNQ03rdHHkw+A63bzGiVeqhAjvGzld/7CIII5EWH156vyxE/lCal31rqdViQHKKXC1edVCGShzm+49NtxFfgweGwag6+GqfHBYhKTIZygWunp4GE7HfAVWf0crCkmrticr9oaXdt3/qThKjUHIUqZ31+cHFRmD12r0g9fohlCUseG8s+5/ZwjyArTtXxnqIKnr/qCR2mYjWXfFFAI8UFETw2ABHksiicfKj/xh02bXog6Rs3lIinKoxUK1X8Y36HMvqGFfSxKUl6RdEat6W2StDjMoOyd0CkmXlGcUBGiulXe1JK76SIUAEDuAYdfqGsFMFiD1JAb481SKhdRytfwIpUYeHiPHoguJ7bIOYFkVaIsjlPmNvo8Ii9oKegBbGumXltAXC7WtoT+tyhuL6MUfdgN/6wJN19uzu3as8mE5AVBfvh7kA0b5Skq1Cpqqq4fG7urlqasJMCPPQ8jo+jduudSYAEh1a6zMNBA9K7ERVuwmF5LhI+QxfNWTWvB03CBoVY9FwF3/CLSVn7BVB0g1g8iclCkE9rEil4TcxlGUlLEQe4ftl2hNd2Pxfw==</diagram></mxfile>

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,35 +36,27 @@ 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 },
selection, selection,
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; public static final int TYPE_WIDGET_2X = 0;
// 常量2x2的widget类型 public static final int TYPE_WIDGET_4X = 1;
public static final int TYPE_WIDGET_2X = 0;
// 常量4x4的widget类型
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;
@ -275,18 +263,17 @@ public class Notes {
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1;
/** /**
* Phone number for this record * Phone number for this record
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final 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");
}//电话内容的数据结构 }
} }

@ -15,33 +15,33 @@
*/ */
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";
} }
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -61,8 +61,8 @@ 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 + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -76,12 +76,12 @@ 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,8 +92,8 @@ 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,8 +105,8 @@ 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,8 +117,8 @@ 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,8 +130,8 @@ 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,8 +143,8 @@ 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,8 +156,8 @@ 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,8 +169,8 @@ 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,8 +180,8 @@ 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,8 +191,8 @@ 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,19 +204,19 @@ 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");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
@ -225,7 +225,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -233,19 +233,18 @@ 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();
/** /**
* call record foler for call notes * call record foler for call notes
*/ */
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
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);
/** /**
* root folder which is default folder * root folder which is default folder
*/ */
@ -253,7 +252,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
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);
/** /**
* temporary folder which is used for moving note * temporary folder which is used for moving note
*/ */
@ -261,7 +260,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
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);
/** /**
* create trash folder * create trash folder
*/ */
@ -269,80 +268,78 @@ 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");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_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) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; oldVersion++;
} }
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} }
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
} }
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
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
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
@ -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是什么意思 }
} }

@ -15,7 +15,8 @@
*/ */
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;
@ -27,38 +28,30 @@ import android.database.sqlite.SQLiteDatabase;
import android.net.Uri; import android.net.Uri;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.micode.notes.R; 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;
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1; private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3; private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4; private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5; private static final int URI_SEARCH = 5;
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);
@ -67,12 +60,11 @@ public class NotesProvider extends ContentProvider {
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
} }
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * 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,32 +72,26 @@ 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 ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " 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,26 +113,23 @@ 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");
} }
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 {
searchString = uri.getQueryParameter("pattern"); searchString = uri.getQueryParameter("pattern");
} }
if (TextUtils.isEmpty(searchString)) { if (TextUtils.isEmpty(searchString)) {
return null; return null;
} }
try { try {
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
@ -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) {
@ -164,19 +146,15 @@ public class NotesProvider extends ContentProvider {
} }
return c; return c;
} }
@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);
@ -185,33 +163,28 @@ public class NotesProvider extends ContentProvider {
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
default: default:
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);
} }
// Notify the data uri // Notify the data uri
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
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)) {
@ -253,9 +226,8 @@ public class NotesProvider extends ContentProvider {
} }
return count; return count;
} }
@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;
@ -285,7 +257,7 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -294,13 +266,11 @@ 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 ");
@ -308,7 +278,7 @@ public class NotesProvider extends ContentProvider {
sql.append(" SET "); sql.append(" SET ");
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
@ -322,15 +292,14 @@ 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());
} }
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
} }

@ -14,101 +14,100 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class MetaData extends Task { public class MetaData extends Task {
/* /*
* TAG * TAG
* getSimpleName () * 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;
/* /*
* *
* JSONObjectput ()TasksetNotes ()setName () * JSONObjectput ()TasksetNotes ()setName ()
* *
*/ */
public void setMeta(String gid, JSONObject metaInfo) 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 * 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 * 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 * 使json
* TasksetContentByRemoteJSON () * TasksetContentByRemoteJSON ()
* *
*/ */
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
if (getNotes() != null) { if (getNotes() != null) {
try { try {
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
mRelatedGid = null; mRelatedGid = null;
} }
} }
} }
/*
* 使json
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/*
* json
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/* /*
* * 使json
*/ */
@Override @Override
public int getSyncAction(Cursor c) { public void setContentByLocalJSON(JSONObject js) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); // this function should not be called
} throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
} /*
* json
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/*
*
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
}

@ -14,93 +14,93 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/* /*
* *
* abstract * 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;
mName = ""; mName = "";
mLastModified = 0; mLastModified = 0;
mDeleted = false; mDeleted = false;
} }
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
} }

@ -14,227 +14,227 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
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;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/* /*
* Description便sqlnotedatanote * Description便sqlnotedatanote
* SqlData * SqlData
*/ */
public class SqlData { public class SqlData {
/* /*
* TAG * TAG
* getSimpleName () * 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;//为mDataId置初始值-99999
/** /**
* NotesDataColumn * NotesDataColumn
*/ */
// 集合了interface DataColumns中所有SF常量 // 集合了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 * 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;
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
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 //判断是否直接用Content生成是为true否则为false
private boolean mIsCreate; private boolean mIsCreate;
private long mDataId; private long mDataId;
private String mDataMimeType; private String mDataMimeType;
private String mDataContent; private String mDataContent;
private long mDataContentData1; private long mDataContentData1;
private String mDataContentData3; private String mDataContentData3;
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
/* /*
* *
* mContentResolverContentProvider * mContentResolverContentProvider
* mIsCreate * 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;//mDataId置初始值-99999
mDataMimeType = DataConstants.NOTE; mDataMimeType = DataConstants.NOTE;
mDataContent = ""; mDataContent = "";
mDataContentData1 = 0; mDataContentData1 = 0;
mDataContentData3 = ""; mDataContentData3 = "";
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/* /*
* *
* mContentResolverContentProvider * mContentResolverContentProvider
* mIsCreate * mIsCreate
*/ */
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
loadFromCursor(c); loadFromCursor(c);
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);
mDataContent = c.getString(DATA_CONTENT_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
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 //如果传入的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);
} }
mDataId = dataId; mDataId = dataId;
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType;
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent);
} }
mDataContent = dataContent; mDataContent = dataContent;
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1;
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
} }
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对象。并将相关数据放入其中并返回。
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);
js.put(DataColumns.CONTENT, mDataContent); js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1); js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3);
return js; return js;
} }
/* /*
* commit * commit
*/ */
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);
} }
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
} else { } else {
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else {
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version) String.valueOf(noteId), String.valueOf(version)
}); });
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
} }
mDiffDataValues.clear(); mDiffDataValues.clear();
mIsCreate = false; mIsCreate = false;
} }
/* /*
* id * id
*/ */
public long getId() { public long getId() {
return mDataId; return mDataId;
} }
} }

File diff suppressed because it is too large Load Diff

@ -14,343 +14,343 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
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;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
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;//对应的优先兄弟Task的指针待完善
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;//TaskList中当前Task前面的Task的指针
mParent = null;//当前Task所在的TaskList mParent = null;//当前Task所在的TaskList
mMetaInfo = null; mMetaInfo = null;
} }
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); 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,
GTaskStringUtils.GTASK_JSON_TYPE_TASK); GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) { if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id // parent_id
if (mParent!= null) { 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) { 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) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject"); throw new ActionFailureException("fail to generate task-create jsonobject");
} }
return js; return js;
} }
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) { if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
} }
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject");
} }
return js; return js;
} }
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
// notes // notes
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
} }
// deleted // deleted
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// completed // completed
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject"); throw new ActionFailureException("fail to get task content from jsonobject");
} }
} }
} }
public void setContentByLocalJSON(JSONObject js) { //<2F><>metadata<74><61><EFBFBD><EFBFBD>ʵʩ public void setContentByLocalJSON(JSONObject js) { //<2F><>metadata<74><61><EFBFBD><EFBFBD>ʵʩ
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");
return; return;
} }
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT));
break; break;
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName();
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) {
// new task created from web // new task created from web
if (name == null) { if (name == null) {
Log.w(TAG, "the note seems to be an empty one"); Log.w(TAG, "the note seems to be an empty one");
return null; return null;
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name); data.put(DataColumns.CONTENT, name);
dataArray.put(data); dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; return js;
} else { } else {
// synced task // synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName()); data.put(DataColumns.CONTENT, getName());
break; break;
} }
} }
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo; return mMetaInfo;
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes());
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, e.toString()); Log.w(TAG, e.toString());
mMetaInfo = null; mMetaInfo = null;
} }
} }
} }
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
} }
if (noteInfo == null) { if (noteInfo == null) {
Log.w(TAG, "it seems that note meta has been deleted"); Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
if (!noteInfo.has(NoteColumns.ID)) { if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted"); Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// validate the note id now // validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // apply remote to local
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT;
} }
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
} }

@ -14,388 +14,388 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; 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.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
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();//tag标记
private int mIndex;//当前TaskList的指针 private int mIndex;//当前TaskList的指针
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getCreateAction(int) * @see net.micode.notes.gtask.data.Node#getCreateAction(int)
* JSONObject * JSONObject
*/ */
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // index
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实体
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,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject"); throw new ActionFailureException("fail to generate tasklist-create jsonobject");
} }
return js; return js;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see net.micode.notes.gtask.data.Node#getUpdateAction(int) * @see net.micode.notes.gtask.data.Node#getUpdateAction(int)
* JSONObject * JSONObject
*/ */
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); throw new ActionFailureException("fail to generate tasklist-update jsonobject");
} }
return js; return js;
} }
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject"); throw new ActionFailureException("fail to get tasklist content from jsonobject");
} }
} }
} }
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE); + GTaskStringUtils.FOLDER_CALL_NOTE);
else else
Log.e(TAG, "invalid system folder"); Log.e(TAG, "invalid system folder");
} else { } else {
Log.e(TAG, "error type"); Log.e(TAG, "error type");
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
String folderName = getName(); String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length());
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
else else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
js.put(GTaskStringUtils.META_HEAD_NOTE, folder); js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js; return js;
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // apply remote to local
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// for folder conflicts, just apply local modification // for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/** /**
* @return * @return
* TaskListmChildren * TaskListmChildren
*/ */
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
/** /**
* @param task * @param task
* @return * @return
* *
*/ */
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
if (ret) { if (ret) {
// need to set prior sibling and parent // need to set prior sibling and parent
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
//注意每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改 //注意每一次ArrayList的变化都要紧跟相关Task中PriorSibling的更改
//,接下来几个函数都有相关操作 //,接下来几个函数都有相关操作
} }
} }
return ret; return ret;
} }
/** /**
* @param task * @param task
* @param index * @param index
* @return * @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");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);
if (task != null && pos == -1) { if (task != null && pos == -1) {
mChildren.add(index, task); mChildren.add(index, task);
// update the task list // update the task list
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0)
preTask = mChildren.get(index - 1); preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask); task.setPriorSibling(preTask);
if (afterTask != null) if (afterTask != null)
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task);
} }
return true; return true;
} }
/** /**
* @param task * @param task
* @return * @return
* TaskListTask * 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);
if (index != -1) { if (index != -1) {
ret = mChildren.remove(task); ret = mChildren.remove(task);
if (ret) { if (ret) {
// reset prior sibling and parent // reset prior sibling and parent
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(null); task.setParent(null);
// update the task list // update the task list
if (index != mChildren.size()) { if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1));
} }
} }
} }
return ret; return ret;
} }
/** /**
* @param task * @param task
* @param index * @param index
* @return * @return
* TaskListTaskindex * 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()) {
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);
if (pos == -1) { if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list");
return false; return false;
} }
if (pos == index) if (pos == index)
return true; return true;
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
//利用已实现好的功能完成当下功能; //利用已实现好的功能完成当下功能;
} }
/** /**
* @param gid * @param gid
* @return * @return
* gidTask * 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);
if (t.getGid().equals(gid)) { if (t.getGid().equals(gid)) {
return t; return t;
} }
} }
return null; return null;
} }
/** /**
* @param task * @param task
* @return * @return
* Taskindex * Taskindex
*/ */
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
/** /**
* @param index * @param index
* @return * @return
* indexTask * 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");
return null; return null;
} }
return mChildren.get(index); return mChildren.get(index);
} }
/** /**
* @param gid * @param gid
* @return * @return
* gidTask * gidTask
*/ */
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {//一种常见的ArrayList的遍历方法四种见精读笔记 for (Task task : mChildren) {//一种常见的ArrayList的遍历方法四种见精读笔记
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
return task; return task;
} }
return null; return null;
} }
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren;
} }
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }
} }

@ -18,30 +18,29 @@
* Description便 * 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 * serialVersionUIDjava
* serialVersionUID * serialVersionUID
*/ */
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
/* /*
* JAVA使superthis. * JAVA使superthis.
* new * new
* 使super * 使super
* super()super (paramString)Exception ()Exception (paramString) * super()super (paramString)Exception ()Exception (paramString)
*/ */
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

@ -18,31 +18,30 @@
* Description便 * 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 * serialVersionUIDjava
* serialVersionUID * serialVersionUID
*/ */
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
/* /*
* JAVA使superthis. * JAVA使superthis.
* new * new
* 使super * 使super
* super()super (paramString)Exception ()Exception (paramString) * super()super (paramString)Exception ()Exception (paramString)
*/ */
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -13,135 +13,136 @@
* 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;
import android.app.Activity;
import android.app.Service; import android.app.Activity;
import android.content.Context; import android.app.Service;
import android.content.Intent; import android.content.Context;
import android.os.Bundle; import android.content.Intent;
import android.os.IBinder; import android.os.Bundle;
import android.os.IBinder;
/* package net.micode.notes.gtask.remote;
* Service
* /*
* private void startSync() * Service
* private void cancelSync() *
* public void onCreate() * private void startSync()
* public int onStartCommand(Intent intent, int flags, int startId) serviceserviceservice * private void cancelSync()
* public void onLowMemory() serviceservice * public void onCreate()
* public IBinder onBind() * public int onStartCommand(Intent intent, int flags, int startId) serviceserviceservice
* public void sendBroadcast(String msg) * public void onLowMemory() serviceservice
* public static void startSync(Activity activity) * public IBinder onBind()
* public static void cancelSync(Context context) * public void sendBroadcast(String msg)
* public static boolean isSyncing() * public static void startSync(Activity activity)
* public static String getProgressString() * public static void cancelSync(Context context)
*/ * public static boolean isSyncing()
* public static String getProgressString()
public class GTaskSyncService extends Service { */
public final static String ACTION_STRING_NAME = "sync_action_type";
public class GTaskSyncService extends Service {
public final static int ACTION_START_SYNC = 0; public final static String ACTION_STRING_NAME = "sync_action_type";
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_START_SYNC = 0;
public final static int ACTION_INVALID = 2; public final static int ACTION_CANCEL_SYNC = 1;
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static int ACTION_INVALID = 2;
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
private static GTaskASyncTask mSyncTask = null; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private static String mSyncProgress = ""; private static GTaskASyncTask mSyncTask = null;
//开始一个同步的工作 private static String mSyncProgress = "";
private void startSync() {
if (mSyncTask == null) { //开始一个同步的工作
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { private void startSync() {
public void onComplete() { if (mSyncTask == null) {
mSyncTask = null; mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
sendBroadcast(""); public void onComplete() {
stopSelf(); mSyncTask = null;
} sendBroadcast("");
}); stopSelf();
sendBroadcast(""); }
mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行 });
} sendBroadcast("");
} mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行
}
}
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync(); private void cancelSync() {
} if (mSyncTask != null) {
} mSyncTask.cancelSync();
}
@Override }
public void onCreate() { //初始化一个service
mSyncTask = null; @Override
} public void onCreate() { //初始化一个service
mSyncTask = null;
@Override }
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); @Override
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { public int onStartCommand(Intent intent, int flags, int startId) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { Bundle bundle = intent.getExtras();
//两种情况,开始同步或者取消同步 if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
case ACTION_START_SYNC: switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
startSync(); //两种情况,开始同步或者取消同步
break; case ACTION_START_SYNC:
case ACTION_CANCEL_SYNC: startSync();
cancelSync(); break;
break; case ACTION_CANCEL_SYNC:
default: cancelSync();
break; break;
} default:
return START_STICKY; //等待新的intent来是这个service继续运行 break;
} }
return super.onStartCommand(intent, flags, startId); return START_STICKY; //等待新的intent来是这个service继续运行
} }
return super.onStartCommand(intent, flags, startId);
@Override }
public void onLowMemory() {
if (mSyncTask != null) { @Override
mSyncTask.cancelSync(); public void onLowMemory() {
} if (mSyncTask != null) {
} mSyncTask.cancelSync();
}
public IBinder onBind(Intent intent) { //不知道干吗用的 }
return null;
} public IBinder onBind(Intent intent) { //不知道干吗用的
return null;
public void sendBroadcast(String msg) { }
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent public void sendBroadcast(String msg) {
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值 mSyncProgress = msg;
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent
sendBroadcast(intent); //发送这个通知 intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值
} intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent); //发送这个通知
public static void startSync(Activity activity) {//执行一个serviceservice的内容里的同步动作就是开始同步 }
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); public static void startSync(Activity activity) {//执行一个serviceservice的内容里的同步动作就是开始同步
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); GTaskManager.getInstance().setActivityContext(activity);
activity.startService(intent); Intent intent = new Intent(activity, GTaskSyncService.class);
} intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
public static void cancelSync(Context context) {//执行一个serviceservice的内容里的同步动作就是取消同步 }
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); public static void cancelSync(Context context) {//执行一个serviceservice的内容里的同步动作就是取消同步
context.startService(intent); Intent intent = new Intent(context, GTaskSyncService.class);
} intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
public static boolean isSyncing() { }
return mSyncTask != null;
} public static boolean isSyncing() {
return mSyncTask != null;
public static String getProgressString() { }
return mSyncProgress;
} public static String getProgressString() {
} return mSyncProgress;
}
}

@ -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.ContentProviderOperation;//批量的更新、插入、删除数据。 import android.content.ContentProviderResult;
import android.content.ContentProviderResult;//操作的结果 import android.content.ContentUris;
import android.content.ContentUris;//用于添加和获取Uri后面的ID import android.content.ContentValues;
import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制 import android.content.Context;
import android.content.Context;//需要用该类来弄清楚调用者的实例 import android.content.OperationApplicationException;
import android.content.OperationApplicationException;//操作应用程序容错 import android.net.Uri;
import android.net.Uri;//表示待操作的数据 import android.os.RemoteException;
import android.os.RemoteException;//远程容错 import android.util.Log;
import android.util.Log;//输出日志,比如说出错、警告等
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
public class Note { 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,67 +49,66 @@ 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);
} }
return noteId; return noteId;
} }
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) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
if (!isLocalModified()) { if (!isLocalModified()) {
return true; return true;
} }
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
@ -100,74 +121,74 @@ public class Note {
// Do not return, fall through // Do not return, fall through
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
} }
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";
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
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;
} }
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
} }
mTextDataId = id; mTextDataId = id;
} }
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
} }
mCallDataId = id; mCallDataId = id;
} }
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.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());
} }
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.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());
} }
//下面函数的作用是将新的数据通过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);
if (mTextDataId == 0) { if (mTextDataId == 0) {
@ -188,8 +209,8 @@ 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);
if (mCallDataId == 0) { if (mCallDataId == 0) {
@ -210,8 +231,8 @@ 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 {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
@ -225,8 +246,8 @@ 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;
@ -9,22 +41,27 @@ public class WorkingNote {
private String mContent; private String mContent;
// Note mode // Note mode
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";
private boolean mIsDeleted; private boolean mIsDeleted;
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,
@ -34,8 +71,7 @@ public class WorkingNote {
DataColumns.DATA3, DataColumns.DATA3,
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,
@ -44,20 +80,29 @@ public class WorkingNote {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
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();
@ -68,8 +113,7 @@ public class WorkingNote {
mMode = 0; mMode = 0;
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;
@ -79,15 +123,12 @@ public class WorkingNote {
mNote = new Note(); mNote = new Note();
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,24 +139,21 @@ 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);
} }
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[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, 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 {
@ -135,35 +173,31 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
} }
} }
// 创建空的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);
return note; return note;
} }
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
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;
} }
} }
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
@ -177,15 +211,12 @@ public class WorkingNote {
return false; return false;
} }
} }
// 是否在数据库中存在
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;
@ -193,15 +224,11 @@ public class WorkingNote {
return true; return true;
} }
} }
// 设置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;
@ -211,21 +238,17 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
// 设定删除标记
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();
@ -233,11 +256,9 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
// 设定检查列表模式
// 参数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);
} }
@ -245,125 +266,98 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
} }
// 设定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,便签更新监视 public interface NoteSettingChangedListener {
// 为NoteEditActivity提供接口
// 提供函数有
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
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
* Called when user set clock * Called when user set clock
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
* Call when user create note from widget * Call when user create note from widget
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
* Call when switch between check list mode and normal mode * Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change * @param oldMode is previous mode before change
@ -371,4 +365,4 @@ public class WorkingNote {
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }
} }

@ -14,351 +14,331 @@
* 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.database.Cursor; import android.database.Cursor;
import android.os.Environment; import android.os.Environment;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.util.Log; import android.util.Log;
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.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;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
/*
便 public class BackupUtils {
便便 private static final String TAG = "BackupUtils";
使Android(ContentProvider)便 // Singleton stuff
便 private static BackupUtils sInstance;
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
//单例对象是一种确保在应用程序中只有一个实例被创建的设计模式 }
//提供一种全局的访问方式 return sInstance;
//这个类描述备份工具的属性和行为 }
public class BackupUtils {
// 声明一个常量 TAG用于在日志中标识这个类 /**
private static final String TAG = "BackupUtils"; * Following states are signs to represents backup or restore
// Singleton stuff * status
// 声明一个私有的静态变量 sInstance保存单例对象 */
private static BackupUtils sInstance; // Currently, the sdcard is not mounted
/* public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
*/ public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
public static synchronized BackupUtils getInstance(Context context) { // The data is not well formated, may be changed by other programs
if (sInstance == null) { public static final int STATE_DATA_DESTROIED = 2;
sInstance = new BackupUtils(context); // Some run-time exception which causes restore or backup fails
} public static final int STATE_SYSTEM_ERROR = 3;
return sInstance; // Backup or restore success
} public static final int STATE_SUCCESS = 4;
/** private TextExport mTextExport;
* Following states are signs to represents backup or restore
* status private BackupUtils(Context context) {
*/ mTextExport = new TextExport(context);
// Currently, the sdcard is not mounted }
//SD卡没有挂载的状态码
public static final int STATE_SD_CARD_UNMOUONTED = 0; private static boolean externalStorageAvailable() {
//备份文件不存在的状态码 return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
// The backup file not exist }
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
//数据格式不正确,可能被其他程序修改的状态码 public int exportToText() {
// The data is not well formated, may be changed by other programs return mTextExport.exportToText();
public static final int STATE_DATA_DESTROIED = 2; }
//运行异常导致恢复或者备份失败的状态码
// Some run-time exception which causes restore or backup fails public String getExportedTextFileName() {
public static final int STATE_SYSTEM_ERROR = 3; return mTextExport.mFileName;
//运行异常导致恢复或者备份成功的状态码 }
// Backup or restore success
public static final int STATE_SUCCESS = 4; public String getExportedTextFileDir() {
//这个用于导出备份数据到文本文件 return mTextExport.mFileDirectory;
private TextExport mTextExport; }
//获取
private BackupUtils(Context context) { private static class TextExport {
mTextExport = new TextExport(context); private static final String[] NOTE_PROJECTION = {
} NoteColumns.ID,
private static boolean externalStorageAvailable() { NoteColumns.MODIFIED_DATE,
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); NoteColumns.SNIPPET,
} NoteColumns.TYPE
};
public int exportToText() {
return mTextExport.exportToText(); private static final int NOTE_COLUMN_ID = 0;
}
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
public String getExportedTextFileName() {
return mTextExport.mFileName; private static final int NOTE_COLUMN_SNIPPET = 2;
}
private static final String[] DATA_PROJECTION = {
public String getExportedTextFileDir() { DataColumns.CONTENT,
return mTextExport.mFileDirectory; DataColumns.MIME_TYPE,
} DataColumns.DATA1,
DataColumns.DATA2,
private static class TextExport { DataColumns.DATA3,
private static final String[] NOTE_PROJECTION = { DataColumns.DATA4,
NoteColumns.ID, };
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET, private static final int DATA_COLUMN_CONTENT = 0;
NoteColumns.TYPE
}; private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int NOTE_COLUMN_ID = 0; private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private static final int NOTE_COLUMN_SNIPPET = 2; private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final String[] DATA_PROJECTION = { private static final int FORMAT_NOTE_DATE = 1;
DataColumns.CONTENT, private static final int FORMAT_NOTE_CONTENT = 2;
DataColumns.MIME_TYPE,
DataColumns.DATA1, private Context mContext;
DataColumns.DATA2, private String mFileName;
DataColumns.DATA3, private String mFileDirectory;
DataColumns.DATA4,
}; public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
private static final int DATA_COLUMN_CONTENT = 0; mContext = context;
mFileName = "";
private static final int DATA_COLUMN_MIME_TYPE = 1; mFileDirectory = "";
}
private static final int DATA_COLUMN_CALL_DATE = 2;
private String getFormat(int id) {
private static final int DATA_COLUMN_PHONE_NUMBER = 4; return TEXT_FORMAT[id];
}
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0; /**
private static final int FORMAT_NOTE_DATE = 1; * Export the folder identified by folder id to text
private static final int FORMAT_NOTE_CONTENT = 2; */
private void exportFolderToText(String folderId, PrintStream ps) {
private Context mContext; // Query notes belong to this folder
private String mFileName; Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
private String mFileDirectory; NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
public TextExport(Context context) { }, null);
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; if (notesCursor != null) {
mFileName = ""; if (notesCursor.moveToFirst()) {
mFileDirectory = ""; do {
} // Print note's last modified date
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
private String getFormat(int id) { mContext.getString(R.string.format_datetime_mdhm),
return TEXT_FORMAT[id]; notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
} // Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
/** exportNoteToText(noteId, ps);
* Export the folder identified by folder id to text } while (notesCursor.moveToNext());
*/ }
private void exportFolderToText(String folderId, PrintStream ps) { notesCursor.close();
// Query notes belong to this folder }
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, }
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId /**
}, null); * Export note identified by id to a print stream
*/
if (notesCursor != null) { private void exportNoteToText(String noteId, PrintStream ps) {
if (notesCursor.moveToFirst()) { Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
do { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
// Print note's last modified date noteId
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( }, null);
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); if (dataCursor != null) {
// Query data belong to this note if (dataCursor.moveToFirst()) {
String noteId = notesCursor.getString(NOTE_COLUMN_ID); do {
exportNoteToText(noteId, ps); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
} while (notesCursor.moveToNext()); if (DataConstants.CALL_NOTE.equals(mimeType)) {
} // Print phone number
notesCursor.close(); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
} long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
} String location = dataCursor.getString(DATA_COLUMN_CONTENT);
/** if (!TextUtils.isEmpty(phoneNumber)) {
* Export note identified by id to a print stream ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
*/ phoneNumber));
private void exportNoteToText(String noteId, PrintStream ps) { }
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, // Print call date
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
noteId .format(mContext.getString(R.string.format_datetime_mdhm),
}, null); callDate)));
// Print call attachment location
if (dataCursor != null) { if (!TextUtils.isEmpty(location)) {
if (dataCursor.moveToFirst()) { ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
do { location));
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); }
if (DataConstants.CALL_NOTE.equals(mimeType)) { } else if (DataConstants.NOTE.equals(mimeType)) {
// Print phone number String content = dataCursor.getString(DATA_COLUMN_CONTENT);
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); if (!TextUtils.isEmpty(content)) {
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
String location = dataCursor.getString(DATA_COLUMN_CONTENT); content));
}
if (!TextUtils.isEmpty(phoneNumber)) { }
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), } while (dataCursor.moveToNext());
phoneNumber)); }
} dataCursor.close();
// Print call date }
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat // print a line separator between note
.format(mContext.getString(R.string.format_datetime_mdhm), try {
callDate))); ps.write(new byte[] {
// Print call attachment location Character.LINE_SEPARATOR, Character.LETTER_NUMBER
if (!TextUtils.isEmpty(location)) { });
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), } catch (IOException e) {
location)); Log.e(TAG, e.toString());
} }
} else if (DataConstants.NOTE.equals(mimeType)) { }
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) { /**
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), * Note will be exported as text which is user readable
content)); */
} public int exportToText() {
} if (!externalStorageAvailable()) {
} while (dataCursor.moveToNext()); Log.d(TAG, "Media was not mounted");
} return STATE_SD_CARD_UNMOUONTED;
dataCursor.close(); }
}
// print a line separator between note PrintStream ps = getExportToTextPrintStream();
try { if (ps == null) {
ps.write(new byte[] { Log.e(TAG, "get print stream error");
Character.LINE_SEPARATOR, Character.LETTER_NUMBER return STATE_SYSTEM_ERROR;
}); }
} catch (IOException e) { // First export folder and its notes
Log.e(TAG, e.toString()); Cursor folderCursor = mContext.getContentResolver().query(
} Notes.CONTENT_NOTE_URI,
} NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
/** + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
* Note will be exported as text which is user readable + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
*/
public int exportToText() { if (folderCursor != null) {
if (!externalStorageAvailable()) { if (folderCursor.moveToFirst()) {
Log.d(TAG, "Media was not mounted"); do {
return STATE_SD_CARD_UNMOUONTED; // Print folder's name
} String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
PrintStream ps = getExportToTextPrintStream(); folderName = mContext.getString(R.string.call_record_folder_name);
if (ps == null) { } else {
Log.e(TAG, "get print stream error"); folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
return STATE_SYSTEM_ERROR; }
} if (!TextUtils.isEmpty(folderName)) {
// First export folder and its notes ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
Cursor folderCursor = mContext.getContentResolver().query( }
Notes.CONTENT_NOTE_URI, String folderId = folderCursor.getString(NOTE_COLUMN_ID);
NOTE_PROJECTION, exportFolderToText(folderId, ps);
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " } while (folderCursor.moveToNext());
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " }
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null); folderCursor.close();
}
if (folderCursor != null) {
if (folderCursor.moveToFirst()) { // Export notes in root's folder
do { Cursor noteCursor = mContext.getContentResolver().query(
// Print folder's name Notes.CONTENT_NOTE_URI,
String folderName = ""; NOTE_PROJECTION,
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
folderName = mContext.getString(R.string.call_record_folder_name); + "=0", null, null);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); if (noteCursor != null) {
} if (noteCursor.moveToFirst()) {
if (!TextUtils.isEmpty(folderName)) { do {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
} mContext.getString(R.string.format_datetime_mdhm),
String folderId = folderCursor.getString(NOTE_COLUMN_ID); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
exportFolderToText(folderId, ps); // Query data belong to this note
} while (folderCursor.moveToNext()); String noteId = noteCursor.getString(NOTE_COLUMN_ID);
} exportNoteToText(noteId, ps);
folderCursor.close(); } while (noteCursor.moveToNext());
} }
noteCursor.close();
// Export notes in root's folder }
Cursor noteCursor = mContext.getContentResolver().query( ps.close();
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, return STATE_SUCCESS;
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID }
+ "=0", null, null);
/**
if (noteCursor != null) { * Get a print stream pointed to the file {@generateExportedTextFile}
if (noteCursor.moveToFirst()) { */
do { private PrintStream getExportToTextPrintStream() {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
mContext.getString(R.string.format_datetime_mdhm), R.string.file_name_txt_format);
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); if (file == null) {
// Query data belong to this note Log.e(TAG, "create file to exported failed");
String noteId = noteCursor.getString(NOTE_COLUMN_ID); return null;
exportNoteToText(noteId, ps); }
} while (noteCursor.moveToNext()); mFileName = file.getName();
} mFileDirectory = mContext.getString(R.string.file_path);
noteCursor.close(); PrintStream ps = null;
} try {
ps.close(); FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
return STATE_SUCCESS; } catch (FileNotFoundException e) {
} e.printStackTrace();
return null;
/** } catch (NullPointerException e) {
* Get a print stream pointed to the file {@generateExportedTextFile} e.printStackTrace();
*/ return null;
private PrintStream getExportToTextPrintStream() { }
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, return ps;
R.string.file_name_txt_format); }
if (file == null) { }
Log.e(TAG, "create file to exported failed");
return null; /**
} * Generate the text file to store imported data
mFileName = file.getName(); */
mFileDirectory = mContext.getString(R.string.file_path); private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
PrintStream ps = null; StringBuilder sb = new StringBuilder();
try { sb.append(Environment.getExternalStorageDirectory());
FileOutputStream fos = new FileOutputStream(file); sb.append(context.getString(filePathResId));
ps = new PrintStream(fos); File filedir = new File(sb.toString());
} catch (FileNotFoundException e) { sb.append(context.getString(
e.printStackTrace(); fileNameFormatResId,
return null; DateFormat.format(context.getString(R.string.format_date_ymd),
} catch (NullPointerException e) { System.currentTimeMillis())));
e.printStackTrace(); File file = new File(sb.toString());
return null;
} try {
return ps; if (!filedir.exists()) {
} filedir.mkdir();
} }
if (!file.exists()) {
/** file.createNewFile();
* Generate the text file to store imported data }
*/ return file;
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { } catch (SecurityException e) {
StringBuilder sb = new StringBuilder(); e.printStackTrace();
sb.append(Environment.getExternalStorageDirectory()); } catch (IOException e) {
sb.append(context.getString(filePathResId)); e.printStackTrace();
File filedir = new File(sb.toString()); }
sb.append(context.getString(
fileNameFormatResId, return null;
DateFormat.format(context.getString(R.string.format_date_ymd), }
System.currentTimeMillis()))); }
File file = new File(sb.toString());
try {
if (!filedir.exists()) {
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

@ -14,302 +14,282 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.OperationApplicationException; import android.content.OperationApplicationException;
import android.database.Cursor; import android.database.Cursor;
import android.os.RemoteException; import android.os.RemoteException;
import android.util.Log; import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
public class DataUtils {
/* public static final String TAG = "DataUtils";
DataUtils public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
使便 if (ids.size() == 0) {
使ContentResolverContentProvider Log.d(TAG, "no id is in the hashset");
return true;
}
使 ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
+ Log.e(TAG, "Don't delete system folder root");
便 continue;
*/ }
ContentProviderOperation.Builder builder = ContentProviderOperation
public class DataUtils { .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
public static final String TAG = "DataUtils"; operationList.add(builder.build());
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { }
if (ids == null) { try {
Log.d(TAG, "the ids is null"); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
return true; if (results == null || results.length == 0 || results[0] == null) {
} Log.d(TAG, "delete notes failed, ids:" + ids.toString());
if (ids.size() == 0) { return false;
Log.d(TAG, "no id is in the hashset"); }
return true; return true;
} } catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); } catch (OperationApplicationException e) {
for (long id : ids) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
if(id == Notes.ID_ROOT_FOLDER) { }
Log.e(TAG, "Don't delete system folder root"); return false;
continue; }
}
ContentProviderOperation.Builder builder = ContentProviderOperation public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); ContentValues values = new ContentValues();
operationList.add(builder.build()); values.put(NoteColumns.PARENT_ID, desFolderId);
} values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
try { values.put(NoteColumns.LOCAL_MODIFIED, 1);
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
if (results == null || results.length == 0 || results[0] == null) { }
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
} long folderId) {
return true; if (ids == null) {
} catch (RemoteException e) { Log.d(TAG, "the ids is null");
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); return true;
} catch (OperationApplicationException e) { }
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
return false; for (long id : ids) {
} ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { builder.withValue(NoteColumns.PARENT_ID, folderId);
ContentValues values = new ContentValues(); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, desFolderId); operationList.add(builder.build());
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); }
values.put(NoteColumns.LOCAL_MODIFIED, 1);
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); try {
} ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, Log.d(TAG, "delete notes failed, ids:" + ids.toString());
long folderId) { return false;
if (ids == null) { }
Log.d(TAG, "the ids is null"); return true;
return true; } catch (RemoteException e) {
} Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
for (long id : ids) { }
ContentProviderOperation.Builder builder = ContentProviderOperation return false;
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); }
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); /**
operationList.add(builder.build()); * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
} */
public static int getUserFolderCount(ContentResolver resolver) {
try { Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); new String[] { "COUNT(*)" },
if (results == null || results.length == 0 || results[0] == null) { NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
return false; null);
}
return true; int count = 0;
} catch (RemoteException e) { if(cursor != null) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); if(cursor.moveToFirst()) {
} catch (OperationApplicationException e) { try {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); count = cursor.getInt(0);
} } catch (IndexOutOfBoundsException e) {
return false; Log.e(TAG, "get folder count failed:" + e.toString());
} } finally {
cursor.close();
/** }
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} }
*/ }
public static int getUserFolderCount(ContentResolver resolver) { return count;
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, }
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null); null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
int count = 0; new String [] {String.valueOf(type)},
if(cursor != null) { null);
if(cursor.moveToFirst()) {
try { boolean exist = false;
count = cursor.getInt(0); if (cursor != null) {
} catch (IndexOutOfBoundsException e) { if (cursor.getCount() > 0) {
Log.e(TAG, "get folder count failed:" + e.toString()); exist = true;
} finally { }
cursor.close(); cursor.close();
} }
} return exist;
} }
return count;
} public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { null, null, null, null);
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, boolean exist = false;
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, if (cursor != null) {
new String [] {String.valueOf(type)}, if (cursor.getCount() > 0) {
null); exist = true;
}
boolean exist = false; cursor.close();
if (cursor != null) { }
if (cursor.getCount() > 0) { return exist;
exist = true; }
}
cursor.close(); public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
} Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
return exist; null, null, null, null);
}
boolean exist = false;
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { if (cursor != null) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), if (cursor.getCount() > 0) {
null, null, null, null); exist = true;
}
boolean exist = false; cursor.close();
if (cursor != null) { }
if (cursor.getCount() > 0) { return exist;
exist = true; }
}
cursor.close(); public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
} Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
return exist; NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
} " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { new String[] { name }, null);
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), boolean exist = false;
null, null, null, null); if(cursor != null) {
if(cursor.getCount() > 0) {
boolean exist = false; exist = true;
if (cursor != null) { }
if (cursor.getCount() > 0) { cursor.close();
exist = true; }
} return exist;
cursor.close(); }
}
return exist; public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
} Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { NoteColumns.PARENT_ID + "=?",
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, new String[] { String.valueOf(folderId) },
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + null);
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", HashSet<AppWidgetAttribute> set = null;
new String[] { name }, null); if (c != null) {
boolean exist = false; if (c.moveToFirst()) {
if(cursor != null) { set = new HashSet<AppWidgetAttribute>();
if(cursor.getCount() > 0) { do {
exist = true; try {
} AppWidgetAttribute widget = new AppWidgetAttribute();
cursor.close(); widget.widgetId = c.getInt(0);
} widget.widgetType = c.getInt(1);
return exist; set.add(widget);
} } catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { }
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, } while (c.moveToNext());
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, }
NoteColumns.PARENT_ID + "=?", c.close();
new String[] { String.valueOf(folderId) }, }
null); return set;
}
HashSet<AppWidgetAttribute> set = null;
if (c != null) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
if (c.moveToFirst()) { Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
set = new HashSet<AppWidgetAttribute>(); new String [] { CallNote.PHONE_NUMBER },
do { CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
try { new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
AppWidgetAttribute widget = new AppWidgetAttribute(); null);
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1); if (cursor != null && cursor.moveToFirst()) {
set.add(widget); try {
} catch (IndexOutOfBoundsException e) { return cursor.getString(0);
Log.e(TAG, e.toString()); } catch (IndexOutOfBoundsException e) {
} Log.e(TAG, "Get call number fails " + e.toString());
} while (c.moveToNext()); } finally {
} cursor.close();
c.close(); }
} }
return set; return "";
} }
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.NOTE_ID },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + CallNote.PHONE_NUMBER + ",?)",
null); new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null && cursor.moveToFirst()) {
try { if (cursor != null) {
return cursor.getString(0); if (cursor.moveToFirst()) {
} catch (IndexOutOfBoundsException e) { try {
Log.e(TAG, "Get call number fails " + e.toString()); return cursor.getLong(0);
} finally { } catch (IndexOutOfBoundsException e) {
cursor.close(); Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
return ""; cursor.close();
} }
return 0;
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { }
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, public static String getSnippetById(ContentResolver resolver, long noteId) {
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
+ CallNote.PHONE_NUMBER + ",?)", new String [] { NoteColumns.SNIPPET },
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, NoteColumns.ID + "=?",
null); new String [] { String.valueOf(noteId)},
null);
if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor != null) {
try { String snippet = "";
return cursor.getLong(0); if (cursor.moveToFirst()) {
} catch (IndexOutOfBoundsException e) { snippet = cursor.getString(0);
Log.e(TAG, "Get call note id fails " + e.toString()); }
} cursor.close();
} return snippet;
cursor.close(); }
} throw new IllegalArgumentException("Note is not found with id: " + noteId);
return 0; }
}
public static String getFormattedSnippet(String snippet) {
public static String getSnippetById(ContentResolver resolver, long noteId) { if (snippet != null) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, snippet = snippet.trim();
new String [] { NoteColumns.SNIPPET }, int index = snippet.indexOf('\n');
NoteColumns.ID + "=?", if (index != -1) {
new String [] { String.valueOf(noteId)}, snippet = snippet.substring(0, index);
null); }
}
if (cursor != null) { return snippet;
String snippet = ""; }
if (cursor.moveToFirst()) { }
snippet = cursor.getString(0);
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);
}
}
return snippet;
}
}

@ -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;

@ -40,12 +40,11 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
// AlarmAlertActivity 类,用于显示闹钟提醒界面
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; // 笔记的唯一标识符 private long mNoteId;
private String mSnippet; // 笔记的片段内容 private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60; // 笔记片段的最大长度 private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer; // 播放器对象 MediaPlayer mPlayer;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -65,10 +64,8 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
Intent intent = getIntent(); Intent intent = getIntent();
try { try {
// 从意图中获取笔记的唯一标识符,并根据标识符获取笔记片段内容
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果笔记片段内容超过最大长度,截取并添加附加信息
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet; : mSnippet;
@ -79,7 +76,6 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 如果笔记在数据库中可见,显示操作对话框并播放闹钟声音
showActionDialog(); showActionDialog();
playAlarmSound(); playAlarmSound();
} else { } else {
@ -93,37 +89,37 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
private void playAlarmSound() { private void playAlarmSound() {
// 获取闹钟铃声的 URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 根据静音模式设置播放器的音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
// 设置播放器的数据源,准备播放并循环播放
mPlayer.setDataSource(this, url); mPlayer.setDataSource(this, url);
mPlayer.prepare(); mPlayer.prepare();
mPlayer.setLooping(true); mPlayer.setLooping(true);
mPlayer.start(); mPlayer.start();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (SecurityException e) { } catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
private void showActionDialog() { private void showActionDialog() {
// 显示操作对话框,包括笔记片段内容和按钮
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name); dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet); dialog.setMessage(mSnippet);
@ -137,7 +133,6 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEGATIVE:
// 点击“进入”按钮,打开 NoteEditActivity 并显示当前笔记
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.putExtra(Intent.EXTRA_UID, mNoteId);
@ -149,13 +144,11 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
// 对话框消失时停止闹钟声音并关闭界面
stopAlarmSound(); stopAlarmSound();
finish(); finish();
} }
private void stopAlarmSound() { private void stopAlarmSound() {
// 停止并释放播放器对象
if (mPlayer != null) { if (mPlayer != null) {
mPlayer.stop(); mPlayer.stop();
mPlayer.release(); mPlayer.release();

@ -30,53 +30,35 @@ import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
// 定义需要查询的列
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE
}; };
// 定义列索引
private static final int COLUMN_ID = 0; private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ALERTED_DATE = 1;
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 获取当前系统时间
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();
// 查询匹配条件的便签信息
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) }, new String[] { String.valueOf(currentDate) },
null); null);
// 检查查询结果是否为空
if (c != null) { if (c != null) {
// 检查是否有匹配的记录
if (c.moveToFirst()) { if (c.moveToFirst()) {
do { do {
// 获取提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个意图对象,用于触发闹钟时执行特定的操作
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
// 设置数据,通常用于唯一标识某个便签
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个用于发送广播的PendingIntent
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
// 获取AlarmManager实例用于设置闹钟 .getSystemService(Context.ALARM_SERVICE);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
// 设置闹钟,触发时间为提醒时间
alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); } while (c.moveToNext());
} }
// 关闭Cursor释放资源
c.close(); c.close();
} }
} }

@ -21,16 +21,10 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 创建一个新的Intent用于启动AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加标志指示要启动一个新的Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动指定的Activity
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -32,7 +32,6 @@ public class DateTimePicker extends FrameLayout {
private static final boolean DEFAULT_ENABLE_STATE = true; private static final boolean DEFAULT_ENABLE_STATE = true;
//定义了一些常用的变量,这些变量是全局的,在这里定义会便于修改
private static final int HOURS_IN_HALF_DAY = 12; private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24; private static final int HOURS_IN_ALL_DAY = 24;
private static final int DAYS_IN_ALL_WEEK = 7; private static final int DAYS_IN_ALL_WEEK = 7;
@ -65,189 +64,133 @@ public class DateTimePicker extends FrameLayout {
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 创建一个监听日期选择器值变化事件的监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
// 当日期选择器的值发生变化时,下面的方法会被调用
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 更新日期对象mDate的日历字段根据新值和旧值之间的差异
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
// 更新与日期选择相关的用户界面控件,以反映新的日期值
updateDateControl(); updateDateControl();
// 可能用于通知日期时间的整体变化具体实现需要查看onDateTimeChanged()方法的定义
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
// 创建一个监听小时选择器值变化事件的监听器 @Override
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@Override boolean isDateChanged = false;
// 当小时选择器的值发生变化时,下面的方法会被调用 Calendar cal = Calendar.getInstance();
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { if (!mIs24HourView) {
boolean isDateChanged = false; // 用于标记日期是否发生变化 if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
Calendar cal = Calendar.getInstance(); // 创建一个日历对象,用于处理日期操作 cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
// 如果不是24小时制 isDateChanged = true;
if (!mIs24HourView) { } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
// 如果不是上午,并且旧值是上午结束的最后一小时,新值是上午开始的第一小时 cal.setTimeInMillis(mDate.getTimeInMillis());
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { cal.add(Calendar.DAY_OF_YEAR, -1);
cal.setTimeInMillis(mDate.getTimeInMillis()); isDateChanged = true;
cal.add(Calendar.DAY_OF_YEAR, 1); // 将日期增加一天 }
isDateChanged = true; // 标记日期发生变化 if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
} oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
// 如果是上午,并且旧值是上午开始的第一小时,新值是上午结束的最后一小时 mIsAm = !mIsAm;
else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { updateAmPmControl();
cal.setTimeInMillis(mDate.getTimeInMillis()); }
cal.add(Calendar.DAY_OF_YEAR, -1); // 将日期减少一天 } else {
isDateChanged = true; // 标记日期发生变化 if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
} cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
// 如果旧值和新值分别跨越上午/下午的边界 isDateChanged = true;
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { cal.setTimeInMillis(mDate.getTimeInMillis());
mIsAm = !mIsAm; // 切换上午和下午标记 cal.add(Calendar.DAY_OF_YEAR, -1);
updateAmPmControl(); // 更新上午/下午相关的用户界面控件 isDateChanged = true;
} }
}
// 如果是24小时制
else {
// 如果旧值是一天中最后一小时,新值是一天中第一小时
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); // 将日期增加一天
isDateChanged = true; // 标记日期发生变化
} }
// 如果旧值是一天中第一小时,新值是一天中最后一小时 int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { mDate.set(Calendar.HOUR_OF_DAY, newHour);
cal.setTimeInMillis(mDate.getTimeInMillis()); onDateTimeChanged();
cal.add(Calendar.DAY_OF_YEAR, -1); // 将日期减少一天 if (isDateChanged) {
isDateChanged = true; // 标记日期发生变化 setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
} }
} }
};
// 计算新的小时值,考虑上午/下午,并更新日期对象中的小时字段
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
// 通知日期时间的整体变化
onDateTimeChanged();
// 如果日期发生变化,更新当前的年、月、日
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
// 创建一个监听分钟选择器值变化事件的监听器
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
// 当分钟选择器的值发生变化时,下面的方法会被调用
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue(); // 获取分钟选择器的最小值 int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue(); // 获取分钟选择器的最大值 int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0; // 用于记录小时的偏移量 int offset = 0;
// 检查是否跨越了分钟的边界,即从最大值切换到最小值或从最小值切换到最大值
if (oldVal == maxValue && newVal == minValue) { if (oldVal == maxValue && newVal == minValue) {
offset += 1; // 如果跨越了分钟的边界将小时偏移量增加1 offset += 1;
} else if (oldVal == minValue && newVal == maxValue) { } else if (oldVal == minValue && newVal == maxValue) {
offset -= 1; // 如果跨越了分钟的边界将小时偏移量减少1 offset -= 1;
} }
// 如果发生了小时的偏移
if (offset != 0) { if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset); // 更新日期对象中的小时字段 mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour()); // 设置小时选择器的值 mHourSpinner.setValue(getCurrentHour());
updateDateControl(); // 更新日期控件 updateDateControl();
int newHour = getCurrentHourOfDay(); // 获取新的小时值 int newHour = getCurrentHourOfDay();
// 根据新的小时值更新上午/下午标记
if (newHour >= HOURS_IN_HALF_DAY) { if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false; // 如果新的小时值大于等于半天的小时数,表示下午 mIsAm = false;
updateAmPmControl(); // 更新上午/下午相关的用户界面控件 updateAmPmControl();
} else { } else {
mIsAm = true; // 否则表示上午 mIsAm = true;
updateAmPmControl(); // 更新上午/下午相关的用户界面控件 updateAmPmControl();
} }
} }
mDate.set(Calendar.MINUTE, newVal);
mDate.set(Calendar.MINUTE, newVal); // 更新日期对象中的分钟字段 onDateTimeChanged();
onDateTimeChanged(); // 通知日期时间的整体变化
} }
}; };
// 创建一个监听上午/下午选择器值变化事件的监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
// 当上午/下午选择器的值发生变化时,下面的方法会被调用
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm; // 切换上午/下午标记的值,如果是上午变为下午,反之亦然 mIsAm = !mIsAm;
// 根据上午/下午标记的变化,调整日期对象中的小时字段
if (mIsAm) { if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); // 如果是上午减少12小时 mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else { } else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); // 如果是下午增加12小时 mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
} }
updateAmPmControl();
updateAmPmControl(); // 更新上午/下午选择器的用户界面控件 onDateTimeChanged();
onDateTimeChanged(); // 通知日期时间的整体变化
} }
}; };
// 定义一个接口,用于监听日期时间变化事件
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
// 构造函数用于创建DateTimePicker实例传入上下文参数
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); // 调用另一个构造函数并传入当前系统时间 this(context, System.currentTimeMillis());
} }
// 构造函数用于创建DateTimePicker实例传入上下文和日期时间参数
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); // 调用另一个构造函数并传入日期时间和是否为24小时制的参数 this(context, date, DateFormat.is24HourFormat(context));
} }
// 构造函数用于创建DateTimePicker实例传入上下文、日期时间和是否为24小时制的参数
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); // 调用父类构造函数 super(context);
mDate = Calendar.getInstance(); // 初始化日期时间对象 mDate = Calendar.getInstance();
mInitialising = true; // 标记初始化过程中的状态 mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; // 根据当前小时判断是否为上午 mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局文件,将其附加到当前视图
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100); mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化上午/下午选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
@ -255,104 +198,92 @@ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPi
mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 更新各控件的初始状态 // update controls to initial state
updateDateControl(); updateDateControl();
updateHourControl(); updateHourControl();
updateAmPmControl(); updateAmPmControl();
set24HourView(is24HourView); // 设置是否为24小时制 set24HourView(is24HourView);
// 设置当前日期时间 // set to current time
setCurrentDate(date); setCurrentDate(date);
setEnabled(isEnabled()); // 设置控件是否可用 setEnabled(isEnabled());
// 设置内容描述,用于辅助功能 // set the content descriptions
mInitialising = false; // 初始化过程结束 mInitialising = false;
} }
/**
*
*
* @param enabled
*/
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) { if (mIsEnabled == enabled) {
return; // 如果已经处于相同状态,无需执行任何操作 return;
} }
super.setEnabled(enabled); // 调用父类方法设置控件的启用状态 super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled); // 设置日期选择器是否启用 mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled); // 设置分钟选择器是否启用 mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled); // 设置小时选择器是否启用 mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled); // 设置上午/下午选择器是否启用 mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled; // 更新控件的启用状态标志 mIsEnabled = enabled;
} }
/**
*
*
* @return
*/
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; // 返回控件的启用状态标志 return mIsEnabled;
} }
/** /**
* * Get the current date in millis
* *
* @return * @return the current date in millis
*/ */
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); // 返回当前日期的毫秒表示 return mDate.getTimeInMillis();
} }
/** /**
* * Set the current date
* *
* @param date * @param date The current date in millis
*/ */
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date); // 将传入的日期毫秒值设置到Calendar对象中 cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); // 设置当前日期和时间 cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
} }
/** /**
* * Set the current date
* *
* @param year * @param year The current year
* @param month * @param month The current month
* @param dayOfMonth * @param dayOfMonth The current dayOfMonth
* @param hourOfDay * @param hourOfDay The current hourOfDay
* @param minute * @param minute The current minute
*/ */
public void setCurrentDate(int year, int month, public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year); // 设置当前年份 setCurrentYear(year);
setCurrentMonth(month); // 设置当前月份 setCurrentMonth(month);
setCurrentDay(dayOfMonth); // 设置当前日 setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay); // 设置当前小时 setCurrentHour(hourOfDay);
setCurrentMinute(minute); // 设置当前分钟 setCurrentMinute(minute);
} }
/** /**
* * Get current year
* *
* @return * @return The current year
*/ */
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
/** /**
* * Set current year
* *
* @param year * @param year The current year
*/ */
public void setCurrentYear(int year) { public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) { if (!mInitialising && year == getCurrentYear()) {
@ -364,18 +295,18 @@ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPi
} }
/** /**
* * Get current month in the year
* *
* @return * @return The current month in the year
*/ */
public int getCurrentMonth() { public int getCurrentMonth() {
return mDate.get(Calendar.MONTH); return mDate.get(Calendar.MONTH);
} }
/** /**
* * Set current month in the year
* *
* @param month * @param month The month in the year
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
@ -387,18 +318,18 @@ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPi
} }
/** /**
* * Get current day of the month
* *
* @return * @return The day of the month
*/ */
public int getCurrentDay() { public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH); return mDate.get(Calendar.DAY_OF_MONTH);
} }
/** /**
* * Set current day of the month
* *
* @param dayOfMonth * @param dayOfMonth The day of the month
*/ */
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -410,21 +341,15 @@ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPi
} }
/** /**
* 24(0~23) * Get current hour in 24 hour mode, in the range (0~23)
* * @return The current hour in 24 hour mode
* @return 24
*/ */
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
/**
*
*
* @return
*/
private int getCurrentHour() { private int getCurrentHour() {
if (mIs24HourView) { if (mIs24HourView){
return getCurrentHourOfDay(); return getCurrentHourOfDay();
} else { } else {
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
@ -436,170 +361,125 @@ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPi
} }
} }
/** /**
* 24(0~23) * Set current hour in 24 hour mode, in the range (0~23)
* *
* @param hourOfDay * @param hourOfDay
*/ */
public void setCurrentHour(int hourOfDay) { public void setCurrentHour(int hourOfDay) {
// 如果不是在初始化状态并且设置的小时与当前小时一致,则不执行任何操作。
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return; return;
} }
// 设置日历对象中的小时字段为指定值。
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
// 如果不是24小时制根据小时值来确定上午或下午。
if (!mIs24HourView) { if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false; // 设置为下午 mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) { if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY; hourOfDay -= HOURS_IN_HALF_DAY;
} }
} else { } else {
mIsAm = true; // 设置为上午 mIsAm = true;
if (hourOfDay == 0) { if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY; hourOfDay = HOURS_IN_HALF_DAY;
} }
} }
// 更新上午/下午控件的显示。
updateAmPmControl(); updateAmPmControl();
} }
// 更新小时控件的显示。
mHourSpinner.setValue(hourOfDay); mHourSpinner.setValue(hourOfDay);
// 通知日期时间变化的监听器。
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* * Get currentMinute
* *
* @return * @return The Current Minute
*/ */
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
/** /**
* * Set current minute
*
*
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
// 如果不是在初始化状态并且设置的分钟与当前分钟一致,则不执行任何操作。
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
return; return;
} }
// 设置分钟控件的显示值。
mMinuteSpinner.setValue(minute); mMinuteSpinner.setValue(minute);
// 设置日历对象中的分钟字段为指定值。
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 通知日期时间变化的监听器。
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* 24 * @return true if this is in 24 hour view else false.
*
* @return 24truefalse
*/ */
public boolean is24HourView() { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
/** /**
* 24/ * Set whether in 24 hour or AM/PM mode.
* *
* @param is24HourView true使24使/ * @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/ */
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
// 如果已经是要设置的小时制,不执行任何操作。
if (mIs24HourView == is24HourView) { if (mIs24HourView == is24HourView) {
return; return;
} }
// 更新小时制的状态。
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
// 根据新的小时制设置上午/下午控件的可见性。
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
// 获取当前小时,并根据小时制更新小时控件。
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
updateHourControl(); updateHourControl();
setCurrentHour(hour); setCurrentHour(hour);
// 更新上午/下午控件的显示。
updateAmPmControl(); updateAmPmControl();
} }
// 更新日期控件的方法
private void updateDateControl() { private void updateDateControl() {
// 创建一个 Calendar 对象用于日期操作
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 设置 Calendar 对象的时间戳为用户选择的日期
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
// 向前调整日期以确保在日期控件中显示一周的日期
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
// 清空日期控件的显示值
mDateSpinner.setDisplayedValues(null); mDateSpinner.setDisplayedValues(null);
// 循环生成一周中的日期并存储在 mDateDisplayValues 数组中
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
// 格式化日期为 "MM.dd EEEE" 的字符串形式并存储在 mDateDisplayValues 数组中
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
} }
// 设置日期控件的显示值为生成的日期数组
mDateSpinner.setDisplayedValues(mDateDisplayValues); mDateSpinner.setDisplayedValues(mDateDisplayValues);
// 将日期控件滚动到一周中间的日期
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
// 刷新日期控件以更新显示
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
// 更新上午/下午控件的方法
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
// 如果应用使用24小时制则隐藏上午/下午控件
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);
} else { } else {
// 如果应用使用12小时制根据 mIsAm 的值确定上午或下午,并设置对应的值
int index = mIsAm ? Calendar.AM : Calendar.PM; int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index); mAmPmSpinner.setValue(index);
// 显示上午/下午控件
mAmPmSpinner.setVisibility(View.VISIBLE); mAmPmSpinner.setVisibility(View.VISIBLE);
} }
} }
// 更新小时控件的方法
private void updateHourControl() { private void updateHourControl() {
if (mIs24HourView) { if (mIs24HourView) {
// 如果应用使用24小时制设置小时控件的最小和最大值
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else { } else {
// 如果应用使用12小时制设置小时控件的最小和最大值
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
} }
} }
/** /**
* * Set the callback that indicates the 'Set' button has been pressed.
* @param callback null * @param callback the callback, if null will do nothing
*/ */
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
// 设置日期时间变化监听器
mOnDateTimeChangedListener = callback; mOnDateTimeChangedListener = callback;
} }
// 当日期时间发生变化时调用的方法
private void onDateTimeChanged() { private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) { if (mOnDateTimeChangedListener != null) {
// 如果监听器不为空,触发监听器的回调方法并传递当前选择的年、月、日、小时和分钟作为参数
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
} }
} }
} }

@ -39,72 +39,52 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker); setView(mDateTimePicker);
// 设置日期时间选择器的监听器,以在日期时间变化时更新标题和数据
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month, public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
// 更新内部日期对象 mDate 的值
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 更新对话框的标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
}); });
// 初始化内部日期对象 mDate并将其秒数设置为 0
mDate.setTimeInMillis(date); mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0); mDate.set(Calendar.SECOND, 0);
// 设置日期时间选择器的当前日期和时间
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框的“确定”按钮文本和点击监听器
setButton(context.getString(R.string.datetime_dialog_ok), this); setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置对话框的“取消”按钮文本,并将其点击监听器设置为 null
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 设置是否使用24小时制时间显示
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新对话框的标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
// 设置是否使用24小时制时间显示
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
// 设置日期时间设置监听器
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
private void updateTitle(long date) { private void updateTitle(long date) {
// 定义用于格式化标题的标志
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME;
// 根据是否使用24小时制时间显示来更新标志
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 根据给定的日期和标志格式化标题并设置为对话框的标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
// 当点击“确定”按钮时,如果监听器不为空,触发监听器的回调方法并传递当前选择的日期时间
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }
} }
} }

@ -33,30 +33,29 @@ public class DropdownMenu {
private Menu mMenu; private Menu mMenu;
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; // 保存传入的按钮引用 mButton = button;
mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮背景图像 mButton.setBackgroundResource(R.drawable.dropdown_icon);
mPopupMenu = new PopupMenu(context, mButton); // 创建弹出菜单与按钮关联 mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu(); // 获取弹出菜单的菜单对象 mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); // 填充菜单项从指定的menuId mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mButton.setOnClickListener(new OnClickListener() { mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mPopupMenu.show(); // 当按钮被点击时,显示弹出菜单 mPopupMenu.show();
} }
}); });
} }
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); // 设置弹出菜单的菜单项点击监听器 mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); // 查找特定ID的菜单项 return mMenu.findItem(id);
} }
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); // 设置按钮的文本标题 mButton.setText(title);
} }
} }

@ -31,21 +31,21 @@ import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, // 列投影数组的索引0 NoteColumns.ID,
NoteColumns.SNIPPET // 列投影数组的索引1 NoteColumns.SNIPPET
}; };
public static final int ID_COLUMN = 0; // 列投影数组的ID列索引 public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; // 列投影数组的名称列索引 public static final int NAME_COLUMN = 1;
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// 构造函数初始化CursorAdapter // TODO Auto-generated constructor stub
} }
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); // 创建新的视图用于显示数据项 return new FolderListItem(context);
} }
@Override @Override
@ -53,14 +53,14 @@ public class FoldersListAdapter extends CursorAdapter {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName); // 将数据绑定到视图 ((FolderListItem) view).bind(folderName);
} }
} }
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); // 获取特定位置的Cursor Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); // 根据游标数据返回文件夹名称 .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
@ -68,12 +68,13 @@ public class FoldersListAdapter extends CursorAdapter {
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.folder_list_item, this); // 填充视图布局 inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name); // 获取文件夹名称的TextView mName = (TextView) findViewById(R.id.tv_folder_name);
} }
public void bind(String name) { public void bind(String name) {
mName.setText(name); // 设置文件夹名称文本 mName.setText(name);
} }
} }
} }

File diff suppressed because it is too large Load Diff

@ -45,7 +45,7 @@ public class NoteEditText extends EditText {
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
// 定义一个映射将不同的URL scheme与资源ID关联起来
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
@ -54,16 +54,24 @@ public class NoteEditText extends EditText {
} }
/** /**
* NoteEditActivityEditText * Call by the {@link NoteEditActivity} to delete or add edit text
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {
// 当文本为空且按下删除键KEYCODE_DEL删除当前EditText /**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);
// 当按下回车键KEYCODE_ENTER在当前EditText之后添加EditText /**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);
// 当文本发生更改时,隐藏或显示项目选项 /**
* Hide or show item option when text change
*/
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);
} }
@ -73,11 +81,11 @@ public class NoteEditText extends EditText {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
// 设置EditText的索引
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
// 设置文本变化监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
@ -88,13 +96,11 @@ public class NoteEditText extends EditText {
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO 自动生成的构造函数存根 // TODO Auto-generated constructor stub
} }
@Override @Override
// 处理touch事件用于选择文本
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
// 在用户按下时,选择文本
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
@ -116,11 +122,9 @@ public class NoteEditText extends EditText {
} }
@Override @Override
// 处理按键按下事件
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 当按下回车键KEYCODE_ENTER如果有文本变化监听器返回false
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
return false; return false;
} }
@ -135,11 +139,9 @@ public class NoteEditText extends EditText {
} }
@Override @Override
// 处理按键释放事件
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { switch(keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
// 处理按键释放事件,回车和删除键
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
@ -150,7 +152,6 @@ public class NoteEditText extends EditText {
} }
break; break;
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart(); int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString(); String text = getText().subSequence(selectionStart, length()).toString();
@ -167,9 +168,7 @@ public class NoteEditText extends EditText {
} }
@Override @Override
// 当焦点发生变化时的回调
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
// 当焦点发生变化时,通知文本变化监听器
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) { if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false); mOnTextViewChangeListener.onTextChange(mIndex, false);
@ -182,8 +181,6 @@ public class NoteEditText extends EditText {
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
// 创建上下文菜单
// 在文本上下文菜单中添加选项
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();

@ -14,215 +14,211 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import net.micode.notes.data.Contact; import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT, NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3; private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5; private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6; private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7; private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8; private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
private long mId; private long mId;
private long mAlertDate; private long mAlertDate;
private int mBgColorId; private int mBgColorId;
private long mCreatedDate; private long mCreatedDate;
private boolean mHasAttachment; private boolean mHasAttachment;
private long mModifiedDate; private long mModifiedDate;
private int mNotesCount; private int mNotesCount;
private long mParentId; private long mParentId;
private String mSnippet; private String mSnippet;
private int mType; private int mType;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
private boolean mIsLastItem; private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
// 构造函数,用于初始化笔记项数据
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = ""; mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) { if (mName == null) {
mName = mPhoneNumber; mName = mPhoneNumber;
} }
} }
} }
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
checkPostion(cursor); checkPostion(cursor);
} }
// 检查笔记项在Cursor中的位置设置一些标志
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
// 检查是否是最后一项 mIsLastItem = cursor.isLast() ? true : false;
mIsLastItem = cursor.isLast() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
// 检查是否是第一项 mIsOnlyOneItem = (cursor.getCount() == 1);
mIsFirstItem = cursor.isFirst() ? true : false; mIsMultiNotesFollowingFolder = false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOneNoteFollowingFolder = false;
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (cursor.moveToPrevious()) {
// 检查笔记项是否在文件夹后有多个笔记 if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
int position = cursor.getPosition(); || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.moveToPrevious()) { if (cursor.getCount() > (position + 1)) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER mIsMultiNotesFollowingFolder = true;
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { } else {
if (cursor.getCount() > (position + 1)) { mIsOneNoteFollowingFolder = true;
mIsMultiNotesFollowingFolder = true; }
} else { }
mIsOneNoteFollowingFolder = true; if (!cursor.moveToNext()) {
} throw new IllegalStateException("cursor move to previous but can't move back");
} }
if (!cursor.moveToNext()) { }
throw new IllegalStateException("cursor move to previous but can't move back"); }
} }
}
} public boolean isOneFollowingFolder() {
} return mIsOneNoteFollowingFolder;
// 检查笔记项是否在文件夹后有一个笔记 }
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; public boolean isMultiFollowingFolder() {
} return mIsMultiNotesFollowingFolder;
// 检查笔记项是否在文件夹后有多个笔记 }
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; public boolean isLast() {
} return mIsLastItem;
// 检查笔记项是否是最后一项 }
public boolean isLast() {
return mIsLastItem; public String getCallName() {
} return mName;
}
public String getCallName() {
return mName; public boolean isFirst() {
} return mIsFirstItem;
// 检查笔记项是否是第一项 }
public boolean isFirst() {
return mIsFirstItem; public boolean isSingle() {
} return mIsOnlyOneItem;
}
public boolean isSingle() {
return mIsOnlyOneItem; public long getId() {
} return mId;
}
public long getId() {
return mId; public long getAlertDate() {
} return mAlertDate;
}
public long getAlertDate() {
return mAlertDate; public long getCreatedDate() {
} return mCreatedDate;
}
public long getCreatedDate() {
return mCreatedDate; public boolean hasAttachment() {
} return mHasAttachment;
}
public boolean hasAttachment() {
return mHasAttachment; public long getModifiedDate() {
} return mModifiedDate;
}
public long getModifiedDate() {
return mModifiedDate; public int getBgColorId() {
} return mBgColorId;
}
public int getBgColorId() {
return mBgColorId; public long getParentId() {
} return mParentId;
}
public long getParentId() {
return mParentId; public int getNotesCount() {
} return mNotesCount;
}
public int getNotesCount() {
return mNotesCount; public long getFolderId () {
} return mParentId;
}
public long getFolderId () {
return mParentId; public int getType() {
} return mType;
}
public int getType() {
return mType; public int getWidgetType() {
} return mWidgetType;
}
public int getWidgetType() {
return mWidgetType; public int getWidgetId() {
} return mWidgetId;
}
public int getWidgetId() {
return mWidgetId; public String getSnippet() {
} return mSnippet;
}
public String getSnippet() {
return mSnippet; public boolean hasAlert() {
} return (mAlertDate > 0);
}
public boolean hasAlert() {
return (mAlertDate > 0); public boolean isCallRecord() {
} return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); public static int getNoteType(Cursor cursor) {
} return cursor.getInt(TYPE_COLUMN);
}
public static int getNoteType(Cursor cursor) { }
return cursor.getInt(TYPE_COLUMN);
}
}

File diff suppressed because it is too large Load Diff

@ -1,109 +1,85 @@
/*
* 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;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import android.view.View; 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;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; 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();
@ -168,90 +127,58 @@ 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;
} }
return mSelectedIndex.get(position); return mSelectedIndex.get(position);
} }
@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,5 +1,21 @@
/*
* 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;
import android.text.format.DateUtils; import android.text.format.DateUtils;
import android.view.View; import android.view.View;
@ -7,50 +23,44 @@ import android.widget.CheckBox;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
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.tool.DataUtils; 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,39 +87,36 @@ 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,5 +1,21 @@
/*
* 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;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.ActionBar; import android.app.ActionBar;
@ -25,151 +41,108 @@ import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
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.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;
} }
} }
} }
} }
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();
@ -177,30 +150,22 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return true; return true;
} }
}); });
//根据新建首选项编辑新的账户分组
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,120 +224,84 @@ 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() {
public void run() { public void run() {
@ -399,34 +311,24 @@ 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() {
public void run() { public void run() {
@ -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;
} }
} }
} }

@ -46,88 +46,52 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider";
@Override @Override
// 当小部件从主屏幕中被删除时调用的方法
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
// 创建 ContentValues 对象,用于存储更新数据库的数值
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
// 将 NoteColumns.WIDGET_ID 的值设置为无效的小部件 IDAppWidgetManager.INVALID_APPWIDGET_ID
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历传入的小部件 ID 数组
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
// 使用 ContentResolver 更新 Notes 数据库中的相应小部件 ID 的记录 context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
context.getContentResolver().update( values,
Notes.CONTENT_NOTE_URI, // 更新的数据表的 URI NoteColumns.WIDGET_ID + "=?",
values, // 更新的数值 new String[] { String.valueOf(appWidgetIds[i])});
NoteColumns.WIDGET_ID + "=?", // 更新的条件,匹配小部件 ID
new String[] { String.valueOf(appWidgetIds[i]) } // 匹配条件的参数,传入当前小部件 ID
);
} }
} }
// 获取与小部件相关的笔记信息的方法
// 参数 context上下文对象用于访问内容提供程序
// 参数 widgetId要获取信息的小部件的唯一标识符
// 返回值:包含笔记信息的游标对象
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
// 使用内容解析器查询 Notes 数据库中的记录 return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
// 查询的条件是NoteColumns.WIDGET_ID 等于给定 widgetId同时 NoteColumns.PARENT_ID 不等于垃圾箱的 IDNotes.ID_TRASH_FOLER PROJECTION,
// 查询的列是由 PROJECTION 常量指定的列数组 NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
return context.getContentResolver().query( new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
Notes.CONTENT_NOTE_URI, // 查询的数据表的 URI null);
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) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用 update 方法的重载版本,传入默认参数 false
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
// update 方法,用于更新小部件 boolean privacyMode) {
// 参数 context上下文对象用于访问资源和小部件管理器
// 参数 appWidgetManager小部件管理器用于更新小部件
// 参数 appWidgetIds包含要更新的小部件 ID 的数组
// 参数 privacyMode一个布尔值表示小部件是否处于隐私模式
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 获取默认背景 ID
int bgId = ResourceParser.getDefaultBgId(context); int bgId = ResourceParser.getDefaultBgId(context);
// 初始化一个空字符串用于存储文本片段
String snippet = ""; String snippet = "";
// 创建一个意图,用于打开 NoteEditActivity
Intent intent = new Intent(context, NoteEditActivity.class); Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
// 查询与当前小部件相关的笔记信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) { if (c != null && c.moveToFirst()) {
// 如果查询结果中有多于一个记录,记录错误并返回
if (c.getCount() > 1) { if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with the same widget id:" + appWidgetIds[i]); Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close(); c.close();
return; return;
} }
// 从查询结果中获取文本片段和背景颜色 ID
snippet = c.getString(COLUMN_SNIPPET); snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID); bgId = c.getInt(COLUMN_BG_COLOR_ID);
// 设置 intent 中的额外数据,包括笔记的唯一标识符和操作类型
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
} else { } else {
// 如果没有查询到相关信息,使用默认文本片段和插入/编辑操作类型
snippet = context.getResources().getString(R.string.widget_havenot_content); snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
} }
@ -136,35 +100,30 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
c.close(); c.close();
} }
// 创建远程视图对象,用于配置小部件的外观
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
// 设置 intent 中的额外数据,包括背景 ID
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
// 生成用于启动小部件的挂起意图 * Generate the pending intent to start host for the widget
*/
PendingIntent pendingIntent = null; PendingIntent pendingIntent = null;
if (privacyMode) { if (privacyMode) {
// 如果小部件处于隐私模式,设置文本为特定文本并创建 NotesListActivity 的意图 rv.setTextViewText(R.id.widget_text,
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
// 如果不是隐私模式,将文本设置为笔记片段,并创建打开笔记编辑界面的意图
rv.setTextViewText(R.id.widget_text, snippet); rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent.FLAG_UPDATE_CURRENT);
} }
// 设置小部件的点击行为
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
} }
} }
} }
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId(); protected abstract int getLayoutId();

@ -14,161 +14,34 @@
* limitations under the License. * limitations under the License.
*/ */
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.Context;
import android.content.ContentValues;
import android.content.Context; import net.micode.notes.R;
import android.content.Intent; import net.micode.notes.data.Notes;
import android.database.Cursor; import net.micode.notes.tool.ResourceParser;
import android.util.Log;
import android.widget.RemoteViews;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
import net.micode.notes.R; @Override
import net.micode.notes.data.Notes; public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
import net.micode.notes.data.Notes.NoteColumns; super.update(context, appWidgetManager, appWidgetIds);
import net.micode.notes.tool.ResourceParser; }
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity; @Override
protected int getLayoutId() {
public abstract class NoteWidgetProvider extends AppWidgetProvider { return R.layout.widget_2x;
public static final String [] PROJECTION = new String [] { }
NoteColumns.ID,
NoteColumns.BG_COLOR_ID, @Override
NoteColumns.SNIPPET protected int getBgResourceId(int bgId) {
}; return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1; @Override
public static final int COLUMN_SNIPPET = 2; protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
private static final String TAG = "NoteWidgetProvider"; }
}
@Override
// 当小部件从主屏幕中被删除时调用的方法
public void onDeleted(Context context, int[] appWidgetIds) {
// 创建 ContentValues 对象,用于存储更新数据库的数值
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) {
c.close();
}
// 创建远程视图对象,用于配置小部件的外观
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
// 设置 intent 中的额外数据,包括背景 ID
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);
}
// 设置小部件的点击行为
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId();
protected abstract int getWidgetType();
}

@ -23,28 +23,22 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
// NoteWidgetProvider_4x 类是 NoteWidgetProvider 的子类,用于特定类型的小部件
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的 update 方法以执行小部件更新操作
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
// 获取小部件的布局资源 ID此处返回 R.layout.widget_4x
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x;
} }
// 获取与小部件类型相关的背景资源 ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
// 使用 ResourceParser 获取 4x 小部件的背景资源
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
} }
// 获取小部件的类型,此处返回 Notes.TYPE_WIDGET_4X
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X;

Loading…
Cancel
Save