Compare commits

..

1 Commits

Author SHA1 Message Date
xxy ea369604c0 commit
1 year ago

@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings"> <component name="GradleSettings">
<option name="linkedExternalProjectsSettings"> <option name="linkedExternalProjectsSettings">
<GradleProjectSettings> <GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" /> <option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="jbr-17" /> <option name="gradleJvm" value="jbr-17" />
<option name="resolveExternalAnnotations" value="false" />
</GradleProjectSettings> </GradleProjectSettings>
</option> </option>
</component> </component>

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectType"> <component name="ProjectType">

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/src.iml" filepath="$PROJECT_DIR$/.idea/src.iml" />
</modules>
</component>
</project>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

@ -13,9 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Phone;
@ -24,11 +22,11 @@ import android.telephony.PhoneNumberUtils;
import android.util.Log; 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";
//用于日志输出的标签,方便在日志中识别该类相关的日志信息
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 "
@ -40,34 +38,38 @@ public class Contact {
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
//检查缓存sContactCache是否已经初始化如果没有则进行初始化
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));
//如果不在缓存中则构建查询条件。通过CALLER_ID_SELECTION字符串构建查询语句其中将+替换为通过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) {
Log.e(TAG, " Cursor get string error " + e.toString()); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
//如果在获取姓名过程中发生索引越界异常则在日志中记录错误信息并返回null
} finally { } finally {
cursor.close(); cursor.close();
} }//无论是否发生异常都需要在finally块中关闭游标以释放资源
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; return null;
} }//如果查询结果为空,表示没有找到匹配的联系人
} }
} }

@ -14,266 +14,277 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
public class Notes { public class Notes {
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes";
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 * Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@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;
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";
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";
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";
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";
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";
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";
public static final int TYPE_WIDGET_INVALIDE = -1; public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
} }
/** /**
* Uri to query all notes and folders * 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 to query data * 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 {
/** /**
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
//行的唯一标识
/** /**
* The parent's id for note or folder * The parent's id for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
//笔记或文件夹的父级 ID
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: 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 * Latest modified date
* <P> Type: 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 * Alert date
* <P> Type: 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 * Folder's name or text content of note
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
//文件夹名称或者笔记的文本内容片段
/** /**
* Note's widget id * Note's widget id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
//与笔记关联的小部件 ID
/** /**
* Note's widget type * Note's widget type
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
//与笔记关联的小部件类型
/** /**
* Note's background color's id * Note's background color's id
* <P> Type: 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";
//笔记背景颜色 ID
/** /**
* For text note, it doesn't has attachment, for multi-media * For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment * note, it has at least one attachment
* <P> Type: INTEGER </P> * <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 * Folder's count of notes
* <P> Type: 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 * The file type: folder or note
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";
//文件类型
/** /**
* The last sync id * The last sync id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
//最后同步 ID
/** /**
* Sign to indicate local modified or not * Sign to indicate local modified or not
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
//是否本地修改
/** /**
* Original parent id before moving into temporary folder * Original parent id before moving into temporary folder
* <P> Type : 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";
//在移动到临时文件夹之前的原始父 ID
/** /**
* The gtask id * The gtask id
* <P> Type : TEXT </P> * <P> Type : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
//与GTASK相关的 ID
/** /**
* The version code * The version code
* <P> Type : 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 {
* The unique ID for a row /**
* <P> Type: INTEGER (long) </P> * The unique ID for a row
*/ * <P> Type: INTEGER (long) </P>
public static final String ID = "_id"; */
public static final String ID = "_id";
/** //标识
* The MIME type of the item represented by this row.
* <P> Type: Text </P> /**
*/ * The MIME type of the item represented by this row.
public static final String MIME_TYPE = "mime_type"; * <P> Type: Text </P>
*/
/** public static final String MIME_TYPE = "mime_type";
* The reference id to note that this data belongs to //数据项的 MIME 类型
* <P> Type: INTEGER (long) </P> /**
*/ * The reference id to note that this data belongs to
public static final String NOTE_ID = "note_id"; * <P> Type: INTEGER (long) </P>
*/
/** public static final String NOTE_ID = "note_id";
* Created data for note or folder //数据所属笔记的引用 ID
* <P> Type: INTEGER (long) </P> /**
*/ * Created data for note or folder
public static final String CREATED_DATE = "created_date"; * <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"; * Latest modified date
* <P> Type: INTEGER (long) </P>
/** */
* Data's content public static final String MODIFIED_DATE = "modified_date";
* <P> Type: TEXT </P> //修改日期
*/
public static final String CONTENT = "content"; /**
* Data's content
* <P> Type: TEXT </P>
/** */
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for public static final String CONTENT = "content";
* 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
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * <P> Type: INTEGER </P>
* integer data type */
* <P> Type: INTEGER </P> public static final String DATA1 = "data1";
*/ //
public static final String DATA2 = "data2";
/**
/** * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * integer data type
* TEXT data type * <P> Type: INTEGER </P>
* <P> Type: TEXT </P> */
*/ public static final String DATA2 = "data2";
public static final String DATA3 = "data3"; //
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA3 = "data3";
//
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for /**
* TEXT data type * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> Type: TEXT </P> * TEXT data type
*/ * <P> Type: TEXT </P>
public static final String DATA5 = "data5"; */
} public static final String DATA4 = "data4";
//
public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* <P> Type: Integer 1:check list mode 0: normal mode </P> * TEXT data type
*/ * <P> Type: TEXT </P>
public static final String MODE = DATA1; */
public static final String DATA5 = "data5";
public static final int MODE_CHECK_LIST = 1; //
}//这个接口定义了与数据相关的列名和对应的数据类型,用于存储与笔记相关的数据信息
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final class TextNote implements DataColumns {
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; /**
* Mode to indicate the text in check list mode or not
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); * <P> Type: Integer 1:check list mode 0: normal mode </P>
} */
public static final String MODE = DATA1;
public static final class CallNote implements DataColumns {
/** public static final int MODE_CHECK_LIST = 1;
* Call date for this record
* <P> Type: INTEGER (long) </P> public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
*/
public static final String CALL_DATE = DATA1; 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");
* Phone number for this record }//实现了DataColumns接口用于表示文本笔记相关的数据
* <P> Type: TEXT </P>
*/ public static final class CallNote implements DataColumns {
public static final String PHONE_NUMBER = DATA3; /**
* Call date for this record
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; * <P> Type: INTEGER (long) </P>
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final String CALL_DATE = DATA1;
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); /**
} * 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");
}//实现了DataColumns接口用于表示通话记录笔记相关的数据
}

@ -14,349 +14,358 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; 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;
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 { //数据库的版本号
public static final String NOTE = "note";
public interface TABLE {
public static final String DATA = "data"; public static final String NOTE = "note";
}
public static final String DATA = "data";
private static final String TAG = "NotesDatabaseHelper"; }//存储笔记信息和相关数据的表
private static NotesDatabaseHelper mInstance; private static final String TAG = "NotesDatabaseHelper";
private static final String CREATE_NOTE_TABLE_SQL = private static NotesDatabaseHelper mInstance;
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + private static final String CREATE_NOTE_TABLE_SQL =
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
")"; NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
private static final String CREATE_DATA_TABLE_SQL = ")";
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + private static final String CREATE_DATA_TABLE_SQL =
DataColumns.MIME_TYPE + " TEXT NOT NULL," + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + DataColumns.MIME_TYPE + " TEXT NOT NULL," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.DATA1 + " INTEGER," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.DATA2 + " INTEGER," + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
")"; DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = ")";
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
/** TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
* Increase folder's note count when move note to the folder
*/ /**
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = * Increase folder's note count when move note to the folder
"CREATE TRIGGER increase_folder_count_on_update "+ */
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
" BEGIN " + "CREATE TRIGGER increase_folder_count_on_update "+
" UPDATE " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " BEGIN " +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
/** " END";
* Decrease folder's note count when move note from folder
*/ /**
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = * Decrease folder's note count when move note from folder
"CREATE TRIGGER decrease_folder_count_on_update " + */
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
" BEGIN " + "CREATE TRIGGER decrease_folder_count_on_update " +
" UPDATE " + TABLE.NOTE + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " BEGIN " +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " UPDATE " + TABLE.NOTE +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" END"; " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
/** " END";
* Increase folder's note count when insert new note to the folder
*/ /**
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = * Increase folder's note count when insert new note to the folder
"CREATE TRIGGER increase_folder_count_on_insert " + */
" AFTER INSERT ON " + TABLE.NOTE + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
" BEGIN " + "CREATE TRIGGER increase_folder_count_on_insert " +
" UPDATE " + TABLE.NOTE + " AFTER INSERT ON " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " BEGIN " +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
/** " END";
* Decrease folder's note count when delete note from the folder
*/ /**
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = * Decrease folder's note count when delete note from the folder
"CREATE TRIGGER decrease_folder_count_on_delete " + */
" AFTER DELETE ON " + TABLE.NOTE + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
" BEGIN " + "CREATE TRIGGER decrease_folder_count_on_delete " +
" UPDATE " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + " BEGIN " +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " UPDATE " + TABLE.NOTE +
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" END"; " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
/** " END";
* Update note's content when insert data with type {@link DataConstants#NOTE}
*/ /**
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = * Update note's content when insert data with type {@link DataConstants#NOTE}
"CREATE TRIGGER update_note_content_on_insert " + */
" AFTER INSERT ON " + TABLE.DATA + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + "CREATE TRIGGER update_note_content_on_insert " +
" BEGIN" + " AFTER INSERT ON " + TABLE.DATA +
" UPDATE " + TABLE.NOTE + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " BEGIN" +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
/** " END";
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*/ /**
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = * Update note's content when data with {@link DataConstants#NOTE} type has changed
"CREATE TRIGGER update_note_content_on_update " + */
" AFTER UPDATE ON " + TABLE.DATA + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + "CREATE TRIGGER update_note_content_on_update " +
" BEGIN" + " AFTER UPDATE ON " + TABLE.DATA +
" UPDATE " + TABLE.NOTE + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + " BEGIN" +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
/** " END";
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/ /**
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = * Update note's content when data with {@link DataConstants#NOTE} type has deleted
"CREATE TRIGGER update_note_content_on_delete " + */
" AFTER delete ON " + TABLE.DATA + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + "CREATE TRIGGER update_note_content_on_delete " +
" BEGIN" + " AFTER delete ON " + TABLE.DATA +
" UPDATE " + TABLE.NOTE + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" SET " + NoteColumns.SNIPPET + "=''" + " BEGIN" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
/** " END";
* Delete datas belong to note which has been deleted
*/ /**
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = * Delete datas belong to note which has been deleted
"CREATE TRIGGER delete_data_on_delete " + */
" AFTER DELETE ON " + TABLE.NOTE + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
" BEGIN" + "CREATE TRIGGER delete_data_on_delete " +
" DELETE FROM " + TABLE.DATA + " AFTER DELETE ON " + TABLE.NOTE +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + " BEGIN" +
" END"; " DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
/** " END";
* Delete notes belong to folder which has been deleted
*/ /**
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = * Delete notes belong to folder which has been deleted
"CREATE TRIGGER folder_delete_notes_on_delete " + */
" AFTER DELETE ON " + TABLE.NOTE + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
" BEGIN" + "CREATE TRIGGER folder_delete_notes_on_delete " +
" DELETE FROM " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " BEGIN" +
" END"; " DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
/** " END";
* Move notes belong to folder which has been moved to trash folder
*/ /**
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = * Move notes belong to folder which has been moved to trash folder
"CREATE TRIGGER folder_move_notes_on_trash " + */
" AFTER UPDATE ON " + TABLE.NOTE + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + "CREATE TRIGGER folder_move_notes_on_trash " +
" BEGIN" + " AFTER UPDATE ON " + TABLE.NOTE +
" UPDATE " + TABLE.NOTE + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + " BEGIN" +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " UPDATE " + TABLE.NOTE +
" END"; " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
public NotesDatabaseHelper(Context context) { " END";
super(context, DB_NAME, null, DB_VERSION);
} public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
public void createNoteTable(SQLiteDatabase db) { }
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); public void createNoteTable(SQLiteDatabase db) {
createSystemFolder(db); db.execSQL(CREATE_NOTE_TABLE_SQL);
Log.d(TAG, "note table has been created"); //执行CREATE_NOTE_TABLE_SQL语句创建表
} reCreateNoteTableTriggers(db);
//重新创建与note表相关的触发器
private void reCreateNoteTableTriggers(SQLiteDatabase db) { createSystemFolder(db);
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); //创建系统文件夹相关的记录
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); Log.d(TAG, "note table has been created");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); }
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); //首先删除可能存在的旧触发器
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
} db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
private void createSystemFolder(SQLiteDatabase db) { db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
ContentValues values = new ContentValues(); db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
/** //按照定义的顺序执行创建触发器的 SQL 语句,这些触发器用于处理文件夹中笔记数量的增减、笔记内容的更新以及删除相关操作
* call record foler for call notes }
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); private void createSystemFolder(SQLiteDatabase db) {
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); ContentValues values = new ContentValues();
db.insert(TABLE.NOTE, null, values);
/**
/** * call record foler for call notes
* root folder which is default folder */
*/ values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.clear(); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); db.insert(TABLE.NOTE, null, values);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); /**
* root folder which is default folder
/** */
* temporary folder which is used for moving note values.clear();
*/ values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.clear(); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); db.insert(TABLE.NOTE, null, values);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); /**
* temporary folder which is used for moving note
/** */
* create trash folder values.clear();
*/ values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.clear(); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); db.insert(TABLE.NOTE, null, values);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); /**
} * create trash folder
*/
public void createDataTable(SQLiteDatabase db) { values.clear();
db.execSQL(CREATE_DATA_TABLE_SQL); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
reCreateDataTableTriggers(db); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.insert(TABLE.NOTE, null, values);
Log.d(TAG, "data table has been created"); }
}
public void createDataTable(SQLiteDatabase db) {
private void reCreateDataTableTriggers(SQLiteDatabase db) { db.execSQL(CREATE_DATA_TABLE_SQL);
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); reCreateDataTableTriggers(db);
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); Log.d(TAG, "data table has been created");
}
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
} db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
mInstance = new NotesDatabaseHelper(context); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
} db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
return mInstance; }
}
static synchronized NotesDatabaseHelper getInstance(Context context) {
@Override if (mInstance == null) {
public void onCreate(SQLiteDatabase db) { mInstance = new NotesDatabaseHelper(context);
createNoteTable(db); }
createDataTable(db); return mInstance;
} }
//这是一个静态方法实现了单例模式。它确保在整个应用程序中只有一个NotesDatabaseHelper实例被创建和使用避免了多次创建数据库连接对象
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { @Override
boolean reCreateTriggers = false; public void onCreate(SQLiteDatabase db) {
boolean skipV2 = false; createNoteTable(db);
createDataTable(db);
if (oldVersion == 1) { }
upgradeToV2(db); //在数据库首次创建时被调用它调用createNoteTable和createDataTable方法分别创建note表和data表
skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; @Override
} public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
if (oldVersion == 2 && !skipV2) { boolean skipV2 = false;
upgradeToV3(db);
reCreateTriggers = true; if (oldVersion == 1) {
oldVersion++; upgradeToV2(db);
} skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++;
if (oldVersion == 3) { }
upgradeToV4(db);
oldVersion++; if (oldVersion == 2 && !skipV2) {
} upgradeToV3(db);
reCreateTriggers = true;
if (reCreateTriggers) { oldVersion++;
reCreateNoteTableTriggers(db); }
reCreateDataTableTriggers(db);
} if (oldVersion == 3) {
upgradeToV4(db);
if (oldVersion != newVersion) { oldVersion++;
throw new IllegalStateException("Upgrade notes database to version " + newVersion }
+ "fails");
} if (reCreateTriggers) {
} reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
private void upgradeToV2(SQLiteDatabase db) { }
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); if (oldVersion != newVersion) {
createNoteTable(db); throw new IllegalStateException("Upgrade notes database to version " + newVersion
createDataTable(db); + "fails");
} }
}
private void upgradeToV3(SQLiteDatabase db) { //用于处理数据库升级操作
// drop unused triggers private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); createNoteTable(db);
// add a column for gtask id createDataTable(db);
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID }
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder private void upgradeToV3(SQLiteDatabase db) {
ContentValues values = new ContentValues(); // drop unused triggers
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.insert(TABLE.NOTE, null, values); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
} // add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
private void upgradeToV4(SQLiteDatabase db) { + " TEXT NOT NULL DEFAULT ''");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION // add a trash system folder
+ " INTEGER NOT NULL DEFAULT 0"); ContentValues values = new ContentValues();
} values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
} values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}//NotesDatabaseHelper类是一个SQLiteOpenHelper的子类用于管理与笔记相关的 SQLite 数据库。它负责数据库的创建、升级以及一些与数据库表和触发器相关的操作

