Compare commits

...

11 Commits
master ... ice

@ -25,10 +25,16 @@ import android.util.Log;
import java.util.HashMap;
/**
*
*/
public class Contact {
// 用于缓存电话号码和对应的联系人姓名,避免重复查询联系人数据库
private static HashMap<String, String> sContactCache;
// 日志标签,方便调试和日志记录
private static final String TAG = "Contact";
// 查询联系人姓名的SQL语句模板根据电话号码匹配联系人信息
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,36 +42,53 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
*
*
* @param context 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
// 初始化联系人缓存
if (sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
if(sContactCache.containsKey(phoneNumber)) {
// 检查缓存中是否已存在该电话号码对应的联系人姓名
if (sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 替换SQL语句模板中的占位符生成最终的查询语句
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人数据库
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
new String[]{Phone.DISPLAY_NAME},
selection,
new String[] { phoneNumber },
new String[]{phoneNumber},
null);
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人姓名
String name = cursor.getString(0);
// 将电话号码和联系人姓名存入缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
// 处理游标获取字符串时可能出现的索引越界异常
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 关闭游标,释放资源
cursor.close();
}
} else {
// 未找到匹配的联系人,记录日志
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

@ -17,234 +17,259 @@
package net.micode.notes.data;
import android.net.Uri;
/**
* 便IDURI
* 便
*/
public class Notes {
// 内容提供者的权限
public static final String AUTHORITY = "micode_notes";
// 日志标签,方便调试和日志记录
public static final String TAG = "Notes";
// 便签类型
public static final int TYPE_NOTE = 0;
// 文件夹类型
public static final int TYPE_FOLDER = 1;
// 系统类型
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
* ID
* {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER } 便
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
// 意图额外数据的键,用于传递提醒日期
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
// 意图额外数据的键用于传递背景颜色ID
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
// 意图额外数据的键用于传递小部件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";
// 意图额外数据的键用于传递文件夹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 int TYPE_WIDGET_INVALIDE = -1;
// 2x大小的小部件类型
public static final int TYPE_WIDGET_2X = 0;
// 4x大小的小部件类型
public static final int TYPE_WIDGET_4X = 1;
/**
* MIME
*/
public static class DataConstants {
// 文本便签的MIME类型
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
// 通话便签的MIME类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
* 便URI
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* URI
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* 便便
*/
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
* 便
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
* 便
* <P> : TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
* 便
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
* 便便
* <P> : INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
* 便
* <P> : INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
* 便
* <P> : INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*
* <P> : INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* ID
* <P> : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* GTask ID
* <P> : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
/**
*
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* <P> : Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
* 便ID
* <P> : INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
* 便
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA5 = "data5";
}
/**
* 便DataColumns便URI
*/
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*
* <P> : Integer 1: 0: </P>
*/
public static final String MODE = DATA1;
@ -257,16 +282,19 @@ public class Notes {
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
* 便DataColumns便URI
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;

@ -26,22 +26,32 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
* SQLiteOpenHelper便
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库文件名
private static final String DB_NAME = "note.db";
// 数据库版本号
private static final int DB_VERSION = 4;
/**
*
*/
public interface TABLE {
// 便签表名
public static final String NOTE = "note";
// 数据记录表名
public static final String DATA = "data";
}
// 日志标签,方便调试和日志记录
private static final String TAG = "NotesDatabaseHelper";
// 单例实例
private static NotesDatabaseHelper mInstance;
// 创建便签表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +73,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建数据记录表的SQL语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,15 +89,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
// 创建数据记录表中note_id索引的SQL语句
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
* 便便SQL
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
"CREATE TRIGGER increase_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
@ -95,7 +107,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Decrease folder's note count when move note from folder
* 便便SQL
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
@ -108,7 +120,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Increase folder's note count when insert new note to the folder
* 便便SQL
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
@ -120,7 +132,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Decrease folder's note count when delete note from the folder
* 便便SQL
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
@ -133,7 +145,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
* 便SQL
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@ -146,7 +158,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
* 便SQL
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
@ -159,7 +171,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
* 便SQL
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
@ -172,7 +184,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete datas belong to note which has been deleted
* 便便SQL
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@ -183,7 +195,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete notes belong to folder which has been deleted
* 便SQL
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@ -194,7 +206,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Move notes belong to folder which has been moved to trash folder
* 便SQL
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
@ -206,18 +218,38 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
*
* @param context
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* 便SQL
*
* @param db
*/
public void createNoteTable(SQLiteDatabase db) {
// 执行创建便签表的SQL语句
db.execSQL(CREATE_NOTE_TABLE_SQL);
// 重新创建便签表的触发器
reCreateNoteTableTriggers(db);
// 创建系统文件夹
createSystemFolder(db);
// 记录日志,表明便签表已创建
Log.d(TAG, "note table has been created");
}
/**
* 便
*
* @param db
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +258,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,18 +268,23 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
*
* @param db
*/
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
* 便
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@ -254,7 +292,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
* 便
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
@ -262,7 +300,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@ -270,23 +308,45 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
/**
* SQL
*
* @param db
*/
public void createDataTable(SQLiteDatabase db) {
// 执行创建数据记录表的SQL语句
db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据记录表的触发器
reCreateDataTableTriggers(db);
// 创建数据记录表中note_id的索引
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
// 记录日志,表明数据记录表已创建
Log.d(TAG, "data table has been created");
}
/**
*
*
* @param db
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
*
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -294,68 +354,105 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
/**
* 便
*
* @param db
*/
@Override
public void onCreate(SQLiteDatabase db) {
// 创建便签表
createNoteTable(db);
// 创建数据记录表
createDataTable(db);
}
/**
*
*
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
if (oldVersion == 1) {
// 从版本1升级到版本2
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // 此升级包含从版本2到版本3的升级
oldVersion++;
}
if (oldVersion == 2 && !skipV2) {
// 从版本2升级到版本3
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
if (oldVersion == 3) {
// 从版本3升级到版本4
upgradeToV4(db);
oldVersion++;
}
if (reCreateTriggers) {
// 重新创建便签表和数据记录表的触发器
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
if (oldVersion != newVersion) {
// 升级失败,抛出异常
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
/**
* 12便
*
* @param db
*/
private void upgradeToV2(SQLiteDatabase db) {
// 删除旧的便签表和数据记录表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 重新创建便签表和数据记录表
createNoteTable(db);
createDataTable(db);
}
/**
* 23gtask_id
*
* @param db
*/
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
// 删除无用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 为便签表添加gtask_id列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加回收站文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* 34便version
*
* @param db
*/
private void upgradeToV4(SQLiteDatabase db) {
// 为便签表添加version列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}

@ -16,7 +16,6 @@
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
@ -34,14 +33,19 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便
* ContentProvider便访
*/
public class NotesProvider extends ContentProvider {
// URI匹配器用于匹配不同的URI请求
private static final UriMatcher mMatcher;
// 数据库帮助类实例
private NotesDatabaseHelper mHelper;
// 日志标签,方便调试和日志记录
private static final String TAG = "NotesProvider";
// 定义不同URI的匹配码
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
@ -51,7 +55,9 @@ public class NotesProvider extends ContentProvider {
private static final int URI_SEARCH_SUGGEST = 6;
static {
// 初始化URI匹配器
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 添加不同URI的匹配规则
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -62,8 +68,8 @@ public class NotesProvider extends ContentProvider {
}
/**
* 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.
* 便
* x'0A'sqlite'\n'
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@ -73,46 +79,71 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 便签片段搜索的SQL查询语句
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
*
*
* @return truefalse
*/
@Override
public boolean onCreate() {
// 获取数据库帮助类实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* URI
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 查询便签表
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
// 获取便签ID
id = uri.getPathSegments().get(1);
// 查询指定ID的便签
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
// 查询数据记录表
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
// 获取数据记录ID
id = uri.getPathSegments().get(1);
// 查询指定ID的数据记录
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
// 搜索查询不允许指定排序规则和投影列
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
@ -120,59 +151,80 @@ public class NotesProvider extends ContentProvider {
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
// 从URI路径中获取搜索字符串
searchString = uri.getPathSegments().get(1);
}
} else {
// 从URI查询参数中获取搜索字符串
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {
// 搜索字符串为空返回null
return null;
}
try {
// 处理搜索字符串,添加通配符
searchString = String.format("%%%s%%", searchString);
// 执行搜索查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
new String[]{searchString});
} catch (IllegalStateException ex) {
// 处理查询异常
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
// 未知URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {
// 设置游标通知URI当数据变化时通知观察者
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
* URI
*
* @param uri URI
* @param values
* @return URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 插入便签数据
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {
// 获取便签ID
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
// 数据格式错误,记录日志
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
// 插入数据记录
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
// 未知URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知便签URI数据变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// 通知数据记录URI数据变化
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
@ -181,96 +233,148 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId);
}
/**
* URI
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 处理删除便签的条件
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
// 删除便签数据
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 获取便签ID
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
* ID0
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
// 删除指定ID的便签
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 删除数据记录
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
// 获取数据记录ID
id = uri.getPathSegments().get(1);
// 删除指定ID的数据记录
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
// 未知URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
// 通知便签URI数据变化
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
// 通知当前URI数据变化
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
/**
* URI便
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 增加便签版本号
increaseNoteVersion(-1, selection, selectionArgs);
// 更新便签数据
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 获取便签ID
id = uri.getPathSegments().get(1);
// 增加指定ID便签的版本号
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
// 更新指定ID的便签
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 更新数据记录
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
// 获取数据记录ID
id = uri.getPathSegments().get(1);
// 更新指定ID的数据记录
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
default:
// 未知URI抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (updateData) {
// 通知便签URI数据变化
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
// 通知当前URI数据变化
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
/**
*
*
* @param selection
* @return
*/
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* 便ID便
*
* @param id 便ID
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
@ -293,13 +397,19 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString);
}
// 执行更新版本号的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URIMIME
*
* @param uri URI
* @return MIME
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

@ -15,6 +15,7 @@
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
@ -33,114 +34,184 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* Note 便便
*/
public class Note {
// 用于存储便签差异值的 ContentValues 对象
private ContentValues mNoteDiffValues;
// 便签数据对象,用于管理便签的文本数据和通话数据
private NoteData mNoteData;
// 日志标签,用于在日志中标识该类的信息
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
* 便 ID 便
* @param context
* @param folderId 便 ID
* @return 便 ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
// 创建一个新的 ContentValues 对象,用于存储便签的初始信息
ContentValues values = new ContentValues();
// 获取当前时间作为便签的创建时间和修改时间
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
// 设置便签的类型为普通便签
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
// 标记便签为本地修改
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 设置便签所属文件夹的 ID
values.put(NoteColumns.PARENT_ID, folderId);
// 插入新的便签信息到数据库中
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
try {
// 从返回的 Uri 中获取便签的 ID
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
// 若获取 ID 失败,记录错误日志
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
if (noteId == -1) {
// 若便签 ID 为 -1抛出异常
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId;
}
/**
* 便便
*/
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
/**
* 便
* @param key
* @param value
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
// 标记便签为本地修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新便签的修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* 便
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* 便 ID
* @param id ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* 便 ID
* @return ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* 便 ID
* @param id ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
* 便
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
* 便
* @return true false
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
* 便
* @param context
* @param noteId 便 ID
* @return true false
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
// 若便签 ID 不合法,抛出异常
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
// 若便签未被修改,直接返回 true
return true;
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
* 便 LOCAL_MODIFIED MODIFIED_DATE
* 使便便
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
// 若更新便签信息失败,记录错误日志
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
// 不返回,继续执行后续操作
}
// 清空便签的差异值
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
// 若便签数据被修改且同步失败,返回 false
return false;
}
return true;
}
/**
* 便
*/
private class NoteData {
// 文本数据的 ID
private long mTextDataId;
// 用于存储文本数据的 ContentValues 对象
private ContentValues mTextDataValues;
// 通话数据的 ID
private long mCallDataId;
// 用于存储通话数据的 ContentValues 对象
private ContentValues mCallDataValues;
// 日志标签,用于在日志中标识该类的信息
private static final String TAG = "NoteData";
/**
* ContentValues
*/
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
@ -148,101 +219,153 @@ public class Note {
mCallDataId = 0;
}
/**
* 便
* @return true false
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* 便 ID
* @param id ID
*/
void setTextDataId(long id) {
if(id <= 0) {
// 若文本数据 ID 不合法,抛出异常
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
/**
* 便 ID
* @param id ID
*/
void setCallDataId(long id) {
if (id <= 0) {
// 若通话数据 ID 不合法,抛出异常
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}
/**
* 便
* @param key
* @param value
*/
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
// 标记便签为本地修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新便签的修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* 便
* @param key
* @param value
*/
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
// 标记便签为本地修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新便签的修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* 便
* @param context
* @param noteId 便 ID
* @return Uri null
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*
*/
if (noteId <= 0) {
// 若便签 ID 不合法,抛出异常
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 创建一个用于批量操作的 ContentProviderOperation 列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// ContentProviderOperation 构建器
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
// 设置文本数据所属的便签 ID
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
// 若文本数据 ID 为 0插入新的文本数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
// 获取插入的文本数据的 ID
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 若插入失败,记录错误日志并清空文本数据
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
// 若文本数据 ID 不为 0更新文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
// 清空文本数据
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
// 设置通话数据所属的便签 ID
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
// 若通话数据 ID 为 0插入新的通话数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
// 获取插入的通话数据的 ID
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 若插入失败,记录错误日志并清空通话数据
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {
// 若通话数据 ID 不为 0更新通话数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
// 清空通话数据
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
// 执行批量操作
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
// 若操作失败,记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
// 若操作失败,记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}

@ -31,37 +31,40 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* WorkingNote 便便
*/
public class WorkingNote {
// Note for the working note
// 便签对象,用于管理便签的具体数据
private Note mNote;
// Note Id
// 便签的 ID
private long mNoteId;
// Note content
// 便签的内容
private String mContent;
// Note mode
// 便签的模式
private int mMode;
// 便签的提醒日期
private long mAlertDate;
// 便签的修改日期
private long mModifiedDate;
// 便签的背景颜色 ID
private int mBgColorId;
// 便签小部件的 ID
private int mWidgetId;
// 便签小部件的类型
private int mWidgetType;
// 便签所属文件夹的 ID
private long mFolderId;
// 上下文对象,用于访问系统服务和资源
private Context mContext;
// 日志标签,用于在日志中标识该类的信息
private static final String TAG = "WorkingNote";
// 标记便签是否被删除
private boolean mIsDeleted;
// 便签设置更改监听器,用于监听便签设置的变化
private NoteSettingChangedListener mNoteSettingStatusListener;
// 用于查询便签数据的投影,指定需要查询的列
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +75,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
// 用于查询便签信息的投影,指定需要查询的列
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -81,27 +85,32 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
// DATA_PROJECTION 中 ID 列的索引
private static final int DATA_ID_COLUMN = 0;
// DATA_PROJECTION 中内容列的索引
private static final int DATA_CONTENT_COLUMN = 1;
// DATA_PROJECTION 中 MIME 类型列的索引
private static final int DATA_MIME_TYPE_COLUMN = 2;
// DATA_PROJECTION 中模式列的索引
private static final int DATA_MODE_COLUMN = 3;
// NOTE_PROJECTION 中父文件夹 ID 列的索引
private static final int NOTE_PARENT_ID_COLUMN = 0;
// NOTE_PROJECTION 中提醒日期列的索引
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
// NOTE_PROJECTION 中背景颜色 ID 列的索引
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
// NOTE_PROJECTION 中小部件 ID 列的索引
private static final int NOTE_WIDGET_ID_COLUMN = 3;
// NOTE_PROJECTION 中小部件类型列的索引
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
// NOTE_PROJECTION 中修改日期列的索引
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
/**
* 便
* @param context
* @param folderId 便 ID
*/
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -114,7 +123,12 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// Existing note construct
/**
* 便
* @param context
* @param noteId 便 ID
* @param folderId 便 ID
*/
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -124,29 +138,45 @@ public class WorkingNote {
loadNote();
}
/**
* 便便便
*/
private void loadNote() {
// 查询便签的基本信息
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
// 获取便签所属文件夹的 ID
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
// 获取便签的背景颜色 ID
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
// 获取便签小部件的 ID
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
// 获取便签小部件的类型
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
// 获取便签的提醒日期
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
// 获取便签的修改日期
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
cursor.close();
} else {
// 若未查询到便签信息,记录错误日志并抛出异常
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
// 加载便签的数据
loadNoteData();
}
/**
* 便便
*/
private void loadNoteData() {
// 查询便签的数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
@ -155,25 +185,40 @@ public class WorkingNote {
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
// 获取便签数据的 MIME 类型
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
// 若为文本便签类型,获取便签的内容和模式
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
// 设置文本数据的 ID
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 若为通话便签类型,设置通话数据的 ID
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
// 若为其他类型,记录日志
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
}
cursor.close();
} else {
// 若未查询到便签数据,记录错误日志并抛出异常
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
/**
* 便
* @param context
* @param folderId 便 ID
* @param widgetId 便 ID
* @param widgetType 便
* @param defaultBgColorId 便 ID
* @return 便
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,23 +228,35 @@ public class WorkingNote {
return note;
}
/**
* 便
* @param context
* @param id 便 ID
* @return 便
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
* 便
* @return true false
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
// 若便签不存在于数据库中,创建新的便签 ID
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
// 若创建失败,记录错误日志并返回 false
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
// 同步便签信息到数据库
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
* 便
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
@ -212,10 +269,18 @@ public class WorkingNote {
}
}
/**
* 便
* @return true false
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
* 便
* @return true false
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +290,19 @@ public class WorkingNote {
}
}
/**
* 便
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
* 便
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,6 +313,10 @@ public class WorkingNote {
}
}
/**
* 便
* @param mark
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -247,6 +325,10 @@ public class WorkingNote {
}
}
/**
* 便 ID
* @param id ID
*/
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -257,6 +339,10 @@ public class WorkingNote {
}
}
/**
* 便
* @param mode
*/
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -267,6 +353,10 @@ public class WorkingNote {
}
}
/**
* 便
* @param type
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +364,10 @@ public class WorkingNote {
}
}
/**
* 便 ID
* @param id ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +375,10 @@ public class WorkingNote {
}
}
/**
* 便
* @param text
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,80 +386,138 @@ public class WorkingNote {
}
}
/**
* 便便
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
/**
* 便
* @return true false
*/
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
/**
* 便
* @return 便
*/
public String getContent() {
return mContent;
}
/**
* 便
* @return 便
*/
public long getAlertDate() {
return mAlertDate;
}
/**
* 便
* @return 便
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* 便 ID
* @return 便 ID
*/
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
/**
* 便 ID
* @return 便 ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* 便 ID
* @return 便 ID
*/
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
/**
* 便
* @return 便
*/
public int getCheckListMode() {
return mMode;
}
/**
* 便 ID
* @return 便 ID
*/
public long getNoteId() {
return mNoteId;
}
/**
* 便 ID
* @return 便 ID
*/
public long getFolderId() {
return mFolderId;
}
/**
* 便 ID
* @return 便 ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* 便
* @return 便
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* 便便
*/
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
* 便
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*
* @param date
* @param set
*/
void onClockAlertChanged(long date, boolean set);
/**
* Call when user create note from widget
* 便
*/
void onWidgetChanged();
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
* 便
* @param oldMode
* @param newMode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}

@ -35,12 +35,13 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
// 该类用于实现笔记数据的备份功能
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
// 单例实例
private static BackupUtils sInstance;
// 获取单例实例的方法
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
@ -48,44 +49,44 @@ public class BackupUtils {
return sInstance;
}
/**
* Following states are signs to represents backup or restore
* status
*/
// Currently, the sdcard is not mounted
// 定义备份或恢复的状态常量
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
// 文本导出对象
private TextExport mTextExport;
// 构造函数
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
// 检查外部存储是否可用的方法
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出笔记数据为文本的方法
public int exportToText() {
return mTextExport.exportToText();
}
// 获取导出的文本文件名的方法
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
// 获取导出的文本文件目录的方法
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
// 内部类,用于实现文本导出功能
private static class TextExport {
// 笔记查询的投影列
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
@ -93,12 +94,16 @@ public class BackupUtils {
NoteColumns.TYPE
};
// 笔记 ID 列的索引
private static final int NOTE_COLUMN_ID = 0;
// 笔记修改日期列的索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
// 笔记摘要列的索引
private static final int NOTE_COLUMN_SNIPPET = 2;
// 数据查询的投影列
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
@ -108,39 +113,51 @@ public class BackupUtils {
DataColumns.DATA4,
};
// 数据内容列的索引
private static final int DATA_COLUMN_CONTENT = 0;
// 数据 MIME 类型列的索引
private static final int DATA_COLUMN_MIME_TYPE = 1;
// 数据通话日期列的索引
private static final int DATA_COLUMN_CALL_DATE = 2;
// 数据电话号码列的索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式数组
private final String [] TEXT_FORMAT;
// 文件夹名称格式的索引
private static final int FORMAT_FOLDER_NAME = 0;
// 笔记日期格式的索引
private static final int FORMAT_NOTE_DATE = 1;
// 笔记内容格式的索引
private static final int FORMAT_NOTE_CONTENT = 2;
// 上下文对象
private Context mContext;
// 导出的文件名
private String mFileName;
// 导出的文件目录
private String mFileDirectory;
// 构造函数
public TextExport(Context context) {
// 获取文本格式数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
}
// 根据索引获取文本格式的方法
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
* Export the folder identified by folder id to text
*/
// 将指定文件夹导出为文本的方法
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
// 查询属于该文件夹的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
@ -149,23 +166,23 @@ public class BackupUtils {
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
// 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询属于该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
// 关闭游标
notesCursor.close();
}
}
/**
* Export note identified by id to a print stream
*/
// 将指定笔记导出为文本的方法
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询属于该笔记的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
@ -174,9 +191,10 @@ public class BackupUtils {
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
do {
// 获取数据的 MIME 类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
// 打印电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
@ -185,16 +203,17 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
// 打印通话附件位置
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 打印笔记内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
@ -203,33 +222,35 @@ public class BackupUtils {
}
} while (dataCursor.moveToNext());
}
// 关闭游标
dataCursor.close();
}
// print a line separator between note
// 打印笔记之间的分隔线
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
} catch (IOException e) {
// 处理 IO 异常
Log.e(TAG, e.toString());
}
}
/**
* Note will be exported as text which is user readable
*/
// 导出所有笔记数据为文本的方法
public int exportToText() {
// 检查外部存储是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取打印流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 首先导出文件夹及其笔记
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -240,7 +261,7 @@ public class BackupUtils {
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 打印文件夹名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
@ -250,14 +271,17 @@ public class BackupUtils {
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
// 获取文件夹 ID
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
// 导出文件夹及其笔记
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
// 关闭游标
folderCursor.close();
}
// Export notes in root's folder
// 导出根文件夹下的笔记
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -267,41 +291,50 @@ public class BackupUtils {
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {
// 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询属于该笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
// 导出笔记数据
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
// 关闭游标
noteCursor.close();
}
// 关闭打印流
ps.close();
return STATE_SUCCESS;
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
// 获取导出文本的打印流的方法
private PrintStream getExportToTextPrintStream() {
// 生成存储导出数据的文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}
// 获取文件名
mFileName = file.getName();
// 获取文件目录
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
// 创建打印流
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// 处理文件未找到异常
e.printStackTrace();
return null;
} catch (NullPointerException e) {
// 处理空指针异常
e.printStackTrace();
return null;
}
@ -309,10 +342,9 @@ public class BackupUtils {
}
}
/**
* Generate the text file to store imported data
*/
// 生成存储导入数据的文本文件的方法
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 构建文件路径
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
@ -324,21 +356,23 @@ public class BackupUtils {
File file = new File(sb.toString());
try {
// 检查文件夹是否存在,不存在则创建
if (!filedir.exists()) {
filedir.mkdir();
}
// 检查文件是否存在,不存在则创建
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
// 处理安全异常
e.printStackTrace();
} catch (IOException e) {
// 处理 IO 异常
e.printStackTrace();
}
return null;
}
}

@ -34,87 +34,112 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
// 该类包含了一系列用于操作笔记数据的工具方法
public class DataUtils {
public static final String TAG = "DataUtils";
// 批量删除笔记的方法
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查传入的 id 集合是否为 null
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 检查 id 集合是否为空
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
}
// 创建一个用于批量操作的列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历 id 集合
for (long id : ids) {
// 检查是否为系统根文件夹,避免删除系统文件夹
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 创建一个删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 将操作添加到列表中
operationList.add(builder.build());
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果是否有效
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
// 处理远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 处理操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
// 将单个笔记移动到指定文件夹的方法
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 创建一个 ContentValues 对象,用于存储要更新的字段和值
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
// 批量将笔记移动到指定文件夹的方法
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
// 检查传入的 id 集合是否为 null
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 创建一个用于批量操作的列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历 id 集合
for (long id : ids) {
// 创建一个更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
// 将操作添加到列表中
operationList.add(builder.build());
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果是否有效
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
// 处理远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 处理操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/
// 获取用户文件夹数量的方法,排除系统文件夹
public static int getUserFolderCount(ContentResolver resolver) {
// 查询用户文件夹的数量
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -122,13 +147,17 @@ public class DataUtils {
null);
int count = 0;
// 检查游标是否有效
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
// 获取文件夹数量
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
// 处理索引越界异常
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
// 关闭游标
cursor.close();
}
}
@ -136,7 +165,9 @@ public class DataUtils {
return count;
}
// 检查笔记是否在数据库中可见的方法
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询笔记是否可见
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
@ -144,60 +175,76 @@ public class DataUtils {
null);
boolean exist = false;
// 检查游标是否有效
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;
}
// 检查笔记是否存在于数据库中的方法
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询笔记是否存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
// 检查游标是否有效
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;
}
// 检查数据是否存在于数据库中的方法
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询数据是否存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
// 检查游标是否有效
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;
}
// 检查可见文件夹名称是否存在的方法
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询可见文件夹名称是否存在
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
// 检查游标是否有效
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;
}
// 获取指定文件夹下的笔记小部件信息的方法
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询指定文件夹下的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
@ -205,26 +252,33 @@ public class DataUtils {
null);
HashSet<AppWidgetAttribute> set = null;
// 检查游标是否有效
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
// 创建一个 AppWidgetAttribute 对象
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
// 将对象添加到集合中
set.add(widget);
} catch (IndexOutOfBoundsException e) {
// 处理索引越界异常
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
}
// 关闭游标
c.close();
}
return set;
}
// 根据笔记 ID 获取通话号码的方法
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询通话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
@ -233,17 +287,22 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取通话号码
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
// 处理索引越界异常
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
// 关闭游标
cursor.close();
}
}
return "";
}
// 根据电话号码和通话日期获取笔记 ID 的方法
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询笔记 ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
@ -254,17 +313,22 @@ public class DataUtils {
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
// 获取笔记 ID
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
// 处理索引越界异常
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
// 关闭游标
cursor.close();
}
return 0;
}
// 根据笔记 ID 获取摘要的方法
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询摘要
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
@ -274,19 +338,26 @@ public class DataUtils {
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
// 获取摘要
snippet = cursor.getString(0);
}
// 关闭游标
cursor.close();
return snippet;
}
// 若未找到笔记,抛出异常
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
// 格式化摘要的方法
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
// 去除前后空格
snippet = snippet.trim();
// 查找换行符的位置
int index = snippet.indexOf('\n');
if (index != -1) {
// 截取换行符之前的内容
snippet = snippet.substring(0, index);
}
}

