data model
DUANYIQUN_BRANCH
pycalf7qb 2 years ago
commit fb9d1d63d7

@ -25,61 +25,50 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
<<<<<<< HEAD public class Contact { // 定义连接类
<<<<<<< HEAD:app/src/main/java/net/micode/notes/data/Contact.java private static HashMap<String, String> sContactCache; // 定义连接哈希表
public class Contact { private static final String TAG = "Contact"; // 设置TAG的值为'连接'
private static HashMap<String, String> sContactCache;//建立哈希表
private static final String TAG = "Contact";//设置TAG值为'联系'
=======
public class Contact {//连接类
private static HashMap<String, String> sContactCache;//建立哈希表
private static final String TAG = "Contact";//设置TAG的值为'连接'
>>>>>>> 0444a65d4e44c509f57ad301a5a2b59200d62177:src/data/Contact.java
=======
public class Contact { //连接类
private static HashMap<String, String> sContactCache; //定义连接哈希表
private static final String TAG = "Contact"; //设置TAG的值为'连接'
>>>>>>> b12b9a8449498593360310c554053628b31cc8c9
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 "
+ "(SELECT raw_contact_id " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; //SQL语句 + " WHERE min_match = '+')"; // SQL语句
public static String getContact(Context context, String phoneNumber) { //获取连接 public static String getContact(Context context, String phoneNumber) { // 获取连接
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); // 连接哈希表存在电话号码时获取值
} }
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); //将电话号码进行函数处理并代替'+'符号 PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); // 将电话号码进行函数处理并代替'+'符号
Cursor cursor = context.getContentResolver().query( //用于查询的结果集
Data.CONTENT_URI, //通话记录uri Cursor cursor = context.getContentResolver().query( // 用于查询的结果集
new String [] { Phone.DISPLAY_NAME }, Data.CONTENT_URI, // 通话记录uri
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) {
Log.e(TAG, " Cursor get string error " + e.toString()); //日志记录信息 Log.e(TAG, " Cursor get string error " + e.toString()); // 日志记录信息
return null; return null;
} finally { } finally {
cursor.close(); //关闭结果集 cursor.close(); // 关闭结果集
} }
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); //日志记录信息 Log.d(TAG, "No contact matched with number:" + phoneNumber); // 日志记录信息
return null; //没找到返回NULL return null; // 没找到返回NULL
} }
} }
} }