@ -14,292 +14,296 @@
* limitations under the License. * limitations under the License.
*/ */
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;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Intent; import android.content.Intent;
import android.content.UriMatcher; import android.content.UriMatcher;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; 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;
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
//1个静态的UriMatcher对象用于匹配传入的Uri以便根据不同的Uri执行不同的操作
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
//NotesDatabaseHelper类型的对象用于辅助数据库操作
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 {
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);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
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);
} }//在静态代码块中初始化mMatcher将不同的Uri模式与对应的整数值进行匹配这些模式包括对笔记note、数据data、搜索search和搜索建议search_suggest相关的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.
*/ */
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; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }//在ContentProvider被创建时调用用于初始化mHelper通过NotesDatabaseHelper.getInstance(getContext())获取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) { String sortOrder) {
Cursor c = null; Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: //根据mMatcher.match(uri)的结果来判断Uri的类型然后针对不同类型的Uri在相应的表上执行查询操作
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, case URI_NOTE:
sortOrder); c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
break; sortOrder);
case URI_NOTE_ITEM: break;
id = uri.getPathSegments().get(1); case URI_NOTE_ITEM:
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id id = uri.getPathSegments().get(1);
+ parseSelection(selection), selectionArgs, null, null, sortOrder); c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
break; + parseSelection(selection), selectionArgs, null, null, sortOrder);
case URI_DATA: break;
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, case URI_DATA:
sortOrder); c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
break; sortOrder);
case URI_DATA_ITEM: break;
id = uri.getPathSegments().get(1); case URI_DATA_ITEM:
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id id = uri.getPathSegments().get(1);
+ parseSelection(selection), selectionArgs, null, null, sortOrder); c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
break; + parseSelection(selection), selectionArgs, null, null, sortOrder);
case URI_SEARCH: break;
case URI_SEARCH_SUGGEST: case URI_SEARCH:
if (sortOrder != null || projection != null) { case URI_SEARCH_SUGGEST:
throw new IllegalArgumentException( if (sortOrder != null || projection != null) {
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); throw new IllegalArgumentException(
} "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { String searchString = null;
if (uri.getPathSegments().size() > 1) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
searchString = uri.getPathSegments().get(1); if (uri.getPathSegments().size() > 1) {
} searchString = uri.getPathSegments().get(1);
} else { }
searchString = uri.getQueryParameter("pattern"); } else {
} searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {
return null; if (TextUtils.isEmpty(searchString)) {
} return null;
}
try {
searchString = String.format("%%%s%%", searchString); try {
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, searchString = String.format("%%%s%%", searchString);
new String[] { searchString }); c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
} catch (IllegalStateException ex) { new String[] { searchString });
Log.e(TAG, "got exception: " + ex.toString()); } catch (IllegalStateException ex) {
} Log.e(TAG, "got exception: " + ex.toString());
break; }
default: break;
throw new IllegalArgumentException("Unknown URI " + uri); default:
} throw new IllegalArgumentException("Unknown URI " + uri);
if (c != null) { }
c.setNotificationUri(getContext().getContentResolver(), uri); if (c != null) {
} c.setNotificationUri(getContext().getContentResolver(), uri);
return c; }//如果查询结果游标不为空则设置通知Uri以便在数据发生变化时通知相关的监听器
} return c;
}//根据传入的Uri执行查询操作
@Override
public Uri insert(Uri uri, ContentValues values) { @Override
SQLiteDatabase db = mHelper.getWritableDatabase(); public Uri insert(Uri uri, ContentValues values) {
long dataId = 0, noteId = 0, insertedId = 0; SQLiteDatabase db = mHelper.getWritableDatabase();
switch (mMatcher.match(uri)) { long dataId = 0, noteId = 0, insertedId = 0;
case URI_NOTE: switch (mMatcher.match(uri)) {
insertedId = noteId = db.insert(TABLE.NOTE, null, values); case URI_NOTE:
break; insertedId = noteId = db.insert(TABLE.NOTE, null, values);
case URI_DATA: break;
if (values.containsKey(DataColumns.NOTE_ID)) { case URI_DATA:
noteId = values.getAsLong(DataColumns.NOTE_ID); if (values.containsKey(DataColumns.NOTE_ID)) {
} else { noteId = values.getAsLong(DataColumns.NOTE_ID);
Log.d(TAG, "Wrong data format without note id:" + values.toString()); } else {
} Log.d(TAG, "Wrong data format without note id:" + values.toString());
insertedId = dataId = db.insert(TABLE.DATA, null, values); }
break; insertedId = dataId = db.insert(TABLE.DATA, null, values);
default: break;
throw new IllegalArgumentException("Unknown URI " + uri); default:
} throw new IllegalArgumentException("Unknown URI " + uri);
// Notify the note uri }//根据mMatcher.match(uri)的结果判断Uri的类型如果是URI_NOTE则向note表插入数据如果是URI_DATA则向data表插入数据
if (noteId > 0) { // Notify the note uri
getContext().getContentResolver().notifyChange( if (noteId > 0) {
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); getContext().getContentResolver().notifyChange(
} ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) { // Notify the data uri
getContext().getContentResolver().notifyChange( if (dataId > 0) {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); getContext().getContentResolver().notifyChange(
} ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId); //在插入数据后,根据插入的记录 IDnoteId或dataId通知相关的UriNotes.CONTENT_NOTE_URI或Notes.CONTENT_DATA_URI数据发生了变化
} return ContentUris.withAppendedId(uri, insertedId);
}//根据传入的Uri执行插入操作
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) { @Override
int count = 0; public int delete(Uri uri, String selection, String[] selectionArgs) {
String id = null; int count = 0;
SQLiteDatabase db = mHelper.getWritableDatabase(); String id = null;
boolean deleteData = false; SQLiteDatabase db = mHelper.getWritableDatabase();
switch (mMatcher.match(uri)) { boolean deleteData = false;
case URI_NOTE: switch (mMatcher.match(uri)) {
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; case URI_NOTE:
count = db.delete(TABLE.NOTE, selection, selectionArgs); selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
break; count = db.delete(TABLE.NOTE, selection, selectionArgs);
case URI_NOTE_ITEM: break;
id = uri.getPathSegments().get(1); case URI_NOTE_ITEM:
/** id = uri.getPathSegments().get(1);
* ID that smaller than 0 is system folder which is not allowed to /**
* trash * ID that smaller than 0 is system folder which is not allowed to
*/ * trash
long noteId = Long.valueOf(id); */
if (noteId <= 0) { long noteId = Long.valueOf(id);
break; if (noteId <= 0) {
} break;
count = db.delete(TABLE.NOTE, }
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); count = db.delete(TABLE.NOTE,
break; NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
case URI_DATA: break;
count = db.delete(TABLE.DATA, selection, selectionArgs); case URI_DATA:
deleteData = true; count = db.delete(TABLE.DATA, selection, selectionArgs);
break; deleteData = true;
case URI_DATA_ITEM: break;
id = uri.getPathSegments().get(1); case URI_DATA_ITEM:
count = db.delete(TABLE.DATA, id = uri.getPathSegments().get(1);
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); count = db.delete(TABLE.DATA,
deleteData = true; DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; deleteData = true;
default: break;
throw new IllegalArgumentException("Unknown URI " + uri); default:
} throw new IllegalArgumentException("Unknown URI " + uri);
if (count > 0) { }//根据mMatcher.match(uri)的结果判断Uri的类型然后在相应的表TABLE.NOTE或TABLE.DATA上执行删除操作
if (deleteData) { if (count > 0) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); if (deleteData) {
} getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
getContext().getContentResolver().notifyChange(uri, null); }
} getContext().getContentResolver().notifyChange(uri, null);
return count; }//对于删除操作,如果删除的行数大于 0则根据情况通知相关的UriNotes.CONTENT_NOTE_URI或uri本身数据发生了变化
} return count;
}//根据传入的Uri执行删除操作
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { @Override
int count = 0; public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
String id = null; int count = 0;
SQLiteDatabase db = mHelper.getWritableDatabase(); String id = null;
boolean updateData = false; SQLiteDatabase db = mHelper.getWritableDatabase();
switch (mMatcher.match(uri)) { boolean updateData = false;
case URI_NOTE: switch (mMatcher.match(uri)) {
increaseNoteVersion(-1, selection, selectionArgs); case URI_NOTE:
count = db.update(TABLE.NOTE, values, selection, selectionArgs); increaseNoteVersion(-1, selection, selectionArgs);
break; count = db.update(TABLE.NOTE, values, selection, selectionArgs);
case URI_NOTE_ITEM: break;
id = uri.getPathSegments().get(1); case URI_NOTE_ITEM:
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); id = uri.getPathSegments().get(1);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
+ parseSelection(selection), selectionArgs); count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
break; + parseSelection(selection), selectionArgs);
case URI_DATA: break;
count = db.update(TABLE.DATA, values, selection, selectionArgs); case URI_DATA:
updateData = true; count = db.update(TABLE.DATA, values, selection, selectionArgs);
break; updateData = true;
case URI_DATA_ITEM: break;
id = uri.getPathSegments().get(1); case URI_DATA_ITEM:
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id id = uri.getPathSegments().get(1);
+ parseSelection(selection), selectionArgs); count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
updateData = true; + parseSelection(selection), selectionArgs);
break; updateData = true;
default: break;
throw new IllegalArgumentException("Unknown URI " + uri); default:
} throw new IllegalArgumentException("Unknown URI " + uri);
}//根据mMatcher.match(uri)的结果判断Uri的类型然后在相应的表TABLE.NOTE或TABLE.DATA上执行更新操作
if (count > 0) {
if (updateData) { if (count > 0) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); if (updateData) {
} getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
getContext().getContentResolver().notifyChange(uri, null); }
} getContext().getContentResolver().notifyChange(uri, null);
return count; }//如果更新的行数大于 0则根据情况通知相关的UriNotes.CONTENT_NOTE_URI或uri本身数据发生了变化
} return count;
}//根据传入的Uri执行更新操作
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); private String parseSelection(String selection) {
} return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}//用于解析查询条件字符串如果原始的查询条件字符串不为空则在前面添加AND并加上括号以便在查询语句中正确使用
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
sql.append("UPDATE "); StringBuilder sql = new StringBuilder(120);
sql.append(TABLE.NOTE); sql.append("UPDATE ");
sql.append(" SET "); sql.append(TABLE.NOTE);
sql.append(NoteColumns.VERSION); sql.append(" SET ");
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) { //构建一个SQL语句根据传入的id和查询条件selection来更新note表中的version列。
sql.append(" WHERE "); if (id > 0 || !TextUtils.isEmpty(selection)) {
} sql.append(" WHERE ");
if (id > 0) { }
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); if (id > 0) {
} sql.append(NoteColumns.ID + "=" + String.valueOf(id));
if (!TextUtils.isEmpty(selection)) { }
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) { if (!TextUtils.isEmpty(selection)) {
selectString = selectString.replaceFirst("\\?", args); String selectString = id > 0 ? parseSelection(selection) : selection;
} for (String args : selectionArgs) {
sql.append(selectString); selectString = selectString.replaceFirst("\\?", args);
} }
sql.append(selectString);
mHelper.getWritableDatabase().execSQL(sql.toString()); }
}
mHelper.getWritableDatabase().execSQL(sql.toString());
@Override //通过mHelper.getWritableDatabase().execSQL执行构建的SQL语句
public String getType(Uri uri) { }//用于增加笔记的版本号
// TODO Auto-generated method stub
return null; @Override
} public String getType(Uri uri) {
// TODO Auto-generated method stub
} return null;
}
}//负责处理与笔记相关的数据的查询、插入、删除和更新操作并通过UriMatcher来匹配不同的Uri以执行相应的操作