@ -16,98 +16,63 @@
package net.micode.notes.tool;
// 该类定义了用于 Google 任务同步的 JSON 字段常量
public class GTaskStringUtils {
// 定义 JSON 字段常量
public final static String GTASK_JSON_ACTION_ID = "action_id";
public final static String GTASK_JSON_ACTION_LIST = "action_list";
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
public final static String GTASK_JSON_COMPLETED = "completed";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
public final static String GTASK_JSON_DELETED = "deleted";
public final static String GTASK_JSON_DEST_LIST = "dest_list";
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
public final static String GTASK_JSON_ID = "id";
public final static String GTASK_JSON_INDEX = "index";
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
public final static String GTASK_JSON_LIST_ID = "list_id";
public final static String GTASK_JSON_LISTS = "lists";
public final static String GTASK_JSON_NAME = "name";
public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PARENT_ID = "parent_id";
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
public final static String GTASK_JSON_RESULTS = "results";
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
public final static String GTASK_JSON_TASKS = "tasks";
public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_TYPE_TASK = "TASK";
public final static String GTASK_JSON_USER = "user";
// 定义小米便签文件夹前缀
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 定义默认文件夹名称
public final static String FOLDER_DEFAULT = "Default";
// 定义通话笔记文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note";
// 定义元数据文件夹名称
public final static String FOLDER_META = "METADATA";
// 定义元数据头部的 Google 任务 ID
public final static String META_HEAD_GTASK_ID = "meta_gid";
// 定义元数据头部的笔记
public final static String META_HEAD_NOTE = "meta_note";
// 定义元数据头部的数据
public final static String META_HEAD_DATA = "meta_data";
// 定义元数据笔记名称
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -22,24 +22,31 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
// 该类用于解析和管理笔记的资源
public class ResourceParser {
// 定义背景颜色常量
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
// 默认背景颜色
public static final int BG_DEFAULT_COLOR = YELLOW;
// 定义字体大小常量
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
// 默认字体大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 笔记编辑时的背景资源类
public static class NoteBgResources {
// 编辑时的背景资源数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
@ -48,6 +55,7 @@ public class ResourceParser {
R.drawable.edit_red
};
// 编辑时标题的背景资源数组
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
@ -56,25 +64,33 @@ public class ResourceParser {
R.drawable.edit_title_red
};
// 根据 ID 获取笔记编辑时的背景资源
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
// 根据 ID 获取笔记编辑时标题的背景资源
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
// 获取默认背景 ID 的方法
public static int getDefaultBgId(Context context) {
// 检查是否设置了背景颜色偏好
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 若设置了,随机生成一个背景 ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 若未设置,返回默认背景 ID
return BG_DEFAULT_COLOR;
}
}
// 笔记列表项的背景资源类
public static class NoteItemBgResources {
// 列表项第一个的背景资源数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
@ -83,6 +99,7 @@ public class ResourceParser {
R.drawable.list_red_up
};
// 列表项中间的背景资源数组
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
@ -91,6 +108,7 @@ public class ResourceParser {
R.drawable.list_red_middle
};
// 列表项最后一个的背景资源数组
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
@ -99,6 +117,7 @@ public class ResourceParser {
R.drawable.list_red_down,
};
// 列表项单个的背景资源数组
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
@ -107,28 +126,35 @@ public class ResourceParser {
R.drawable.list_red_single
};
// 根据 ID 获取列表项第一个的背景资源
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
// 根据 ID 获取列表项最后一个的背景资源
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
// 根据 ID 获取列表项单个的背景资源
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
// 根据 ID 获取列表项中间的背景资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹的背景资源
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// 小部件的背景资源类
public static class WidgetBgResources {
// 2x 小部件的背景资源数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
@ -137,10 +163,12 @@ public class ResourceParser {
R.drawable.widget_2x_red,
};
// 根据 ID 获取 2x 小部件的背景资源
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 4x 小部件的背景资源数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
@ -149,12 +177,15 @@ public class ResourceParser {
R.drawable.widget_4x_red
};
// 根据 ID 获取 4x 小部件的背景资源
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// 文本外观资源类
public static class TextAppearanceResources {
// 文本外观资源数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
@ -162,18 +193,16 @@ public class ResourceParser {
R.style.TextAppearanceSuper
};
// 根据 ID 获取文本外观资源
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
// 处理资源 ID 越界的情况
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取文本外观资源数组的大小
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}

@ -0,0 +1 @@
test
Loading…
Cancel
Save