@ -17,263 +17,326 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
public class Notes { //定义类,为模块的其他类提供变量定义
public static final String AUTHORITY = "micode_notes"; //设置AUTHORITY
public static final String TAG = "Notes"; //设置TAG
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants { //获取记录
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");//查询所有笔记与文件的uri
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");//查询数据的uri
public interface NoteColumns { //定义便签变量接口
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id"; //父文件夹的id
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date"; //表示文件夹或便签创建日期
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date"; //便签的最新的修改日期
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date"; //提醒日期
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet"; //文件夹名称或便签内容
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id"; //便签的widget的id
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type"; //便签widget的类型
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id"; //背景颜色代号
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count"; //文件夹内的便签数
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type"; //文件类型,是文件夹或便签
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id"; //最后一次同步id
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified"; //本地修改名称标识
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; //移动文件时文件的前父类文件夹
/** public class Notes { // 定义类,给模块的其他类提供变量定义
* The gtask id public static final String AUTHORITY = "micode_notes"; // 设置AUTHORITY
* <P> Type : TEXT </P> public static final String TAG = "Notes"; // 设置TAG
*/ public static final int TYPE_NOTE = 0;
public static final String GTASK_ID = "gtask_id"; public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version"; //版本名称
}
public interface DataColumns { //定义数据变量接口
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/** /**
* The reference id to note that this data belongs to * Following IDs are system folders' identifiers
* <P> Type: INTEGER (long) </P> * {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/ */
public static final String NOTE_ID = "note_id"; //便签名称 public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants { // 获取记录
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/** /**
* Created data for note or folder * Uri to query all notes and folders
* <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; //创建文件夹或者便签的名称 public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");// 查询所有笔记与文件的uri
/** /**
* Latest modified date * Uri to query data
* <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; //最后修改日期 public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");// 查询数据的uri
/** public interface NoteColumns { // 定义便签变量接口
* Data's content /**
* <P> Type: TEXT </P> * The unique ID for a row
*/ * <P>
public static final String CONTENT = "content"; //便签内容数据 * Type: INTEGER (long)
* </P>
*/
/** public static final String ID = "_id";
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type /**
* <P> Type: INTEGER </P> * The parent's id for note or folder
*/ * <P>
public static final String DATA1 = "data1"; //不同类型的通用数据列,用于可能的存储与查找 * Type: INTEGER (long)
* </P>
/** */
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for public static final String PARENT_ID = "parent_id"; // 父文件夹的id
* integer data type
* <P> Type: INTEGER </P> /**
*/ * Created data for note or folder
public static final String DATA2 = "data2"; * <P>
* Type: INTEGER (long)
/** * </P>
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for */
* TEXT data type public static final String CREATED_DATE = "created_date"; // 表示文件夹或便签创建日期
* <P> Type: TEXT </P>
*/ /**
public static final String DATA3 = "data3"; * Latest modified date
* <P>
/** * Type: INTEGER (long)
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * </P>
* TEXT data type */
* <P> Type: TEXT </P> public static final String MODIFIED_DATE = "modified_date"; // 便签的最新的修改日期
*/
public static final String DATA4 = "data4"; /**
* Alert date
/** * <P>
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Type: INTEGER (long)
* TEXT data type * </P>
* <P> Type: TEXT </P> */
*/ public static final String ALERTED_DATE = "alert_date"; // 提醒日期
public static final String DATA5 = "data5";
} /**
* Folder's name or text content of note
public static final class TextNote implements DataColumns { * <P>
/** * Type: TEXT
* Mode to indicate the text in check list mode or not * </P>
* <P> Type: Integer 1:check list mode 0: normal mode </P> //1为列表检查模式0为普通模式 */
*/ public static final String SNIPPET = "snippet"; // 文件夹名称或便签内容
public static final String MODE = DATA1; //模式
/**
public static final int MODE_CHECK_LIST = 1; //列表检查模式 * Note's widget id
* <P>
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; * Type: INTEGER (long)
* </P>
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; */
public static final String WIDGET_ID = "widget_id"; // 便签的widget的id
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//访问数据表uri
} /**
* Note's widget type
public static final class CallNote implements DataColumns { * <P>
/** * Type: INTEGER (long)
* Call date for this record * </P>
* <P> Type: INTEGER (long) </P> */
*/ public static final String WIDGET_TYPE = "widget_type"; // 便签widget的类型
public static final String CALL_DATE = DATA1; //呼叫数据
/**
/** * Note's background color's id
* Phone number for this record * <P>
* <P> Type: TEXT </P> * Type: INTEGER (long)
*/ * </P>
public static final String PHONE_NUMBER = DATA3; //呼叫号码 */
public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色代号
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"; * For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P>
* Type: INTEGER
* </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String NOTES_COUNT = "notes_count"; // 文件夹内的便签数
/**
* The file type: folder or note
* <P>
* Type: INTEGER
* </P>
*/
public static final String TYPE = "type"; // 文件类型,是文件夹或便签
/**
* The last sync id
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String SYNC_ID = "sync_id"; // 最后一次同步id
/**
* Sign to indicate local modified or not
* <P>
* Type: INTEGER
* </P>
*/
public static final String LOCAL_MODIFIED = "local_modified"; // 本地修改名称标识
/**
* Original parent id before moving into temporary folder
* <P>
* Type : INTEGER
* </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 移动文件时文件的前父类文件夹
/**
* The gtask id
* <P>
* Type : TEXT
* </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P>
* Type : INTEGER (long)
* </P>
*/
public static final String VERSION = "version"; // 版本名称
}
public interface DataColumns { // 定义数据变量接口
/**
* The unique ID for a row
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P>
* Type: Text
* </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String NOTE_ID = "note_id"; // 便签名称
/**
* Created data for note or folder
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String CREATED_DATE = "created_date"; // 创建文件夹或者便签的名称
/**
* Latest modified date
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String MODIFIED_DATE = "modified_date"; // 最后修改日期
/**
* Data's content
* <P>
* Type: TEXT
* </P>
*/
public static final String CONTENT = "content"; // 便签内容数据
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P>
* Type: INTEGER
* </P>
*/
public static final String DATA1 = "data1"; // 不同类型的通用数据列,用于可能的存储与查找
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P>
* Type: INTEGER
* </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P>
* Type: TEXT
* </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P>
* Type: TEXT
* </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P>
* Type: TEXT
* </P>
*/
public static final String DATA5 = "data5";
}
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P>
* Type: Integer 1:check list mode 0: normal mode
* </P>
* //1为列表检查模式0为普通模式
*/
public static final String MODE = DATA1; // 模式
public static final int MODE_CHECK_LIST = 1; // 列表检查模式
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");// 访问数据表uri
}
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P>
* Type: INTEGER (long)
* </P>
*/
public static final String CALL_DATE = DATA1; // 呼叫数据
/**
* Phone number for this record
* <P>
* Type: TEXT
* </P>
*/
public static final String PHONE_NUMBER = DATA3; // 呼叫号码
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");// 访问电话记录uri
}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");//访问电话记录uri
}
} }