@ -14,240 +14,247 @@
* limitations under the License. * 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;
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;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
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.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
public class Note { public class Note {
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
private NoteData mNoteData; //一个ContentValues对象用于存储笔记的基本信息如创建日期、修改日期、类型等的变化
private static final String TAG = "Note"; private NoteData mNoteData;
/** //NoteData类型的对象用于处理笔记中的数据相关信息
* Create a new note id for adding a new note to databases private static final String TAG = "Note";
*/ //用于日志输出的标签
public static synchronized long getNewNoteId(Context context, long folderId) { /**
// Create a new note in the database * Create a new note id for adding a new note to databases
ContentValues values = new ContentValues(); */
long createdTime = System.currentTimeMillis(); public static synchronized long getNewNoteId(Context context, long folderId) {
values.put(NoteColumns.CREATED_DATE, createdTime); // Create a new note in the database
values.put(NoteColumns.MODIFIED_DATE, createdTime); ContentValues values = new ContentValues();
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); long createdTime = System.currentTimeMillis();
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.MODIFIED_DATE, createdTime);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
long noteId = 0; values.put(NoteColumns.PARENT_ID, folderId);
try { //创建一个ContentValues对象设置一些默认的笔记信息如创建时间、修改时间、类型、是否本地修改以及父文件夹 ID 等)
noteId = Long.valueOf(uri.getPathSegments().get(1)); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
} catch (NumberFormatException e) { //通过context.getContentResolver().insert方法将这些信息插入到数据库中并获取插入后的Uri
Log.e(TAG, "Get note id error :" + e.toString()); long noteId = 0;
noteId = 0; try {
} noteId = Long.valueOf(uri.getPathSegments().get(1));
if (noteId == -1) { } catch (NumberFormatException e) {
throw new IllegalStateException("Wrong note id:" + noteId); Log.e(TAG, "Get note id error :" + e.toString());
} noteId = 0;
return noteId; }
} if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
public Note() { }//从Uri中提取出笔记 ID如果提取过程中发生NumberFormatException或者笔记 ID 为 -1则抛出异常或者记录错误信息
mNoteDiffValues = new ContentValues(); return noteId;
mNoteData = new NoteData(); }//用于创建一个新的笔记 ID
}
public Note() {
public void setNoteValue(String key, String value) { mNoteDiffValues = new ContentValues();
mNoteDiffValues.put(key, value); mNoteData = new NoteData();
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); }
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
public void setTextData(String key, String value) { mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteData.setTextData(key, value); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} //将传入的键值对放入mNoteDiffValues中并同时设置LOCAL_MODIFIED和MODIFIED_DATE表示笔记已被本地修改以及修改的时间
}//用于设置笔记的基本信息
public void setTextDataId(long id) {
mNoteData.setTextDataId(id); public void setTextData(String key, String value) {
} mNoteData.setTextData(key, value);
}//用于设置笔记中的文本数据
public long getTextDataId() {
return mNoteData.mTextDataId; public void setTextDataId(long id) {
} mNoteData.setTextDataId(id);
}
public void setCallDataId(long id) {
mNoteData.setCallDataId(id); public long getTextDataId() {
} return mNoteData.mTextDataId;
}
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); public void setCallDataId(long id) {
} mNoteData.setCallDataId(id);
}
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); public void setCallData(String key, String value) {
} mNoteData.setCallData(key, value);
}
public boolean syncNote(Context context, long noteId) { //用于设置笔记中的通话数据
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); public boolean isLocalModified() {
} return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}//用于判断笔记是否被本地修改
if (!isLocalModified()) {
return true; public boolean syncNote(Context context, long noteId) {
} if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
/** }
* 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 if (!isLocalModified()) {
* note data info return true;
*/ }
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, /**
null) == 0) { * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
Log.e(TAG, "Update note error, should not happen"); * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
// Do not return, fall through * note data info
} */
mNoteDiffValues.clear(); if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
if (mNoteData.isLocalModified() null) == 0) {
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { Log.e(TAG, "Update note error, should not happen");
return false; // Do not return, fall through
} }
mNoteDiffValues.clear();
return true;
} if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
private class NoteData { return false;
private long mTextDataId; }
private ContentValues mTextDataValues; return true;
}//用于同步笔记
private long mCallDataId;
private class NoteData {
private ContentValues mCallDataValues; private long mTextDataId;//存储文本数据 ID
private static final String TAG = "NoteData"; private ContentValues mTextDataValues;
public NoteData() { private long mCallDataId;
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); private ContentValues mCallDataValues;
mTextDataId = 0;
mCallDataId = 0; private static final String TAG = "NoteData";
}
public NoteData() {
boolean isLocalModified() { mTextDataValues = new ContentValues();
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; mCallDataValues = new ContentValues();
} mTextDataId = 0;
mCallDataId = 0;
void setTextDataId(long id) { }
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); boolean isLocalModified() {
} return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
mTextDataId = id; }
}
void setTextDataId(long id) {
void setCallDataId(long id) { if(id <= 0) {
if (id <= 0) { throw new IllegalArgumentException("Text data id should larger than 0");
throw new IllegalArgumentException("Call data id should larger than 0"); }
} mTextDataId = id;
mCallDataId = id; }
}
void setCallDataId(long id) {
void setCallData(String key, String value) { if (id <= 0) {
mCallDataValues.put(key, value); throw new IllegalArgumentException("Call data id should larger than 0");
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); }
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mCallDataId = id;
} }
void setTextData(String key, String value) { void setCallData(String key, String value) {
mTextDataValues.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());
} }
Uri pushIntoContentResolver(Context context, long noteId) { void setTextData(String key, String value) {
/** mTextDataValues.put(key, value);
* Check for safety mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
*/ mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
if (noteId <= 0) { }
throw new IllegalArgumentException("Wrong note id:" + noteId);
} Uri pushIntoContentResolver(Context context, long noteId) {
/**
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); * Check for safety
ContentProviderOperation.Builder builder = null; */
if (noteId <= 0) {
if(mTextDataValues.size() > 0) { throw new IllegalArgumentException("Wrong note id:" + noteId);
mTextDataValues.put(DataColumns.NOTE_ID, noteId); }
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, ContentProviderOperation.Builder builder = null;
mTextDataValues);
try { if(mTextDataValues.size() > 0) {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
} catch (NumberFormatException e) { if (mTextDataId == 0) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
mTextDataValues.clear(); Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
return null; mTextDataValues);
} try {
} else { setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( } catch (NumberFormatException e) {
Notes.CONTENT_DATA_URI, mTextDataId)); Log.e(TAG, "Insert new text data fail with noteId" + noteId);
builder.withValues(mTextDataValues); mTextDataValues.clear();
operationList.add(builder.build()); return null;
} }
mTextDataValues.clear(); } else {
} builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
if(mCallDataValues.size() > 0) { builder.withValues(mTextDataValues);
mCallDataValues.put(DataColumns.NOTE_ID, noteId); operationList.add(builder.build());
if (mCallDataId == 0) { }
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); mTextDataValues.clear();
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, }
mCallDataValues);
try { if(mCallDataValues.size() > 0) {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
} catch (NumberFormatException e) { if (mCallDataId == 0) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId); mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
mCallDataValues.clear(); Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
return null; mCallDataValues);
} try {
} else { setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( } catch (NumberFormatException e) {
Notes.CONTENT_DATA_URI, mCallDataId)); Log.e(TAG, "Insert new call data fail with noteId" + noteId);
builder.withValues(mCallDataValues); mCallDataValues.clear();
operationList.add(builder.build()); return null;
} }
mCallDataValues.clear(); } else {
} builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
if (operationList.size() > 0) { builder.withValues(mCallDataValues);
try { operationList.add(builder.build());
ContentProviderResult[] results = context.getContentResolver().applyBatch( }
Notes.AUTHORITY, operationList); mCallDataValues.clear();
return (results == null || results.length == 0 || results[0] == null) ? null }
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { if (operationList.size() > 0) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); try {
return null; ContentProviderResult[] results = context.getContentResolver().applyBatch(
} catch (OperationApplicationException e) { Notes.AUTHORITY, operationList);
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); return (results == null || results.length == 0 || results[0] == null) ? null
return null; : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} } catch (RemoteException e) {
} Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} } catch (OperationApplicationException e) {
} Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} return null;
}
}
return null;
}
}//用于处理笔记中的数据相关操作
}

