pull/3/head
6p0 7 months ago
commit ee8aabf987

@ -0,0 +1,87 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.content.Context; // 导入Android上下文类用于访问系统资源
import android.database.Cursor; // 导入Android游标类用于查询数据库
import android.provider.ContactsContract.CommonDataKinds.Phone; // 导入Android联系人电话信息类
import android.provider.ContactsContract.Data; // 导入Android联系人数据类
import android.telephony.PhoneNumberUtils; // 导入Android电话号码工具类
import android.util.Log; // 导入Android日志工具类
import java.util.HashMap; // 导入Java哈希表类用于缓存查询结果
public class Contact {
// 静态的哈希表,用于缓存电话号码和对应的联系人姓名
private static HashMap<String, String> sContactCache;
// 日志标签,用于在日志中标识来自该类的消息
private static final String TAG = "Contact";
// SQL查询条件用于查找与给定电话号码匹配的联系人信息
// 使用PHONE_NUMBERS_EQUAL函数比较电话号码确保号码格式的一致性
// 限制数据类型为电话号码类型,并通过子查询确保电话号码的最小匹配字符为'+'
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 "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 根据给定的电话号码获取联系人的姓名
public static String getContact(Context context, String phoneNumber) {
// 如果缓存为空,则初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存中是否已有该电话号码对应的联系人姓名
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 }, // 需要查询的字段:联系人显示名称
selection, // 查询条件
new String[] { phoneNumber }, // 查询条件中的占位符参数
null); // 排序条件这里为null表示不排序
// 检查查询结果是否为空且是否可以移动到第一行
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0); // 获取联系人显示名称
sContactCache.put(phoneNumber, name); // 将查询结果存入缓存
return name; // 返回联系人姓名
} catch (IndexOutOfBoundsException e) {
// 如果发生数组越界异常记录错误日志并返回null
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close(); // 关闭游标,释放资源
}
} else {
// 如果没有找到匹配的联系人记录调试日志并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}

@ -0,0 +1,298 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*
*
*/
package net.micode.notes.data;
import android.net.Uri;
// 定义了一个名为Notes的类包含了与笔记应用相关的常量和接口
public class Notes {
// 定义了Content Provider的权限字符串
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; // 系统类型
/**
* ID
* {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER}
* {@link Notes#ID_TRASH_FOLER}
*/
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;
// 定义了一些Intent的extra键名
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"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
// 定义了小部件类型的常量
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的小部件
public static final int TYPE_WIDGET_2X = 0; // 2x尺寸的小部件
public static final int TYPE_WIDGET_4X = 1; // 4x尺寸的小部件
// 定义一个内部类DataConstants包含一些与数据类型相关的常量
public static class DataConstants {
// 定义了文本笔记的数据类型
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
// 定义了通话笔记的数据类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri
* content://micode_notes/note
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri
* content://micode_notes/data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
// 定义了一个接口NoteColumns包含了一些与笔记和文件夹相关的列名
public interface NoteColumns {
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
*
* <P> TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
*
* <P> INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
*
* <P> INTEGER </P>
*/
public static final String TYPE = "type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
*
* <P> INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* ID
* <P> INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* GoogleID
* <P> TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
// 定义了一个接口DataColumns包含了一些与数据相关的列名
public interface DataColumns {
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* MIME
* <P> TEXT </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> TEXT </P>
*/
public static final String CONTENT = "content";
/**
* {@link #MIME_TYPE}
* <P> INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* {@link #MIME_TYPE}
* <P> INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* {@link #MIME_TYPE}
* <P> TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* {@link #MIME_TYPE}
* <P> TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* {@link #MIME_TYPE}
* <P> TEXT </P>
*/
public static final String DATA5 = "data5";
}
// 定义了一个内部类TextNote继承自DataColumns表示文本笔记的数据结构
public static final class TextNote implements DataColumns {
/**
*
* <P> Integer 1: 0: </P>
*/
public static final String MODE = DATA1;
// 定义了文本笔记模式的常量
public static final int MODE_CHECK_LIST = 1;
// 定义了文本笔记的MIME类型
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
/**
* Uri
* content://micode_notes/text_note
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
// 定义了一个内部类CallNote继承自DataColumns表示通话笔记的数据结构
public static final class CallNote implements DataColumns {
/**
*
* <P> INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
*
* <P> TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
// 定义了通话笔记的MIME类型
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";
/**
* Uri
* content://micode_notes/call_note
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -0,0 +1,389 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*
*
*/
package net.micode.notes.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
// NotesDatabaseHelper 是一个 SQLiteOpenHelper 类的子类,用于管理笔记应用的数据库
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 定义了数据库名称
private static final String DB_NAME = "note.db";
// 定义了数据库版本号
private static final int DB_VERSION = 4;
// 定义了一个内部接口TABLE包含了表名常量
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," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " 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" +
")";
// 定义了创建 DATA 表的SQL语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
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 + "); ";
/**
*
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
*
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
/**
*
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
*
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
/**
* {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
/**
*
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
// 构造函数,初始化数据库帮助器
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// 创建笔记表的方法
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
createSystemFolder(db);
Log.d(TAG, "note table has been created");
}
// 重新创建笔记表触发器的方法
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");
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_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);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
// 创建系统文件夹的方法
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
*
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
// 创建数据表的方法
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created");
}
// 重新创建数据表触发器的方法
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);
}
// 获取 NotesDatabaseHelper 单例实例的方法
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
// 当数据库第一次创建时调用的方法
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
// 当数据库需要升级时调用的方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
// 如果当前版本是1直接删除旧表并创建新表
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // 这次升级包含了从v2到v3的升级
oldVersion++;
}
// 如果当前版本是2添加新的列并创建系统文件夹
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
// 如果当前版本是3添加版本号列
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 如果需要重新创建触发器,调用相应的方法
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 如果升级失败,抛出异常
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ " fails");
}
}
// 升级到数据库版本2的方法
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);
}
// 升级到数据库版本3的方法
private void upgradeToV3(SQLiteDatabase db) {
// 删除不再使用的触发器
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");
// 添加 gtask id 列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// 添加回收站系统文件夹
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);
}
// 升级到数据库版本4的方法
private void upgradeToV4(SQLiteDatabase db) {
// 添加版本号列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}

@ -0,0 +1,342 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {
// UriMatcher用于匹配不同的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;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
// 静态代码块在类加载时初始化UriMatcher
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
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);
}
/**
* x'0A'sqlite'\n'
* '\n'便
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ 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_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + 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;
// 创建ContentProvider时调用初始化NotesDatabaseHelper
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
// 根据不同的URI请求类型执行查询操作
@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);
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);
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(
"不允许在搜索时指定排序条件、选择条件、选择参数或投影");
}
String searchString = null;
// 获取搜索字符串
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
// 如果搜索字符串为空返回null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 格式化搜索字符串使其可以用于LIKE查询
searchString = String.format("%%%s%%", searchString);
// 执行搜索查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "发生异常: " + ex.toString());
}
break;
default:
// 如果URI请求类型未知抛出异常
throw new IllegalArgumentException("未知的URI " + uri);
}
// 设置游标的通知URI以便内容变化时通知监听者
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
// 根据不同的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)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "数据格式错误缺少笔记ID:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
// 如果URI请求类型未知抛出异常
throw new IllegalArgumentException("未知的URI " + uri);
}
// 通知笔记URI变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// 通知数据URI变化
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
}
// 根据不同的URI请求类型删除数据
@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:
// 删除笔记时确保ID大于0
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
long noteId = Long.valueOf(id);
// ID小于等于0的笔记为系统文件夹不允许删除
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 = uri.getPathSegments().get(1);
// 删除特定ID的笔记数据
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
// 如果URI请求类型未知抛出异常
throw new IllegalArgumentException("未知的URI " + uri);
}
// 如果有数据被删除通知URI变化
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
// 根据不同的URI请求类型更新数据
@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 = uri.getPathSegments().get(1);
long noteId = Long.valueOf(id);
// 更新特定ID的笔记并增加笔记版本号
increaseNoteVersion(noteId, selection, selectionArgs);
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 = 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("未知的URI " + uri);
}
// 如果有数据被更新通知URI变化
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
// 解析选择条件字符串如果存在选择条件则添加到SQL查询中
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
// 增加笔记版本号
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
// 构建WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
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) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
// 执行更新操作
mHelper.getWritableDatabase().execSQL(sql.toString());
}
// 返回URI对应的数据类型这里未实现返回null
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

@ -36,56 +36,59 @@ import java.io.IOException;
import java.io.PrintStream;
`BackupUtils.java`
```java
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static BackupUtils sInstance;
private static final String TAG = "BackupUtils"; // 定义日志标签,用于识别日志输出的来源
private static BackupUtils sInstance; // 声明一个静态实例变量,用于实现单例模式
// 提供一个公共的静态方法用于获取BackupUtils的单例实例
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
sInstance = new BackupUtils(context); // 如果实例不存在,则新建一个实例
}
return sInstance;
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;
// 定义一系列状态码,用于表示备份或恢复的状态
public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD卡未挂载
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在
public static final int STATE_DATA_DESTROIED = 2; // 数据格式不正确,可能被其他程序更改
public static final int STATE_SYSTEM_ERROR = 3; // 系统错误,导致备份或恢复失败
public static final int STATE_SUCCESS = 4; // 备份或恢复成功
private TextExport mTextExport;
private TextExport mTextExport; // TextExport对象用于将数据导出到文本
// BackupUtils的私有构造函数传入Context对象
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
mTextExport = new TextExport(context); // 初始化TextExport对象
}
// 检查外部存储SD卡是否可用
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); // 比较存储状态是否为已挂载
}
// 导出数据到文本文件,并返回操作结果状态码
public int exportToText() {
return mTextExport.exportToText();
return mTextExport.exportToText(); // 调用TextExport对象的exportToText方法
}
// 获取导出文本文件的文件名
public String getExportedTextFileName() {
return mTextExport.mFileName;
return mTextExport.mFileName; // 返回TextExport对象中保存的文件名
}
// 获取导出文本文件的目录路径
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
return mTextExport.mFileDirectory; // 返回TextExport对象中保存的文件目录
}
// 内部类TextExport封装了将笔记数据导出到文本文件的逻辑
private static class TextExport {
// 定义查询笔记信息时需要的字段
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
@ -93,12 +96,12 @@ public class BackupUtils {
NoteColumns.TYPE
};
// 定义NOTE_PROJECTION数组中各个字段的索引
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,93 +111,88 @@ public class BackupUtils {
DataColumns.DATA4,
};
// 定义DATA_PROJECTION数组中各个字段的索引
private static final int DATA_COLUMN_CONTENT = 0;
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 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;
private Context mContext; // 应用程序上下文
private String mFileName; // 导出文本文件的文件名
private String mFileDirectory; // 导出文本文件的目录
// TextExport类的构造函数初始化上下文和格式化字符串数组
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); // 从资源文件中获取格式化字符串数组
mContext = context; // 保存上下文对象
mFileName = ""; // 初始化文件名为空字符串
mFileDirectory = ""; // 初始化文件目录为空字符串
}
// 根据索引获取格式化字符串
private String getFormat(int id) {
return TEXT_FORMAT[id];
return TEXT_FORMAT[id]; // 返回格式化字符串数组中指定索引的字符串
}
/**
* Export the folder identified by folder id to text
*/
// 导出指定文件夹ID的笔记到文本
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
}, null);
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();
notesCursor.close(); // 关闭游标
}
}
/**
* Export note identified by id to a print stream
*/
// 导出指定ID的笔记到文本
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询笔记数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
// 如果MIME类型为通话笔记则打印电话号码、通话日期和位置
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) {
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)) {
// 如果MIME类型为普通笔记则打印笔记内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
@ -203,9 +201,9 @@ public class BackupUtils {
}
} while (dataCursor.moveToNext());
}
dataCursor.close();
dataCursor.close(); // 关闭游标
}
// print a line separator between note
// 打印笔记之间的分隔符
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -215,130 +213,37 @@ public class BackupUtils {
}
}
/**
* Note will be exported as text which is user readable
*/
// 执行导出操作,将笔记数据导出为用户可读的文本格式
public int exportToText() {
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
Log.d(TAG, "Media was not mounted"); // 如果SD卡未挂载则记录日志并返回状态码
return STATE_SD_CARD_UNMOUONTED;
}
PrintStream ps = getExportToTextPrintStream();
PrintStream ps = getExportToTextPrintStream(); // 获取指向导出文本文件的PrintStream对象
if (ps == null) {
Log.e(TAG, "get print stream error");
Log.e(TAG, "get print stream error"); // 如果获取PrintStream失败则记录日志并返回状态码
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 查询所有文件夹和其笔记,除了垃圾箱文件夹和通话记录文件夹
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
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);
folderName = mContext.getString(R.string.call_record_folder_name); // 如果是通话记录文件夹,则使用资源文件中的名称
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); // 否则,使用查询到的文件夹名称
}
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
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,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
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;
}
return ps;
}
}
/**
* 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));
File filedir = new File(sb.toString());
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
File file = new File(sb.toString());
try {
if (!filedir.exists()) {
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
exportFolderToText(folderId

@ -34,262 +34,161 @@ 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 final String TAG = "DataUtils"; // 定义日志标签
/**
*
* @param resolver ContentResolver访
* @param ids ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
if (ids == null) { // 检查传入的ID集合是否为空
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) {
if (ids.size() == 0) { // 检查ID集合是否为空
Log.d(TAG, "no id is in the hashset");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // 操作列表,用于批量操作
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
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());
.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) {
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) {
} catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
} catch (OperationApplicationException e) { // 捕获操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
return false; // 发生异常时返回false
}
/**
*
* @param resolver ContentResolver访
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
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);
ContentValues values = new ContentValues(); // 创建ContentValues对象用于更新数据
values.put(NoteColumns.PARENT_ID, desFolderId); // 设置新的父ID即目标文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置原始的父ID即当前文件夹ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记笔记为本地修改
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); // 更新笔记数据
}
/**
*
* @param resolver ContentResolver访
* @param ids ID
* @param folderId ID
* @return truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
if (ids == null) {
if (ids == null) { // 检查传入的ID集合是否为空
Log.d(TAG, "the ids is null");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // 操作列表,用于批量操作
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());
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); // 构建更新操作
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置新的父ID即目标文件夹ID
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) {
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) {
} catch (RemoteException e) { // 捕获远程异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
} catch (OperationApplicationException e) { // 捕获操作应用异常
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
return false; // 发生异常时返回false
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
* @param resolver ContentResolver访
* @return
*/
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, // 查询笔记内容URI
new String[] { "COUNT(*)" }, // 查询计数
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件,类型为文件夹且不是垃圾箱
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, // 查询参数
null);
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
if (cursor != null) { // 检查游标是否为空
if (cursor.moveToFirst()) { // 移动到游标的第一行
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
count = cursor.getInt(0); // 获取文件夹数量
} catch (IndexOutOfBoundsException e) { // 捕获索引越界异常
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
cursor.close(); // 关闭游标
}
}
}
return count;
return count; // 返回文件夹数量
}
/**
*
* @param resolver ContentResolver访
* @param noteId ID
* @param type
* @return truefalse
*/
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,
new String [] {String.valueOf(type)},
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), // 查询笔记URI
null, // 无特定列
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, // 查询条件,类型匹配且不在垃圾箱
new String[] {String.valueOf(type)}, // 查询参数
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;
if (cursor != null) { // 检查游标是否为空
if (cursor.getCount() > 0) { // 检查查询结果数量
exist = true; // 设置存在标志为true
}
cursor.close();
cursor.close(); // 关闭游标
}
return exist;
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 + "=?",
new String[] { String.valueOf(folderId) },
null);
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
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;
}
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 + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
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 "";
}
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0;
}
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
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);
}
}
return snippet;
}
}
/**
*
* @param resolver ContentResolver访
* @param noteId ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId)

@ -17,97 +17,98 @@
package net.micode.notes.tool;
public class GTaskStringUtils {
// 定义GTASK_JSON_ACTION_ID常量用于标识动作ID
public final static String GTASK_JSON_ACTION_ID = "action_id";
// 定义GTASK_JSON_ACTION_LIST常量用于标识动作列表
public final static String GTASK_JSON_ACTION_LIST = "action_list";
// 定义GTASK_JSON_ACTION_TYPE常量用于标识动作类型
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// 定义GTASK_JSON_ACTION_TYPE_CREATE常量表示创建动作
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// 定义GTASK_JSON_ACTION_TYPE_GETALL常量表示获取所有动作
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// 定义GTASK_JSON_ACTION_TYPE_MOVE常量表示移动动作
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// 定义GTASK_JSON_ACTION_TYPE_UPDATE常量表示更新动作
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// 定义GTASK_JSON_CREATOR_ID常量用于标识创建者ID
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// 定义GTASK_JSON_CHILD_ENTITY常量用于标识子实体
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// 定义GTASK_JSON_CLIENT_VERSION常量用于标识客户端版本
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// 定义GTASK_JSON_COMPLETED常量用于标识任务是否完成
public final static String GTASK_JSON_COMPLETED = "completed";
// 定义GTASK_JSON_CURRENT_LIST_ID常量用于标识当前列表ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// 定义GTASK_JSON_DEFAULT_LIST_ID常量用于标识默认列表ID
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// 定义GTASK_JSON_DELETED常量用于标识任务是否被删除
public final static String GTASK_JSON_DELETED = "deleted";
// 定义GTASK_JSON_DEST_LIST常量用于标识目标列表
public final static String GTASK_JSON_DEST_LIST = "dest_list";
// 定义GTASK_JSON_DEST_PARENT常量用于标识目标父任务
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// 定义GTASK_JSON_DEST_PARENT_TYPE常量用于标识目标父任务类型
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// 定义GTASK_JSON_ENTITY_DELTA常量用于标识实体变化
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// 定义GTASK_JSON_ENTITY_TYPE常量用于标识实体类型
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// 定义GTASK_JSON_GET_DELETED常量表示获取已删除的任务
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// 定义GTASK_JSON_ID常量用于标识任务ID
public final static String GTASK_JSON_ID = "id";
// 定义GTASK_JSON_INDEX常量用于标识任务在列表中的索引
public final static String GTASK_JSON_INDEX = "index";
// 定义GTASK_JSON_LAST_MODIFIED常量用于标识任务最后修改时间
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// 定义GTASK_JSON_LATEST_SYNC_POINT常量用于标识最新的同步点
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// 定义GTASK_JSON_LIST_ID常量用于标识列表ID
public final static String GTASK_JSON_LIST_ID = "list_id";
// 定义GTASK_JSON_LISTS常量用于标识列表集合
public final static String GTASK_JSON_LISTS = "lists";
// 定义GTASK_JSON_NAME常量用于标识任务或列表的名称
public final static String GTASK_JSON_NAME = "name";
// 定义GTASK_JSON_NEW_ID常量用于标识新的任务ID
public final static String GTASK_JSON_NEW_ID = "new_id";
// 定义GTASK_JSON_NOTES常量用于标识任务的备注信息
public final static String GTASK_JSON_NOTES = "notes";
// 定义GTASK_JSON_PARENT_ID常量用于标识父任务ID
public final static String GTASK_JSON_PARENT_ID = "parent_id";
// 定义GTASK_JSON_PRIOR_SIBLING_ID常量用于标识前一个兄弟任务ID
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// 定义GTASK_JSON_RESULTS常量用于标识操作结果
public final static String GTASK_JSON_RESULTS = "results";
// 定义GTASK_JSON_SOURCE_LIST常量用于标识源列表
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// 定义GTASK_JSON_TASKS常量用于标识任务集合
public final static String GTASK_JSON_TASKS = "tasks";
// 定义GTASK_JSON_TYPE常量用于标识实体类型
public final static String GTASK_JSON_TYPE = "type";
// 定义GTASK_JSON_TYPE_GROUP常量表示分组类型
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// 定义GTASK_JSON_TYPE_TASK常量表示任务类型
public final static String GTASK_JSON_TYPE_TASK = "TASK";
// 定义GTASK_JSON_USER常量用于标识用户信息
public final static String GTASK_JSON_USER = "user";
// 定义MIUI_FOLDER_PREFFIX常量用于标识MIUI笔记的文件夹前缀
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 定义FOLDER_DEFAULT常量用于标识默认文件夹名称
public final static String FOLDER_DEFAULT = "Default";
// 定义FOLDER_CALL_NOTE常量用于标识通话记录文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note";
// 定义FOLDER_META常量用于标识元数据文件夹名称
public final static String FOLDER_META = "METADATA";
// 定义META_HEAD_GTASK_ID常量用于标识元数据中的GTask ID
public final static String META_HEAD_GTASK_ID = "meta_gid";
// 定义META_HEAD_NOTE常量用于标识元数据中的笔记信息
public final static String META_HEAD_NOTE = "meta_note";
// 定义META_HEAD_DATA常量用于标识元数据中的其他数据
public final static String META_HEAD_DATA = "meta_data";
// 定义META_NOTE_NAME常量用于标识元数据笔记的名称警告不要更新或删除
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}
}

@ -22,24 +22,35 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* ID
*/
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;
/**
* ID
*/
public static class NoteBgResources {
// 定义编辑状态下不同颜色的笔记背景资源ID数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
@ -48,6 +59,7 @@ public class ResourceParser {
R.drawable.edit_red
};
// 定义编辑状态下不同颜色的笔记标题背景资源ID数组
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
@ -56,15 +68,21 @@ 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
* IDID
*/
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -74,7 +92,11 @@ public class ResourceParser {
}
}
/**
* ID
*/
public static class NoteItemBgResources {
// 定义列表中首项不同颜色的笔记背景资源ID数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
@ -83,6 +105,7 @@ public class ResourceParser {
R.drawable.list_red_up
};
// 定义列表中普通项不同颜色的笔记背景资源ID数组
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
@ -91,6 +114,7 @@ public class ResourceParser {
R.drawable.list_red_middle
};
// 定义列表中末项不同颜色的笔记背景资源ID数组
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
@ -99,6 +123,7 @@ public class ResourceParser {
R.drawable.list_red_down,
};
// 定义列表中单项不同颜色的笔记背景资源ID数组
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
@ -107,28 +132,37 @@ 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];
}
// 获取文件夹背景资源ID
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
* 2x24x4ID
*/
public static class WidgetBgResources {
// 定义2x2大小不同颜色的部件背景资源ID数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
@ -137,10 +171,12 @@ public class ResourceParser {
R.drawable.widget_2x_red,
};
// 获取2x2大小指定颜色的部件背景资源ID
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 定义4x4大小不同颜色的部件背景资源ID数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
@ -149,12 +185,17 @@ public class ResourceParser {
R.drawable.widget_4x_red
};
// 获取4x4大小指定颜色的部件背景资源ID
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
/**
* ID
*/
public static class TextAppearanceResources {
// 定义不同大小的文本外观资源ID数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
@ -162,6 +203,7 @@ public class ResourceParser {
R.style.TextAppearanceSuper
};
// 获取指定大小的文本外观资源ID
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
@ -174,8 +216,9 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取文本外观资源数组的大小
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}
Loading…
Cancel
Save