@ -26,198 +26,197 @@ 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;
//引入Notes中接口 //引入Notes中接口
public class NotesDatabaseHelper extends SQLiteOpenHelper { //该类为便签SQL表的定义以及操作便于进行文件夹与便签的各种操作,例如添加或删除的行为 public class NotesDatabaseHelper extends SQLiteOpenHelper { // 该类为便签SQL表的定义以及操作于进行文件夹与便签的各种操作,例如添加或删除的行为
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 { //定义一个数据库表接口 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; //创建NotesDatabaseHelper类对象 private static NotesDatabaseHelper mInstance; // 创建NotesDatabaseHelper类对象
private static final String CREATE_NOTE_TABLE_SQL = //SQL语句创建便签表包含ID、最后修改日期、背景颜色、便签数等在Notes类中的内容 private static final String CREATE_NOTE_TABLE_SQL = // SQL语句创建便签表包含ID、最后修改日期、背景颜色、便签数等在Notes类中的内容
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
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 = //创建数据表的SQL语句 private static final String CREATE_DATA_TABLE_SQL = // 创建数据表的SQL语句
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," + DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," +
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
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER increase_folder_count_on_update "
"CREATE TRIGGER increase_folder_count_on_update "+ +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " + " BEGIN " +
" 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"; //创建触发器,方便进行操作,当移动便签时统计新的父文件夹内便签数量 " END"; // 创建触发器,方便进行操作,当移动便签时统计新的父文件夹内便签数量
/** /**
* Decrease folder's note count when move note from folder * Decrease folder's note count when move note from folder
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_update "
"CREATE TRIGGER decrease_folder_count_on_update " + +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " + " BEGIN " +
" 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 + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END"; //与上一个方法作用相反,统计旧的父文件夹便签数量 " 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
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = "CREATE TRIGGER increase_folder_count_on_insert "
"CREATE TRIGGER increase_folder_count_on_insert " + +
" AFTER INSERT ON " + TABLE.NOTE + " AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " + " BEGIN " +
" 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"; //创建便签时增加统计数量 " END"; // 创建便签时增加统计数量
/** /**
* Decrease folder's note count when delete note from the folder * Decrease folder's note count when delete note from the folder
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = "CREATE TRIGGER decrease_folder_count_on_delete "
"CREATE TRIGGER decrease_folder_count_on_delete " + +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " + " BEGIN " +
" 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 + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END"; //删除时减少数量 " 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}
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = "CREATE TRIGGER update_note_content_on_insert "
"CREATE TRIGGER update_note_content_on_insert " + +
" AFTER INSERT ON " + TABLE.DATA + " AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" 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"; //更新便签数据时更改table表内容 " END"; // 更新便签数据时更改table表内容
/** /**
* 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
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = "CREATE TRIGGER update_note_content_on_update "
"CREATE TRIGGER update_note_content_on_update " + +
" AFTER UPDATE ON " + TABLE.DATA + " AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" 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"; //改变便签数据时更改table表内容 " END"; // 改变便签数据时更改table表内容
/** /**
* 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
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = "CREATE TRIGGER update_note_content_on_delete "
"CREATE TRIGGER update_note_content_on_delete " + +
" AFTER delete ON " + TABLE.DATA + " AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" 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"; //删除便签数据时改变table表内容 " END"; // 删除便签数据时改变table表内容
/** /**
* Delete datas belong to note which has been deleted * Delete datas belong to note which has been deleted
*/ */
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = "CREATE TRIGGER delete_data_on_delete " +
"CREATE TRIGGER delete_data_on_delete " + " AFTER DELETE ON " + TABLE.NOTE +
" AFTER DELETE ON " + TABLE.NOTE + " 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
*/ */
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = "CREATE TRIGGER folder_delete_notes_on_delete "
"CREATE TRIGGER folder_delete_notes_on_delete " + +
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" 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
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = "CREATE TRIGGER folder_move_notes_on_trash " +
"CREATE TRIGGER folder_move_notes_on_trash " + " AFTER UPDATE ON " + TABLE.NOTE +
" AFTER UPDATE ON " + TABLE.NOTE + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + " BEGIN" +
" BEGIN" + " 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) { //数据库对象DB private void reCreateNoteTableTriggers(SQLiteDatabase db) { // 数据库对象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");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -233,17 +232,17 @@ 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);
} //用于执行SQL语句运行重新创建便签表触发器函数 } // 用于执行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
@ -251,7 +250,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.clear(); values.clear();
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
@ -259,7 +258,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.clear(); values.clear();
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
@ -267,24 +266,24 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.clear(); values.clear();
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); //SQL输入保存的语句 db.execSQL(CREATE_DATA_TABLE_SQL); // 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); // 重新创建被删除的触发器
} }
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
@ -292,16 +291,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
} }
return mInstance; return mInstance;
} //静态同步方法用于返回NotesDatabaseHelper的对象实例mInstance } // 静态同步方法用于返回NotesDatabaseHelper的对象实例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;
@ -309,31 +308,31 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
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++;
} //检测到版本为1升级版本 } // 检测到版本为1升级版本
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; //重建触发器标志 reCreateTriggers = true; // 重建触发器标志
oldVersion++; //检测到版本为2升级版本 oldVersion++; // 检测到版本为2升级版本
} }
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} //检测到版本为3升级版本 } // 检测到版本为3升级版本
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);
@ -349,14 +348,15 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder // add a trash system folder
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
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);
} //删除不用的触发器,并添加不为空的新列,添加键值对 } // 删除不用的触发器,并添加不为空的新列,添加键值对
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");
} //添加新的不为空的列 } // 添加新的不为空的列
} }