@ -14,355 +14,356 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.model; package net.micode.notes.model;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.content.ContentUris; import android.content.ContentUris;
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 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.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.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;
// 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;
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;
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,
DataColumns.DATA1, DataColumns.DATA1,
DataColumns.DATA2, DataColumns.DATA2,
DataColumns.DATA3, DataColumns.DATA3,
DataColumns.DATA4, DataColumns.DATA4,
}; };
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,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
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
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();
mFolderId = folderId; mFolderId = folderId;
mNote = new Note(); mNote = new Note();
mNoteId = 0; mNoteId = 0;
mIsDeleted = false; mIsDeleted = false;
mMode = 0; mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
//用于新建笔记初始化了一些默认值并创建了一个新的Note对象。
// 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;
mIsDeleted = false; mIsDeleted = false;
mNote = new Note(); mNote = new Note();
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);
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);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
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();
} }//用于加载笔记的基本属性,如父文件夹 ID、提醒日期、背景颜色等。
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)) {
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));
} 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,
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);
} }
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
*/ */
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 {
return false; return false;
} }
} }//判断笔记是否值得保存,如果值得保存则将笔记保存到数据库。如果笔记是新创建的,会获取一个新的笔记 ID。保存成功后如果有相关的小部件会通知监听器更新小部件内容
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) {
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));
} }
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);
} }
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
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);
} }
} }

@ -14,145 +14,171 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener; import android.content.DialogInterface.OnDismissListener;
import android.content.Intent; import android.content.Intent;
import android.media.AudioManager; import android.media.AudioManager;
import android.media.MediaPlayer; import android.media.MediaPlayer;
import android.media.RingtoneManager; import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.PowerManager; import android.os.PowerManager;
import android.provider.Settings; import android.provider.Settings;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
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 java.io.IOException; import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { // 定义一个名为 AlarmAlertActivity 的类,继承自 Activity并实现了 OnClickListener 和 OnDismissListener 接口
private long mNoteId; public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private String mSnippet; // 存储笔记的 ID
private static final int SNIPPET_PREW_MAX_LEN = 60; private long mNoteId;
MediaPlayer mPlayer; // 存储笔记的片段内容
private String mSnippet;
@Override // 定义一个常量,表示片段预览的最大长度
protected void onCreate(Bundle savedInstanceState) { private static final int SNIPPET_PREW_MAX_LEN = 60;
super.onCreate(savedInstanceState); // 媒体播放器对象
requestWindowFeature(Window.FEATURE_NO_TITLE); MediaPlayer mPlayer;
final Window win = getWindow(); @Override
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isScreenOn()) { // 请求无标题栏的窗口特征
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON requestWindowFeature(Window.FEATURE_NO_TITLE);
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON final Window win = getWindow();
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); // 设置窗口标志,使其在锁定时显示
} win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
Intent intent = getIntent(); if (!isScreenOn()) {
// 如果屏幕未点亮,设置一系列窗口标志以保持屏幕常亮、点亮屏幕等
try { win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) }
: mSnippet;
} catch (IllegalArgumentException e) { Intent intent = getIntent();
e.printStackTrace();
return; try {
} // 从 Intent 的数据路径中获取笔记 ID并转换为长整型
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mPlayer = new MediaPlayer(); // 根据笔记 ID 获取片段内容
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
showActionDialog(); // 如果片段内容长度大于最大长度,截取并添加提示信息,否则保持不变
playAlarmSound(); mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN? mSnippet.substring(0,
} else { SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
finish(); : mSnippet;
} } catch (IllegalArgumentException e) {
} // 打印异常信息
e.printStackTrace();
private boolean isScreenOn() { return;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); }
return pm.isScreenOn();
} mPlayer = new MediaPlayer();
// 如果笔记在数据库中可见且类型为 Notes.TYPE_NOTE
private void playAlarmSound() { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 显示操作对话框
showActionDialog();
int silentModeStreams = Settings.System.getInt(getContentResolver(), // 播放闹钟声音
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); playAlarmSound();
} else {
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { // 如果不满足条件,结束活动
mPlayer.setAudioStreamType(silentModeStreams); finish();
} else { }
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); }
}
try { // 判断屏幕是否点亮的方法
mPlayer.setDataSource(this, url); private boolean isScreenOn() {
mPlayer.prepare(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mPlayer.setLooping(true); return pm.isScreenOn();
mPlayer.start(); }
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block // 播放闹钟声音的方法
e.printStackTrace(); private void playAlarmSound() {
} catch (SecurityException e) { // 获取系统默认的闹钟铃声 Uri
// TODO Auto-generated catch block Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
e.printStackTrace();
} catch (IllegalStateException e) { int silentModeStreams = Settings.System.getInt(getContentResolver(),
// TODO Auto-generated catch block Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
e.printStackTrace();
} catch (IOException e) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM))!= 0) {
// TODO Auto-generated catch block // 根据系统设置设置媒体播放器的音频流类型
e.printStackTrace(); mPlayer.setAudioStreamType(silentModeStreams);
} } else {
} mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
private void showActionDialog() { try {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 设置数据源、准备播放、设置循环播放并开始播放
dialog.setTitle(R.string.app_name); mPlayer.setDataSource(this, url);
dialog.setMessage(mSnippet); mPlayer.prepare();
dialog.setPositiveButton(R.string.notealert_ok, this); mPlayer.setLooping(true);
if (isScreenOn()) { mPlayer.start();
dialog.setNegativeButton(R.string.notealert_enter, this); } catch (IllegalArgumentException e) {
} // 打印非法参数异常信息
dialog.show().setOnDismissListener(this); e.printStackTrace();
} } catch (SecurityException e) {
// 打印安全异常信息
public void onClick(DialogInterface dialog, int which) { e.printStackTrace();
switch (which) { } catch (IllegalStateException e) {
case DialogInterface.BUTTON_NEGATIVE: // 打印非法状态异常信息
Intent intent = new Intent(this, NoteEditActivity.class); e.printStackTrace();
intent.setAction(Intent.ACTION_VIEW); } catch (IOException e) {
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 打印输入输出异常信息
startActivity(intent); e.printStackTrace();
break; }
default: }
break;
} // 显示操作对话框的方法
} private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
public void onDismiss(DialogInterface dialog) { dialog.setTitle(R.string.app_name);
stopAlarmSound(); dialog.setMessage(mSnippet);
finish(); dialog.setPositiveButton(R.string.notealert_ok, this);
} if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
private void stopAlarmSound() { }
if (mPlayer != null) { // 显示对话框并设置其消失监听器
mPlayer.stop(); dialog.show().setOnDismissListener(this);
mPlayer.release(); }
mPlayer = null;
} // 实现 OnClickListener 接口的方法,处理对话框按钮点击事件
} public void onClick(DialogInterface dialog, int which) {
} switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
break;
}
}
// 实现 OnDismissListener 接口的方法,处理对话框消失事件
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
}
// 停止闹钟声音的方法
private void stopAlarmSound() {
if (mPlayer!= null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
}

@ -14,52 +14,63 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
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;
// 定义一个名为 AlarmInitReceiver 的类,继承自 BroadcastReceiver
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
private static final String [] PROJECTION = new String [] { // 定义查询数据库时的投影数组,包含笔记 ID 和提醒日期两个字段
NoteColumns.ID, private static final String[] PROJECTION = new String[]{
NoteColumns.ALERTED_DATE NoteColumns.ID,
}; NoteColumns.ALERTED_DATE
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1; // 定义常量,表示投影数组中 ID 和提醒日期字段的索引
private static final int COLUMN_ID = 0;
@Override private static final int COLUMN_ALERTED_DATE = 1;
public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis(); @Override
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, public void onReceive(Context context, Intent intent) {
PROJECTION, // 获取当前时间
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, long currentDate = System.currentTimeMillis();
new String[] { String.valueOf(currentDate) }, // 查询数据库,获取提醒日期大于当前时间且类型为笔记的记录
null); Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
if (c != null) { NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
if (c.moveToFirst()) { new String[]{String.valueOf(currentDate)},
do { null);
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
Intent sender = new Intent(context, AlarmReceiver.class); if (c!= null) {
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); if (c.moveToFirst()) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); do {
AlarmManager alermManager = (AlarmManager) context // 获取每条记录的提醒日期
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建 Intent用于发送给 AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
// 设置 Intent 的数据为带有笔记 ID 的 Uri
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建 PendingIntent用于触发广播
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取系统的 AlarmManager 服务
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); // 设置闹钟,在指定时间触发 PendingIntent
} while (c.moveToNext()); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} } while (c.moveToNext());
c.close(); }
} // 关闭游标
} c.close();
} }
}
}

@ -14,17 +14,22 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver { // 定义一个名为 AlarmReceiver 的类,它继承自 BroadcastReceiver
@Override public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) { // 重写 onReceive 方法,当接收到广播时会调用这个方法
intent.setClass(context, AlarmAlertActivity.class); @Override
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); public void onReceive(Context context, Intent intent) {
context.startActivity(intent); // 设置 Intent 的目标类为 AlarmAlertActivity
} intent.setClass(context, AlarmAlertActivity.class);
} // 为 Intent 添加标志,表示启动一个新的任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 以给定的 Intent 启动一个新的 Activity
context.startActivity(intent);
}
}

@ -14,77 +14,101 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import java.util.Calendar; import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker; import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { // 定义一个名为 DateTimePickerDialog 的类,它继承自 AlertDialog 并实现了 OnClickListener 接口
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance();
private boolean mIs24HourView; // 存储日期的 Calendar 对象
private OnDateTimeSetListener mOnDateTimeSetListener; private Calendar mDate = Calendar.getInstance();
private DateTimePicker mDateTimePicker; // 标记是否为 24 小时制显示
private boolean mIs24HourView;
public interface OnDateTimeSetListener { // 日期时间设置监听器
void OnDateTimeSet(AlertDialog dialog, long date); private OnDateTimeSetListener mOnDateTimeSetListener;
} // 日期时间选择器
private DateTimePicker mDateTimePicker;
public DateTimePickerDialog(Context context, long date) {
super(context); // 定义日期时间设置监听器接口
mDateTimePicker = new DateTimePicker(context); public interface OnDateTimeSetListener {
setView(mDateTimePicker); void OnDateTimeSet(AlertDialog dialog, long date);
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { }
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) { // 构造函数,接受上下文和一个日期时间的长整型值
mDate.set(Calendar.YEAR, year); public DateTimePickerDialog(Context context, long date) {
mDate.set(Calendar.MONTH, month); super(context);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); // 创建一个 DateTimePicker 对象
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDateTimePicker = new DateTimePicker(context);
mDate.set(Calendar.MINUTE, minute); // 设置对话框的视图为 DateTimePicker
updateTitle(mDate.getTimeInMillis()); setView(mDateTimePicker);
} // 设置日期时间改变监听器
}); mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
mDate.setTimeInMillis(date); public void onDateTimeChanged(DateTimePicker view, int year, int month,
mDate.set(Calendar.SECOND, 0); int dayOfMonth, int hourOfDay, int minute) {
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); // 设置 Calendar 对象的年、月、日、时、分
setButton(context.getString(R.string.datetime_dialog_ok), this); mDate.set(Calendar.YEAR, year);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); mDate.set(Calendar.MONTH, month);
set24HourView(DateFormat.is24HourFormat(this.getContext())); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateTitle(mDate.getTimeInMillis()); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
} mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题
public void set24HourView(boolean is24HourView) { updateTitle(mDate.getTimeInMillis());
mIs24HourView = is24HourView; }
} });
// 设置 Calendar 对象的时间为传入的日期时间
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mDate.setTimeInMillis(date);
mOnDateTimeSetListener = callBack; // 将秒设置为 0
} mDate.set(Calendar.SECOND, 0);
// 设置 DateTimePicker 的当前日期时间
private void updateTitle(long date) { mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
int flag = // 设置确定按钮的文本和点击监听器
DateUtils.FORMAT_SHOW_YEAR | setButton(context.getString(R.string.datetime_dialog_ok), this);
DateUtils.FORMAT_SHOW_DATE | // 设置取消按钮的文本和点击监听器为 null
DateUtils.FORMAT_SHOW_TIME; setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; // 根据上下文设置是否为 24 小时制显示
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); set24HourView(DateFormat.is24HourFormat(this.getContext()));
} // 更新对话框标题
updateTitle(mDate.getTimeInMillis());
public void onClick(DialogInterface arg0, int arg1) { }
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); // 设置是否为 24 小时制显示的方法
} public void set24HourView(boolean is24HourView) {
} mIs24HourView = is24HourView;
}
}
// 设置日期时间设置监听器的方法
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
// 更新对话框标题的私有方法
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
// 实现 OnClickListener 接口的方法,当点击确定按钮时调用
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener!= null) {
// 调用日期时间设置监听器的方法
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -14,48 +14,60 @@
* 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.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import android.widget.PopupMenu; import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
public class DropdownMenu { // 定义一个名为 DropdownMenu 的类
private Button mButton; public class DropdownMenu {
private PopupMenu mPopupMenu; // 下拉菜单的按钮
private Menu mMenu; private Button mButton;
// 弹出菜单对象
public DropdownMenu(Context context, Button button, int menuId) { private PopupMenu mPopupMenu;
mButton = button; // 菜单对象
mButton.setBackgroundResource(R.drawable.dropdown_icon); private Menu mMenu;
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu(); // 构造函数,接受上下文、按钮和菜单资源 ID
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); public DropdownMenu(Context context, Button button, int menuId) {
mButton.setOnClickListener(new OnClickListener() { mButton = button;
public void onClick(View v) { // 设置按钮的背景为下拉图标
mPopupMenu.show(); mButton.setBackgroundResource(R.drawable.dropdown_icon);
} // 创建一个弹出菜单,关联到按钮
}); mPopupMenu = new PopupMenu(context, mButton);
} mMenu = mPopupMenu.getMenu();
// 从给定的菜单资源 ID 中填充菜单
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
if (mPopupMenu != null) { // 为按钮设置点击监听器,点击时显示弹出菜单
mPopupMenu.setOnMenuItemClickListener(listener); mButton.setOnClickListener(new OnClickListener() {
} public void onClick(View v) {
} mPopupMenu.show();
}
public MenuItem findItem(int id) { });
return mMenu.findItem(id); }
}
// 设置弹出菜单项点击监听器的方法
public void setTitle(CharSequence title) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
mButton.setText(title); if (mPopupMenu!= null) {
} mPopupMenu.setOnMenuItemClickListener(listener);
} }
}
// 根据 ID 查找菜单项的方法
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
// 设置按钮标题的方法
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}

@ -14,67 +14,79 @@
* 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.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
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.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
// 定义一个名为 FoldersListAdapter 的类,继承自 CursorAdapter
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
public static final String [] PROJECTION = { // 定义查询投影,包含 ID 和片段SNIPPET
NoteColumns.ID, public static final String[] PROJECTION = {
NoteColumns.SNIPPET NoteColumns.ID,
}; NoteColumns.SNIPPET
};
public static final int ID_COLUMN = 0; // ID 列的索引
public static final int NAME_COLUMN = 1; public static final int ID_COLUMN = 0;
// 名称列的索引(实际上是片段列在这个上下文中用作名称)
public FoldersListAdapter(Context context, Cursor c) { public static final int NAME_COLUMN = 1;
super(context, c);
// TODO Auto-generated constructor stub // 构造函数,接受上下文和游标
} public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
@Override // TODO Auto-generated constructor stub
public View newView(Context context, Cursor cursor, ViewGroup parent) { }
return new FolderListItem(context);
} // 创建新视图的方法
@Override
@Override public View newView(Context context, Cursor cursor, ViewGroup parent) {
public void bindView(View view, Context context, Cursor cursor) { return new FolderListItem(context);
if (view instanceof FolderListItem) { }
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
// 绑定数据到视图的方法
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 根据 ID 判断是否为根文件夹,设置不同的文件夹名称
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) { // 获取指定位置的文件夹名称的方法
Cursor cursor = (Cursor) getItem(position); public String getFolderName(Context context, int position) {
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER)? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
private class FolderListItem extends LinearLayout { // 内部类 FolderListItem代表列表中的单个文件夹项视图
private TextView mName; private class FolderListItem extends LinearLayout {
private TextView mName;
public FolderListItem(Context context) {
super(context); // 构造函数,接受上下文
inflate(context, R.layout.folder_list_item, this); public FolderListItem(Context context) {
mName = (TextView) findViewById(R.id.tv_folder_name); super(context);
} // 从布局文件中填充视图
inflate(context, R.layout.folder_list_item, this);
public void bind(String name) { // 获取显示文件夹名称的 TextView
mName.setText(name); mName = (TextView) findViewById(R.id.tv_folder_name);
} }
}
// 绑定文件夹名称到视图的方法
} public void bind(String name) {
mName.setText(name);
}
}
}