@ -16,7 +16,6 @@
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;
@ -34,24 +33,23 @@ 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;
public class NotesProvider extends ContentProvider {// uri操作相关类用于对数据库进行操作
private static final UriMatcher mMatcher; // UriMatcher类用于分辨数据操作类型用于匹配不同的uri
public class NotesProvider extends ContentProvider { private NotesDatabaseHelper mHelper; // 建立NotesDatabaseHelper类对象用于数据库操作
private static final UriMatcher mMatcher; //UriMatcher类用于分辨数据表
private NotesDatabaseHelper mHelper; //建立NotesDatabaseHelper类对象
private static final String TAG = "NotesProvider"; //设置类名值 private static final String TAG = "NotesProvider"; // 设置类名标签,用于调试
private static final int URI_NOTE = 1; //设置便签uri private static final int URI_NOTE = 1; // 设置便签uri
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3; //设置数据uri private static final int URI_DATA = 3; // 设置数据uri
private static final int URI_DATA_ITEM = 4; private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5; //设置搜索uri private static final int URI_SEARCH = 5; // 设置搜索uri
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6;
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); //进行初始化 mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 进行初始化
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);
@ -59,48 +57,49 @@ public class NotesProvider extends ContentProvider {
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
} //将不同的uri与数值相匹配 } // 将不同的uri与数值相匹配
/** /**
* 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.
*/ //用0A代表\n为搜索结果换行 */ // 用0A代表\n为搜索结果换行
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 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ 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; // ...
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; //检索便签的sql语句在列表中搜寻。使用Notes类中的接口与变量 + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 检索便签的sql语句在列表中搜寻。使用Notes类中的接口与变量
@Override @Override
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; //创建NotesDatabaseHelper类并返回成果标识 return true; // 创建NotesDatabaseHelper类并返回成果标识
} }
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { //负责查询数据接受uri、返回烈、选择、排列方式 String sortOrder) { // 负责查询数据接受uri、返回烈、选择、排列方式
Cursor c = null; //创建空游标,表示数据库操作结果集合 Cursor c = null; // 创建空游标,表示数据库操作结果集合
SQLiteDatabase db = mHelper.getReadableDatabase(); //获取数据库对象 SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取数据库对象
String id = null; String id = null;
switch (mMatcher.match(uri)) { //确定uri类型 switch (mMatcher.match(uri)) { // 确定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); // 传参,进行标准查询
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; //传参对id进行查询 break; // 传参对id进行查询
case URI_DATA: case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
@ -112,13 +111,13 @@ public class NotesProvider extends ContentProvider {
break; break;
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) { //提取uri中搜索模式 if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { // 提取uri中搜索模式
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
@ -133,43 +132,43 @@ public class NotesProvider extends ContentProvider {
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,
new String[] { searchString }); //在Notes表进行搜索 new String[] { searchString }); // 在Notes表进行搜索
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString()); //日志 Log.e(TAG, "got exception: " + ex.toString()); // 日志
} }
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); //抛出异常 throw new IllegalArgumentException("Unknown URI " + uri); // 抛出异常
} }
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); //在游标查询的数据变化时进行通知 c.setNotificationUri(getContext().getContentResolver(), uri); // 在游标查询的数据变化时进行通知
} //通知uri是标识查询结果的urisetNotificationUri方法可注册通知uri与对象c相关联 } // 通知uri是标识查询结果的urisetNotificationUri方法可注册通知uri与对象c相关联
return c; return c;
} }
@Override @Override
public Uri insert(Uri uri, ContentValues values) { //uri表示要插入的urivalues表示要插入的数据 public Uri insert(Uri uri, ContentValues values) { // uri表示要插入的urivalues表示要插入的数据
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)) { //匹配uri switch (mMatcher.match(uri)) { // 匹配uri
case URI_NOTE: case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); //将数据插入到Notes表中 insertedId = noteId = db.insert(TABLE.NOTE, null, values); // 将数据插入到Notes表中
break; break;
case URI_DATA: case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) { //检查values是否含有NOTE_ID内容返回bool值 if (values.containsKey(DataColumns.NOTE_ID)) { // 检查values是否含有NOTE_ID内容返回bool值
noteId = values.getAsLong(DataColumns.NOTE_ID); //关联noteId noteId = values.getAsLong(DataColumns.NOTE_ID); // 关联noteId
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values.toString()); //日志记录 Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 日志记录
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); //数据库插入新行的id返回到两个变量中 insertedId = dataId = db.insert(TABLE.DATA, null, values); // 数据库插入新行的id返回到两个变量中
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri // Notify the note uri
if (noteId > 0) { //不为零表示插入成功, if (noteId > 0) { // 不为零表示插入成功,
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); //通知uri发生变化 ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); // 通知uri发生变化
} }
// Notify the data uri // Notify the data uri
@ -178,22 +177,23 @@ public class NotesProvider extends ContentProvider {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
return ContentUris.withAppendedId(uri, insertedId); //返回新的uri表示插入位置 return ContentUris.withAppendedId(uri, insertedId); // 返回新的uri表示插入位置
} }
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { //表示要删除的uri、SQL中的WHERE与参数 public int delete(Uri uri, String selection, String[] selectionArgs) { // 表示要删除的uri、SQL中的WHERE与参数
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)) { //uri匹配
switch (mMatcher.match(uri)) { // uri匹配
case URI_NOTE: case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; //设置WHERE selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 设置WHERE
count = db.delete(TABLE.NOTE, selection, selectionArgs); //删除,并计数 count = db.delete(TABLE.NOTE, selection, selectionArgs); // 删除,并计数
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); //获取id id = uri.getPathSegments().get(1); // 获取id
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID that smaller than 0 is system folder which is not allowed to
* trash * trash
@ -204,45 +204,46 @@ public class NotesProvider extends ContentProvider {
} }
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; //删除指定id并计数 break; // 删除指定id并计数
case URI_DATA: case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs); //删除,并计数 count = db.delete(TABLE.DATA, selection, selectionArgs); // 删除,并计数
deleteData = true; deleteData = true;
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); //获取id id = uri.getPathSegments().get(1); // 获取id
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true; //删除指定id并计数 deleteData = true; // 删除指定id并计数
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); //报错 throw new IllegalArgumentException("Unknown URI " + uri); // 报错
} }
if (count > 0) { //表示有删除操作通知uri发生变化
if (count > 0) { // 表示有删除操作通知uri发生变化
if (deleteData) { if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count; //返回删除的记录数 return count; // 返回删除的记录数
} }
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { //表示更新的uri、values为新的列值、where以及参数 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // 表示更新的uri、values为新的列值、where以及参数
int count = 0; //更新条数 int count = 0; // 更新条数
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); //打开数据库 SQLiteDatabase db = mHelper.getWritableDatabase(); // 打开数据库
boolean updateData = false; //设置数据表更新表示 boolean updateData = false; // 设置数据表更新表示
switch (mMatcher.match(uri)) { //匹配uri switch (mMatcher.match(uri)) { // 匹配uri
case URI_NOTE: case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs); //跟新便签 increaseNoteVersion(-1, selection, selectionArgs); // 跟新便签
count = db.update(TABLE.NOTE, values, selection, selectionArgs); //更新指定表的行,并计数 count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 更新指定表的行,并计数
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); //提取id id = uri.getPathSegments().get(1); // 提取id
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); //增加指定的id条件 + parseSelection(selection), selectionArgs); // 增加指定的id条件
break; break;
case URI_DATA: case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs);
@ -255,50 +256,50 @@ public class NotesProvider extends ContentProvider {
updateData = true; updateData = true;
break; break;
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);//通知指定uri数据更改 getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);// 通知指定uri数据更改
} }
getContext().getContentResolver().notifyChange(uri, null); //通知uri数据更改 getContext().getContentResolver().notifyChange(uri, null); // 通知uri数据更改
} }
return count; return count;
} }
private String parseSelection(String selection) { //检查selection是否为空 private String parseSelection(String selection) { // 检查selection是否为空
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); //为空则返回“” return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); // 为空则返回“”
} }
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 ");
sql.append(TABLE.NOTE); sql.append(TABLE.NOTE);
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)) { //selection不为空或存在id则增加where条件 if (id > 0 || !TextUtils.isEmpty(selection)) { // selection不为空或存在id则增加where条件
sql.append(" WHERE "); sql.append(" WHERE ");
} }
if (id > 0) { if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); sql.append(NoteColumns.ID + "=" + String.valueOf(id));
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection; //parseSelection将传入的参数中的占位符替换为实际的值 String selectString = id > 0 ? parseSelection(selection) : selection; // parseSelection将传入的参数中的占位符替换为实际的值
for (String args : selectionArgs) { // for (String args : selectionArgs) { //
selectString = selectString.replaceFirst("\\?", args); //replaceFirst选择参数数组中的值替换语句中的占位符 selectString = selectString.replaceFirst("\\?", args); // replaceFirst选择参数数组中的值替换语句中的占位符
} }
sql.append(selectString); sql.append(selectString);
} }
mHelper.getWritableDatabase().execSQL(sql.toString()); //执行SQL语句 mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL语句
} }
@Override @Override
public String getType(Uri uri) { //获取指定uri的MIME类型 public String getType(Uri uri) { // 获取指定uri的MIME类型
// TODO Auto-generated method stub //表示该方法没有实现 // TODO Auto-generated method stub //表示该方法没有实现
return null; return null;
} }
} }