@ -14,204 +14,218 @@
* 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.graphics.Rect; import android.graphics.Rect;
import android.text.Layout; import android.text.Layout;
import android.text.Selection; import android.text.Selection;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.URLSpan; import android.text.style.URLSpan;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.ContextMenu; import android.view.ContextMenu;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener; import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.widget.EditText; import android.widget.EditText;
import net.micode.notes.R; import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class NoteEditText extends EditText { // 定义一个名为 NoteEditText 的自定义 EditText 类
private static final String TAG = "NoteEditText"; public class NoteEditText extends EditText {
private int mIndex; private static final String TAG = "NoteEditText";
private int mSelectionStartBeforeDelete; // 当前 EditText 的索引
private int mIndex;
private static final String SCHEME_TEL = "tel:" ; // 删除操作前的选中文本起始位置
private static final String SCHEME_HTTP = "http:" ; private int mSelectionStartBeforeDelete;
private static final String SCHEME_EMAIL = "mailto:" ;
// 不同的链接方案常量
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final String SCHEME_TEL = "tel:";
static { private static final String SCHEME_HTTP = "http:";
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); private static final String SCHEME_EMAIL = "mailto:";
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 存储链接方案和对应的资源 ID 的映射
} private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
/** sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
* Call by the {@link NoteEditActivity} to delete or add edit text sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
*/ sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
public interface OnTextViewChangeListener { }
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens // 定义接口,用于在 NoteEditActivity 中监听 EditText 的变化
* and the text is null public interface OnTextViewChangeListener {
*/ // 当按下删除键且文本为空时,删除当前 EditText
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);
/** // 当按下回车键时,在当前 EditText 后添加一个新的 EditText
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} void onEditTextEnter(int index, String text);
* happen
*/ // 根据文本是否存在显示或隐藏选项
void onEditTextEnter(int index, String text); void onTextChange(int index, boolean hasText);
}
/**
* Hide or show item option when text change // 用于监听文本变化的接口实例
*/ private OnTextViewChangeListener mOnTextViewChangeListener;
void onTextChange(int index, boolean hasText);
} // 构造函数,接受上下文
public NoteEditText(Context context) {
private OnTextViewChangeListener mOnTextViewChangeListener; super(context, null);
mIndex = 0;
public NoteEditText(Context context) { }
super(context, null);
mIndex = 0; // 设置当前 EditText 的索引
} public void setIndex(int index) {
mIndex = index;
public void setIndex(int index) { }
mIndex = index;
} // 设置文本变化监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener;
mOnTextViewChangeListener = listener; }
}
// 构造函数,接受上下文和属性集
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { // 构造函数,接受上下文、属性集和样式
super(context, attrs, defStyle); public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
// TODO Auto-generated constructor stub super(context, attrs, defStyle);
} // TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) { // 处理触摸事件
switch (event.getAction()) { @Override
case MotionEvent.ACTION_DOWN: public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
int x = (int) event.getX(); case MotionEvent.ACTION_DOWN:
int y = (int) event.getY(); // 获取触摸点坐标并进行调整
x -= getTotalPaddingLeft(); int x = (int) event.getX();
y -= getTotalPaddingTop(); int y = (int) event.getY();
x += getScrollX(); x -= getTotalPaddingLeft();
y += getScrollY(); y -= getTotalPaddingTop();
x += getScrollX();
Layout layout = getLayout(); y += getScrollY();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x); Layout layout = getLayout();
Selection.setSelection(getText(), off); // 获取触摸点所在的行
break; int line = layout.getLineForVertical(y);
} // 获取触摸点在行中的偏移量
int off = layout.getOffsetForHorizontal(line, x);
return super.onTouchEvent(event); // 设置选中文本
} Selection.setSelection(getText(), off);
break;
@Override }
public boolean onKeyDown(int keyCode, KeyEvent event) { return super.onTouchEvent(event);
switch (keyCode) { }
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) { // 处理按键按下事件
return false; @Override
} public boolean onKeyDown(int keyCode, KeyEvent event) {
break; switch (keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_ENTER:
mSelectionStartBeforeDelete = getSelectionStart(); if (mOnTextViewChangeListener!= null) {
break; return false;
default: }
break; break;
} case KeyEvent.KEYCODE_DEL:
return super.onKeyDown(keyCode, event); // 记录删除操作前的选中文本起始位置
} mSelectionStartBeforeDelete = getSelectionStart();
break;
@Override default:
public boolean onKeyUp(int keyCode, KeyEvent event) { break;
switch(keyCode) { }
case KeyEvent.KEYCODE_DEL: return super.onKeyDown(keyCode, event);
if (mOnTextViewChangeListener != null) { }
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); // 处理按键抬起事件
return true; @Override
} public boolean onKeyUp(int keyCode, KeyEvent event) {
} else { switch (keyCode) {
Log.d(TAG, "OnTextViewChangeListener was not seted"); case KeyEvent.KEYCODE_DEL:
} if (mOnTextViewChangeListener!= null) {
break; // 如果起始位置为 0 且不是第一个 EditText则调用删除方法
case KeyEvent.KEYCODE_ENTER: if (0 == mSelectionStartBeforeDelete && mIndex!= 0) {
if (mOnTextViewChangeListener != null) { mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
int selectionStart = getSelectionStart(); return true;
String text = getText().subSequence(selectionStart, length()).toString(); }
setText(getText().subSequence(0, selectionStart)); } else {
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); Log.d(TAG, "OnTextViewChangeListener was not seted");
} else { }
Log.d(TAG, "OnTextViewChangeListener was not seted"); break;
} case KeyEvent.KEYCODE_ENTER:
break; if (mOnTextViewChangeListener!= null) {
default: int selectionStart = getSelectionStart();
break; // 获取选中文本后的剩余文本
} String text = getText().subSequence(selectionStart, length()).toString();
return super.onKeyUp(keyCode, event); // 设置 EditText 的文本为选中前的部分
} setText(getText().subSequence(0, selectionStart));
// 调用添加新 EditText 的方法
@Override mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { } else {
if (mOnTextViewChangeListener != null) { Log.d(TAG, "OnTextViewChangeListener was not seted");
if (!focused && TextUtils.isEmpty(getText())) { }
mOnTextViewChangeListener.onTextChange(mIndex, false); break;
} else { default:
mOnTextViewChangeListener.onTextChange(mIndex, true); break;
} }
} return super.onKeyUp(keyCode, event);
super.onFocusChanged(focused, direction, previouslyFocusedRect); }
}
// 处理焦点变化事件
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (getText() instanceof Spanned) { if (mOnTextViewChangeListener!= null) {
int selStart = getSelectionStart(); // 根据是否有焦点和文本是否为空,调用文本变化监听器方法
int selEnd = getSelectionEnd(); if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
int min = Math.min(selStart, selEnd); } else {
int max = Math.max(selStart, selEnd); mOnTextViewChangeListener.onTextChange(mIndex, true);
}
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); }
if (urls.length == 1) { super.onFocusChanged(focused, direction, previouslyFocusedRect);
int defaultResId = 0; }
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) { // 创建上下文菜单
defaultResId = sSchemaActionResMap.get(schema); @Override
break; protected void onCreateContextMenu(ContextMenu menu) {
} if (getText() instanceof Spanned) {
} int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
if (defaultResId == 0) {
defaultResId = R.string.note_link_other; int min = Math.min(selStart, selEnd);
} int max = Math.max(selStart, selEnd);
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
new OnMenuItemClickListener() { if (urls.length == 1) {
public boolean onMenuItemClick(MenuItem item) { int defaultResId = 0;
// goto a new intent for (String schema : sSchemaActionResMap.keySet()) {
urls[0].onClick(NoteEditText.this); if (urls[0].getURL().indexOf(schema) >= 0) {
return true; defaultResId = sSchemaActionResMap.get(schema);
} break;
}); }
} }
}
super.onCreateContextMenu(menu); if (defaultResId == 0) {
} defaultResId = R.string.note_link_other;
} }
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// 点击菜单项时触发链接的点击事件
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -14,211 +14,247 @@
* 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;
// 定义一个名为 NoteItemData 的类,用于存储笔记项的数据
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { // 定义查询投影,包含多个列
NoteColumns.ID, static final String[] PROJECTION = new String[]{
NoteColumns.ALERTED_DATE, NoteColumns.ID,
NoteColumns.BG_COLOR_ID, NoteColumns.ALERTED_DATE,
NoteColumns.CREATED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.HAS_ATTACHMENT, NoteColumns.CREATED_DATE,
NoteColumns.MODIFIED_DATE, NoteColumns.HAS_ATTACHMENT,
NoteColumns.NOTES_COUNT, NoteColumns.MODIFIED_DATE,
NoteColumns.PARENT_ID, NoteColumns.NOTES_COUNT,
NoteColumns.SNIPPET, NoteColumns.PARENT_ID,
NoteColumns.TYPE, NoteColumns.SNIPPET,
NoteColumns.WIDGET_ID, NoteColumns.TYPE,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_ID,
}; NoteColumns.WIDGET_TYPE,
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; // 各个列的索引常量
private static final int BG_COLOR_ID_COLUMN = 2; private static final int ID_COLUMN = 0;
private static final int CREATED_DATE_COLUMN = 3; private static final int ALERTED_DATE_COLUMN = 1;
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int MODIFIED_DATE_COLUMN = 5; private static final int CREATED_DATE_COLUMN = 3;
private static final int NOTES_COUNT_COLUMN = 6; private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int PARENT_ID_COLUMN = 7; private static final int MODIFIED_DATE_COLUMN = 5;
private static final int SNIPPET_COLUMN = 8; private static final int NOTES_COUNT_COLUMN = 6;
private static final int TYPE_COLUMN = 9; private static final int PARENT_ID_COLUMN = 7;
private static final int WIDGET_ID_COLUMN = 10; private static final int SNIPPET_COLUMN = 8;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private long mId; private static final int WIDGET_TYPE_COLUMN = 11;
private long mAlertDate;
private int mBgColorId; // 笔记项的各个属性
private long mCreatedDate; private long mId;
private boolean mHasAttachment; private long mAlertDate;
private long mModifiedDate; private int mBgColorId;
private int mNotesCount; private long mCreatedDate;
private long mParentId; private boolean mHasAttachment;
private String mSnippet; private long mModifiedDate;
private int mType; private int mNotesCount;
private int mWidgetId; private long mParentId;
private int mWidgetType; private String mSnippet;
private String mName; private int mType;
private String mPhoneNumber; private int mWidgetId;
private int mWidgetType;
private boolean mIsLastItem; private String mName;
private boolean mIsFirstItem; private String mPhoneNumber;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder; // 用于标记笔记项在列表中的位置相关属性
private boolean mIsMultiNotesFollowingFolder; private boolean mIsLastItem;
private boolean mIsFirstItem;
public NoteItemData(Context context, Cursor cursor) { private boolean mIsOnlyOneItem;
mId = cursor.getLong(ID_COLUMN); private boolean mIsOneNoteFollowingFolder;
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); private boolean mIsMultiNotesFollowingFolder;
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 构造函数,接受上下文和游标,用于从游标中提取数据初始化笔记项
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; public NoteItemData(Context context, Cursor cursor) {
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 从游标中获取各个列的值并初始化相应的属性
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mId = cursor.getLong(ID_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
NoteEditActivity.TAG_UNCHECKED, ""); mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0)? true : false;
mType = cursor.getInt(TYPE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
mPhoneNumber = ""; // 处理片段内容,去除特定标记
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); NoteEditActivity.TAG_UNCHECKED, "");
if (!TextUtils.isEmpty(mPhoneNumber)) { mType = cursor.getInt(TYPE_COLUMN);
mName = Contact.getContact(context, mPhoneNumber); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
if (mName == null) { mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mName = mPhoneNumber;
} mPhoneNumber = "";
} // 如果父 ID 是通话记录文件夹的 ID则获取通话号码并设置名称
} if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (mName == null) { if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = ""; mName = Contact.getContact(context, mPhoneNumber);
} if (mName == null) {
checkPostion(cursor); mName = mPhoneNumber;
} }
}
private void checkPostion(Cursor cursor) { }
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; if (mName == null) {
mIsOnlyOneItem = (cursor.getCount() == 1); mName = "";
mIsMultiNotesFollowingFolder = false; }
mIsOneNoteFollowingFolder = false; // 检查笔记项在游标中的位置
checkPostion(cursor);
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { }
int position = cursor.getPosition();
if (cursor.moveToPrevious()) { // 检查笔记项在游标中的位置的私有方法
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER private void checkPostion(Cursor cursor) {
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { // 设置是否为最后一项、第一项、唯一项等标志
if (cursor.getCount() > (position + 1)) { mIsLastItem = cursor.isLast()? true : false;
mIsMultiNotesFollowingFolder = true; mIsFirstItem = cursor.isFirst()? true : false;
} else { mIsOnlyOneItem = (cursor.getCount() == 1);
mIsOneNoteFollowingFolder = true; mIsMultiNotesFollowingFolder = false;
} mIsOneNoteFollowingFolder = false;
}
if (!cursor.moveToNext()) { // 如果笔记类型为普通笔记且不是第一项
throw new IllegalStateException("cursor move to previous but can't move back"); if (mType == Notes.TYPE_NOTE &&!mIsFirstItem) {
} int position = cursor.getPosition();
} // 移动游标到前一项并检查其类型
} if (cursor.moveToPrevious()) {
} if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
public boolean isOneFollowingFolder() { if (cursor.getCount() > (position + 1)) {
return mIsOneNoteFollowingFolder; mIsMultiNotesFollowingFolder = true;
} } else {
mIsOneNoteFollowingFolder = true;
public boolean isMultiFollowingFolder() { }
return mIsMultiNotesFollowingFolder; }
} // 尝试将游标移回原位,如果失败则抛出异常
if (!cursor.moveToNext()) {
public boolean isLast() { throw new IllegalStateException("cursor move to previous but can't move back");
return mIsLastItem; }
} }
}
public String getCallName() { }
return mName;
} // 判断是否有一个笔记项跟随在文件夹后面
public boolean isOneFollowingFolder() {
public boolean isFirst() { return mIsOneNoteFollowingFolder;
return mIsFirstItem; }
}
// 判断是否有多个笔记项跟随在文件夹后面
public boolean isSingle() { public boolean isMultiFollowingFolder() {
return mIsOnlyOneItem; return mIsMultiNotesFollowingFolder;
} }
public long getId() { // 判断是否为最后一项
return mId; public boolean isLast() {
} return mIsLastItem;
}
public long getAlertDate() {
return mAlertDate; // 获取通话记录的名称
} public String getCallName() {
return mName;
public long getCreatedDate() { }
return mCreatedDate;
} // 判断是否为第一项
public boolean isFirst() {
public boolean hasAttachment() { return mIsFirstItem;
return mHasAttachment; }
}
// 判断是否为唯一项
public long getModifiedDate() { public boolean isSingle() {
return mModifiedDate; return mIsOnlyOneItem;
} }
public int getBgColorId() { // 获取笔记项的 ID
return mBgColorId; public long getId() {
} return mId;
}
public long getParentId() {
return mParentId; // 获取提醒日期
} public long getAlertDate() {
return mAlertDate;
public int getNotesCount() { }
return mNotesCount;
} // 获取创建日期
public long getCreatedDate() {
public long getFolderId () { return mCreatedDate;
return mParentId; }
}
// 判断是否有附件
public int getType() { public boolean hasAttachment() {
return mType; return mHasAttachment;
} }
public int getWidgetType() { // 获取修改日期
return mWidgetType; public long getModifiedDate() {
} return mModifiedDate;
}
public int getWidgetId() {
return mWidgetId; // 获取背景颜色 ID
} public int getBgColorId() {
return mBgColorId;
public String getSnippet() { }
return mSnippet;
} // 获取父 ID文件夹 ID
public long getParentId() {
public boolean hasAlert() { return mParentId;
return (mAlertDate > 0); }
}
// 获取笔记数量
public boolean isCallRecord() { public int getNotesCount() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return mNotesCount;
} }
public static int getNoteType(Cursor cursor) { // 获取文件夹 ID
return cursor.getInt(TYPE_COLUMN); public long getFolderId() {
} return mParentId;
} }
// 获取笔记类型
public int getType() {
return mType;
}
// 获取小部件类型
public int getWidgetType() {
return mWidgetType;
}
// 获取小部件 ID
public int getWidgetId() {
return mWidgetId;
}
// 获取片段内容
public String getSnippet() {
return mSnippet;
}
// 判断是否有提醒
public boolean hasAlert() {
return (mAlertDate > 0);
}
// 判断是否为通话记录
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER &&!TextUtils.isEmpty(mPhoneNumber));
}
// 静态方法,从游标中获取笔记类型
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

@ -14,171 +14,198 @@
* 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.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;
// 定义一个名为 NotesListAdapter 的类,继承自 CursorAdapter
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 int mNotesCount; private HashMap<Integer, Boolean> mSelectedIndex;
private boolean mChoiceMode; // 笔记数量
private int mNotesCount;
public static class AppWidgetAttribute { // 是否处于选择模式
public int widgetId; private boolean mChoiceMode;
public int widgetType;
}; // 内部类,用于存储小部件的属性
public static class AppWidgetAttribute {
public NotesListAdapter(Context context) { public int widgetId;
super(context, null); public int widgetType;
mSelectedIndex = new HashMap<Integer, Boolean>(); };
mContext = context;
mNotesCount = 0; // 构造函数,接受上下文
} public NotesListAdapter(Context context) {
super(context, null);
@Override // 初始化选中项的哈希表
public View newView(Context context, Cursor cursor, ViewGroup parent) { mSelectedIndex = new HashMap<Integer, Boolean>();
return new NotesListItem(context); mContext = context;
} mNotesCount = 0;
}
@Override
public void bindView(View view, Context context, Cursor cursor) { // 创建新视图的方法
if (view instanceof NotesListItem) { @Override
NoteItemData itemData = new NoteItemData(context, cursor); public View newView(Context context, Cursor cursor, ViewGroup parent) {
((NotesListItem) view).bind(context, itemData, mChoiceMode, return new NotesListItem(context);
isSelectedItem(cursor.getPosition())); }
}
} // 绑定数据到视图的方法
@Override
public void setCheckedItem(final int position, final boolean checked) { public void bindView(View view, Context context, Cursor cursor) {
mSelectedIndex.put(position, checked); if (view instanceof NotesListItem) {
notifyDataSetChanged(); // 创建 NoteItemData 对象,用于存储笔记项的数据
} NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到 NotesListItem 视图
public boolean isInChoiceMode() { ((NotesListItem) view).bind(context, itemData, mChoiceMode,
return mChoiceMode; isSelectedItem(cursor.getPosition()));
} }
}
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); // 设置指定位置的项为选中或未选中状态的方法
mChoiceMode = mode; public void setCheckedItem(final int position, final boolean checked) {
} mSelectedIndex.put(position, checked);
// 通知数据改变,刷新视图
public void selectAll(boolean checked) { notifyDataSetChanged();
Cursor cursor = getCursor(); }
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { // 判断是否处于选择模式
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { public boolean isInChoiceMode() {
setCheckedItem(i, checked); return mChoiceMode;
} }
}
} // 设置选择模式的方法
} public void setChoiceMode(boolean mode) {
// 清空选中项的哈希表
public HashSet<Long> getSelectedItemIds() { mSelectedIndex.clear();
HashSet<Long> itemSet = new HashSet<Long>(); mChoiceMode = mode;
for (Integer position : mSelectedIndex.keySet()) { }
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position); // 全选或全不选的方法
if (id == Notes.ID_ROOT_FOLDER) { public void selectAll(boolean checked) {
Log.d(TAG, "Wrong item id, should not happen"); Cursor cursor = getCursor();
} else { for (int i = 0; i < getCount(); i++) {
itemSet.add(id); if (cursor.moveToPosition(i)) {
} // 如果是笔记类型,则设置选中状态
} if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
} setCheckedItem(i, checked);
}
return itemSet; }
} }
}
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); // 获取选中项的 ID 集合的方法
for (Integer position : mSelectedIndex.keySet()) { public HashSet<Long> getSelectedItemIds() {
if (mSelectedIndex.get(position) == true) { HashSet<Long> itemSet = new HashSet<Long>();
Cursor c = (Cursor) getItem(position); for (Integer position : mSelectedIndex.keySet()) {
if (c != null) { if (mSelectedIndex.get(position) == true) {
AppWidgetAttribute widget = new AppWidgetAttribute(); Long id = getItemId(position);
NoteItemData item = new NoteItemData(mContext, c); if (id == Notes.ID_ROOT_FOLDER) {
widget.widgetId = item.getWidgetId(); Log.d(TAG, "Wrong item id, should not happen");
widget.widgetType = item.getWidgetType(); } else {
itemSet.add(widget); itemSet.add(id);
/** }
* Don't close cursor here, only the adapter could close it }
*/ }
} else {
Log.e(TAG, "Invalid cursor"); return itemSet;
return null; }
}
} // 获取选中的小部件属性集合的方法
} public HashSet<AppWidgetAttribute> getSelectedWidget() {
return itemSet; HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
} for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
public int getSelectedCount() { Cursor c = (Cursor) getItem(position);
Collection<Boolean> values = mSelectedIndex.values(); if (c!= null) {
if (null == values) { AppWidgetAttribute widget = new AppWidgetAttribute();
return 0; NoteItemData item = new NoteItemData(mContext, c);
} widget.widgetId = item.getWidgetId();
Iterator<Boolean> iter = values.iterator(); widget.widgetType = item.getWidgetType();
int count = 0; itemSet.add(widget);
while (iter.hasNext()) { /**
if (true == iter.next()) { * Don't close cursor here, only the adapter could close it
count++; */
} } else {
} Log.e(TAG, "Invalid cursor");
return count; return null;
} }
}
public boolean isAllSelected() { }
int checkedCount = getSelectedCount(); return itemSet;
return (checkedCount != 0 && checkedCount == mNotesCount); }
}
// 获取选中项的数量的方法
public boolean isSelectedItem(final int position) { public int getSelectedCount() {
if (null == mSelectedIndex.get(position)) { Collection<Boolean> values = mSelectedIndex.values();
return false; if (null == values) {
} return 0;
return mSelectedIndex.get(position); }
} Iterator<Boolean> iter = values.iterator();
int count = 0;
@Override while (iter.hasNext()) {
protected void onContentChanged() { if (true == iter.next()) {
super.onContentChanged(); count++;
calcNotesCount(); }
} }
return count;
@Override }
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); // 判断是否全选的方法
calcNotesCount(); public boolean isAllSelected() {
} int checkedCount = getSelectedCount();
return (checkedCount!= 0 && checkedCount == mNotesCount);
private void calcNotesCount() { }
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { // 判断指定位置的项是否被选中的方法
Cursor c = (Cursor) getItem(i); public boolean isSelectedItem(final int position) {
if (c != null) { if (null == mSelectedIndex.get(position)) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { return false;
mNotesCount++; }
} return mSelectedIndex.get(position);
} else { }
Log.e(TAG, "Invalid cursor");
return; // 当数据内容改变时调用的方法
} @Override
} protected void onContentChanged() {
} super.onContentChanged();
} // 计算笔记数量
calcNotesCount();
}
// 更换游标时调用的方法
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
// 计算笔记数量
calcNotesCount();
}
// 计算笔记数量的私有方法
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c!= null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -14,109 +14,144 @@
* 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.text.format.DateUtils; import android.text.format.DateUtils;
import android.view.View; import android.view.View;
import android.widget.CheckBox; 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;
// 定义一个名为 NotesListItem 的类,继承自 LinearLayout
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; // 提醒图标
private TextView mTitle; private ImageView mAlert;
private TextView mTime; // 标题文本视图
private TextView mCallName; private TextView mTitle;
private NoteItemData mItemData; // 时间文本视图
private CheckBox mCheckBox; private TextView mTime;
// 通话记录名称文本视图
public NotesListItem(Context context) { private TextView mCallName;
super(context); // 复选框
inflate(context, R.layout.note_item, this); private NoteItemData mItemData;
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); private CheckBox mCheckBox;
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time); // 构造函数,接受上下文
mCallName = (TextView) findViewById(R.id.tv_name); public NotesListItem(Context context) {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); super(context);
} // 从布局文件中填充视图
inflate(context, R.layout.note_item, this);
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { mTitle = (TextView) findViewById(R.id.tv_title);
mCheckBox.setVisibility(View.VISIBLE); mTime = (TextView) findViewById(R.id.tv_time);
mCheckBox.setChecked(checked); mCallName = (TextView) findViewById(R.id.tv_name);
} else { mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
mCheckBox.setVisibility(View.GONE); }
}
// 绑定数据到视图的方法
mItemData = data; public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { // 如果处于选择模式且数据类型为笔记类型
mCallName.setVisibility(View.GONE); if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mAlert.setVisibility(View.VISIBLE); // 显示复选框并设置选中状态
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mCheckBox.setVisibility(View.VISIBLE);
mTitle.setText(context.getString(R.string.call_record_folder_name) mCheckBox.setChecked(checked);
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); } else {
mAlert.setImageResource(R.drawable.call_record); // 隐藏复选框
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { mCheckBox.setVisibility(View.GONE);
mCallName.setVisibility(View.VISIBLE); }
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mItemData = data;
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 如果是通话记录文件夹
if (data.hasAlert()) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mAlert.setImageResource(R.drawable.clock); // 隐藏通话记录名称视图
mAlert.setVisibility(View.VISIBLE); mCallName.setVisibility(View.GONE);
} else { // 显示提醒图标
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE);
} // 设置标题文本外观和内容
} else { mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mCallName.setVisibility(View.GONE); mTitle.setText(context.getString(R.string.call_record_folder_name)
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
// 设置提醒图标资源为通话记录图标
if (data.getType() == Notes.TYPE_FOLDER) { mAlert.setImageResource(R.drawable.call_record);
mTitle.setText(data.getSnippet() } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
+ context.getString(R.string.format_folder_files_count, // 显示通话记录名称视图
data.getNotesCount())); mCallName.setVisibility(View.VISIBLE);
mAlert.setVisibility(View.GONE); // 设置通话记录名称文本
} else { mCallName.setText(data.getCallName());
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本外观
if (data.hasAlert()) { mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
mAlert.setImageResource(R.drawable.clock); // 设置标题文本为格式化后的片段内容
mAlert.setVisibility(View.VISIBLE); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
} else { // 如果有提醒,则显示提醒图标
mAlert.setVisibility(View.GONE); if (data.hasAlert()) {
} mAlert.setImageResource(R.drawable.clock);
} mAlert.setVisibility(View.VISIBLE);
} } else {
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); // 没有提醒则隐藏提醒图标
mAlert.setVisibility(View.GONE);
setBackground(data); }
} } else {
// 隐藏通话记录名称视图
private void setBackground(NoteItemData data) { mCallName.setVisibility(View.GONE);
int id = data.getBgColorId(); // 设置标题文本外观
if (data.getType() == Notes.TYPE_NOTE) { mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); if (data.getType() == Notes.TYPE_FOLDER) {
} else if (data.isLast()) { // 如果是文件夹类型,设置标题文本为片段内容加上文件数量
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); mTitle.setText(data.getSnippet()
} else if (data.isFirst() || data.isMultiFollowingFolder()) { + context.getString(R.string.format_folder_files_count,
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); data.getNotesCount()));
} else { // 隐藏提醒图标
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); mAlert.setVisibility(View.GONE);
} } else {
} else { // 如果是笔记类型,设置标题文本为格式化后的片段内容
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
} // 如果有提醒,则显示提醒图标
} if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
public NoteItemData getItemData() { mAlert.setVisibility(View.VISIBLE);
return mItemData; } else {
} // 没有提醒则隐藏提醒图标
} mAlert.setVisibility(View.GONE);
}
}
}
// 设置时间文本为相对时间
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置背景
setBackground(data);
}
// 设置背景的私有方法
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) {
// 根据不同的位置状态设置不同的笔记背景资源
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
// 设置文件夹的背景资源
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
// 获取当前项的数据对象
public NoteItemData getItemData() {
return mItemData;
}
}