@ -15,6 +15,7 @@
*/ */
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;
@ -33,88 +34,90 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
public class Note {// 便签类
private ContentValues mNoteDiffValues; // 用于保存便签修改值
private NoteData mNoteData; // 保存便签的数据
private static final String TAG = "Note"; // 设置TAG为Note
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * Create a new note id for adding a new note to databases
*/ */
public static synchronized long getNewNoteId(Context context, long folderId) { public static synchronized long getNewNoteId(Context context, long folderId) { // 为一个新的便签创建id返回数据库
// Create a new note in the database // Create a new note in the database
ContentValues values = new ContentValues(); ContentValues values = new ContentValues(); // 用于保存创建日期等字段的值
long createdTime = System.currentTimeMillis(); long createdTime = System.currentTimeMillis(); // 获取创建时间
values.put(NoteColumns.CREATED_DATE, createdTime); values.put(NoteColumns.CREATED_DATE, createdTime);
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); // 将values插入数据库中并返回uri
long noteId = 0; long noteId = 0;
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1)); // 解析uri获取新笔记id
} 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;
} }
if (noteId == -1) { if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId); throw new IllegalStateException("Wrong note id:" + noteId); // 获取id出错抛出异常
} }
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); // key为属性values为新值
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 本地修改标识为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);
} } // 设置通讯数据,添加键值对
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#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails,
* we also update the
* note data info * note data info
*/ */
if (context.getContentResolver().update( if (context.getContentResolver().update( // 打包并同步
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) { null) == 0) {
Log.e(TAG, "Update note error, should not happen"); Log.e(TAG, "Update note error, should not happen");
@ -124,13 +127,13 @@ public class Note {
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;
@ -141,77 +144,76 @@ public class Note {
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 pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) { // 将文本数据与通讯数据添加到context
/** /**
* 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); // 将便签id与数据值相关联
if (mTextDataId == 0) { if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); // 并将键值对添加到mTextDataValues中
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues); // 插入新的数据行保存返回的uri
try { try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId); Log.e(TAG, "Insert new text data fail with noteId" + noteId); // 异常日志
mTextDataValues.clear(); mTextDataValues.clear();
return null; return null;
} }
} else { } else { // 表示需要更新现有数据行
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues);
operationList.add(builder.build()); operationList.add(builder.build());
} }
mTextDataValues.clear(); mTextDataValues.clear(); // 清空mTextDataValues
} }
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) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
@ -233,7 +235,7 @@ public class Note {
mCallDataValues.clear(); mCallDataValues.clear();
} }
if (operationList.size() > 0) { if (operationList.size() > 0) { // 检查operationList对载入的操作进行批量提交
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); Notes.AUTHORITY, operationList);

@ -31,38 +31,37 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; 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; // 表示工作便签
// Note Id // Note Id
private long mNoteId; private long mNoteId; // 便签id
// Note content // Note content
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; // 背景颜色id
private int mWidgetId; private int mWidgetId; // 小部件id
private int mWidgetType; private int mWidgetType; // 小部件类型
private long mFolderId; private long mFolderId; // 所在文件夹id
private Context mContext; private Context mContext; // 表示上下文
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote"; // 设置TAG
private boolean mIsDeleted; private boolean mIsDeleted; // 表示是否被删除
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener; // 表示便签设置状态
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] { // 用于指定需要从数据库查询的数据列
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -81,28 +80,28 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0; // 表示查询数据的id列
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; // 表示查询数据的MIME类型列
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; // 表示查询便签的父文件夹id列
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; // 表示便签的背景颜色id列
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3; // 表示便签小组件id列
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
private 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();
@ -115,7 +114,7 @@ public class 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;
mNoteId = noteId; mNoteId = noteId;
mFolderId = folderId; mFolderId = folderId;
@ -124,13 +123,13 @@ public class WorkingNote {
loadNote(); loadNote();
} }
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); // 返回一个Cursor对象
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);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -141,70 +140,70 @@ public class WorkingNote {
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); // 抛出异常表示未找到指定id的便签
} }
loadNoteData(); loadNoteData(); // 加载便签内容和其他数据
} }
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[] { // 获取与便签id相对应的所有数据
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null); // 遍历Cursor对象所有数据
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)) { // 类型相对应则设置WorkingNote对象成员变量
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) { } else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); // 设置为Notes对象的成员变量
} 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 {
Log.e(TAG, "No data with id:" + mNoteId); Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); // 抛出异常,无查询结果
} }
} }
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, // 上下文对象、文件夹id、组件id、组件类型、默认背景颜色id
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) { // 创建空白便签
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId); // 用上下文对象、父文件夹id创建WorkingNote
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) { // 用上下文对象和id创建新的WorkingNote对象
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
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) { // 不存在则获取id
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
*/ */
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID // 诺该便签与组件关联
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged(); // 更新组件
} }
return true; return true;
} else { } else {
@ -214,155 +213,156 @@ public class WorkingNote {
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} } // 判断便签是否存在数据库
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) // 不存在于数据库且为空,或者没本地修改
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
} else { } else {
return true; return true;
} }
} } // 判断是否值得保存
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} } // 设置便签状态监视器
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) { // 设置提醒
if (date != mAlertDate) { if (date != mAlertDate) { // 判断传入是否相同
mAlertDate = date; mAlertDate = date; // 更新
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); // 更新数据库
} }
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
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(); // 已删除则更新组件
} }
} }
public void setBgColorId(int id) { public void setBgColorId(int id) { // 设置背景颜色
if (id != mBgColorId) { if (id != mBgColorId) { // 检查
mBgColorId = id; mBgColorId = id; // 更新设置
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged(); // 通知监听器
} }
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); // 更新数据库
} }
} }
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) { // 设置便签的检查清单模式
if (mMode != mode) { if (mMode != mode) { // 检查
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); // 通知
} }
mMode = mode; mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); // 更新数据库
} }
} }
public void setWidgetType(int type) { public void setWidgetType(int type) { // 设置组件类型
if (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)); // 更新数据库
} }
} }
public void setWidgetId(int id) { public void setWidgetId(int id) { // 设置组件id
if (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)); // 更新数据库
} }
} }
public void setWorkingText(String text) { public void setWorkingText(String text) { // 设置文本
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent); // 更新
} }
} }
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)); // 修改父文件夹id为呼叫记录id
} }
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} } // 是否设置提醒数据
public String getContent() { public String getContent() {
return mContent; return mContent;
} } // 获取内容
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} } // 获取提醒时间
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} } // 获取最后修改时间
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);
} } // 获取标题栏背景颜色资源id
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} } // 获取检查清单模式
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} } // 获取便签id
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} } // 获取父文件夹id
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} } // 获取组件id
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} } // 获取组件类型
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener { // 接口
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed
*/ */
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
* @param newMode is new mode * @param newMode is new mode
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode); // 清单模式转为笔记模式时启动
} }
} }

Loading…
Cancel
Save