@ -14,367 +14,388 @@
* limitations under the License. * 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;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.Preference; import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener; import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory; import android.preference.PreferenceCategory;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; 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 的类,继承自 PreferenceActivity
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;
@Override
protected void onCreate(Bundle icicle) { // 活动创建时调用的方法
super.onCreate(icicle); @Override
protected void onCreate(Bundle icicle) {
/* using the app icon for navigation */ super.onCreate(icicle);
getActionBar().setDisplayHomeAsUpEnabled(true);
/* using the app icon for navigation */
addPreferencesFromResource(R.xml.preferences); getActionBar().setDisplayHomeAsUpEnabled(true);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver(); // 从资源文件中加载偏好设置
IntentFilter filter = new IntentFilter(); addPreferencesFromResource(R.xml.preferences);
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
registerReceiver(mReceiver, filter); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
mOriAccounts = null; filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); // 注册广播接收器
getListView().addHeaderView(header, null, true); registerReceiver(mReceiver, filter);
}
mOriAccounts = null;
@Override // 加载头部视图
protected void onResume() { View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
super.onResume(); getListView().addHeaderView(header, null, true);
}
// need to set sync account automatically if user has added a new
// account // 活动恢复时调用的方法
if (mHasAddedAccount) { @Override
Account[] accounts = getGoogleAccounts(); protected void onResume() {
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { super.onResume();
for (Account accountNew : accounts) {
boolean found = false; // 如果添加了账户,则需要自动设置同步账户
for (Account accountOld : mOriAccounts) { if (mHasAddedAccount) {
if (TextUtils.equals(accountOld.name, accountNew.name)) { Account[] accounts = getGoogleAccounts();
found = true; if (mOriAccounts!= null && accounts.length > mOriAccounts.length) {
break; for (Account accountNew : accounts) {
} boolean found = false;
} for (Account accountOld : mOriAccounts) {
if (!found) { if (TextUtils.equals(accountOld.name, accountNew.name)) {
setSyncAccount(accountNew.name); found = true;
break; break;
} }
} }
} if (!found) {
} setSyncAccount(accountNew.name);
break;
refreshUI(); }
} }
}
@Override }
protected void onDestroy() {
if (mReceiver != null) { // 刷新用户界面
unregisterReceiver(mReceiver); refreshUI();
} }
super.onDestroy();
} // 活动销毁时调用的方法
@Override
private void loadAccountPreference() { protected void onDestroy() {
mAccountCategory.removeAll(); if (mReceiver!= null) {
// 注销广播接收器
Preference accountPref = new Preference(this); unregisterReceiver(mReceiver);
final String defaultAccount = getSyncAccountName(this); }
accountPref.setTitle(getString(R.string.preferences_account_title)); super.onDestroy();
accountPref.setSummary(getString(R.string.preferences_account_summary)); }
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) { // 加载账户偏好设置的方法
if (!GTaskSyncService.isSyncing()) { private void loadAccountPreference() {
if (TextUtils.isEmpty(defaultAccount)) { mAccountCategory.removeAll();
// the first time to set account
showSelectAccountAlertDialog(); Preference accountPref = new Preference(this);
} else { final String defaultAccount = getSyncAccountName(this);
// if the account has already been set, we need to promp accountPref.setTitle(getString(R.string.preferences_account_title));
// user about the risk accountPref.setSummary(getString(R.string.preferences_account_summary));
showChangeAccountConfirmAlertDialog(); accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
} public boolean onPreferenceClick(Preference preference) {
} else { if (!GTaskSyncService.isSyncing()) {
Toast.makeText(NotesPreferenceActivity.this, if (TextUtils.isEmpty(defaultAccount)) {
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) // 如果是第一次设置账户,则显示选择账户的警告对话框
showSelectAccountAlertDialog();
} else {
// 如果账户已经设置,则显示更改账户确认的警告对话框
showChangeAccountConfirmAlertDialog();
}
} else {
// 如果正在同步,则显示不能更改账户的吐司消息
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
} }
return true; return true;
} }
}); });
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
private void loadSyncButton() { // 加载同步按钮的方法
Button syncButton = (Button) findViewById(R.id.preference_sync_button); private void loadSyncButton() {
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
if (GTaskSyncService.isSyncing()) { // 设置按钮状态
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); if (GTaskSyncService.isSyncing()) {
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setText(getString(R.string.preferences_button_sync_cancel));
public void onClick(View v) { syncButton.setOnClickListener(new View.OnClickListener() {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); public void onClick(View v) {
} GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}); }
} else { });
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); } else {
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setText(getString(R.string.preferences_button_sync_immediately));
public void onClick(View v) { syncButton.setOnClickListener(new View.OnClickListener() {
GTaskSyncService.startSync(NotesPreferenceActivity.this); public void onClick(View v) {
} GTaskSyncService.startSync(NotesPreferenceActivity.this);
}); }
} });
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
if (GTaskSyncService.isSyncing()) { // 设置最后同步时间文本
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
} else { lastSyncTimeView.setVisibility(View.VISIBLE);
long lastSyncTime = getLastSyncTime(this); } else {
if (lastSyncTime != 0) { long lastSyncTime = getLastSyncTime(this);
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, if (lastSyncTime!= 0) {
DateFormat.format(getString(R.string.preferences_last_sync_time_format), lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
lastSyncTime))); DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTime)));
} else { lastSyncTimeView.setVisibility(View.VISIBLE);
lastSyncTimeView.setVisibility(View.GONE); } else {
} lastSyncTimeView.setVisibility(View.GONE);
} }
} }
}
private void refreshUI() {
loadAccountPreference(); // 刷新用户界面的方法
loadSyncButton(); private void refreshUI() {
} loadAccountPreference();
loadSyncButton();
private void showSelectAccountAlertDialog() { }
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 显示选择账户警告对话框的方法
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); private void showSelectAccountAlertDialog() {
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
dialogBuilder.setCustomTitle(titleView); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
dialogBuilder.setPositiveButton(null, null); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
Account[] accounts = getGoogleAccounts(); dialogBuilder.setCustomTitle(titleView);
String defAccount = getSyncAccountName(this); dialogBuilder.setPositiveButton(null, null);
mOriAccounts = accounts; Account[] accounts = getGoogleAccounts();
mHasAddedAccount = false; String defAccount = getSyncAccountName(this);
if (accounts.length > 0) { mOriAccounts = accounts;
CharSequence[] items = new CharSequence[accounts.length]; mHasAddedAccount = false;
final CharSequence[] itemMapping = items;
int checkedItem = -1; if (accounts.length > 0) {
int index = 0; CharSequence[] items = new CharSequence[accounts.length];
for (Account account : accounts) { final CharSequence[] itemMapping = items;
if (TextUtils.equals(account.name, defAccount)) { int checkedItem = -1;
checkedItem = index; int index = 0;
} for (Account account : accounts) {
items[index++] = account.name; if (TextUtils.equals(account.name, defAccount)) {
} checkedItem = index;
dialogBuilder.setSingleChoiceItems(items, checkedItem, }
new DialogInterface.OnClickListener() { items[index++] = account.name;
public void onClick(DialogInterface dialog, int which) { }
setSyncAccount(itemMapping[which].toString()); dialogBuilder.setSingleChoiceItems(items, checkedItem,
dialog.dismiss(); new DialogInterface.OnClickListener() {
refreshUI(); public void onClick(DialogInterface dialog, int which) {
} setSyncAccount(itemMapping[which].toString());
}); dialog.dismiss();
} refreshUI();
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); });
dialogBuilder.setView(addAccountView); }
final AlertDialog dialog = dialogBuilder.show(); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
addAccountView.setOnClickListener(new View.OnClickListener() { dialogBuilder.setView(addAccountView);
public void onClick(View v) {
mHasAddedAccount = true; final AlertDialog dialog = dialogBuilder.show();
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); addAccountView.setOnClickListener(new View.OnClickListener() {
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { public void onClick(View v) {
"gmail-ls" mHasAddedAccount = true;
}); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
startActivityForResult(intent, -1); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
dialog.dismiss(); "gmail-ls"
} });
}); startActivityForResult(intent, -1);
} dialog.dismiss();
}
private void showChangeAccountConfirmAlertDialog() { });
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); }
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 显示更改账户确认警告对话框的方法
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); private void showChangeAccountConfirmAlertDialog() {
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
dialogBuilder.setCustomTitle(titleView); titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
CharSequence[] menuItemArray = new CharSequence[] { TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
getString(R.string.preferences_menu_change_account), subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
getString(R.string.preferences_menu_remove_account), dialogBuilder.setCustomTitle(titleView);
getString(R.string.preferences_menu_cancel)
}; CharSequence[] menuItemArray = new CharSequence[] {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { getString(R.string.preferences_menu_change_account),
public void onClick(DialogInterface dialog, int which) { getString(R.string.preferences_menu_remove_account),
if (which == 0) { getString(R.string.preferences_menu_cancel)
showSelectAccountAlertDialog(); };
} else if (which == 1) { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
removeSyncAccount(); public void onClick(DialogInterface dialog, int which) {
refreshUI(); if (which == 0) {
} showSelectAccountAlertDialog();
} } else if (which == 1) {
}); removeSyncAccount();
dialogBuilder.show(); refreshUI();
} }
}
private Account[] getGoogleAccounts() { });
AccountManager accountManager = AccountManager.get(this); dialogBuilder.show();
return accountManager.getAccountsByType("com.google"); }
}
// 获取谷歌账户数组的方法
private void setSyncAccount(String account) { private Account[] getGoogleAccounts() {
if (!getSyncAccountName(this).equals(account)) { AccountManager accountManager = AccountManager.get(this);
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return accountManager.getAccountsByType("com.google");
SharedPreferences.Editor editor = settings.edit(); }
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 设置同步账户的方法
} else { private void setSyncAccount(String account) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); if (!getSyncAccountName(this).equals(account)) {
} SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
editor.commit(); SharedPreferences.Editor editor = settings.edit();
if (account!= null) {
// clean up last sync time editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
setLastSyncTime(this, 0); } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
// clean up local gtask related info }
new Thread(new Runnable() { editor.commit();
public void run() {
ContentValues values = new ContentValues(); // 清理最后同步时间
values.put(NoteColumns.GTASK_ID, ""); setLastSyncTime(this, 0);
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 清理本地与谷歌任务相关的信息
} new Thread(new Runnable() {
}).start(); public void run() {
ContentValues values = new ContentValues();
Toast.makeText(NotesPreferenceActivity.this, values.put(NoteColumns.GTASK_ID, "");
getString(R.string.preferences_toast_success_set_accout, account), values.put(NoteColumns.SYNC_ID, 0);
Toast.LENGTH_SHORT).show(); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
} }).start();
private void removeSyncAccount() { Toast.makeText(NotesPreferenceActivity.this,
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); getString(R.string.preferences_toast_success_set_accout, account),
SharedPreferences.Editor editor = settings.edit(); Toast.LENGTH_SHORT).show();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { }
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); }
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { // 移除同步账户的方法
editor.remove(PREFERENCE_LAST_SYNC_TIME); private void removeSyncAccount() {
} SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
editor.commit(); SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
// clean up local gtask related info editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
new Thread(new Runnable() { }
public void run() { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
ContentValues values = new ContentValues(); editor.remove(PREFERENCE_LAST_SYNC_TIME);
values.put(NoteColumns.GTASK_ID, ""); }
values.put(NoteColumns.SYNC_ID, 0); editor.commit();
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} // 清理本地与谷歌任务相关的信息
}).start(); new Thread(new Runnable() {
} public void run() {
ContentValues values = new ContentValues();
public static String getSyncAccountName(Context context) { values.put(NoteColumns.GTASK_ID, "");
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, values.put(NoteColumns.SYNC_ID, 0);
Context.MODE_PRIVATE); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); }
} }).start();
}
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, // 获取同步账户名称的静态方法
Context.MODE_PRIVATE); public static String getSyncAccountName(Context context) {
SharedPreferences.Editor editor = settings.edit(); SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); Context.MODE_PRIVATE);
editor.commit(); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
public static long getLastSyncTime(Context context) { // 设置最后同步时间的静态方法
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, public static void setLastSyncTime(Context context, long time) {
Context.MODE_PRIVATE); SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); Context.MODE_PRIVATE);
} SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
private class GTaskReceiver extends BroadcastReceiver { editor.commit();
}
@Override
public void onReceive(Context context, Intent intent) { // 获取最后同步时间的静态方法
refreshUI(); public static long getLastSyncTime(Context context) {
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); Context.MODE_PRIVATE);
syncStatus.setText(intent return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
// 广播接收器内部类
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }
} }
} }
public boolean onOptionsItemSelected(MenuItem item) { // 选项菜单项被选择时调用的方法
public boolean onOptionsItemSelected(
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);

@ -2,6 +2,7 @@
# as it contains information specific to your local configuration. # as it contains information specific to your local configuration.
# #
# Location of the SDK. This is only used by Gradle. # Location of the SDK. This is only used by Gradle.
# # For customization when using a Version Control System, please read the
#Sun Sep 08 13:35:35 CST 2024 # header note.
sdk.dir=D\:\\Android\\Sdk #Sun Sep 22 17:32:55 CST 2024
sdk.dir=D\:\\sdk

Loading…
Cancel
Save